fastadmin的微信公众号授权登录(踩坑!!!)

话不多说,直接上代码,仅限于fastadmin使用,其他的可能需要修改一下 


/**
     * @ApiTitle    (微信登录)
     * @ApiMethod   (POST)
     * @ApiParams   (name="code", type="string", required=true, description="微信code")
     */
    public function wxLogin()
    {
        $rules = [
            'code' => 'require',
        ];
        $message = [
            'code.require' => 'code不能为空',
        ];

        $validate = new \think\Validate($rules, $message);
        $param = $this->request->param();
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }

            $config = \addons\wechat\library\Config::load();

            
            $tokenResult = $this->getMpAccessTokenAndOpenid($param['code'], $config['app_id'], $config['secret']);
    
            if (!$tokenResult || !isset($tokenResult['access_token'], $tokenResult['openid'])) {
                $this->error("微信公众号登录失败");
            }
    
            $access_token = $tokenResult['access_token'];
            $openid = $tokenResult['openid'];
            $unionid = isset($tokenResult['unionid']) ? $tokenResult['unionid'] : '';
    
            $userInfo = $this->getUserInfoFromWeixin($access_token, $openid);
    
            $data = [
                'openid' => $openid,
                'unionid' => $unionid,
                'userinfo' => [
                    'nickname' => $userInfo['nickname'] ?? '默认昵称',
                    'avatar' => $userInfo['headimgurl'] ?? '',
                    'unionid' => $unionid,
                ],
                'access_token' => $access_token,
                'refresh_token' => '',
                'expires_in' => 0,
            ];
    
            $extend = ['group_id' => 1, 'gender' => '1', 'is_third' => 1, 'openid' => $openid];
            $ret = Service::connect('mp', $data, $extend);
    
            if ($ret) {
                $auth = Auth::instance();
                $this->success("登录成功", ['userInfo' => $auth->getUserinfo(), 'sessionKey' => $tokenResult]);
            } else {
                $this->error("连接失败");
            }
    }
    

    private function getMpAccessTokenAndOpenid($code, $appId, $appSecret)
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appId}&secret={$appSecret}&code={$code}&grant_type=authorization_code";
        $res = $this->httpRequest($url,'get');
        return json_decode($res, true);
    }
    

    private function getUserInfoFromWeixin($access_token, $openid)
    {
        $userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
        $userInfoResponse = $this->httpRequest($userInfoUrl,'get');
        return json_decode($userInfoResponse, true);
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值