uniapp微信小程序开发测试获取手机号码

先申请测试号

注意认证但是没有完全认证不要试测试号解密如下

总结我自己的两大坑

1.官网的WXBizDataCrypt需要导入crypto要提前下载但是试了很多次没有效果重新编写这个。将crypto库换成crypto-js库

2.我一直在尝试用下有下面这个界面的测试号不行获取不到用户的code还是啥忘记了s

新建WXBizDataCrypt.js官网也有也可以直接负责下面的内容

javascript 复制代码
import CryptoJS from 'crypto-js';

class WXBizDataCrypt {
  constructor(appId, sessionKey) {
    this.appId = appId;
    this.sessionKey = sessionKey;
  }

  decryptData(encryptedData, iv) {
    // 确保 encryptedData 和 iv 都是 Base64 编码的字符串
    const sessionKey = CryptoJS.enc.Base64.parse(this.sessionKey);
    const encryptedBuffer = CryptoJS.enc.Base64.parse(encryptedData);
    const ivBuffer = CryptoJS.enc.Base64.parse(iv);

    try {
      // 使用 AES 解密
      const decrypted = CryptoJS.AES.decrypt(
        { ciphertext: encryptedBuffer },
        sessionKey,
        {
          iv: ivBuffer,
          mode: CryptoJS.mode.CBC,
          padding: CryptoJS.pad.Pkcs7,
        }
      );

      // 将解密后的数据转换为 UTF-8 字符串
      const decoded = decrypted.toString(CryptoJS.enc.Utf8);

      // 解析 JSON 数据
      const result = JSON.parse(decoded);

      // 检查解密结果中的 App ID
      if (result.watermark.appid !== this.appId) {
        throw new Error('Illegal Buffer: App ID mismatch');
      }

      return result;
    } catch (err) {
      console.error('解密失败', err);
      throw new Error('Illegal Buffer: ' + err.message);
    }
  }
}

export default WXBizDataCrypt;

npm 下载 crypto-js:将node_modules中 crypto-js文件夹中的 crypto-js.js复制到WXBizDataCrypt同级目录

接下来在生成按钮

html 复制代码
<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
	<view class="wx_text">微信授权登录</view>
</button>

接下来在第一张图片中的appid与AppSecret(小程序密钥)复制下来

typescript 复制代码
getPhoneNumber(e) {
		    uni.login({
		        provider: 'weixin', // 使用微信登录
		        success: (res) => {
		            uni.request({
		                url: 'https://api.weixin.qq.com/sns/jscode2session',
		                method: 'GET',
		                data: {
		                    appid: "appid自己的",
		                    secret: "AppSecret(小程序密钥)复制下来",
		                    js_code: res.code, // wx.login 登录成功后的code  
		                    grant_type: 'authorization_code',
		                },
		                success: (res) => {
		                    console.log('Request success:', res);
		                    if (res.data && res.data.session_key) {
		                        let pc = new WXBizDataCrypt('appid自己的', res.data.session_key);
		                        try {
		                            let data = pc.decryptData(e.detail.encryptedData, e.detail.iv);
		                            console.log('手机号码信息', data);
		                        } catch (err) {
		                            console.error('解密失败', err);
		                        }
		                    } else {
		                        console.error('未能获取 session_key:', res);
		                    }
		                },
		                fail: (err) => {
		                    console.error('Request failed:', err);
		                }
		            });
		        },
		        fail: (err) => {
		            console.error('Login failed:', err);
		        }
		    });
		}

简写的方法

typescript 复制代码
getPhoneNumber(e) {
				console.log(e)
				// 用户同意授权,拿到code去获取手机号
				uni.login({
					provider: 'weixin', //使用微信登录
					success: (res) => {
						uni.request({
							url: 'https://api.weixin.qq.com/sns/jscode2session',
							method: 'GET',
							data: {
								appid:"appid自己的",
								secret:"ppSecret(小程序密钥)复制下来",
								js_code: res.code, //wx.login 登录成功后的code  
								grant_type: 'authorization_code',
							},
							success: (res) => {
								let pc = new WXBizDataCrypt('appid自己的', res.data.session_key);
								
								try {
								  let data = pc.decryptData(e.detail.encryptedData, e.detail.iv);
								  console.log('手机号码信息', data);
								} catch (err) {
								  console.error('解密失败', err);
								}
							}
						});
					}
				})
		
		}
相关推荐
李纲明9 小时前
微信小程序团课临开课才取消或空位没人补:先核取消时限与自动释放,再查候补确认与预扣回滚
微信小程序·devdiy·团课预约·取消时限·空位释放·候补确认·预扣回滚
用户0341876713819 小时前
用秒哒做了个拍照识餐小程序,上线两周踩的 4 个坑
微信小程序
李纲明21 小时前
微信小程序租赁归还说本来就坏或配件对不上:先核借还点验与随单存证,再查差异计价公示
微信小程序·devdiy·租赁点验·借还拍照·随单存证·差异计价·押金释放
李纲明2 天前
微信小程序次卡跨店对不上账或前台随手改余次:先核流水只增不改与统一日切,再查冲正权限与总部只读
微信小程序·devdiy·核销流水·跨店次卡·日切对账·冲正权限·总部只读
李纲明2 天前
微信小程序维修拆机后口头加价或未确认就开工:先核验机快照与报价确认,再查补充报价与取机核验
微信小程序·devdiy·维修验机·报价确认·报价快照·补充报价·取机核验
wx1qq1com2 天前
一桩带几台车:共享租赁桩位配比、取电与结算闭环设计
物联网·微信小程序·小程序
李纲明2 天前
微信小程序场地长租月底对不上或口头占场撞场:先核合约预约与核销流水出账,再查附加费与转租归属
微信小程序·devdiy·场地长租·月结账单·核销流水·附加费·转租归属
2401_879692512 天前
微信小程序照相与摄像功能实现——chooseImage 与 chooseVideo 详解
微信小程序·小程序·notepad++
律宏阔3 天前
微信小程序 + Taro + TDesign 去掉 [&&&],让普通 Tailwind 类接管局部样式
前端·微信小程序·taro
律宏阔3 天前
微信小程序 + Taro + 多语言实现与国际化检查实录
前端·微信小程序·taro