uniapp 开发微信小程序笔记

1、授权获取openId和手机号

html 复制代码
<button class="sub_btn " v-if="!phone&&!openId" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">授权并获取手机号</button>
javascript 复制代码
getPhoneNumber (e) {
			  
			  console.log(e.detail,'获取手机号')  // 动态令牌
			  // console.log(e.detail.code)  // 动态令牌
			  // console.log(e.detail.errMsg) // 回调信息(成功失败都会返回)
			  // console.log(e.detail.errno)  // 错误码(失败时返回)
			  this.phoneCode=e.detail.code
			  this.phoneEncryptedData=e.detail.encryptedData
			  this.phoneIv=e.detail.iv
			   //
			  this.login()
			},
login(){
				uni.login({
				        provider: 'weixin',
				        success:  async (loginRes)=> {
				        	//	打印临时凭证
				        	console.log(loginRes.code,'code');
							this.getSessionKey(loginRes.code)
							// let res = await getOpenId({code:loginRes.code})
							// console.log(JSON.parse(res).openId,'获取opneid')
							// uni.setStorageSync('openId',JSON.parse(res).openId);
							 // // 获取用户信息
							 //    uni.getUserInfo({
							 //      provider: 'weixin',
							 //      success: function (infoRes) {
							 //        console.log('用户昵称为:' + infoRes.userInfo.nickName);
							 //        console.log(infoRes);
							 //      }
							 //    });
				    	}
				});
			},
async getSessionKey(code){
				console.log('开始获取openId')
				let res = await getOpenId({code})
				console.log(JSON.parse(res),'获取opneid')
				this.openId = JSON.parse(res).openId;
				this.sessionKey = JSON.parse(res).session_key;
				uni.setStorageSync('openId',JSON.parse(res).openId);
				this.decrypt()
				// uni.request({
				// 	url: 'https://api.weixin.qq.com/sns/jscode2session',// 请求微信服务器
				// 	method:'GET',
				// 	data: {
				// 		appid: this.appid,        //你的小程序的APPID
				// 		secret: this.secret,    //你的小程序秘钥secret,  
				// 		js_code: code,    //wx.login 登录成功后的code
				// 		grant_type:'authorization_code' //此处为固定值
				// 	},
				// 	success: (res) => {
				// 		console.log('获取信息',res); 
				// 		this.openId = res.data.openid;
				// 		uni.setStorageSync('openId',res.data.openid)
				// 		this.sessionKey = res.data.session_key;
				// 		this.decrypt()
				// 	}
				// });
			},
decrypt(){
				console.log(this.sessionKey,this.phoneEncryptedData,this.phoneIv,'解密参数')
				let pc = new WXBizDataCrypt(appId,this.sessionKey);
				let data = pc.decryptData(this.phoneEncryptedData , this.phoneIv);  
				console.log(data,'解密结果')       //data就是最终解密的用户信息  
				this.phone = data.phoneNumber // 手机号
				uni.setStorageSync('phone',data.phoneNumber)
				this.savePhone()
				
			},
async savePhone(){
				let res = await saveGndhSign({openId:this.openId,phone:this.phone})
				console.log(res,'保存手机号')
				uni.showModal({
					title: '提示',
					content: '是否允许订阅消息',
					success:  (res) =>{
						if (res.confirm) {
							uni.requestSubscribeMessage({
									tmplIds,
									success: res => {
										console.log(res,'订阅消息成功')
										//if(res.tmplId=='acc')
									},
									fail: res=>{
										console.log(res,'取消订阅消息')
									}
									
						});
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			}

WXBizDataCrypt.js

javascript 复制代码
var crypto = require('crypto')

function WXBizDataCrypt(appId, sessionKey) {
  this.appId = appId
  this.sessionKey = sessionKey
}

WXBizDataCrypt.prototype.decryptData = function (encryptedData, iv) {
  // base64 decode
  var sessionKey = new Buffer(this.sessionKey, 'base64')
  encryptedData = new Buffer(encryptedData, 'base64')
  iv = new Buffer(iv, 'base64')

  try {
     // 解密
    var decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv)
    // 设置自动 padding 为 true,删除填充补位
    decipher.setAutoPadding(true)
    var decoded = decipher.update(encryptedData, 'binary', 'utf8')
    decoded += decipher.final('utf8')
    
    decoded = JSON.parse(decoded)

  } catch (err) {
    throw new Error('Illegal Buffer')
  }

  if (decoded.watermark.appid !== this.appId) {
    throw new Error('Illegal Buffer')
  }

  return decoded
}

module.exports = WXBizDataCrypt
相关推荐
日更嵌入式的打工仔4 分钟前
嵌入式入门:APP+BSP+HAL 三层分级架构浅析
笔记·单片机·嵌入式硬件·学习
长桥夜波18 分钟前
【第十八周】机器学习笔记07
人工智能·笔记·机器学习
摇滚侠19 分钟前
Spring Boot 3零基础教程,yml文件中配置和类的属性绑定,笔记15
spring boot·redis·笔记
摇滚侠1 小时前
Spring Boot 3零基础教程,WEB 开发 HTTP 缓存机制 笔记29
spring boot·笔记·缓存
大白的编程日记.1 小时前
【Linux学习笔记】线程同步与互斥之生产者消费者模型
linux·笔记·学习
新子y1 小时前
【小白笔记】strip的含义
笔记·python
摇滚侠1 小时前
Spring Boot 3零基础教程,WEB 开发 内容协商 接口返回 YAML 格式的数据 笔记35
spring boot·笔记·后端
小岛前端2 小时前
🔥Vue3 移动端组件精选!满足各种场景!
前端·vue.js·微信小程序
Chunyyyen2 小时前
【第十八周】自然语言处理的学习笔记03
笔记·学习·自然语言处理
聪明的笨猪猪2 小时前
Java JVM “类加载与虚拟机执行” 面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试