活字格C#代码调用服务器给百度ai接口发送请求设置

先配置环境

创建类库

活字格C#代码调用服务器给百度ai接口发送请求设置_第1张图片

创建项目

活字格C#代码调用服务器给百度ai接口发送请求设置_第2张图片

配置引用

创建服务端Web API - 活字格V9帮助手册 - 葡萄城产品文档中心 (grapecity.com.cn)

添加引用 

活字格C#代码调用服务器给百度ai接口发送请求设置_第3张图片

Microsoft.AspNetCore.Http.Abstractions

活字格C#代码调用服务器给百度ai接口发送请求设置_第4张图片

配置百度ai的NuGet环境

查看百度AI代码示例的环境说明

活字格C#代码调用服务器给百度ai接口发送请求设置_第5张图片

到NuGet里找到对应环境并下载 

活字格C#代码调用服务器给百度ai接口发送请求设置_第6张图片

编写C#代码

using GrapeCity.Forguncy.ServerApi;
using Microsoft.AspNetCore.Http;
using RestSharp;

namespace FaPiaoApi
{
    public class FaPiaoApi : ForguncyApi
    {
        [Post]
        public async Task GetTokenApi()
        {
            //获取post请求的数据
            var form = await Context.Request.ReadFormAsync();
            var url = form["url"][0];
            var client = new RestClient(url);
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json");
            var body = @"";
            request.AddParameter("application/json", body, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
            Console.WriteLine(response.Content);
            //响应数据
            await this.Context.Response.WriteAsync(response.Content);

        }
        //发送发票识别请求
        [Post]
        public async Task VatInvoiceByImg()
        {
            //获取post请求的数据
            var form = await Context.Request.ReadFormAsync();
            var token = form["token"][0];
            var image = form["imageUrl"][0];
            var client = new RestClient("https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice?access_token=" + token);
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddHeader("Accept", "application/json");
            request.AddParameter("image", image);
            request.AddParameter("seal_tag", "false");
            IRestResponse response = client.Execute(request);
            Console.WriteLine(response.Content);
            //响应数据
            await this.Context.Response.WriteAsync(response.Content);
        }
        [Post]
        public async Task VatInvoiceByUrl()
        {
            //获取post请求的数据
            var form = await Context.Request.ReadFormAsync();
            var token = form["token"][0];
            var url = form["url"][0];
            var client = new RestClient("https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice?access_token=" + token);
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddHeader("Accept", "application/json");
            request.AddParameter("url", url);
            request.AddParameter("seal_tag", "false");
            IRestResponse response = client.Execute(request);
            Console.WriteLine(response.Content);
            //响应数据
            await this.Context.Response.WriteAsync(response.Content);
        }
        [Post]
        public async Task VatInvoiceByPdf()
        {
            //获取post请求的数据
            var form = await Context.Request.ReadFormAsync();
            var token = form["token"][0];
            var pdf_file = form["pdf_file"][0];
            var client = new RestClient("https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice?access_token=" + token);
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddHeader("Accept", "application/json");
            request.AddParameter("pdf_file", pdf_file);
            request.AddParameter("seal_tag", "false");
            IRestResponse response = client.Execute(request);
            Console.WriteLine(response.Content);
            //响应数据
            await this.Context.Response.WriteAsync(response.Content);
        }
        [Post]
        public async Task VatInvoiceVerification()
        {
            //获取post请求的数据
            var form = await Context.Request.ReadFormAsync();
            var token = form["token"][0];
            var invoice_code = form["invoice_code"][0];
            var invoice_num = form["invoice_num"][0];
            var invoice_date = form["invoice_date"][0];
            var invoice_type = form["invoice_type"][0];
            var check_code = form["check_code"][0];
            var total_amount = form["total_amount"][0];

            var client = new RestClient("https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice_verification?access_token=" + token);
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddHeader("Accept", "application/json");
            request.AddParameter("invoice_code", invoice_code);
            request.AddParameter("invoice_num", invoice_num);
            request.AddParameter("invoice_date", invoice_date);
            request.AddParameter("invoice_type", invoice_type);
            request.AddParameter("check_code", check_code);
            request.AddParameter("total_amount", total_amount);
            IRestResponse response = client.Execute(request);
            Console.WriteLine(response.Content);
            //响应数据
            await this.Context.Response.WriteAsync(response.Content);
        }
    }
}
遇到个AssemblyInfo特性重复BUG

在异常的csproj文件中添加以下代码取消程序集信息生成即可

false

	
		net8.0
		enable
		enable
		false
	

生成 dll文件

活字格C#代码调用服务器给百度ai接口发送请求设置_第7张图片

把ddl文件导入活字格

显示出API列表表示成功

活字格C#代码调用服务器给百度ai接口发送请求设置_第8张图片

编写前端

主体

标红的地方改为自己的逻辑

//获取单元格的值

var data = {

//传入请求地址

    url: `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${APIKey}&client_secret=${SecretKey}`

};

Forguncy.Helper.post("customapi/fapiaoapi/gettokenapi", data, function (res) {

    console.log(res);

    const jsonData=JSON.parse(res);

    console.log(jsonData.access_token);

    access_tokenCell.setValue(jsonData.access_token);

});

 我的获取access_token代码
// 获取当前页面上名称为account的单元格
// 获取当前页面
var page = Forguncy.Page;
// var AppID = page.getCell("AppID").getValue();
var APIKey = page.getCell("APIKey").getValue();
var SecretKey = page.getCell("SecretKey").getValue();
// var AESKey = page.getCell("AESKey").getValue();
var access_tokenCell = page.getCell("access_token");

//获取单元格的值
var data = {
    //传入请求地址
    url: `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${APIKey}&client_secret=${SecretKey}`
};
Forguncy.Helper.post("customapi/fapiaoapi/gettokenapi", data, function (res) {
    console.log(res);
    const jsonData=JSON.parse(res);
    console.log(jsonData.access_token);
    access_tokenCell.setValue(jsonData.access_token);
});
我的发票识别代码
// 获取当前页面上名称为account的单元格
// 获取当前页面
var page = Forguncy.Page;
var access_token = page.getCell("access_token").getValue();
var imageUrl = page.getCell("imageUrl").getValue();
var resultCell = page.getCell("result");
var invoiceCodeCell = page.getCell("invoice_code");
var invoiceNumCell = page.getCell("invoice_num");
var invoiceDateCell = page.getCell("invoice_date");
var invoiceTypeCell = page.getCell("invoice_type");
var checkCodeCell = page.getCell("check_code");
var totalAmountCell = page.getCell("total_amount");

var invoiceTypeChooseCell = page.getCell("invoice_type_choose");

//获取单元格的值
var data = {
    //传入请求地址
    token: access_token,
    imageUrl: imageUrl
};

Forguncy.Helper.post("customapi/fapiaoapi/vatInvoice", data, function (res) {
    console.log("res:" + res);
    let jsonData = JSON.parse(res);
    jsonData = jsonData.words_result;
    console.log(jsonData);
    //获取发票类型
    let invoiceType = invoiceTypeChooseCell.getValue();
    console.log("获取发票类型:" + invoiceType);
    //获取不到,自动识别
    if (invoiceType == "" || invoiceType == null) {
        console.log(jsonData.InvoiceType);
        invoiceType = translateInvoiceType(jsonData.InvoiceType);
    }
    console.log("识别发票类型:" + invoiceType);
    //识别不到
    if (invoiceType == "" || invoiceType == null) {
        alert("无法自动识别出发票类型!!!");
        return;
    }
    invoiceCodeCell.setValue(jsonData.InvoiceCode);
    invoiceNumCell.setValue(jsonData.InvoiceNum);
    invoiceDateCell.setValue(convertDateFormat(jsonData.InvoiceDate));
    invoiceTypeCell.setValue(invoiceType);
    let checkCode = jsonData.CheckCode;
    /**
     * 处理分类逻辑
     */
    // 发票金额
    // 增值税专票、电子专票、区块链电子发票、机动车销售发票、货运专票填写不含税金额
    // 二手车销售发票填写车价合计
    // 全电发票(专用发票)、全电发票(普通发票)填写价税合计金额
    // 其他类型发票可为空
    if (invoiceType == "elec_invoice_special" || invoiceType == "elec_invoice_normal") {
        console.log("价税合计金额");
        //价税合计金额
        totalAmountCell.setValue(jsonData.AmountInFiguers);
    } else if (invoiceType == "used_vehicle_invoice") {
        console.log("车价合计");
        //车价合计
        totalAmountCell.setValue(jsonData.AmountInFiguers);
    } else {
        console.log("不含税金额");
        // 不含税金额
        totalAmountCell.setValue(jsonData.TotalAmount);
    }
    //invoice_code:全电发票(专用发票)、全电发票(普通发票)此参数可为空
    if (invoiceType != "elec_invoice_special" && invoiceType != "elec_invoice_normal") {
        //其他的类型不能为空
        if (jsonData.InvoiceCode == "" || jsonData.InvoiceCode == null) {
            alert("发票代码不可为空!!!");
            return;
        }
    }
    //校验码。填写发票校验码后6位。
    //增值税电子专票、普票、电子普票、卷票、
    //区块链电子发票、通行费增值税电子普通发票此参数必填;
    if (invoiceType == "elec_special_vat_invoice" || invoiceType == "normal_invoice" || invoiceType == "elec_normal_invoice" || invoiceType == "roll_normal_invoice"
        || invoiceType == "blockchain_invoice" || invoiceType == "toll_elec_normal_invoice") {
        console.log("需要校验码");
        if (checkCode != "" && checkCode != null) {
            checkCode = getLastSixDigits(checkCode);
            console.log(checkCode);
            checkCodeCell.setValue(checkCode);
        } else {
            alert("校验码不可为空!!!");
            return;
        }
    } else {
        console.log("不需要校验码");
        checkCodeCell.setValue(checkCode);
    }
    resultCell.setValue(JSON.stringify(jsonData));
});


//日期格式转换
function convertDateFormat(inputDateString) {
    // 使用正则表达式提取数字
    var numbersArray = inputDateString.match(/\d+/g);
    // 将数字字符串拼接在一起
    var outputDateString = numbersArray.join("");
    return outputDateString;
}


//发票类型自动识别转换
function translateInvoiceType(chineseInvoiceType) {
    var translationMap = {
        //增值税专票、电子专票、区块链电子发票、机动车销售发票、货运专票填写不含税金额
        "电子专用发票": "elec_special_vat_invoice",
        "普通发票(电子)": "elec_normal_invoice",
        "电子普通发票": "elec_normal_invoice",
        "普通发票(卷式)": "roll_normal_invoice",
        "卷式普通发票": "roll_normal_invoice",
        "通行费增值税电子普通发票": "toll_elec_normal_invoice",
        "区块链电子发票": "blockchain_invoice",
        // 全电发票(专用发票)、全电发票(普通发票)填写价税合计金额
        "全电发票(专用发票)": "elec_invoice_special",
        "电子发票(专用发票)": "elec_invoice_special",
        "全电发票(普通发票)": "elec_invoice_normal",
        "电子发票(普通发票)": "elec_invoice_normal",

        "货运运输业增值税专用发票": "special_freight_transport_invoice",
        "机动车销售发票": "motor_vehicle_invoice",
        //二手车销售发票填写车价合计
        "二手车销售发票": "used_vehicle_invoice",
        "普通发票": "normal_invoice",
        "专用发票": "special_vat_invoice",
    };

    // 检查输入的中文发票类型是否在映射中,如果是则返回对应的英文翻译,否则返回原始值
    for (var chineseType in translationMap) {
        if (chineseInvoiceType.includes(chineseType)) {
            return translationMap[chineseType];
        }
    }

    // 如果未找到匹配的中文发票类型,则返回空值
    return "";
}

//获取发票校验码后六位数
function getLastSixDigits(str) {
    // 通过正则表达式匹配字符串中的数字
    const matches = str.match(/\d+/g);

    // 如果有匹配到数字
    if (matches) {
        // 获取最后一个匹配到的数字
        const lastNumber = matches[matches.length - 1];

        // 如果数字的长度大于等于六位,则返回后六位
        if (lastNumber.length >= 6) {
            return lastNumber.slice(-6);
        } else {
            // 如果数字的长度小于六位,则直接返回该数字
            return lastNumber;
        }
    } else {
        // 如果没有匹配到数字,则返回空字符串或其他适当的值
        return "";
    }
}

我的发票验真代码
// 获取当前页面上名称为account的单元格
// 获取当前页面
var page = Forguncy.Page;
var access_token = page.getCell("access_token").getValue();
var invoiceCode = page.getCell("invoice_code").getValue();
var invoiceNum = page.getCell("invoice_num").getValue();
var invoiceDate = page.getCell("invoice_date").getValue();
var invoiceType = page.getCell("invoice_type").getValue();
var checkCode = page.getCell("check_code").getValue();
var totalAmount = page.getCell("total_amount").getValue();
var verifyMessageCell = page.getCell("verifyMessage");
//重复条件
var conditionCell = page.getCell("condition");
//获取单元格的值
var data = {
    //传入请求地址
    token: access_token,
    invoice_code: invoiceCode,
    invoice_num: invoiceNum,
    invoice_date: invoiceDate,
    invoice_type: invoiceType,
    check_code: checkCode,
    total_amount: totalAmount,
};

console.log("************发票信息显示****************");
console.log("代码:" + invoiceCode);
console.log("*号码*:" + invoiceNum);
console.log("日期:" + invoiceDate);
console.log("类型:" + invoiceType);
console.log("校验码:" + checkCode);
console.log("金额:" + totalAmount);
console.log("**************************************");

/**
 * 判断是否满足验真条件,减少发送请求次数,节约成本
 */
if (conditionCell.getValue() === null) {
    //1.判断没有进行发票识别操作

    alert("请先识别发票");
    console.log("请先识别发票");

} else if (invoiceNum == "" || invoiceType == "" || invoiceDate == "" || invoiceNum == null || invoiceType == null || invoiceDate == null) {
    //2.判断必须值为空

    alert("识别失败,无法验真");
    console.log("识别失败,无法验真");

} else if (conditionCell.getValue() === false) {
    //3.重复识别,先检索数据库

    console.log("重复识别,检索数据库中字段");
    // 检索数据库中invoice_num值对应的对象
    Forguncy.getTableData("invoice", {"invoice_num": page.getCell("invoice_num").getValue()}, function (data) {
        if (data.invoice_code != invoiceCode) {
            console.log("发票代码不一致,需要重新验真");
            conditionCell.setValue(true);
        }
        if (data.invoice_date != invoiceDate) {
            console.log("发票日期不一致,需要重新验真");
            conditionCell.setValue(true);
        }
        if (data.invoice_type != invoiceType) {
            console.log("发票类型不一致,需要重新验真");
            conditionCell.setValue(true);
        }
        if (data.check_code != checkCode) {
            console.log("校验码不一致,需要重新验真");
            conditionCell.setValue(true);
        }
        if (data.total_amount != totalAmount) {
            console.log("发票金额不一致,需要重新验真");
            conditionCell.setValue(true);
        }
        if (conditionCell.getValue() === false) {
            console.log("发票一致,直接输出验真结果");
            console.log(data.result);
            verifyMessageCell.setValue(data.result);
        }
    }, function (errorMessage) {
        //数据库检索到invoice_num才能进入程序,按逻辑一定能检索到数据库中对象,这个模块无法执行到
        alert("啊?你黑入程序了??? Error:" + errorMessage);
        return false;
    });
}
console.log(conditionCell.getValue());
if (conditionCell.getValue() === true) {
    /**
     * 4.百度AI验真请求,一次两毛
     */
    console.log("发送百度AI验真请求");
    Forguncy.Helper.post("customapi/fapiaoapi/vatinvoiceverification", data, function (res) {
        console.log("res:" + res);
        let jsonData = JSON.parse(res);
        console.log(jsonData);
        verifyMessageCell.setValue(jsonData.VerifyMessage);
        page.getCell("condition2").setValue(true);
    });
}

你可能感兴趣的:(c#,服务器,百度)