uni-app 微信小程序 手机号 一键登录

实现思路 非常简单

1.button 按钮设置 获取手机号的类型。
2.code 需要提前提前提前提前获取。写在onshow 或者 onload中 ,从缓存中获取登录状态,如未登录就获取code。
3.执行 bindPhone 时,带着code 、iv、encryptedData 一起去后端请求接口 。解密后返回token 即可。

<button  open-type="getPhoneNumber" @getphonenumber="bindPhone">微信一键登陆</button>
	data() {
			return {
				code: ''
			}
	},
	onShow() {
			// 已经登陆 获取用户信息

			// 如未登录 获取code
			let _this = this;
			
				uni.showLoading({
					title: '登录中...'
				});
				// 1.wx获取登录用户code
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						console.log("登录", loginRes.code)
						_this.code = loginRes.code;
						uni.hideLoading();
					},
				})
	},
	methods: {
	
		// 绑定手机号码
		bindPhone(e) {
			let that = this;

			let param = {
				"iv": e.detail.iv,
				"encryptedData": e.detail.encryptedData,
				code: this.code
			}
			// 执行后端接口 这里就是请求后端接口
			loginService.bindPhone(param).then(result => {

					if (result !== '' && result.errno === 0) {
						uni.showToast({
							title: '登录成功',
							icon: 'none'
						})
						// 存储登录信息  修改登录状态 登录成功
					}
				}).catch((error) => {
					
				});
		}
	}

java 后端代码

pom 引入 三方工具类

  <dependency>
     <groupId>com.github.binarywang</groupId>
     <artifactId>weixin-java-miniapp</artifactId>
     <version>3.9.0</version>
 </dependency>

实现类

	@Autowired
	private WxMaService wxService;


    /**
     * 微信手机号码绑定
     * @param body
     * @return
     */
    @PostMapping("bindPhone")
    public Object bindPhone(@RequestBody String body) {

		//  code 可换取openId 用于账户的创建 查询 等操作
        String code = JacksonUtil.parseString(body, "code");

        WxMaJscode2SessionResult result = null;
        try {
            result = this.wxService.getUserService().getSessionInfo(code);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        // 也能获取opneId result.getOpoenId();
        String sessionKey = result.getSessionKey();

        String encryptedData = JacksonUtil.parseString(body, "encryptedData");
        String iv = JacksonUtil.parseString(body, "iv");
        
 		//获取手机号码
        WxMaPhoneNumberInfo phoneNumberInfo = this.wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
       
        String phone = phoneNumberInfo.getPhoneNumber();
        // 这里处理你的用户逻辑,具体的自己写叭。 我这里是演示 直接返回 phone 就行
		
        return ResponseUtil.ok(phone);
    }



注意事项:code 一直要在之前获取,在页面初始化的时候获取,用户点了登录的时候,一块将code 和手机还要信息传递给后端,不然后端必然会报错,报错示例如下。

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐