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
相关推荐
不爱说话郭德纲12 小时前
告别漫长的HbuilderX云打包排队!uni-app x 安卓本地打包保姆级教程(附白屏、包体积过大排坑指南)
android·前端·uni-app
大米饭消灭者2 天前
Taro是怎么实现一码多端的【底层原理】
微信小程序·taro
HashTang2 天前
【AI 编程实战】第 12 篇:从 0 到 1 的回顾 - 项目总结与 AI 协作心得
前端·uni-app·ai编程
JunjunZ2 天前
uniapp 文件预览:从文件流到多格式预览的完整实现
前端·uni-app
郑州光合科技余经理2 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
西岸行者3 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
starlaky3 天前
Django入门笔记
笔记·django
勇气要爆发3 天前
吴恩达《LangChain LLM 应用开发精读笔记》1-Introduction_介绍
笔记·langchain·吴恩达
悠哉悠哉愿意3 天前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习
勇气要爆发3 天前
吴恩达《LangChain LLM 应用开发精读笔记》2-Models, Prompts and Parsers 模型、提示和解析器
android·笔记·langchain