本文介绍如果通过微信小程序的getPhoneNumber方法获取用户微信绑定的手机号并自动注册登录。
- <template>
- <nut-button size="large" block color="#1890FF" :loading="loading" openType="getPhoneNumber" @getphonenumber="wxLogin">微信一键登录nut-button>
- template>
1、按钮类型 openType 指定 "getPhoneNumber"
2、@getphonenumber必须全部小写
- // 微信一键登录事件
- async function wxLogin(e) {
- loading.value = true;
- try {
- const result = await wxNumberLogin({
- appid: getAppId(), // 微信小程序APPID
- code: e?.detail?.code,
- openId: openId.value, // 微信小程序openID
- });
- if (isRespondSuccess(result)){
- const from_url = Taro.getCurrentInstance().router?.params["from_url"];
- if (from_url && (from_url !== 'undefined')){
- Taro.reLaunch({url: from_url});
- } else {
- Taro.switchTab({url: `${ROUTER_ENUM.PAGE_HOME}`});
- }
- }
- } finally {
- loading.value = false;
- }
- }
code:手机号获取凭证:动态令牌。可通过动态令牌换取用户手机号。
后台根据前端传入的code获取手机号并自动将手机号注册为账号。
- public CommonResult
getPhoneNumberRegister(String code, String appid, RegisterParams params) { - String urlGetPhoneNumber = WxPlatformConstants.CODE_GET_PHONENUMBER
- .replaceFirst("ACCESS_TOKEN", getAuthAccessToken(appid));
- Map
map = new HashMap<>(); - map.put("code", code);
- String result = HttpUtil.doPostUseJsonParams(urlGetPhoneNumber, map, HttpCharset.UTF8);
- log.info("getPhoneNumber_result:" + result);
- JSONObject object = JSON.parseObject(result);
- JSONObject phoneObject = object.getJSONObject("phone_info");
- String phone = phoneObject.getString("phoneNumber");
- params.setMobile(phone);
-
- return sysUserService.register(params, false); // 不需要校验验证码
- }
1、 常量参数CODE_GET_PHONENUMBER :
CODE_GET_PHONENUMBER = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN";2、微信返回的参数:
{ "errcode":0, "errmsg":"ok", "phone_info": { "phoneNumber":"xxxxxx", "purePhoneNumber": "xxxxxx", "countryCode": 86, "watermark": { "timestamp": 1637744274, "appid": "xxxx" } } }