当前位置:   article > 正文

实习日志2(活字格调用服务端向百度ai发接口请求)_调用百度ai接口

调用百度ai接口

试了一下前端获取token,失败,报错:

Access to XMLHttpRequest at 'https://aip.baidubce.com/oauth/2.0/token' from origin 'http://localhost:44203' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

问题描述:

遇到的错误消息与跨域资源共享(CORS)有关。CORS是由Web浏览器实施的安全功能,用于限制网页对不同于提供网页的域的请求。

在情况下,从http://localhost:44203https://aip.baidubce.com/oauth/2.0/token发出请求,而https://aip.baidubce.com上的服务器未配置为允许来自本地域的请求。

解决办法:

在本地机器上设置代理服务器,将请求转发到https://aip.baidubce.com。这样,你的请求将来自与页面相同的域,就不会遇到CORS问题。

报错的代码
  1. // 获取当前页面上名称为account的单元格
  2. // 获取当前页面
  3. var page = Forguncy.Page;
  4. var AppID = page.getCell("AppID").getValue();
  5. var APIKey = page.getCell("APIKey").getValue();
  6. var SecretKey = page.getCell("SecretKey").getValue();
  7. var AESKey = page.getCell("AESKey").getValue();
  8. var access_tokenCell = page.getCell("access_token");
  9. // 请求地址
  10. const url = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${APIKey}&client_secret=${SecretKey}`;
  11. // 创建XHR对象
  12. const xhr = new XMLHttpRequest();
  13. // 设置请求方法和URL
  14. xhr.open('POST', url, true);
  15. // 设置请求头
  16. xhr.setRequestHeader('Content-Type', 'application/json');
  17. xhr.setRequestHeader('Accept', 'application/json');
  18. // 处理响应
  19. xhr.onreadystatechange = function () {
  20. if (xhr.readyState === 4) {
  21. if (xhr.status === 200) {
  22. // 处理响应数据
  23. const responseData = xhr.responseText;
  24. alert("响应数据: " + responseData);
  25. console.log('responseData: ' + responseData)
  26. // 将JSON字符串解析为JavaScript对象
  27. const responseObject = JSON.parse(responseData);
  28. console.log('responseObject: ' + responseObject)
  29. // 获取data值
  30. const data = responseObject.data;
  31. console.log('data: ' + data)
  32. access_tokenCell.setValue(data.access_token);
  33. // //获取页面上的表格
  34. // var listview = page.getListView("表格1");
  35. // //添加新行
  36. // listview.addNewRow(jsonDataObject);
  37. } else {
  38. // 处理错误
  39. console.error('Error:', xhr.status, xhr.statusText);
  40. alert("Error" + xhr.status + " " + xhr.statusText);
  41. }
  42. }
  43. };
  44. // 发送请求
  45. xhr.send(JSON.stringify(""));

修改后的代码:

  1. // 获取当前页面上名称为account的单元格
  2. // 获取当前页面
  3. var page = Forguncy.Page;
  4. var access_token = page.getCell("access_token").getValue();
  5. var imageUrl = page.getCell("imageUrl").getValue();
  6. var result=page.getCell("result");
  7. //获取单元格的值
  8. var data = {
  9. //传入请求地址
  10. token: access_token,
  11. imageUrl: imageUrl
  12. };
  13. Forguncy.Helper.post("customapi/fapiaoapi/vatInvoice", data, function (res) {
  14. console.log("res:"+res);
  15. let jsonData=JSON.parse(res);
  16. console.log(jsonData.words_result);
  17. jsonData=JSON.stringify(jsonData.words_result);
  18. console.log(jsonData);
  19. result.setValue(res);
  20. });
其中调用的C#类库代码:
  1. using GrapeCity.Forguncy.ServerApi;
  2. using Microsoft.AspNetCore.Http;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Runtime.InteropServices;
  7. using System.Runtime.Remoting.Contexts;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.IO;
  11. using RestSharp;
  12. using System.Net;
  13. using System.Web;
  14. namespace FaPiaoApi
  15. {
  16. public class FaPiaoApi : ForguncyApi
  17. {
  18. [Post]
  19. public async Task GetTokenApi()
  20. {
  21. //获取post请求的数据
  22. var form = await Context.Request.ReadFormAsync();
  23. var url = form["url"][0];
  24. var client = new RestClient(url);
  25. client.Timeout = -1;
  26. var request = new RestRequest(Method.POST);
  27. request.AddHeader("Content-Type", "application/json");
  28. request.AddHeader("Accept", "application/json");
  29. var body = @"";
  30. request.AddParameter("application/json", body, ParameterType.RequestBody);
  31. IRestResponse response = client.Execute(request);
  32. Console.WriteLine(response.Content);
  33. //响应数据
  34. await this.Context.Response.WriteAsync(response.Content);
  35. }
  36. [Post]
  37. public async Task VatInvoice()
  38. {
  39. //获取post请求的数据
  40. var form = await Context.Request.ReadFormAsync();
  41. var token = form["token"][0];
  42. var imageUrl = form["imageUrl"][0];
  43. var client = new RestClient("https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice?access_token=" + token);
  44. client.Timeout = -1;
  45. var request = new RestRequest(Method.POST);
  46. request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
  47. request.AddHeader("Accept", "application/json");
  48. request.AddParameter("url", imageUrl);
  49. request.AddParameter("seal_tag", "false");
  50. IRestResponse response = client.Execute(request);
  51. Console.WriteLine(response.Content);
  52. //响应数据
  53. await this.Context.Response.WriteAsync(response.Content);
  54. }
  55. }
  56. }
返回的信息普通发票没有check_code校验码,我蚌埠住了,验真功能好像做不出来了qwq

先提取发票验真需要的参数,并做一些参数类型转换
  1. // 获取当前页面上名称为account的单元格
  2. // 获取当前页面
  3. var page = Forguncy.Page;
  4. var access_token = page.getCell("access_token").getValue();
  5. var imageUrl = page.getCell("imageUrl").getValue();
  6. var resultCell = page.getCell("result");
  7. var invoiceCodeCell = page.getCell("invoice_code");
  8. var invoiceNumCell = page.getCell("invoice_num");
  9. var invoiceDateCell = page.getCell("invoice_date");
  10. var invoiceTypeCell = page.getCell("invoice_type");
  11. var checkCodeCell = page.getCell("check_code");
  12. var totalAmountCell = page.getCell("total_amount");
  13. //获取单元格的值
  14. var data = {
  15. //传入请求地址
  16. token: access_token,
  17. imageUrl: imageUrl
  18. };
  19. Forguncy.Helper.post("customapi/fapiaoapi/vatInvoice", data, function (res) {
  20. console.log("res:" + res);
  21. let jsonData = JSON.parse(res);
  22. jsonData = jsonData.words_result;
  23. console.log(jsonData);
  24. invoiceCodeCell.setValue(jsonData.InvoiceCode);
  25. invoiceNumCell.setValue(jsonData.InvoiceNum);
  26. invoiceDateCell.setValue(convertDateFormat(jsonData.InvoiceDate));
  27. invoiceTypeCell.setValue(translateInvoiceType(jsonData.InvoiceType));
  28. checkCodeCell.setValue(jsonData.CheckCode);
  29. totalAmountCell.setValue(jsonData.TotalAmount);
  30. resultCell.setValue(JSON.stringify(jsonData));
  31. });
  32. //日期格式转换
  33. function convertDateFormat(inputDateString) {
  34. // 使用正则表达式提取数字
  35. var numbersArray = inputDateString.match(/\d+/g);
  36. // 将数字字符串拼接在一起
  37. var outputDateString = numbersArray.join("");
  38. return outputDateString;
  39. }
  40. //发票种类格式转换
  41. function translateInvoiceType(chineseInvoiceType) {
  42. var translationMap = {
  43. "增值税专用发票": "special_vat_invoice",
  44. "增值税电子专用发票": "elec_special_vat_invoice",
  45. "增值税普通发票": "normal_invoice",
  46. "增值税普通发票(电子)": "elec_normal_invoice",
  47. "电子发票(普通发票)": "elec_normal_invoice",
  48. "增值税普通发票(卷式)": "roll_normal_invoice",
  49. "通行费增值税电子普通发票": "toll_elec_normal_invoice",
  50. "区块链电子发票(目前仅支持深圳地区)": "blockchain_invoice",
  51. "全电发票(专用发票)": "elec_invoice_special",
  52. "全电发票(普通发票)": "elec_invoice_normal",
  53. "货运运输业增值税专用发票": "special_freight_transport_invoice",
  54. "机动车销售发票": "motor_vehicle_invoice",
  55. "二手车销售发票": "used_vehicle_invoice"
  56. };
  57. // 检查输入的中文发票类型是否在映射中,如果是则返回对应的英文翻译,否则返回原始值
  58. for (var chineseType in translationMap) {
  59. if (chineseInvoiceType.includes(chineseType)) {
  60. return translationMap[chineseType];
  61. }
  62. }
  63. // 如果未找到匹配的中文发票类型,则返回空值
  64. return "";
  65. }
然后验真的C#请求百度ai代码
  1. using GrapeCity.Forguncy.ServerApi;
  2. using Microsoft.AspNetCore.Http;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Runtime.InteropServices;
  7. using System.Runtime.Remoting.Contexts;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.IO;
  11. using RestSharp;
  12. using System.Net;
  13. using System.Web;
  14. namespace FaPiaoApi
  15. {
  16. public class FaPiaoApi : ForguncyApi
  17. {
  18. [Post]
  19. public async Task GetTokenApi()
  20. {
  21. //获取post请求的数据
  22. var form = await Context.Request.ReadFormAsync();
  23. var url = form["url"][0];
  24. var client = new RestClient(url);
  25. client.Timeout = -1;
  26. var request = new RestRequest(Method.POST);
  27. request.AddHeader("Content-Type", "application/json");
  28. request.AddHeader("Accept", "application/json");
  29. var body = @"";
  30. request.AddParameter("application/json", body, ParameterType.RequestBody);
  31. IRestResponse response = client.Execute(request);
  32. Console.WriteLine(response.Content);
  33. //响应数据
  34. await this.Context.Response.WriteAsync(response.Content);
  35. }
  36. [Post]
  37. public async Task VatInvoice()
  38. {
  39. //获取post请求的数据
  40. var form = await Context.Request.ReadFormAsync();
  41. var token = form["token"][0];
  42. var imageUrl = form["imageUrl"][0];
  43. var client = new RestClient("https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice?access_token=" + token);
  44. client.Timeout = -1;
  45. var request = new RestRequest(Method.POST);
  46. request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
  47. request.AddHeader("Accept", "application/json");
  48. request.AddParameter("url", imageUrl);
  49. request.AddParameter("seal_tag", "false");
  50. IRestResponse response = client.Execute(request);
  51. Console.WriteLine(response.Content);
  52. //响应数据
  53. await this.Context.Response.WriteAsync(response.Content);
  54. }
  55. [Post]
  56. public async Task VatInvoiceVerification()
  57. {
  58. //获取post请求的数据
  59. var form = await Context.Request.ReadFormAsync();
  60. var token = form["token"][0];
  61. var invoice_code = form["invoice_code"][0];
  62. var invoice_num = form["invoice_num"][0];
  63. var invoice_date = form["invoice_date"][0];
  64. var invoice_type = form["invoice_type"][0];
  65. var check_code = form["check_code"][0];
  66. var total_amount = form["total_amount"][0];
  67. var client = new RestClient("https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice_verification?access_token=" + token);
  68. client.Timeout = -1;
  69. var request = new RestRequest(Method.POST);
  70. request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
  71. request.AddHeader("Accept", "application/json");
  72. request.AddParameter("invoice_code", invoice_code);
  73. request.AddParameter("invoice_num", invoice_num);
  74. request.AddParameter("invoice_date", invoice_date);
  75. request.AddParameter("invoice_type", invoice_type);
  76. request.AddParameter("check_code", check_code);
  77. request.AddParameter("total_amount", total_amount);
  78. IRestResponse response = client.Execute(request);
  79. Console.WriteLine(response.Content);
  80. //响应数据
  81. await this.Context.Response.WriteAsync(response.Content);
  82. }
  83. }
  84. }
发票验真的前端js代码
  1. // 获取当前页面上名称为account的单元格
  2. // 获取当前页面
  3. var page = Forguncy.Page;
  4. var access_token = page.getCell("access_token").getValue();
  5. var invoiceCode = page.getCell("invoice_code").getValue();
  6. var invoiceNum = page.getCell("invoice_num").getValue();
  7. var invoiceDate = page.getCell("invoice_date").getValue();
  8. var invoiceType = page.getCell("invoice_type").getValue();
  9. var checkCode = page.getCell("check_code").getValue();
  10. var totalAmount = page.getCell("total_amount").getValue();
  11. var verifyMessageCell= page.getCell("verifyMessage");
  12. //获取单元格的值
  13. var data = {
  14. //传入请求地址
  15. token: access_token,
  16. invoice_code: invoiceCode,
  17. invoice_num: invoiceNum,
  18. invoice_date: invoiceDate,
  19. invoice_type: invoiceType,
  20. check_code: checkCode,
  21. total_amount: totalAmount,
  22. };
  23. console.log("check_code:"+checkCode);
  24. if(checkCode==""){
  25. alert("check_code未检测到,无法验真");
  26. }else{
  27. Forguncy.Helper.post("customapi/fapiaoapi/vatinvoiceverification", data, function (res) {
  28. console.log("res:" + res);
  29. let jsonData = JSON.parse(res);
  30. console.log(jsonData);
  31. verifyMessageCell.setValue(jsonData.VerifyMessage);
  32. });
  33. }
添加验真提示防止资源浪费 

 验真返回结果 

BUG记录:

调用的接口:

1.增值税发票识别(bug:识别不出校验码)

2.增值税发票验真(bug:验真结果与实际情况不符)

问题:

验真功能调用后识别结果为不一致,我感觉是识别功能没把校验码识别出来导致的

试了很多次,校验码识别不出

这是我用来测试的增值税发票,这是发票在服务器minio中的url:http://47.109.133.206:9000/fapiao/fapiao.png

可以直接通过url访问这个图片

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/441747
推荐阅读
相关标签
  

闽ICP备14008679号