微信小程序登录接口

作者: wxfeng 分类: php 发布时间: 2022-04-23 09:08    阅读 257 次
/**
 * 用户接口
 */
class User extends Api
{
    protected $appid;
    protected $secret;
    protected $loginUrl;

    public function _initialize()
    {
        $this->appid    = 'appId';
        $this->secret   = 'secretId';
        $this->loginUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
        parent::_initialize();
    }
    /**
     * 用户登录
     * encryptedData,iv,code 前端传递
     */
    public function login()
    {
        $encryptedData = $this->request->post('encryptedData');
        $iv            = $this->request->post('iv');
        $code          = $this->request->post('code');
        if (!$code) {
            $this->error('code不能为空');
        }
        $item       = self::getOpenid($code);
        $sessionKey = $item['session_key'];
        $openid     = $item['openid'];
        if (empty($encryptedData) || empty($iv) || empty($sessionKey) || empty($openid)) {
            $this->error('缺少参数');
        }
        $errCode = self::decryptData($encryptedData, $iv, $data, $sessionKey, $this->appid);
        if ($errCode == 0) {
            $result = json_decode($data, true);

            $userinfo = \app\common\model\User::where(['openid' => $openid])->find();

            if ($userinfo) {
                $userinfo->nickname = $result['nickName'];
                $userinfo->avatar   = $result['avatarUrl'];
                $userinfo->gender   = $result['gender'];
                $userinfo->city     = $result['city'];
                $userinfo->province = $result['province'];
                $userinfo->country  = $result['country'];
                $userinfo->save();
                $this->auth->direct($userinfo['id']);
            } else {
                $user = new \app\common\model\User();
                $user->data([
                    'nickname' => $result['nickName'],
                    'avatar'   => $result['avatarUrl'],
                    'gender'   => $result['gender'],
                    'city'     => $result['city'],
                    'province' => $result['province'],
                    'country'  => $result['country'],
                    'status'   => 'normal',
                    'openid'   => $openid
                ]);
                $user->save();
                $this->auth->direct($user->id);
            }
            $this->success('登录成功', $this->auth->getUserinfo());
        } else {
            $this->error('登录失败' . $errCode);
        }
    }

    /**
     * @param $code 用来交换获取openid 跟 session_key
     */
    public function getOpenid($code)
    {
        $url      = sprintf($this->loginUrl, $this->appid, $this->secret, $code);
        $result   = Http::get($url);
        $wxResult = json_decode($result, true);
        if (empty($wxResult)) {
            $this->error('获取sessin_key及openID时异常');
        }
        if (isset($wxResult['errcode']) && $wxResult['errcode'] != 0) {
            $this->error($wxResult['errmsg']);
        }
        $item = [
            'openid'      => $wxResult['openid'],
            'session_key' => $wxResult['session_key']
        ];
        return $item;
    }

    /**
     * 获取手机号
     */
    public function getPhone()
    {
        $iv            = $this->request->post("iv", '', 'trim');
        $encryptedData = $this->request->post("encryptedData", '', 'trim');
        $sessionKey    = $this->request->post('sessionKey');
        $datainfo      = $this->auth->getUserinfo();
        if (!$iv || !$encryptedData) {
            $this->error('传参有误');
        }
        $errCode = self::decryptData($encryptedData, $iv, $data, $sessionKey, $this->appid);
        if ($errCode == 0) {
            $result = json_decode($data, true);
            if (isset($result['phoneNumber'])) {
                $user         = \app\admin\model\User::get($datainfo['id']);
                $user->mobile = $result['phoneNumber'];
                $user->save();
                $this->success('获取成功', $result);
            } else {
                $this->error('号码获取失败');
            }
        } else {
            $this->error('用户信息更新失败');
        }
    }

    /**
     * 检验数据的真实性,并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0,失败返回对应的错误码
     */
    public function decryptData($encryptedData, $iv, &$data, $sessionKey, $appid)
    {
        if (strlen($sessionKey) != 24) {
            return -41001;
        }
        $aesKey = base64_decode($sessionKey);


        if (strlen($iv) != 24) {
            return -41002;
        }
        $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 -41003;
        }
        if ($dataObj->watermark->appid != $appid) {
            return -41004;
        }
        $data = $result;
        return 0;
    }

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!

发表评论

您的电子邮箱地址不会被公开。