天天看點

php微信小程式登陸完整流程

小程式登陸流程:

1、使用wx.login 擷取code,

2、使用wx.getUserInfo 擷取使用者資訊,然後上傳到服務端,

3、服務端在通過codee擷取access_token,openid 或 unionid

4、根據wx.getUserInfo 上傳encryptdata 和 iv 解密獲得使用者的基本資訊

5、執行注冊流程傳回注冊資訊

小程式端代碼

// 登入
    wx.login({
      success: res => {
        console.log(res.code)
        // 擷取使用者資訊
        wx.getUserInfo({
          success: rs => {
            console.log(rs)
            // 發送 res.code 到背景換取 openId, sessionKey, unionId
            wx.request({
              url: 'http://api.****.com/v1/login/wx_login', 
              method:"POST",
              data: {
                code: res.code, iv: rs.iv, encryptdata: rs.encryptedData
              },
              header: {
                'content-type': 'application/json' // 預設值
              },
              success(res) {
                console.log(res.data)
              }
            })
          }
        })
      },
    })
           

php服務端代碼

/**
     * 微信登陸
     * @Author wzb
     * @Date 2022/9/7 21:16
     */
    function wx_login()
    {
        $encryptdata = input('encryptdata', '', 'strip_tags,trim');
        $iv = input('iv', '', 'strip_tags,trim');
        $code = input('code', '', 'strip_tags,trim');
        if (empty($code) || !$encryptdata || !$iv) {
            $this->ThrowExcption('請求資料不能為空');
        }

        $appId = config('wx_appid');
        $secret = config('wx_secret');
        // 根據拿的code來拿access_token
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appId}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        $return = $this->https_request($url);
        $jsonrt = json_decode($return, true);
        if (isset($jsonrt['errcode'])) {
            $this->ThrowExcption("微信授權發生錯誤:{$jsonrt['errmsg']},錯誤代碼:" . $jsonrt['errcode']);
        }
		// 文檔 https://developers.weixin.qq.com/miniprogram/dev/framework/plugin/functional-pages/user-info.html
        $sessionKey = $jsonrt['session_key'] ?? '';
		// 根據encryptdata 和 iv 解密獲得使用者的基本資訊
        $pc = new WxBizDataCrypt($appId, $sessionKey);
        $errCode = $pc->decryptData($encryptdata, $iv, $data);
        if ($errCode != 0) {
            $this->ThrowExcption("資料解析錯誤,代碼:" . $errCode);
        }
        $userInfo = json_decode($data);
//        $unionid = $userInfo->unionId;
        $openid = $userInfo->openId;
        $avatar = $userInfo->avatarUrl;
        $nickname = $userInfo->nickName;
        $data = [];
        $data['sex'] = max(0, intval($userInfo->gender)); // 使用者的性别,值為 1 時是男性,值為 2 時是女性,值為 0 時是未知
        $data = [
            'nickname' => $nickname, 'avatar' => $avatar, 'openid' => $openid
        ];
		// 業務代碼 
        $data['uid'] = $uid; 
        $this->successReturn($data);
    }

    function https_request($url, $data = null)
    {
        $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);
        return $output;
    }
           

解密類

目錄 my
  1. WXBizDataCrypt.php 檔案
<?php


namespace my;


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;
    }
}


/**
 * 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;
}