TP6前后端分离微信授权登录

第一步:让前端跳转到微信授权地址

https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxx&redirect_uri=xxx&response_type=code&scope=xxx&state=STATE#wechat_redirect
appid: 公众号的唯一标识,比如wxca78bba21a91b789;
 
redirect_uri: 页面授权后的回调页面,授权后重定向的回调链接地址, 请使用 urlEncode 对链接进行处理
 
比如: www.test.com/index,通过urlEncode处理后是www.test.com%2Findex;
 
scope: 应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )

接口:

    public function getCode($url)
    {
        $appid        = 'xxxxxxxxx';
        $redirect_uri = urldecode($url);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $appid . "&redirect_uri=" . $redirect_uri . "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
    }

第二步:前端获取到code传给后端获取用户信息

接口:


    public function getToken($code)
    {
        $config = [
            'app_id'        => 'xxx',
            'secret'        => 'xxxx',
            'response_type' => 'array',
        ];

        $app = Factory::officialAccount($config);

        $auth = $app->oauth->scopes(['snsapi_userinfo'])->getAccessToken($code);
        if (!empty($auth['openid'])) {
            $where = ['openid' => $auth['openid']];
            $user  = M_User::where($where)->find();
            if(!$user){
                $user = M_User::create(['openid'=>$auth['openid']]);
            }
            $token = (new Token)->signToken($user['id'], 476406973);
            $user->save(['token' => $token]);
            return [
                'token' => $token
            ];

        }
        return [];
    }

Pasa吴技术博客
请先登录后发表评论
  • latest comments
  • 总共0条评论