微信小程序登录-手机号授权并获取手机号

做微信小程序时,记录实现微信小程序登录

这里已经获取用户openId和sessionKey

        1、通过按钮触发手机号授权

必须要通过按钮触发授权,open-type='getPhoneNumber'不能少

<button open-type='getPhoneNumber' @getphonenumber='onGetPhoneNumber'>手机号授权登录</button>

需要通过后台进行解析

onGetPhoneNumber(e) {
    if (e.detail.errMsg == "getPhoneNumber:fail user deny") {
        //    用户拒绝授权  
        //    拒绝授权后弹出一些提示  
        uni.showToast({
            icon: 'error',
            duration: 2000,
            title: '登录失败'
        })

    } else { 
        //    允许授权  
        console.log('-加密的用户信息-', e.detail)
        //    e.detail.encryptedData //加密的用户信息  
        //    e.detail.iv //加密算法的初始向量  时要用到  
        //    调用接口获取手机号并修改小程序登录状态及相关信息
        this.$myRequest({
            url: '后台接口url(去后台解析加密的用户信息)',
            data: {
                encryptedData: e.detail.encryptedData,
                iv: e.detail.iv,
                sessionKey: that.sessionKey
            }
        }).then(rest => {
            console.log('返回的手机号', rest.message);
        })
    }
}

后台解析springboot

        AESUtils工具

public class AESUtils {

    public static boolean initialized = false;

    /**
     * AES解密
     *
     * @param content 密文
     * @return
     * @throws InvalidAlgorithmParameterException
     * @throws NoSuchProviderException
     */
    public byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws InvalidAlgorithmParameterException {
        initialize();
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            Key sKeySpec = new SecretKeySpec(keyByte, "AES");
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 初始化
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static void initialize() {
        if (initialized) {
            return;
        }
        Security.addProvider(new BouncyCastleProvider());
        initialized = true;
    }

    //生成iv
    public static AlgorithmParameters generateIV(byte[] iv) throws Exception {
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        return params;
    }
}
@GetMapping(value = "/getPhoneNumber")
    public Result getPhoneNumber(@RequestParam(required = true, value = "encryptedData") String encryptedData,
                                 @RequestParam(required = true, value = "iv") String iv,
                                 @RequestParam(required = true, value = "sessionKey") String sessionKey
    ) throws UnsupportedEncodingException, InvalidAlgorithmParameterException, JSONException {
        Result result = new Result();
        //AESUtils微信获取手机号解密工具类
        AESUtils aes = new AESUtils();
        //调用AESUtils工具类decrypt方法解密获取json串
        byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));
        //判断返回参数是否为空
        if (null != resultByte && resultByte.length > 0) {
            String jsons = new String(resultByte, "UTF-8");
            System.out.println(jsons);
            JSONObject json = new JSONObject(jsons);
            //json解析phoneNumber值
            String phoneNumber = json.getString("phoneNumber");
            System.out.println("phoneNumber:" + phoneNumber);
            return result;
        }

        return result.error("session_key:失败");
    }


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Taro开发微信小程序中,如果你需要获取用户的手机号码,可以按照以下步骤进行操作: 1. 首先,确保在微信公众平台上已经设置了小程序获取用户手机号的权限。你可以在小程序管理后台的"开发-开发设置-接口设置"中找到相关设置。 2. 在Taro的页面或组件中,引入微信小程序的API:通过`import Taro from '@tarojs/taro'`引入微信小程序的API。 3. 调用`Taro.login()`方法获取用户登录凭证code,用于后续的手机号授权验证。 4. 在获取到code后,调用`Taro.getUserInfo()`方法获取用户信息,包括手机号码。示例代码如下: ```javascript Taro.login().then((loginRes) => { if (loginRes.code) { Taro.getUserInfo().then((userRes) => { const { encryptedData, iv } = userRes.userInfo // 在这里可以将encryptedData和iv发送到后端解密获取手机号码 // 也可以直接在前端解密获取手机号码 }).catch((err) => { console.log(err) }) } else { console.log('登录失败') } }).catch((err) => { console.log(err) }) ``` 5. 在上述代码中,`encryptedData`和`iv`是用户信息的加密数据,你可以将它们发送到后端进行解密,或者在前端使用相应的解密算法解密获取手机号。 需要注意的是,获取用户手机号的过程需要用户授权,并且用户必须在微信设置中允许小程序获取手机号的权限。如果用户未授权或未设置权限,将无法获取手机号。 希望这些信息对你有所帮助!如果你还有其他问题,请继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值