小程序調用阿里雲身份證識別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 = this
    var 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, // 默認9
      sizeType: ['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
    // debugger
    if (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.html
      that.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)
    備註:說明來意
  • 閒暇之餘寫了個小程序:不二顏究所,歡迎搜索~
相關文章
相關標籤/搜索