Yii2 使用 QQ 和 Weibo 第三方登錄源碼

我們社區在 yii2-authclient 多次升級後,登錄異常。一直想尋求一種通用的方法,儘量不重寫 OAuth2, BaseOAuth 以及 OAuthToken 類, 所以本次直接在 initUserAttributes 方法返回結果的地方去修改,這樣會受 yii2-authclient 升級影響較小,我把 QQClient.php 和 WeiboClient.php 放在 frontend/widgets 下了,接下來我們來看代碼!

QQClient.php

<?php

namespace frontend\widgets;

use yii\authclient\OAuth2;
use yii\web\HttpException;
use Yii;

class QQClient extends OAuth2
{
    public $authUrl = 'https://graph.qq.com/oauth2.0/authorize';

    public $tokenUrl = 'https://graph.qq.com/oauth2.0/token';

    public $apiBaseUrl = 'https://graph.qq.com';


    protected function initUserAttributes()
    {
        $user = $this->api('user/get_user_info', 'GET', ['oauth_consumer_key' => $this->user->client_id, 'openid' => $this->user->openid]);

        return [
            'client' => 'qq',
            'openid' => $this->user->openid,
            'nickname' => $user['nickname'],
            'gender' => $user['gender'],
            'location' => $user['province'] . $user['city'],
        ];
    }

    /**
     * @inheritdoc
     */
    protected function getUser()
    {
        $str = file_get_contents('https://graph.qq.com/oauth2.0/me?access_token=' . $this->accessToken->token);

        if (strpos($str, "callback") !== false) {
            $lpos = strpos($str, "(");
            $rpos = strrpos($str, ")");
            $str = substr($str, $lpos + 1, $rpos - $lpos -1);
        }

        return json_decode($str);
    }

    /**
     * @inheritdoc
     */
    protected function defaultName()
    {
        return 'QQ';
    }

    /**
     * @inheritdoc
     */
    protected function defaultTitle()
    {
        return 'QQ 登錄';
    }
}

WeiboClient.php

?php

namespace frontend\widgets;

use yii\authclient\OAuth2;
use yii\web\HttpException;
use Yii;

class WeiboClient extends OAuth2
{
    public $authUrl = 'https://api.weibo.com/oauth2/authorize';

    public $tokenUrl = 'https://api.weibo.com/oauth2/access_token';

    public $apiBaseUrl = 'https://api.weibo.com/2';

    protected function initUserAttributes()
    {
        $user = $this->api('users/show.json', 'GET', ['uid' => $this->user->uid]);

        return [
            'client' => 'weibo',
            'openid' => $user['id'],
            'nickname' => $user['name'],
            'gender' => $user['gender'],
            'location' => $user['location'],
        ];
    }


    /**
     * @inheritdoc
     */
    protected function getUser()
    {
        $str = file_get_contents('https://api.weibo.com/2/account/get_uid.json?access_token=' . $this->accessToken->token);
        return json_decode($str);
    }

    /**
     * @inheritdoc
     */
    protected function defaultName()
    {
        return 'Weibo';
    }

    /**
     * @inheritdoc
     */
    protected function defaultTitle()
    {
        return '微博登錄';
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章