场景:用户上传身份证照片后,把照片保存再云存储,然后通过cloud.getTempFileURL换出这个照片的临时url,把这个url通过云函数传递给腾讯云接口并且得到返回的结果。
已知:通过腾讯云的 API Explorer 得到node环境中请求的代码(附上API Explorer链接:https://console.cloud.tencent.com/api/explorer?Product=ocr&Version=2018-11-19&Action=IDCardOCR&SignVersion=
代码如下:(腾讯云ID和密钥,以及图片url没有写入,替换进去即可)(我已经再node环境中使用过以下代码可以得到满意的结果)
问题:如何把这个代码迁移到微信云函数里去??
const tencentcloud = require("../../../../tencentcloud-sdk-nodejs");
const OcrClient = tencentcloud.ocr.v20181119.Client;
const models = tencentcloud.ocr.v20181119.Models;
const Credential = tencentcloud.common.Credential;
const ClientProfile = tencentcloud.common.ClientProfile;
const HttpProfile = tencentcloud.common.HttpProfile;
let cred = new Credential("腾讯云ID", "腾讯云密钥");
let httpProfile = new HttpProfile();
httpProfile.endpoint = "ocr.tencentcloudapi.com";
let clientProfile = new ClientProfile();
clientProfile.httpProfile = httpProfile;
let client = new OcrClient(cred, "ap-guangzhou", clientProfile);
let req = new models.IDCardOCRRequest();
let params = '{"ImageUrl":"这里写入图片URL连接","CardSide":"FRONT"}'
req.from_json_string(params);
client.IDCardOCR(req, function(errMsg, response) {
if (errMsg) {
console.log(errMsg);
return;
}
console.log(response.to_json_string());
});
云函数
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
//
exports.main = async (event, context) => {
}
已解决
解决代码如下:
关键在于把client.IDcardOCR函数包装成一个promise对象返回,不然得不到返回值,也可以使用async/await。
// 云函数入口文件 const cloud = require('wx-server-sdk') cloud.init() // 导入腾讯云密钥配置文件 const { TENCENTCLOUD_APPID, TENCENTCLOUD_SECRETID, TENCENTCLOUD_SECRETKEY, } = require('./config.js') // const tencentcloud = require("tencentcloud-sdk-nodejs"); const OcrClient = tencentcloud.ocr.v20181119.Client; const models = tencentcloud.ocr.v20181119.Models; const Credential = tencentcloud.common.Credential; const ClientProfile = tencentcloud.common.ClientProfile; const HttpProfile = tencentcloud.common.HttpProfile; // 设置腾讯云密钥 let cred = new Credential(TENCENTCLOUD_SECRETID,TENCENTCLOUD_SECRETKEY); let httpProfile = new HttpProfile(); httpProfile.endpoint = "ocr.tencentcloudapi.com"; let clientProfile = new ClientProfile(); clientProfile.httpProfile = httpProfile; let client = new OcrClient(cred, "ap-guangzhou", clientProfile); let req = new models.IDCardOCRRequest(); // 云函数入口函数 exports.main = async (event, context) => { // 传入参数url let params = `{"ImageUrl":"${event.url}","CardSide":"FRONT"}` req.from_json_string(params); // 需要返回一个Promise对象 return new Promise((resolve,reject)=>{ client.IDCardOCR(req, function (errMsg, response) { if (errMsg) { // console.log(errMsg); reject(errMsg) return; } resolve(response.to_json_string()) // console.log(response.to_json_string()); }); }) }
将node的代码按koa2的格式改写,复制到云函数里就行。
--↓↓👍如果觉得有帮助的话请点个【赞】吧