网页手机号抓取程序(微信小程序用户授权获取手机号的相关资料,文中通过示例代码介绍)
优采云 发布时间: 2021-11-18 13:07网页手机号抓取程序(微信小程序用户授权获取手机号的相关资料,文中通过示例代码介绍)
本文文章主要为大家介绍微信小程序用户授权获取手机号码的相关信息。文中介绍的示例代码非常详细,对大家的学习或工作有一定的参考学习价值。有需要的朋友和小编一起学习吧
前言
小程序有一个很方便的获取用户的api,就是通过getPhoneNumber获取用户已经绑定微信的手机号。需要注意的一点是,现在微信注重用户体验,有些方法需要用户主动触发,比如getPhoneNumber。
实现思路:
1、通过wx.login获取code获取用户的openID和sessionKey
2、 通过getPhoneNumber, iv 获取encryptedData
3、通过参数[encryptedData]、[iv]、[sessionKey]请求后台解密获取用户手机号
干货直送:
1、用户点击按钮获取用户手机号
获取用户手机号
2、 弹出授权图片:
3、 解密获取手机号
直接上代码:
wxlogin: function() { //获取用户的openID和sessionKey var that = this; wx.login({ //获取code 使用wx.login得到的登陆凭证,用于换取openid success: (res) = >{ wx.request({ method: "GET", url: 'https://xxxwx/wxlogin.do', data: { code: res.code, appId: "appIdSbcx", a*敏*感*词*ey: "a*敏*感*词*eySbcx" }, header: { 'content-type': 'application/json' // 默认值 }, success: (res) = >{ console.log(res); that.setData({ sessionKey: res.data.session_key }); } }); } }); } getPhoneNumber: function(e) { //点击获取手机号码按钮 var that = this; wx.checkSession({ success: function() { console.log(e.detail.errMsg) console.log(e.detail.iv) console.log(e.detail.encryptedData) var ency = e.detail.encryptedData; var iv = e.detail.iv; var sessionk = that.data.sessionKey; if (e.detail.errMsg == 'getPhoneNumber:fail user deny') { that.setData({ modalstatus: true }); } else { //同意授权 wx.request({ method: "GET", url: 'https://xxx/wx/deciphering.do', data: { encrypdata: ency, ivdata: iv, sessionkey: sessionk }, header: { 'content-type': 'application/json' // 默认值 }, success: (res) = >{ console.log("解密成功~~~~~~~将解密的号码保存到本地~~~~~~~~"); console.log(res); var phone = res.data.phoneNumber; console.log(phone); }, fail: function(res) { console.log("解密失败~~~~~~~~~~~~~"); console.log(res); } }); } }, fail: function() { console.log("session_key 已经失效,需要重新执行登录流程"); that.wxlogin(); //重新登录 } }); }
后台代码:
/** * 解密并且获取用户手机号码 * @param encrypdata * @param ivdata * @param sessionkey * @param request * @return * @throws Exception */ @RequestMapping(value = "deciphering", method = RequestMethod.GET) public @ResponseBody String deciphering(String encrypdata, String ivdata, String sessionkey, HttpServletRequest request) { byte[] encrypData = Base64.decode(encrypdata); byte[] ivData = Base64.decode(ivdata); byte[] sessionKey = Base64.decode(sessionkey); String str=""; try { str = decrypt(sessionKey,ivData,encrypData); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(str); return str; } public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception { AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); //解析解密后的字符串 return new String(cipher.doFinal(encData),"UTF-8"); }
总结
以上是微信小程序用户授权获取手机号码(getPhoneNumber)的详细内容。更多详情请关注其他相关html中文网站文章!