这里我是在微信小程序中使用的。
官方文档传送门
正好小程序所有请求需要https协议的。这里使用的话,就可以直接去小程序后台页面,在开发配置中加入合法域名。
请求参数如下图:
app_id : 你腾讯ai账号的id
time_stamp: 取秒级别的时间
nonce_str: 随机32位字符串
sign: 这里是将其他所有参数,拼接起来,并将appkey放到最后一位,再通过MD5加密,再把所有都转成大写
image:你图片转成的base64数据。
card_tyoe: 正反面,
上代码,公共部分(转换sign 和 生成 nonce_str):
const md5 = require('js-md5')
export const getReqSign = function (params, appKey = '你自己的appkey') {
// 1. 字典升序排序
params = objKeySort(params)
// 2. 拼按URL键值对
let sign = ''
Object.keys(params).forEach(function (key) {
sign += key + '=' + encodeURIComponent(params[key]) + '&'
})
// 3. 拼接app_key
sign += 'app_key' + '=' + appKey
// 4. MD5运算+转换大写,得到请求签名
sign = md5(sign).toUpperCase()
return sign
}
const objKeySort = function (obj) {
// 排序的函数
var newkey = Object.keys(obj).sort()
// 先用Object内置类的keys方法获取要排序对象的属性名,再利用Array原型上的sort方法对获取的属性名进行排序,newkey是一个数组
var newObj = {}
for (var i = 0; i < newkey.length; i++) {
// 遍历newkey数组
newObj[newkey[i]] = obj[newkey[i]]// 向新创建的对象中按照排好的顺序依次增加键值对
}
return newObj
}
var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
export function generateMixed (n) {
var res = ''
for (var i = 0; i < n; i++) {
var id = Math.ceil(Math.random() * 35)
res += chars[id]
}
return res
}
export default {
getReqSign,
generateMixed
}
页面中使用,这里是小程序中使用
<camera class="Mycamera" device-position="back" flash="off" binderror="error"></camera>
<div class="PhotoBtnList">
<button @click="getCardInfo" size="small">识别</button>
</div>
import common from '../../utils/common'
import {GetCardInfo} from '../../api/index'
// 引入公用方法和请求
getCardInfo () {
wx.showLoading({
title: '识别中...'
})
const ctx = wx.createCameraContext()
ctx.takePhoto({
quality: 'high',
success: (res) => {
const file = wx.getFileSystemManager()
const base64 = file.readFileSync(res.tempImagePath, 'base64')
let str = common.generateMixed(32)
let params = {
app_id: '你的app_id',
time_stamp: Math.ceil(new Date().getTime() / 1000),
nonce_str: str,
image: base64,
card_type: 0
}
params.sign = common.getReqSign(params)
GetCardInfo(params).then(res => {
if (res.data.ret === 0) {
let info = res.data.data
console.log(info, '-------')
wx.hideLoading()
} else {
wx.hideLoading()
this.showToast('识别失败', 'none')
}
})
},
error (e) {
wx.hideLoading()
this.showToast('识别失败', 'none')
}
})
}
ret为0的时候,是请求成功。可以获取到身份证的信息。为其他数值的时候,在msg里会有错误信息。