调用百度OCR接口识别身份证 微信小程序

申请百度AI账号获取百度OCR接口API Key和Secret Key

申请地址:

http://ai.baidu.com/?track=cp:aipinzhuan|pf:pc|pp:AIpingtai|pu:title|ci:|kw:10005792
除了身份证识别,百度还提供了人脸识别、车牌识别等接口,有兴趣都可以申请试试,日请求量不超过500好像是免费的。
在这里插入图片描述
身份证识别接口相关文档地址https://ai.baidu.com/ai-doc/OCR/rk3h7xzck,申请过程文档基本上有说明

Access Token

本文档主要针对HTTP API调用者,百度AIP开放平台使用OAuth2.0授权调用开放API,调用API时必须在URL中带上access_token参数,获取Access Token的流程如下:
向授权服务地址https://aip.baidubce.com/oauth/2.0/token发送请求(推荐使用POST),并在URL中带上以下参数:

grant_type: 必须参数,固定为client_credentials;
client_id: 必须参数,应用的API Key;
client_secret: 必须参数,应用的Secret Key;

例如

https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=Va5yQRHlA4Fq5eR3LT0vuXV4&client_secret=0rDSjzQ20XUj5itV6WRtznPQSzr5pVw2&

获取access_token示例代码

#!/bin/bash
curl -i -k 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【百度云应用的AK】&client_secret=【百度云应用的SK】'

**百度云应用的AK(API Key)和SK(Secret Key)获取参考:https://cloud.baidu.com/doc/Reference/s/9jwvz2egb

服务器返回的JSON文本参数如下:

access_token: 要获取的Access Token; expires_in: Access
Token的有效期(秒为单位,有效期30天);
其他参数忽略,暂时不用;

例如:

{
  "refresh_token": "25.b55fe1d287227ca97aab219bb249b8ab.315360000.1798284651.282335-8574074",
  "expires_in": 2592000,
  "scope": "public wise_adapt",
  "session_key": "9mzdDZXu3dENdFZQurfg0Vz8slgSgvvOAUebNFzyzcpQ5EnbxbF+hfG9DQkpUVQdh4p6HbQcAiz5RmuBAja1JJGgIdJI",
  "access_token": "24.6c5e1ff107f0e8bcef8c46d3424a0e78.2592000.1485516651.282335-8574074",
  "session_secret": "dfac94a3489fe9fca7c3221cbf7525ff"
}

若请求错误,服务器将返回的JSON文本包含以下参数:
例如认证失败返回:
鉴权认证错误码

errorerror_description
invalid_clientunknown client id 代表API Key不正确
invalid_clientClient authentication failed 代表Secret Key不正确
{
    "error": "invalid_client",
    "error_description": "unknown client id"
}

error: 错误码;关于错误码的详细信息请参考下方鉴权认证错误码。 error_description:
错误描述信息,帮助理解和解决发生的错误。

以下是整体调用代码

function OcrIdCard(access_token) {
  return new Promise(function (resolve, reject) {
    //识别身份证
    wx.chooseImage({  //选择身份证图片/拍照
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['camera'],
      success: function (res) {   //调用照片选择成功的回调函数
        console.log(res.tempFilePaths)
        //图片编码部分核心代码
        wx.getFileSystemManager().readFile({
          filePath: res.tempFilePaths[0],
          encoding: 'base64', //编码格式
          success(ans) {
            // console.log(ans.data)
            wx.showLoading({ title: '识别中' })
            //ans.data:保存了图片转码之后的数据
            // 请求获取token
            wx.request({
            //url中的&client_id=client-i&client_secret=client—s中的参数client-i和client—s需要申请百度身份证识别的账号和密码,具体申请流程参考上面
              url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=client_id&client_secret=client_secret',
              data: {},//请求参数,此处没有参数,则置空
              header: {
                'content-type': 'application/x-www-form-urlencoded' // 默认值
              },
              success(rep) {
                var access_token = rep.data.access_token;
                console.log("access_token:", access_token)
                //带着token与转码后的图片编码请求百度OCR接口,对身份证信息进行识别
                wx.request({
                  url: 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=' + access_token,
                  method: 'POST',
                  header: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                  },
                  data: {
                    image: ans.data,  //ans.data:图片编码
                    id_card_side: 'front'
                  },
                  success(_res) {
                    wx.hideLoading();
                    resolve(_res)
                    console.log("身份证识别成功:", _res)
                  }, fail(_res) {
                    wx.hideLoading();
                    wx.showToast({
                      title: '请求出错',
                      icon:'none'
                    })
                    reject(_res)
                  }
                })
              },fail(rep) {
                wx.hideLoading();
                wx.showToast({
                  title: '请求出错',
                  icon:'none'
                })
                reject(rep)
              }

            });
          },fail(res) {
            wx.hideLoading();
            wx.showToast({
              title: '所选图片编码失败,请重试',
              icon:'none'
            })
            reject(res)
          }
        })

      },fail(res) {
        wx.hideLoading();
        wx.showToast({
          title: '图片选择失败,请重试',
          icon:'none'
        })
        reject(res)
      }
    })
  })
}
module.exports = {
  OcrIdCard: OcrIdCard
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值