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
相关推荐
智者知已应修善业1 小时前
【51单片机普通延时奇偶灯切换】2023-4-4
c语言·经验分享·笔记·嵌入式硬件·51单片机
wdfk_prog1 小时前
[Linux]学习笔记系列 -- [block]bio
linux·笔记·学习
卡提西亚5 小时前
C++笔记-34-map/multimap容器
开发语言·c++·笔记
2501_915106326 小时前
iOS App 测试工具全景分析,构建从开发调试到线上监控的多阶段工具链体系
android·测试工具·ios·小程序·uni-app·iphone·webview
dchen776 小时前
uniapp实现上拉刷新和下拉刷新的两种方式
uni-app
一个平凡而乐于分享的小比特6 小时前
UCOSIII笔记(十三)CPU利用率及栈检测统计与同时等待多个内核对象
笔记·ucosiii
摇滚侠7 小时前
2025最新 SpringCloud 教程,编写微服务 API,笔记08
笔记·spring cloud·微服务
FinelyYang8 小时前
uniapp+unipush2.0+WebRTC实现h5一对一视频通话
uni-app·音视频·webrtc
我的老子姓彭9 小时前
N32WB蓝牙芯片开发
笔记
历程里程碑9 小时前
各种排序法大全
c语言·数据结构·笔记·算法·排序算法