在uniapp中实现小程序调用百度智能云免费的身份证识别接口进行实名认证

本来以为比较简单,结果一路踩坑。

网上找了很多,各种报错。说多了都是泪。

抄了人家不少,自己也不好意思,所以共享出来。

代码比较齐全,改了key就能用,希望对你有所帮助。

<template>
	<view class="content">
		<view class="uni-common-mt">
			<uni-section title="姓名" type="line" padding>
				<uni-easyinput errorMessage type="text" v-model="name" focus placeholder="请输入真实姓名"></uni-easyinput>
			</uni-section>
			<uni-section title="身份证号码" type="line" padding>
				<uni-easyinput type="number" errorMessage v-model="IdNumber" focus
					placeholder="请输入身份证号码"></uni-easyinput>
			</uni-section>
			<uni-section title="上传身份证正面照" type="line" padding="60rpx">
				<image class="img" :src="src" @tap="scan()"></image>
			</uni-section>
		</view>
		<view style="padding: 20rpx;">
			<button type="primary" @click="getIDCard()">点击认证身份信息</button>
		</view>
	</view>
</template>
<script>
	var that;
	// const card = uni.requireNativePlugin('DC-CardRecognize');
	import {
		pathToBase64,
		base64ToPath
	} from 'image-tools'
	export default {
		data() {
			return {
				title: 'input',
				focus: false,
				name: "",
				IdNumber: "",
				src: "/static/photo.png",
				httpUrl: "https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token=",
				imageBase64Str: "",
				APIKey: "用你自己的",
				SecretKey: "还是用你自己的",
				access_token: "",
				filePath: ""

			}
		},
		onLoad() {
			that = this;
			//token验证
			this.getAccess_token();
		},
		methods: {
			getAccess_token() {
				var accessToken = that.cache("accessToken", null, null);
				console.log(accessToken)
				if (!accessToken) {
					uni.request({
						method: 'POST',
						header: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						url: "https://aip.baidubce.com/oauth/2.0/token",
						data: {
							grant_type: "client_credentials",
							client_id: this.APIKey,
							client_secret: this.SecretKey
						},
						success: function(res) {
							console.log(res.data.access_token);
							//uni.setStorageSync("Baidu",res.data);
							that.access_token = res.data.access_token;
							that.cache("accessToken", res.data.access_token, null);
						}
					})
				} else {
					that.access_token = accessToken;
				}

			},
			//缓存,默认有效期28天
			cache: function(key, value, seconds) {
				var timestamp = Date.parse(new Date()) / 1000
				console.log(timestamp + "===" + key)
				if (key && value === null) {
					//删除缓存
					//获取缓存
					var val = uni.getStorageSync(key);
					var tmp = val.split("|")
					if (!tmp[1] || timestamp >= tmp[1]) {
						console.log("key已失效")
						uni.removeStorageSync(key)
						return ""
					} else {
						console.log("key未失效")
						return tmp[0]
					}
				} else if (key && value) {
					//设置缓存
					if (!seconds) {
						var expire = timestamp + (3600 * 24 * 28)
					} else {
						var expire = timestamp + seconds
					}
					value = value + "|" + expire
					uni.setStorageSync(key, value);
				} else {
					console.log("key不能空")
				}
			},
			getIDCard() {
				var flag = this.verifyData();
				var that = this

				if (flag) {
					console.log("==")
					//百度名片识别接口处理开始
					uni.showLoading({
						mask: true,
						title: "识别中,请等待",

					});
					console.log('请求', this.filepath)

					uni.request({
						url: "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" +
							that.access_token,
						method: 'POST',
						header: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						data: {
							image: this.filePath,
							id_card_side: "front"
						},
						success(res) {
							console.log('返回结果', res);
							var IdCard = res.data.words_result.公民身份号码.words;
							var userName = res.data.words_result.姓名.words;
							console.log(res.data.words_result.公民身份号码.words)
							if (IdCard == that.IdNumber && userName == that.name) {
								console.log("身份验证成功");
								uni.showToast({
									icon: 'success',
									title: '身份验证成功',
									duration: 1000
								});
							} else {
								uni.showToast({
									icon: 'none',
									title: '身份信息有误请审核信息',
									duration: 1000
								});
							}
						},
						complete() {
							uni.hideLoading();
						}
					})
				}

			},

			//校验输入的数据
			verifyData() {
				var flag = true;
				if (!this.name) {
					flag = false;
					uni.showToast({
						icon: 'none',
						title: '姓名不能为空'
					});
					return false;
				}
				if (!this.IdNumber) {
					flag = false;
					uni.showToast({
						icon: 'none',
						title: '身份证号不能为空'
					});
					return false;
				}
				var re15 = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/;
				var re18 = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$/;
				var res = (re15.test(this.IdNumber) || re18.test(this.IdNumber));
				if (res == false) {
					flag = false;
					uni.showToast({
						icon: 'none',
						title: '身份证号填写有误'
					});
					return false;
				}
				// if (this.filePath === "") {
				// 	flag = false;
				// 	uni.showToast({
				// 		icon: 'none',
				// 		title: '请上传身份证照片面'
				// 	});
				// 	return false;
				// }
				return flag;

			},


			scan() {
				var that = this
				uni.chooseMedia({
					mediaType: ['image'],
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: function(res) {
						console.log(res)
						that.src = res.tempFiles[0].tempFilePath
						that.imgToBase64(res.tempFiles[0].tempFilePath).then(base64 => {
							that.filePath = base64
							console.log("[转换成base64]", base64)
						})

					}
				})


			},
			imgToBase64(data) {
				return new Promise((resolve, reject) => {
					pathToBase64(data).then(base64 => {
						resolve(base64)
					}).catch(error => {
						console.error(error)
						reject(error)
					})
				})
			}

		}
	}
</script>

<style>
	.option {
		display: flex;
		margin-top: 4%;
		margin-left: 30upx;
		padding-bottom: 30upx;
		border-bottom: #333333 solid 0.5upx;
	}

	.msg-left {
		flex: 5;
		display: flex;
		justify-content: flex-start;
		align-items: center;
	}

	.msg-right {
		flex: 2;
		display: flex;
		justify-content: center;
		text-align: center;
		margin-right: 15upx;
		border-bottom: #000000 solid 0.5upx;
	}

	.img {
		display: flex;
		margin-top: 4%;
		margin-left: 30upx;
		padding-bottom: 30upx;

	}

	.img image {
		justify-content: center;
		margin-top: 8%;

	}
</style>

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值