╃巡洋艦㊣ 2016-09-03 18:17:33 20816次浏览 24条评论 95 25 0

我们社区在 yii2-authclient 多次升级后,登录异常。一直想寻求一种通用的方法,尽量不重写 OAuth2, BaseOAuth 以及 OAuthToken 类, 所以本次直接在 initUserAttributes 方法返回结果的地方去修改,这样会受 yii2-authclient 升级影响较小,我把 QQClient.phpWeiboClient.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 '微博登录';
    }
}
觉得很赞
您需要登录后才可以评论。登录 | 立即注册