当前位置:网站首页>Wechat authorization to obtain mobile phone number

Wechat authorization to obtain mobile phone number

2022-06-11 12:07:00 Zhangu gooyuit

<button class="u-reset-button bindPhone" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber"> To bind </button>
//kunga Get your phone number 
decryptPhoneNumber(e){
   var that = this;
   uni.showLoading({
      title: ' Loading ...',
      mark: true
   });
   uni.login({
      success: function(info) {
         let jsCode = info.code;
         uni.request({
            method: 'POST',
            url: BASE_URL + '/index/index/update_phone',
            data: {
               jsCode: jsCode,
               encryptedData: e.detail.encryptedData,
               iv: e.detail.iv,
               user_id:uni.getStorageSync('user_id')
            },
            success: (res) => {
               uni.hideLoading();
               if(res.data.code == 200){
                  uni.showToast({
                     title: ' The update is successful !',
                     duration: 2000
                  });
               }
            }
         });
      }
   })


},

php

<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use service\JsonService;

include_once "wxBizDataCrypt.php";
class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    

    public function update_phone()
    {
        $code   =   input('jsCode');
        $encryptedData   =   input('encryptedData');
        $iv   =  input('iv');
        $user_id   =  input('user_id');
        // Applet development account 
        $appid  =  "********" ;
        $secret =   "********";
        $URL = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
        $apiData=file_get_contents($URL);
        if(!isset(json_decode($apiData)->errcode))
        {
            $sessionKey = json_decode($apiData)->session_key;
            $info = new \WXBizDataCrypt($appid, $sessionKey);
            $errCode = $info->decryptData($encryptedData, $iv, $data );
            if ($errCode == 0 && !empty($user_id))
            {
                $phone = json_decode($data)->phoneNumber;
                db("user")->where('id', $user_id)->update(['mobile' => $phone]);
                $data_res['phone'] = $phone;
                return JsonService::successful($data_res);
            }
            else {
                return JsonService::fail($errCode);
            }
        }
    }


}

wxBizDataCrypt.php File download separately

<?php

/**
 *  Example code for decrypting encrypted data of wechat applet users .
 *
 * @copyright Copyright (c) 1998-2014 Tencent Inc.
 */


include_once "errorCode.php";


class WXBizDataCrypt
{
    private $appid;
   private $sessionKey;

   /**
    *  Constructors 
    * @param $sessionKey string  The session key obtained by the user after the applet logs in 
    * @param $appid string  Applet appid
    */
   public function __construct( $appid, $sessionKey)
   {
      $this->sessionKey = $sessionKey;
      $this->appid = $appid;
   }


   /**
    *  Check the authenticity of the data , And get the decrypted plaintext .
    * @param $encryptedData string  Encrypted user data 
    * @param $iv string  The initial vector returned with the user data 
    * @param $data string  The original text after decryption 
     *
    * @return int  success 0, Failure returns the corresponding error code 
    */
   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;
   }

}

<?php

/**
 * error code  explain .
 * <ul>

 *    <li>-41001: encodingAesKey  illegal </li>
 *    <li>-41003: aes  Decryption failed </li>
 *    <li>-41004:  After decryption buffer illegal </li>
 *    <li>-41005: base64 Encryption failed </li>
 *    <li>-41016: base64 Decryption failed </li>
 * </ul>
 */
class ErrorCode
{
   public static $OK = 0;
   public static $IllegalAesKey = -41001;
   public static $IllegalIv = -41002;
   public static $IllegalBuffer = -41003;
   public static $DecodeBase64Error = -41004;
}

?>
原网站

版权声明
本文为[Zhangu gooyuit]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111157046995.html