记录一下首次调用wx公众号JSSDK心路

需求为 公众号点击按钮调用手机摄像头或本地图库 取身份证图片 OCR 识别(智能接口)得到相关信息 放到表单内 注册信息 查阅官网

第一步

是绑定域名(导致 修改一次打版到服务器 域名不同步 得不到config签名中url)

第二步

引js文件 我是采用 npm install weixin-js-sdk

第三步

vx.config 查询大部分的文档都是后端一个接口 给出必填的4项 我是只有appId token 其余自己处理

mounted() {
			this.wx();
		},
methods: {
         //微信初始化
			wx() {
				this.getJsapiTicket(this.getJsapiTicketCallback);
			},
			//签名需要   获取jsapi_ticket
			getJsapiTicket(callback) {
				JsapTick({}).then(response => {
					callback(response.data.result);
				});
			},
			/**
			 * 获得随机字符串
			 * @param e 字符串位数
			 */
			getNonceStr(e) {
				e = e || 32;
				var t = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
					a = t.length,
					n = "";
				for (let i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
				return n;
			},

			/**
			 * 获得时间戳
			 */
			getTimestamp() {
				return (parseInt(new Date().getTime()) + "").substring(0, 10);
			},
			/**
			 * 获得config微信签名
			 * npm install js-sha1 引入
			 * @param
			 */
			getConfigSignature(jsapi_ticket, timestamp, nonceStr, url) {
				//待签名数据
				let obj = new Map();
				obj.set("timestamp", timestamp);
				obj.set("noncestr", nonceStr);
				obj.set("jsapi_ticket", jsapi_ticket);
				obj.set("url", url);
				//排序签名串
				let waitSignatureStr = this.sort_ascii(obj);
				// console.log("waitSignatureStr:",waitSignatureStr)
				//签名加密
				let sha1 = require("js-sha1");
				let signtureStr = sha1(waitSignatureStr);
				// console.log("signtureStr:",signtureStr)
				return signtureStr;
			},
			/**
			 * 获得按ASCII排序的签名串
			 * @param obj 待加密数据Map
			 */
			sort_ascii(obj) {
				console.log(obj, "obj");
				let arr = new Array();
				let num = 0;
				//遍历Key
				for (let i of obj.keys()) {
					// console.log(i,"i")
					arr[num] = i;
					num++;
				}
				// console.log(arr,"arr")
				//按ascii排序
				let sortArr = arr.sort();
				//自定义排序字符串
				let str = "";
				for (let i in sortArr) {
					str += sortArr[i] + "=" + obj.get(sortArr[i]) + "&";
				}
				//去除两侧字符串
				let char = "&";
				str = str.replace(
					new RegExp("^\\" + char + "+|\\" + char + "+$", "g"),
					""
				);
				return str;
			},
			/* 
			 配置wx.config
			 */
			getJsapiTicketCallback(jsapi_ticket) {
				let timestamp = this.getTimestamp();
				let nonceStr = this.getNonceStr();
				let url = window.location.href.substring(
					0,
					window.location.href.lastIndexOf("#")
				);
				let signature = this.getConfigSignature(
					jsapi_ticket,
					timestamp,
					nonceStr,
					url
				);
				wx.config({
					debug: false, // 开启调试模式。
					appId: this.vx, // 必填,公众号的唯一标识
					timestamp: timestamp, // 必填,生成签名的时间戳
					nonceStr: nonceStr, // 必填,生成签名的随机串
					signature: signature, // 必填,签名
					jsApiList: ["chooseImage", 'uploadImage', 'downloadImage', 'getLocalImgData'] // 必填,需要使用的JS接口列表
				});
			},
}

第四步

配置ok后 点击按钮 给后端一张照片 调用wx成功后 图片是base64 OCR是需要file文件 所以得到图片后还要将base64 转换成file 采用"Content-Type": "multipart/form-data" 传输 拿到接口返回的信息

//点击按钮
scanning() {
				let that = this;
				//判断当前客户端版本是否支持指定JS接口
				wx.checkJsApi({
					jsApiList: ['chooseImage', 'getLocalImgData'],
					success: function(res) {
					//拍照或从手机相册中选图接口
						wx.chooseImage({
							count: 1, // 默认9
							sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
							sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
							success: function(res) {
								var localIds = res.localIds[0].toString(); // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
								//获取本地图片接口 这项localData是图片的base64数据,可以用img标签显示
								wx.getLocalImgData({
									localId: res.localIds[0].toString(),
									success: function(res) {
										const localData = res.localData;
										let imageBase64 = '';
										if (localData.indexOf('data:image') == 0) {
											//苹果的直接赋值,默认生成'data:image/jpeg;base64,'的头部拼接
											imageBase64 = localData;
										} else {
											//此处是安卓中的唯一得坑!在拼接前需要对localData进行换行符的全局替换
											//此时一个正常的base64图片路径就完美生成赋值到img的src中了
											imageBase64 = 'data:image/jpeg;base64,' + localData.replace(/\n/g, '');
										}
										//base64做处理 然后传给后端
										that.handleAvatar(that.dataURLtoBlob(imageBase64));
									}
								});
							}
						});
					}
				});
			},
			//base转换file (还有文档 采用 blob 刚开始我也是用blob  最终因为 return 的file  和element ui 上传得到格式是一致) 
			dataURLtoBlob(dataurl) {
				let arr = dataurl.split(',');
				let mime = arr[0].match(/:(.*?);/)[1];
				let bstr = atob(arr[1]);
				let n = bstr.length;
				let u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new File([u8arr], 'multipartFile', {
					type: mime
				});
			},
			//正常传输 
			handleAvatar(imageData) {
				let multipartFile = new FormData();
				multipartFile.append('multipartFile', imageData);
				Orcheck(
					multipartFile,
				).then((response) => {
					this.userName = response.data.result.name
					this.idCardNum = response.data.result.id
					this.birthday = response.data.result.birth
					this.address = response.data.result.addr
					this.sexName = response.data.result.gender
					if (this.sexName == '男') {
						this.sex = '1'
					} else {
						this.sex = '2'
					}
					//日期字符串转换日期格式 计算年龄
					var strDa = this.birthday.split(" ");
					var strDatepart = strDa[0].split("-");
					var time = new Date(strDatepart[0], strDatepart[1] - 1, strDatepart[2]);
					time = time.Format("yyyy-MM-dd");
					this.age = patient.jsGetAge(time);
				}).catch((error) => {
					Toast(error);
				});

			},
   //下面就是转换的方法
	/*根据出生日期算出年龄*/
	jsGetAge(strBirthday) {
		var returnAge;
		var birthYear = strBirthday.substr(0, 4);
		var birthMonth = strBirthday.substr(4, 2);
		var birthDay = strBirthday.substr(6, 2);
		var d = new Date();
		var nowYear = d.getFullYear();
		var nowMonth = d.getMonth() + 1;
		var nowDay = d.getDate();

		if (nowYear == birthYear) {
			returnAge = 0;//同年 则为0岁
		} else {
			var ageDiff = nowYear - birthYear; //年之差
			if (ageDiff > 0) {
				if (nowMonth == birthMonth) {
					var dayDiff = nowDay - birthDay;//日之差
					if (dayDiff < 0) {
						returnAge = ageDiff - 1;
					} else {
						returnAge = ageDiff;
					}
				} else {
					var monthDiff = nowMonth - birthMonth;//月之差
					if (monthDiff < 0) {
						returnAge = ageDiff - 1;
					} else {
						returnAge = ageDiff;
					}
				}
			} else {
				returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天
			}
		}
		return "" + returnAge;//返回周岁年龄
	},
	/*根据身份证号算出出生日期*/
	getBirthdayFromIdCard : function(idCard) {  
		var birthday = "";  
		if(idCard != null && idCard != ""){  
			if(idCard.length == 15){  
				birthday = "19"+idCard.substr(6,6);  
			} else if(idCard.length == 18){  
				birthday = idCard.substr(6,8);  
			}  
		  
			birthday = birthday.replace(/(.{4})(.{2})/,"$1-$2-");  
		}  
		  
		return birthday;  
	  },
		/*根据身份证号算出性别*/
		//男返回“1”,女返回“2”
		getSexFromIdCard : function(idCard) {  
			if (parseInt(idCard.substr(16, 1)) % 2 == 1) {
			    return "1";
			 } else {
			    return "2";
			 }
		  },  
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值