小程序調用阿里云身份證識別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.pswp.cn/news/280053.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/280053.shtml
英文地址,請注明出處:http://en.pswp.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(表達式有…