獲取用戶授權(quán)的手機(jī)號(hào)【微信小程序】

作者:辰風(fēng)沐陽 閱讀:2377 發(fā)布時(shí)間:2021-06-02 上次更新:2022-08-05

1. 前言


特別注意:個(gè)人號(hào)小程序無法使用

目前該接口針對(duì)非個(gè)人開發(fā)者,且完成了認(rèn)證的小程序開放(不包含海外主體)

微信開發(fā)文檔: https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html

2. 獲取用戶授權(quán)手機(jī)號(hào) button 組件


定義按鈕組件,用于調(diào)起授權(quán)手機(jī)號(hào)彈窗

  1. <button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">獲取手機(jī)號(hào)</button>

bindgetphonenumber 事件回調(diào)

  1. methods: {
  2. // 獲取用戶授權(quán)的手機(jī)號(hào)
  3. getPhoneNumber: e => {
  4. if (e.detail.errMsg === 'getPhoneNumber:ok') {
  5. wx.request({
  6. url: 'http://tp6.cy/',
  7. method: 'POST',
  8. data: {
  9. iv: e.detail.iv,
  10. encryptedData: e.detail.encryptedData,
  11. },
  12. success: res => {
  13. console.log(res)
  14. }
  15. })
  16. } else {
  17. wx.showToast({
  18. title: '拒絕授權(quán)',
  19. })
  20. }
  21. },
  22. }

將以下數(shù)據(jù)傳給后端,后臺(tái)可通過解密數(shù)據(jù)得到手機(jī)號(hào)

  1. {
  2. "encryptedData": "PIxZLRab9M9EQha6Od5WA5NT...",
  3. "iv": "CVN4qd7zUe6+vz9wuAvReQ=="
  4. }

3. 使用 EasyWechat 4.x 消息解密獲取手機(jī)號(hào)


  1. composer require overtrue/wechat:~4.0

消息解密文檔: https://easywechat.com/docs/4.x/mini-program/decrypt

一、獲取小程序相關(guān)功能所屬實(shí)例

  1. $app = Factory::miniProgram($config);

https://easywechat.com/docs/4.x/mini-program/index

二、進(jìn)行消息解密時(shí)最好使用 try catch 捕獲可能出現(xiàn)的異常

  1. try {
  2. // 消息解密
  3. // $session 根據(jù) wx.login 的臨時(shí)登錄憑證 code 換取的 session_key
  4. // $iv, $encryptedData 在 bindgetphonenumber 事件回調(diào)中獲取
  5. $decryptedData = $app->encryptor->decryptData($session, $iv, $encryptedData);
  6. } catch (\Throwable $th) {
  7. // 解密失敗
  8. // 當(dāng)使用的$session已過期時(shí),解密會(huì)拋出異常,
  9. // 此時(shí)錯(cuò)誤信息:The given payload is invalid.
  10. echo $th->getMessage();
  11. }
  12. // 手機(jī)號(hào)為空代表解密失敗 fault 是自定義的拋出異常的函數(shù)
  13. empty($decryptedData['phoneNumber']) && fault('解密失敗');
  14. // 解密成功后的操作
  15. // ...

三、解密成功 $decryptedData 的值

  1. {
  2. "phoneNumber": "15037846666",
  3. "purePhoneNumber": "15037846666",
  4. "countryCode": "86",
  5. "watermark": {
  6. "timestamp": 1622695392,
  7. "appid": "wxb80ec74221f8a9ff"
  8. }
  9. }

4. 在 EasyWechat 4.x 使用新接口獲取手機(jī)號(hào)


從基礎(chǔ)庫 2.21.2 開始,對(duì)獲取手機(jī)號(hào)的接口進(jìn)行了安全升級(jí),bindgetphonenumber 事件回調(diào)方法中的 e.detail 中增加了一個(gè) code 屬性。新版本接口不再需要提前調(diào)用 wx.login 進(jìn)行登錄(調(diào)用 wx.login 是為了獲取 session_key)

  1. {
  2. "code": "dbad746bbaf51214f081e133668cc5a5ebbb9a526ad9e7b503e337a59c60414c",
  3. "encryptedData": "PIxZLRab9M9EQha6Od5WA5NT...",
  4. "iv": "CVN4qd7zUe6+vz9wuAvReQ=="
  5. }

前端開發(fā)者只需要將上面的 code 傳遞給接口,后端開發(fā)者就能獲取到手機(jī)號(hào),因?yàn)檫@個(gè)接口是新版的,EasyWechat4.x 還沒有更新,所以需要自己手動(dòng)調(diào)用新版接口,代碼示例如下所示

  1. /**
  2. * 獲取用戶授權(quán)手機(jī)號(hào)
  3. * @param string $code
  4. */
  5. function getPhoneNumber(string $code)
  6. {
  7. $app = Factory::miniProgram($config);
  8. $access_token = $app->access_token->getToken()['access_token'];
  9. $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $access_token;
  10. // 使用 curl 發(fā)送網(wǎng)絡(luò)請(qǐng)求
  11. $result = https_request($url, json_encode(['code' => $code]));
  12. $array = json_decode($res, true);
  13. if (isset($array['errcode']) && $array['errcode'] == 0) {
  14. // 獲取成功
  15. // 手機(jī)號(hào): $array['phone_info']['phoneNumber']
  16. } else {
  17. // 獲取失敗
  18. }
  19. }
  20. /**
  21. * http請(qǐng)求
  22. * @param string $url 請(qǐng)求的地址
  23. * @param string $data 請(qǐng)求參數(shù)
  24. */
  25. function https_request($url, $data = null)
  26. {
  27. $curl = curl_init();
  28. curl_setopt($curl, CURLOPT_URL, $url);
  29. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  30. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  31. if (!empty($data)) {
  32. curl_setopt($curl, CURLOPT_POST, 1);
  33. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  34. }
  35. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  36. $output = curl_exec($curl);
  37. curl_close($curl);
  38. return $output;
  39. }

標(biāo)簽: 微信小程序