uniapp 百度身份证识别功能

290 阅读1分钟

1. Access_token

向授权服务地址https://aip.baidubce.com/oauth/2.0/token发送请求(推荐使用POST),并在URL中带上以下参数:

  • grant_type:  必须参数,固定为client_credentials
  • client_id:  必须参数,应用的API Key
  • client_secret:  必须参数,应用的Secret Key
//发送请求
uni.request({
'method': 'POST',
 'url': 'https://aip.baidubce.com/oauth/2.0/tokenclient_id=&client_secret=&grant_type=client_credentia',
 'headers': {
           'Content-Type': 'application/json',
            'Accept': 'application/json'
        }

我这里是通过公司服务器获取的token,当时我获取token在报跨域问题,当时没去管

2.身份证识别

image:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/jpeg/png/bmp格式

uni.request({
	url: `https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=${token}`, //百度api。
	data: {
		id_card_side: 'front',
		detect_direction: true,
		image: localData
	},
	method: 'POST',
	header: {
		'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
		},
	success: res => {
        
        }
        })

下面是识别成功后返回的JSON数据,部分参数抹去

{
	"data": {
		"direction": 3,
		"words_result": {
			"姓名": {
				"location ": {
					"top": 585,
					"left": 724,
					"width": 53,
					"height": 140
				},
				"words": "" //名字
			},
			"民族": {
				"location": {
					"top": 790,
					"left": 638,
					"width": 43,
					" height ": 37
				},
				"words ": "汉" //民族
			},
			"住址 ": {
				"location": {
					"top": 562,
					"left ": 410,
					"width ": 106,
					"height ": 432
				},
				"words ": "" //身份证地址
			},
			"公民身份号码 ": {

				"location": {
					"top": 742,
					"left": 233,
					"width": 61,
					"height": 590
				},
				"words": "" //身份证号码
			},
			"出生": {

				"location": {
					"top": 572,
					"left": 557,
					"width": 46,
					"height": 350
				},
				"words": "" //出生日期
			},
			"性别 ": {
                                       "location": {
					"top": 576,
					"left": 641,
					"width": 46,
					"height": 41
				},
				"words": "男" //性别
			}
		},
		"words_result_num": 6,
		"idcard_number_type": 1,
		"image_status": "normal",
		"log_id": 1643865701021825000
	},
	"statusCode": 200,
	"header ": {
		"content -length ": "394 ",
		"content - type ": "application / json "
	},
	"errMsg ": "request: ok "
}

百度开发文档:ai.baidu.com/ai-doc/OCR/…