有需求联系

Information

- 信息浏览 -

微信小程序获取手机号

2023-11-30 599

几个步骤

1、通过用户点击按钮授权手机号

2、根据wx.login获取session_key

3、根据session_key,iv,encryptedData发送服务器解密手机号


WXML


JS

 getPhoneNumber(e) {

    if (e.detail.errMsg === 'getPhoneNumber:ok') {

      wx.login({

        success: (res) => {

          // 远程获取session_key

          request({

            url: "/api/get_session_key.php", data: {

              code: res.code,

            }, header: { "Content-Type": "application/x-www-form-urlencoded" }, method: 'POST'

          }).then(res => {

            // 远程解密手机

            request({

              url: "/api/get_phone.php", data: {

                session_key: res.data.session_key,

                iv: e.detail.iv,

                encryptedData: e.detail.encryptedData

              }, header: { "Content-Type": "application/x-www-form-urlencoded" }, method: 'POST'

            }).then(res => {

              // 拿到解密后的手机号

              console.log(res.data.phoneNumber)

            })


          })

        }

      })


    }

  },


PHP-get_session_key.php

<?php

$appid = 'wx*********395fa'; // 小程序APPID

$secret = '9bfcd2*************973e47db6'; // 小程序secret

$code = $_POST['code'];

$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);

curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);

curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

if (!empty($data)) {

    curl_setopt($curl, CURLOPT_POST, 1);

    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

}

curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$output = curl_exec($curl);

curl_close($curl);

echo $output;



PHP-get_phone.php

<?php

function getPhone()

{

    $aesKey = base64_decode($_REQUEST['session_key']);

    $aesIV = base64_decode($_REQUEST['iv']);

    $aesCipher = base64_decode($_REQUEST['encryptedData']);


    $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

    return  $result;

}

$phone = getPhone();

echo $phone;


Copyright © 2024 镇江小蚂蚁信息科技有限公司 All Rights Reserved.