• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

php微信小程序登陆完整流程

武飞扬头像
小吴-斌
帮助1

小程序登陆流程:
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;
}

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgfbkii
系列文章
更多 icon
同类精品
更多 icon
继续加载