微信小程序獲取手機號


 

 







wxml 代碼:
<!-- 授權 --> <button type="primary" open-type="getUserInfo" bind:tap="getUserProfile">授權登錄</button> <!-- 獲取用戶手機號 --> <button open-type="getPhoneNumber" bindgetphonenumber="getphone">獲取手機號</button> <!-- 展示手機號 --> <view>您的手機號:{{phone}}</view>

 

 wxjs:代碼

// 授權登錄
  getUserProfile(e) {
    // 獲取用戶信息
    wx.getUserProfile({
      desc: '用於完善會員資料', // 聲明獲取用戶個人信息后的用途,后續會展示在彈窗中,請謹慎填寫
      success: (res) => {
        // 頭像
       let avatarUrl=res.userInfo.avatarUrl;
      //  昵稱
       let nickName=res.userInfo.nickName;
       wx.login({
        success:res=>{
          //  獲取code
        let code=res.code;
          wx.request({
          url: 'http://www.yan.com/api/xcx/getLogin',
          data: {
            code:code,
            avatarUrl:avatarUrl,
            nickName:nickName,
          },
          method:"POST",
          header: {
            'content-type': 'application/json' // 默認值
          },
      // 數據返回json格式
          success (res) {
            console.log(res);
              // 存儲openid 用戶獲取手機號
              wx.setStorageSync('openid', res.data.data.openid );
              // 存儲session_key用於獲取手機號
              wx.setStorageSync('sessionKey', res.data.data.sessionKey);
                // 存儲用戶id
                wx.setStorageSync('userid',res.data.data.uid);
            }
      })

      }
        })
        }
      })
  },

將用戶信息發送后台

/*獲取用戶信息的路由*/
Route::post('xcx/getLogin','xcx\LoginController@getLogin');

控制器代碼:

    public function  getLogin(Request $request){
//        接受code
        $code=$request->post('code');
//        接受頭像
        $avatarUrl=$request->post('avatarUrl');
//        接受昵稱
        $nickName=$request->post('nickName');
//        獲取appid
        $appid = "wx64832aa6eaea82b0";
        // 從微信公眾平台獲得secret
        $secret = "95e2acaf355dbcb443f5cd4748a152ed";
        // 發送請求換取openid和sessionkey
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=" . $code. "&grant_type=authorization_code";
        // 暫使用file_get_contents()發送請求,你可以使用CURL擴展的形式實現,獲取opid和session_key
        $res = json_decode(file_get_contents($url), true);
//        給$params追加openid
        $params['openid'] = $res['openid'];
        //  給$params追加session_key
        $params['sessionKey'] = $res['session_key'];
//        查看數據庫里是否有openid,有就修改,沒有就添加
        $user = Wxuser::where('openid', $params['openid'])->first();
        $params['uid']=$user['id'];
//        有就修改用戶的額openID
        if ($user) {
//            將sessionKey 發送至小程序緩沖用於獲取手機號
             Wxuser::where('openid', $params['openid'])->update(['sessionKey'=>$params['sessionKey']]);
            return ['code' => 201, 'meg' => '修改成功', 'data' =>  $params];
        } else {
//           沒有就添加新用戶
            $add = Wxuser::create($params);
            return ['code' => 200, 'meg' => '添加成功', 'data' => $res];
        }

    }

小程序點擊獲取手機號按鈕

 

 

<!-- 獲取用戶手機號 -->
<button  type="primary" open-type="getPhoneNumber" bindgetphonenumber="getphone">獲取手機號</button>

wx.js代碼

需要將 button 組件 open-type 的值設置為 getPhoneNumber,當用戶點擊並同意之后,可以通過 bindgetphonenumber 事件回調獲取到微信服務器返回的加密數據, 然后在第三方服務端結合 session_key 以及 app_id 進行解密獲取手機號。

  // 獲取手機號
      getphone(e){
        // open-type="getPhoneNumber" bindgetphonenumber="getphone" 獲取encryptedData
      var encryptedData =e.detail.encryptedData;
      var iv =e.detail.iv;
       // 取出授權登錄的openid
      let openid= wx.getStorageSync('openid')
      // 取出授權登錄的sessionKey
      let sessionKey= wx.getStorageSync('sessionKey')
    // 取出用戶id
      var userid= wx.getStorageSync('userid')
      wx.request({
        url: 'http://www.yan.com/api/xcx/send',
        data: {
          encryptedData:encryptedData,
          iv:iv,
          openid:openid,
          sessionKey:sessionKey,
          userid:userid
        },
        method:"POST",
        header: {
          'content-type': 'application/json' // 默認值
        },
        // 數據返回json格式
            success :res=> {
              console.log(res);
            if (res) {
              this.setData({
                phone:res.data.data
              })
            }
            }


        
      })
      }
  

laravel 路由

/*獲取手機號*/
Route::post('xcx/send','xcx\LoginController@send');

laravel控制器

//獲取手機號
public function send(Request $request){
    $encryptedData = $request->post('encryptedData');
    $iv = $request->post('iv');
    $sessionKey = $request->post('sessionKey');
    $id=$request->post('userid');
    $appid = 'wx64832aa6eaea82b0';
    $pc = new WXBizDataCrypt($appid, $sessionKey);
    $errCode = $pc->decryptData($encryptedData, $iv, $data );
    if ($errCode == 0) {
        $phone = json_decode($data, true)['phoneNumber'];
        //根據用戶id 將手機號添加到數據表里面
        Wxuser::where('id','=',$id)->update(['phone' => $phone]);
        return ['code' => 200, 'meg' => 'success', 'data' => $phone];
    } else {
        return ['code' => 500, 'meg' => 'error', 'data' => $errCode];
    }
    

模型代碼

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Wxuser extends Model
{
    //
    protected $guarded=[];
    public $timestamps=false;
}

解密官方文檔:

https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html

 

 

下載php

 

 將文件放入開發的項目中,並修改文件名稱和修改命名空間

 

 

 

 

 

 

demo.php

<?php
namespace App\Service\PHP;
use  App\Service\PHP\wxBizDataCrypt;
//include_once "WXBizDataCrypt.php";


$appid = 'wx4f4bc4dec97d474b';
$sessionKey = 'tiihtNczf5v6AKRyjwEUhQ==';

$encryptedData="CiyLU1Aw2KjvrjMdj8YKliAjtP4gsMZM
                QmRzooG2xrDcvSnxIMXFufNstNGTyaGS
                9uT5geRa0W4oTOb1WT7fJlAC+oNPdbB+
                3hVbJSRgv+4lGOETKUQz6OYStslQ142d
                NCuabNPGBzlooOmB231qMM85d2/fV6Ch
                evvXvQP8Hkue1poOFtnEtpyxVLW1zAo6
                /1Xx1COxFvrc2d7UL/lmHInNlxuacJXw
                u0fjpXfz/YqYzBIBzD6WUfTIF9GRHpOn
                /Hz7saL8xz+W//FRAUid1OksQaQx4CMs
                8LOddcQhULW4ucetDf96JcR3g0gfRK4P
                C7E/r7Z6xNrXd2UIeorGj5Ef7b1pJAYB
                6Y5anaHqZ9J6nKEBvB4DnNLIVWSgARns
                /8wR2SiRS7MNACwTyrGvt9ts8p12PKFd
                lqYTopNHR1Vf7XjfhQlVsAJdNiKdYmYV
                oKlaRv85IfVunYzO0IKXsyl7JCUjCpoG
                20f0a04COwfneQAGGwd5oa+T8yO5hzuy
                Db/XcxxmK01EpqOyuxINew==";

$iv = 'r7BXXKkLb8qrSNn05n0qiA==';

$pc = new WXBizDataCrypt($appid, $sessionKey);
$errCode = $pc->decryptData($encryptedData, $iv, $data );

if ($errCode == 0) {
    print($data . "\n");
} else {
    print($errCode . "\n");
}
ErrorCode.php
<?php
namespace App\Service\PHP;
/**
 * error code 說明.
 * <ul>

 *    <li>-41001: encodingAesKey 非法</li>
 *    <li>-41003: aes 解密失敗</li>
 *    <li>-41004: 解密后得到的buffer非法</li>
 *    <li>-41005: base64加密失敗</li>
 *    <li>-41016: base64解密失敗</li>
 * </ul>
 */
class ErrorCode
{
    public static $OK = 0;
    public static $IllegalAesKey = -41001;
    public static $IllegalIv = -41002;
    public static $IllegalBuffer = -41003;
    public static $DecodeBase64Error = -41004;
}

?>
WXBizDataCrypt.php
<?php

namespace App\Service\PHP;
use App\Service\PHP\errorCode;

class WXBizDataCrypt
{
    private $appid;
    private $sessionKey;
    /**
     * 構造函數
     * @param $sessionKey string 用戶在小程序登錄后獲取的會話密鑰
     * @param $appid string 小程序的appid
     */
    public function __construct( $appid, $sessionKey)
    {
        $this->sessionKey = $sessionKey;
        $this->appid = $appid;
    }


    /**
     * 檢驗數據的真實性,並且獲取解密后的明文.
     * @param $encryptedData string 加密的用戶數據
     * @param $iv string 與用戶數據一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0,失敗返回對應的錯誤碼
     */
    public function decryptData( $encryptedData, $iv, &$data )
    {
        if (strlen($this->sessionKey) != 24) {
            return ErrorCode::$IllegalAesKey;
        }
        $aesKey=base64_decode($this->sessionKey);


        if (strlen($iv) != 24) {
            return ErrorCode::$IllegalIv;
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

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

        $dataObj=json_decode( $result );
        if( $dataObj  == NULL )
        {
            return ErrorCode::$IllegalBuffer;
        }
        if( $dataObj->watermark->appid != $this->appid )
        {
            return ErrorCode::$IllegalBuffer;
        }
        $data = $result;
        return ErrorCode::$OK;
    }

}

tp框架獲取手機號的代碼,參看以下鏈接

https://blog.csdn.net/guanj0623/article/details/121139157?spm=1001.2014.3001.5501

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM