• 写在前面:
  • 实现的逻辑是拍照上传调用后端封装好的身份证接口,然后同时调用七牛云接口把照片传过去以便后台管理系统审核看
  • 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)
    备注:说明来意

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

  1. 调用阿里云身份证识别OCR

    这个是需要收费的第三方身份证识别OCR的接口 这个是官方给出的案例和文档 https://market.aliyun.com/products/57124001/cmapi028587.htmlspm ...

  2. 使用java调用阿里云车牌识别API

    实现车牌识别功能我采用调用阿里云车牌识别API的方法,我使用的是eclipse,jdk 1.8,Tomcat 9.0 1.进入阿里云主页先创建阿里云账号 2.在控制台的头像那里找到AccessKey管 ...

  3. 微信小程序使用阿里云物联网API开发物联网应用

    微信小程序是一种不需要下载安装即可使用的应用,它实现了应用"触手可及"的梦想,用户扫一扫或者搜一下就可以打开的应用. 微信小程序具有方便快捷,速度快,安全及保密性高的优点,同时开发 ...

  4. .Net 调用阿里云接口-识别车牌

    参考文档:生成URL - 阿里云视觉智能开放平台 - 阿里云 参考文档:https://next.api.aliyun.com/api/ocr/2019-12-30/RecognizeLicenseP ...

  5. 【物联网】微信小程序接入阿里云物联网平台

    微信小程序接入阿里云物联网平台 一 阿里云平台端 1.登录阿里云 阿里云物联网平台 点击进入公共实例,之前没有的点进去申请 2.点击产品->创建产品 3.产品名称自定义,按项目选择类型,节点类型 ...

  6. 微信小程序接入阿里云直播

    小程序接入阿里云直播 前言:最近工作中遇到了小程序接入阿里云直播的需求(暂时只做播流,也就是播放端),于是打开阿里云直播文档发现居然没有小程序的相关文档,sdk也没有小程序的版本,网上也没搜到相关案例 ...

  7. 小程序配置阿里云OSS下载文件,在请求头里配置生成强制下载链接,(拿到下载链接可以下载文件至本地)

    小程序配置阿里云OSS下载文件,在请求头里配置生成强制下载链接,(拿到下载链接可以下载文件至本地)(Win10电脑开发环境)**这里只说明小程序端问题**<菜鸡总结大神勿喷!蟹蟹~> 大体 ...

  8. 调用阿里云人脸识别接口示例

    下面我为大家展示一下我调用阿里云人脸识别接口的示例 首先说下开发环境,springboot 开发的 org.apache.commons.codec.binary.Base64; 这个主要是用来进行b ...

  9. 三方直播SDK对比(腾讯云,阿里云,网易云信,七牛云,金山云,声网,即构科技)

    三方直播SDK对比(腾讯云,阿里云,网易云信,七牛云,金山云,声网,即构科技) 首先看过各个平台直播SDK后大致知道平台SDK分为有2种: 直播:传统方式,1个主播,

最新文章

  1. 家校通Android源码,基于Android的家校通系统设计与实现
  2. 位于/var/log目录下的20个Linux日志文件
  3. 用ASP实现在线压缩与解压缩
  4. Python urllib与requests、XML和HTMLParser
  5. CompletableFuture API用法介绍(一)
  6. windows获取本地时间_如何在Windows 8中重新获得本地登录
  7. 如何成功搞垮一个团队?
  8. (五)Struts2 标签
  9. 鸿蒙系统正式开源,余承东:鸿蒙系统正式开源,友商也可以使用!
  10. licode学习之erizo篇--Pipeline_service
  11. ejabberd源码学习——方法注册模式
  12. 为什么空集是集合的子集_「离散数学」1.41.5特殊的集合和集合的计算
  13. [译] Sklearn 与 TensorFlow 机器学习实用指南
  14. 从 Jacobian 矩阵、Hessian 矩阵到 Theano 实现
  15. Educational Codeforces Round 12 F. Four Divisors 求小于x的素数个数(待解决)
  16. Mail: JMail, System.Net.Mail, System.Web.Mail
  17. 对于给定的一个百分比制成绩,输出相应的五分制成绩
  18. fhq——treap
  19. telnet登录SMTP发送邮件
  20. 【物联网】14.物联网设备控制器选择 - 单片机(MCU)

热门文章

  1. 标准C库对文件操作的引入
  2. 利用 k8s 建立软件商店_为企业建立应用商店
  3. 网站快速成型_我的老板对快速成型有什么期望?
  4. sketch浮动布局_使用智能布局和调整大小在Sketch中创建更好的可重用符号
  5. 幕后常驻嘉宾配音小姐姐的2021年度总结
  6. Lucene学习总结之三:Lucene的索引文件格式(2)
  7. 本周ASP.NET英文技术文章推荐[04/08 - 04/14](附赠自弹超级玛丽主题曲)
  8. CentOS 5.9 yum安装LAMP(Apache+MySQL+PHP)
  9. subclipse用法
  10. 鄙人之斗,读IT之洋(1)