微信小程序实现 身份证,银行卡…识别
OCR 识别
1. 使用微信的OCR
购买成功后在 设置 插件中添加,详情中查看使用方法–开发文档
开发文档中的代码直接使用就可以了
2. 使用百度的 OCR
百度云链接
wxml
<button bindtap="uploadImg">百度上传身份证</button>
js
Page({
/**
* 页面的初始数据
*/
data: {
a_token: '',
},
onLoad: function (options) {
this.getBaiduToken()
},
// 获取百度access_token
getBaiduToken: function() {
const apiKey = 'API Key';
const seckey = 'Secret Key';
const tokenUrl = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${apiKey}&client_secret=${seckey}`;
let that = this;
wx.request({
url: tokenUrl,
method: 'POST',
dataType: 'json',
header: {
'content-type': 'application/json; charset=UTF-8'
},
success: function(res) {
console.log('getBaiduToken提示pass', res);
that.setData({
baiduToken: res.data.access_token
})
},
fail: function(res) {
console.log('getBaiduToken提示fail', res);
}
})
},
// 上传图片
uploadImg: function() {
let that = this;
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success(res) {
// tempFilePath可以作为img标签的src属性显示图片
const tempFilePaths = res.tempFilePaths
console.log(tempFilePaths)
// 路径转化为base64图片
wx.getFileSystemManager().readFile({
filePath: tempFilePaths[0],
encoding: 'base64',
success: res => {
console.log('读图片数据pass', res.data);
that.scanImageInfo(res.data);
},
fail: res => {
console.log('读图片数据fail', res.data);
}
})
}
})
},
// 扫描图片中的数据
scanImageInfo: function(imageData) {
let that = this;
const detecUrl = 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=' + this.data.baiduToken;
wx.showLoading({
title: '加载中',
});
wx.request({
url: detecUrl,
data: {
image: imageData,
id_card_side: 'front'
},
method: 'POST',
dataType: 'json',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
success: res => {
console.log('success', res.data.words_result)
},
fail: res => {
console.log('fail')
},
complete: res => {
wx.hideLoading();
}
})
},
})