小程序调用阿里云身份证识别OCR(附带七牛云上传图片)


  • 写在前面:
  • 实现的逻辑是拍照上传调用后端封装好的身份证接口,然后同时调用七牛云接口把照片传过去以便后台管理系统审核看
  • 1:首选需要这么一张页面

图片描述

  • 接下来就写我是怎么做的

首先是布局(以下是wxml)

<view><view class='idcard'><image class="idcard_front" catchtap='uploadImageFront' src="{{idCardUrlFront}}"></image><view class='idcard_front_desc'>扫描身份证人像面</view></view><view class='idcard'><image class="idcard_front" catchtap='uploadImageBack' src="{{idCardUrlBack}}"></image><view class='idcard_front_desc'>扫描身份证国徽面</view></view><view class="submit {{islogo?'logo_bg':'logo_disabled'}}" catchtap='submit'>下一步</view>
</view>

接着来写样式,要来就来全套不是,哈哈哈

/* pages/idcard/index.wxss */.idcard {text-align: center;margin: 100rpx auto;
}
.logo_disabled {/* background: #FADFCB; */background: rgba(255, 173, 118, 0.40);
}.logo_bg {background: #ffad76;
}.idcard_front, .idcard_con {height: 370rpx;width: 580rpx;
}.myCanvas {width: 600rpx;height: 450rpx;visibility: hidden;position: absolute;
}.judgeCanvas {width: 2px;height: 2px;visibility: hidden;
}.idcard_front_desc{font-size: 30rpx;color: #666666;margin-top: 20rpx;
}
.submit {height: 80rpx;width: 622rpx;line-height: 80rpx;border-radius: 40rpx;text-align: center;color: #fff;font-size: 32rpx;margin: 50rpx auto 40rpx;/* background: #ffad76; */
}

接着就是最重要的js了(我直接全选复制,各位见谅,封装的七牛云上传和wx.request在下面?)

// pages/idcard/index.js
const util = require('../../utils/util.js');
const qiniuUploader = require("../../utils/qiniuUploader");
import api from '../../utils/api.js';
const apiurl = 'https://yuesao.wutongdaojia.com';
const imgPath = 'https://cdn.wutongdaojia.com/';Page({/*** 页面的初始数据*/data: {x: 0,y: 0,areaWith: 750,areaHeight: 750,idCardUrlFront: '../../imgs/front.png',idCardUrlBack: "../../imgs/back.png",imagewidth: '',imageheight: '',base64: '',islogo:false,headerImage: '',picValue: '',showMagnifyIdCard: false,hasServerMsg: false,auth: {},// android: util.browser.versions.android},/*** 生命周期函数--监听页面初次渲染完成*/onReady: function() {// helper.checkOrientation('judgeCanvas');},uploadImageFront() {var that = this// front 代表正面that.checkIdCard(that, 'front', function(res) {wx.setStorageSync('address', res.address)wx.removeStorageSync('cardErrFront')wx.setStorage({key: 'idcardFront',data: {address: res.address,birthday: res.birthday,code: res.code,name: res.name,nation: res.nation,sex: res.sex,}})that.checkIsSuc()})},uploadImageBack() {var that = this// back 代表反面that.checkIdCard(that, 'back', function(res) {wx.setStorageSync('issue', res.issue)wx.removeStorageSync('cardErrBack')wx.setStorage({key: 'idcardBack',data: {expiryDate: res.expiryDate, // 结束日期issue: res.issue, //签发籍贯issueDate: res.issueDate, // 开始日期}})that.checkIsSuc()})},checkIsSuc() {var that = thisvar address = wx.getStorageSync('address')var issue = wx.getStorageSync('issue')if (address && issue) {that.setData({islogo: true})}},checkIdCard(that, type, callback) {util.getUploadToken()wx.chooseImage({count: 1, // 默认9sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有success: function(res) {// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片var tempFilePaths = res.tempFilePaths;that.qiniuUploader(that, tempFilePaths[0], function(res) {console.log(res)if (type == "front") {that.setData({idCardUrlFront: imgPath + res.key})wx.setStorageSync('idCardFrontUrl', imgPath + res.key)that.uploadFile(that, type, tempFilePaths, that.data.idCardUrlFront, function(res) {console.log(res)callback(res)})} else {that.setData({idCardUrlBack: imgPath + res.key})wx.setStorageSync('idCardBackUrl', imgPath + res.key)that.uploadFile(that, type, tempFilePaths, that.data.idCardUrlBack, function(res) {console.log(res)callback(res)})}})// that.getIdcardInfo('front')}})},qiniuUploader(that, filePath, callback) {qiniuUploader.upload(filePath, (res) => {console.log(res)callback(res)}, (error) => {console.error('error: ' + JSON.stringify(error));},null, // 可以使用上述参数,或者使用 null 作为参数占位符(progress) => {// console.log('上传进度', progress.progress)// console.log('已经上传的数据长度', progress.totalBytesSent)// console.log('预期需要上传的数据总长度', progress.totalBytesExpectedToSend)}, cancelTask => that.setData({cancelTask}))},/*图片上传*/uploadFile(that, idCardSide, files, idCardUrl, callback) {wx.uploadFile({url: apiurl + '/weixin/getIdcardInfo', //里面填写你的上传图片服务器API接口的路径 filePath: files[0], //要上传文件资源的路径 String类型 name: 'file', //按个人情况修改,文件对应的 key,开发者在服务器端通过这个 key 可以获取到文件二进制内容,(后台接口规定的关于图片的请求参数)header: {"Content-Type": "multipart/form-data" //记得设置// "Content-Type": "image/jpeg" //记得设置},formData: {//和服务器约定的token, 一般也可以放在header中'token': wx.getStorageSync('token'),'idCardSide': idCardSide,'idCardUrl': idCardUrl},success: function(res) {//当调用uploadFile成功之后,再次调用后台修改的操作,这样才真正做了修改头像console.log(JSON.parse(res.data))var responce = JSON.parse(JSON.parse(res.data).data)if (res.status = 200) {if (responce.code == 1) {callback(responce.result)} else {wx.showToast({title: responce.msg,icon: 'none',duration: 1000})if (idCardSide =="front"){wx.setStorageSync('cardErrFront', responce.msg)}else{wx.setStorageSync('cardErrBack', responce.msg)}return}} else {wx.showToast({title: responce.msg,icon: 'none',duration: 1000})return}}})},submit() {var address = wx.getStorageSync('address')var issue = wx.getStorageSync('issue')var cardErrFront = wx.getStorageSync('cardErrFront')var cardErrBack = wx.getStorageSync('cardErrBack')if(!this.data.islogo) return// debuggerif (cardErrFront) {wx.showToast({title: '人像面'+cardErrFront+',请重新上传',icon: 'none',duration: 1000})return} else if (cardErrBack){wx.showToast({title: '国徽面' + cardErrBack + ',请重新上传',icon: 'none',duration: 1000})return} else if (!address) {wx.showToast({title: '请上传身份证人像面',icon: 'none',duration: 1000})return} else if (!issue) {wx.showToast({title: '请上传身份证国徽面',icon: 'none',duration: 1000})return} else {wx.navigateTo({url: '../editcard/index',})}},/*** 生命周期函数--监听页面加载*/onLoad: function(options) {wx.removeStorageSync('address')wx.removeStorageSync('issue')wx.removeStorageSync('cardErrFront')wx.removeStorageSync('cardErrBack')wx.removeStorage({key: 'idcardFront',success: function(res) {console.log(res)},})wx.removeStorage({key: 'idcardBack',success: function(res) {console.log(res)},})},/*** 生命周期函数--监听页面显示*/onShow: function() {},/*** 生命周期函数--监听页面隐藏*/onHide: function() {},
## 标题文字 ##/*** 生命周期函数--监听页面卸载*/onUnload: function() {},/*** 页面相关事件处理函数--监听用户下拉动作*/onPullDownRefresh: function() {},/*** 页面上拉触底事件的处理函数*/onReachBottom: function() {},/*** 用户点击右上角分享*/onShareAppMessage: function() {}
})

封装wx.request来了(api.js)

/** 使用方法*@method ajax*@param{参数类型}参数名 参数说明* Type:请求类型(get、post)* params:请求参数* url:请求地址*/// http('dataUrl', param).then(res => {
//       ...
//     })
const ajax = (Type, params, url) => {var methonType = "application/json";// var https = "http://www.wutongdaojia.com"var https = "https://yuesao.wutongdaojia.com"var st = new Date().getTime()if (Type == "POST") {methonType = "application/x-www-form-urlencoded"}return new Promise(function (resolve, reject) {wx.request({url: https + url,method: Type,data: params,header: {'content-type': methonType,'Muses-Timestamp': st,'version': 'v1.0' // 版本号// 'Muses-Signature': sign},success: function (res) {// if (res.statusCode != 200) {//   reject({ error: '服务器忙,请稍后重试', code: 500 });//   return;// }// resolve(res.data);wx.hideLoading()console.log(res)if (res.data.status == 200) {resolve(res.data);} else if (res.data.status == 400) {wx.showToast({title: res.data.message,icon: 'none',duration: 1000})return} else if (res.data.status == 401){wx.removeStorageSync('phone')wx.removeStorageSync('token')wx.showToast({title: res.data.message,icon: 'none',duration: 1000,success:function(){wx.navigateTo({url: '../login/index',})}})return} else {//错误信息处理wx.showToast({title: '服务器错误,请联系客服',icon: 'none',duration: 1000})}},fail: function (res) {// fail调用接口失败reject({ error: '网络错误', code: 0 });},complete: function (res) {// complete}})})
}module.exports = {ajax: ajax
}

util.js

const qiniuUploader = require("./qiniuUploader");
import api from './api.js';
const getUploadToken = () => {var params = {token: wx.getStorageSync('token')}api.ajax("GET", params, "/weixin/getUploadToken").then(res => {console.log(res.data)initQiniu(res.data)});
}
// 初始化七牛相关参数
const initQiniu = (uptoken) => {var options = {region: 'NCN', // 华北区// uptokenURL: 'https://[yourserver.com]/api/uptoken',// cdn.wutongdaojia.com// uptokenURL: 'http://upload-z1.qiniup.com',// uptokenURL: 'https://yuesao.wutongdaojia.com/weixin/getUploadToken',// uptoken: 'xxx',uptoken: uptoken,// domain: 'http://[yourBucketId].bkt.clouddn.com',domain: 'image.bkt.clouddn.com',shouldUseQiniuFileName: false};qiniuUploader.init(options);
}export function didPressChooesImage(that, count, callback) {getUploadToken();// 微信 API 选文件wx.chooseImage({count: count,success: function(res) {console.log(res)var filePath = res.tempFilePaths[0];console.log(filePath)callback(filePath)// 交给七牛上传}})
}/*** 文件上传* 服务器端上传:http(s)://up.qiniup.com* 客户端上传: http(s)://upload.qiniup.com* cdn.wutongdaojia.com*/
function uploader(file, callback) {initQiniu();qiniuUploader.upload(filePath, (res) => {// 每个文件上传成功后,处理相关的事情// 其中 info 是文件上传成功后,服务端返回的json,形式如// {//    "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",//    "key": "gogopher.jpg"//  }// 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.htmlthat.setData({'imageURL': res.imageURL,});}, (error) => {console.log('error: ' + error);},// , {//     region: 'NCN', // 华北区//     uptokenURL: 'https://[yourserver.com]/api/uptoken',//     domain: 'http://[yourBucketId].bkt.clouddn.com',//     shouldUseQiniuFileName: false//     key: 'testKeyNameLSAKDKASJDHKAS'//     uptokenURL: 'myServer.com/api/uptoken'// }null, // 可以使用上述参数,或者使用 null 作为参数占位符(res) => {console.log('上传进度', res.progress)console.log('已经上传的数据长度', res.totalBytesSent)console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)});
};
module.exports = {initQiniu: initQiniu,getUploadToken: getUploadToken,didPressChooesImage: didPressChooesImage
}
  • 如需帮助请加微信(18310911617)
    备注:说明来意

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/280053.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

windows 安装yaml支持和pytest支持等

打开cmd 输入pip install pyyaml #yaml文件支持 输入pip install pytest #pytest框架支持 输入pip install requests #requests接口测试支持 输入pip install pyopenssl #openssl支持 前提是电脑上的python已经配置好了转载于:https://www.cnblogs.com/mghhzAnne/p/92…

史上最好记的神经网络结构速记表(上)

本文讲的是史上最好记的神经网络结构速记表&#xff08;上&#xff09;&#xff0c;新的神经网络结构不断涌现&#xff0c;我们很难一一掌握。哪怕一开始只是记住所有的简称&#xff08; DCIGN&#xff0c;BiLSTM&#xff0c;DCGAN &#xff09;&#xff0c;也会让同学们吃不消…

厚积薄发,微软OFFICE云时代宏脚本来临,Excel Srcipt已经推进到桌面端可用

前一阵子&#xff0c;已经发现微软在Excel上发布了Office Script For Excel&#xff0c;当时只能在网页端的Excel上使用&#xff0c;今天打开桌面端的Excel&#xff0c;发现多了一个【自动执行】选项卡。再一次看了下&#xff0c;比起以前的Office Addin&#xff0c;要先进得多…

如何使用Amazon Echo控制您的Eero Wi-Fi网络

Thanks to the power of Alexa and its open API, you’re able to control a vast number of devices using just your voice. If you have an Eero Wi-Fi system, you can even control your home network with the Amazon Echo. 得益于Alexa的强大功能及其开放的API&#xf…

H5在WebView上开发小结

背景 来自我司业务方要求&#xff0c;需开发一款APP。但由于时间限制&#xff0c;只能采取套壳app方式&#xff0c;即原生app内嵌webview展示前端页面。本文主要记述JavaScript与原生app间通信&#xff0c;以及内嵌webview开发时&#xff0c;前端方面可能踩的一些坑。 技术架构…

C#的?和??

1.&#xff1f;&#xff1f; 为了实现Nullable数据类型转换成non-Nullable类型数据&#xff0c;才有的一个操作符&#xff1b; 意义&#xff1a;一变量取值&#xff0c;取符号左边的值&#xff0c;若左边为null&#xff0c;那么取赋值&#xff1f;&#xff1f;右边的&#xff1…

odoo 自定义视图_如何使用Windows的五个模板自定义文件夹视图

odoo 自定义视图If you’re particular about how Windows displays the contents of your folders, you can cut your customization time down considerably by taking advantage of File Explorer’s five built-in folder templates. 如果您特别想知道Windows如何显示文件夹…

C#之ILC和C++的CLR前者更快?

楔子ILC是C#写的&#xff0c;CLR是C。.Net 7中&#xff0c;为何微软执意用一个托管的模型去尝试取代非托管框架呢&#xff1f;至少native code方面它是这么做的这个问题一直萦绕脑海。非托管和托管十年前出版的那本久负盛名的《CLR via C#》至今都是不可或缺的存在&#xff0c;…

历史

python的历史 kfsaldkfsdf fdskfdsa fdsjkafsjda fdshkfjsdja View Codefjdskaffdsjkaffdsjakflsad;fjdsklaf 转载于:https://www.cnblogs.com/jin-xin/articles/10448286.html

typescript+react+antd基础环境搭建

typescriptreactantd基础环境搭建&#xff08;包含样式定制&#xff09; tsconfig.json 配置 // 具体配置可以看上面的链接 这里module moduleResolution的配置都会影响到antd的显示 // allowSyntheticDefaultImports 是antd官网给的配置 必须加上 {"compilerOptions&quo…

最小生成树Prim算法和Kruskal算法

https://www.cnblogs.com/JoshuaMK/p/prim_kruskal.html 转载于:https://www.cnblogs.com/DixinFan/p/9225105.html

如何重新打开Windows防火墙提示?

If you are setting up a new program that needs network access, but are not paying close enough attention, you might end up accidentally causing Windows firewall to block the program. How do you fix such a mistake? Today’s SuperUser Q&A post helps a f…

判断字符串出现次数最多的字符 及 次数

分析 题目的意思大致就是找出每个字符出现的次数&#xff0c;然后比较大小。那么每个字符都应该对应它出现的次数。既然是一一对应的&#xff0c;那我们就想到用对象的key和value来储存字符和其出现的次数。具体做法 新建一个空对象obj 遍历给定的字符串接下来就是最重要的 把字…

AI x 量化:华尔街老司机解密智能投资正确姿势

随着中国经济的腾飞&#xff0c;中产阶级的崛起&#xff0c;投资管理逐渐步入寻常百姓家。 值得注意的是&#xff0c;在十年前“无财可理”问题解决后&#xff0c;另一个矛盾愈发凸显——层次不齐的投资素质。据wind数据统计&#xff0c;2004年至2015年12年间&#xff0c;只有3…

如何远程调试 MAUI blazor / Blazor Hybrid

我们知道浏览器模式下 Blazor 可以使用 F12 打开开发工具,调试js查看页面元素,那当 Maui Blazor 提示烦人的 an unhandled error has occurred 该怎么进行调试呢?1. VS 运行工程于 Debug 模式下,只要 BlazorWebview 控件处于焦点,直接按F12就可以打开开发工具了. 没有焦点就鼠…

笔记本触摸键盘驱动自动禁用_如何为iPad的蓝牙键盘禁用自动更正

笔记本触摸键盘驱动自动禁用The take-for-granted features we enjoy when using an on-screen keyboard—like auto-corrections and auto-capitalization–quickly become a hindrance if you’re using a physical keyboard with your iOS device. Let’s look at how to qu…

发票的作用

目录 发票上的两个章&#xff1a;税种&#xff1a;发票的作用&#xff1a;征税方式&#xff1a;发票限额&#xff1a;参考链接发票上的两个章&#xff1a; 税务局的发票监制章商家的发票专用章税种&#xff1a; 增值税&#xff1a;商家在卖东西时为获利&#xff0c;而提高价格的…

opencv-原图基础上添加指定颜色

前言 项目中需要将某些区域使用不同的颜色表示出来&#xff0c;同时能够看到原图作为底色。 代码 #include "opencv2/highgui/highgui.hpp" #include <opencv2/imgproc.hpp> #include <iostream> using namespace cv;int main() {Mat image imread( &q…

微软发布Azure Application Insights for Node.js 1.0版本

在北美举行的Node.js交互大会上&#xff0c;微软发布了用于Node.js的Application Insights SDK。\\来自微软JavaScript平台和工具部门的高级经理Arunesh Chandra在博客上发布了这一消息&#xff0c;他说&#xff0c;微软“希望能够提升开发者在Azure上构建和运行Node.js应用程序…

正则表达式应用:实现一个简单的计算器

实现一个简单的计算器&#xff0c;代码如下&#xff1a; 下面的函数用来检验数学表达式的合规性&#xff0c;当然此处只实现两个检验&#xff1a;(1)括号应该闭合 (2)不能出现字母 def check_expression(str):check_result Trueif str.count(() ! str.count()):print(表达式有…