当前位置:首页 > CMS教程 > 其它CMS > 列表

Yii2中OAuth扩展及QQ互联登录实现方法

发布:smiling 来源: PHP粉丝网  添加日期:2021-08-06 10:19:27 浏览: 评论:0 

这篇文章主要介绍了Yii2中OAuth扩展及QQ互联登录的方法,实例分析了OAuth扩展的相关配置与QQ互联登陆的实现技巧,需要的朋友可以参考下。

本文实例讲述了Yii2中OAuth扩展及QQ互联登录实现方法,分享给大家供大家参考,具体如下:

php composer.phar require --prefer-dist yiisoft/yii2-authclient "*"

Quick start 快速开始

更改Yii2的配置文件config/main.php,在components中增加如下内容

  1. 'components' => [ 
  2.  'authClientCollection' => [ 
  3.  'class' => 'yii\authclient\Collection', 
  4.  'clients' => [ 
  5.   'google' => [ 
  6.   'class' => 'yii\authclient\clients\GoogleOpenId' 
  7.   ], 
  8.   'facebook' => [ 
  9.   'class' => 'yii\authclient\clients\Facebook', 
  10.   'clientId' => 'facebook_client_id', 
  11.   'clientSecret' => 'facebook_client_secret', 
  12.   ], 
  13.  ], 
  14.  ] 
  15.  ... 
  16. ] 

更改入口文件,一般是app/controllers/SiteController.php,在function actions增加代码,同时增加回调函数successCallback,大致如下

  1. class SiteController extends Controller 
  2. { 
  3.  public function actions() 
  4.  { 
  5.  return [ 
  6.   'auth' => [ 
  7.   'class' => 'yii\authclient\AuthAction', 
  8.   'successCallback' => [$this, 'successCallback'], 
  9.   ], 
  10.  ] 
  11.  } 
  12.  public function successCallback($client) 
  13.  { 
  14.  $attributes = $client->getUserAttributes(); 
  15.  // user login or signup comes here 
  16.  } 
  17. } 

在登录的Views中,增加如下代码:

  1. <?= yii\authclient\widgets\AuthChoice::widget([ 
  2.  'baseAuthUrl' => ['site/auth'] 
  3. ])?> 

以上是官方的说明文档,下面我们来接入QQ互联

增加QQ登录的组件 我这里是放在 common/components/QqOAuth.php 中,源代码如下

  1. <?php 
  2. namespace common\components; 
  3. use yii\authclient\OAuth2; 
  4. use yii\base\Exception; 
  5. use yii\helpers\Json; 
  6. /** 
  7.  * 
  8.  * ~~~ 
  9.  * 'components' => [ 
  10.  * 'authClientCollection' => [ 
  11.  *  'class' => 'yii\authclient\Collection', 
  12.  *  'clients' => [ 
  13.  *  'qq' => [ 
  14.  *   'class' => 'common\components\QqOAuth', 
  15.  *   'clientId' => 'qq_client_id', 
  16.  *   'clientSecret' => 'qq_client_secret', 
  17.  *  ], 
  18.  *  ], 
  19.  * ] 
  20.  * ... 
  21.  * ] 
  22.  * ~~~ 
  23.  * 
  24.  * @see http://connect.qq.com/ 
  25.  * 
  26.  * @author easypao <admin@easypao.com> 
  27.  * @since 2.0 
  28.  */ 
  29. class QqOAuth extends OAuth2 
  30. { 
  31.  public $authUrl = 'https://graph.qq.com/oauth2.0/authorize'; 
  32.  public $tokenUrl = 'https://graph.qq.com/oauth2.0/token'; 
  33.  public $apiBaseUrl = 'https://graph.qq.com'; 
  34.  public function init() 
  35.  { 
  36.  parent::init(); 
  37.  if ($this->scope === null) { 
  38.   $this->scope = implode(',', [ 
  39.   'get_user_info', 
  40.   ]); 
  41.  } 
  42.  } 
  43.  protected function initUserAttributes() 
  44.  { 
  45.  $openid = $this->api('oauth2.0/me', 'GET'); 
  46.  $qquser = $this->api("user/get_user_info", 'GET', ['oauth_consumer_key'=>$openid['client_id'], 'openid'=>$openid['openid']]); 
  47.  $qquser['openid']=$openid['openid']; 
  48.  return $qquser; 
  49.  } 
  50.  protected function defaultName() 
  51.  { 
  52.  return 'qq'; 
  53.  } 
  54.  protected function defaultTitle() 
  55.  { 
  56.  return 'Qq'; 
  57.  } 
  58.  /** 
  59.  * 该扩展初始的处理方法似乎QQ互联不能用,应此改写了方法 
  60.  * @see \yii\authclient\BaseOAuth::processResponse() 
  61.  */ 
  62.  protected function processResponse($rawResponse, $contentType = self::CONTENT_TYPE_AUTO) 
  63.  { 
  64.    if (emptyempty($rawResponse)) { 
  65.      return []; 
  66.    } 
  67.    switch ($contentType) { 
  68.      case self::CONTENT_TYPE_AUTO: { 
  69.        $contentType = $this->determineContentTypeByRaw($rawResponse); 
  70.        if ($contentType == self::CONTENT_TYPE_AUTO) { 
  71.    //以下代码是特别针对QQ互联登录的,也是与原方法不一样的地方  
  72.          if(strpos($rawResponse, "callback") !== false){ 
  73.            $lpos = strpos($rawResponse, "("); 
  74.            $rpos = strrpos($rawResponse, ")"); 
  75.            $rawResponse = substr($rawResponse, $lpos + 1, $rpos - $lpos -1); 
  76.            $response = $this->processResponse($rawResponse, self::CONTENT_TYPE_JSON); 
  77.            break; 
  78.          } 
  79.    //代码添加结束 
  80.          throw new Exception('Unable to determine response content type automatically.'); 
  81.        } 
  82.        $response = $this->processResponse($rawResponse, $contentType); 
  83.        break; 
  84.      } 
  85.      case self::CONTENT_TYPE_JSON: { 
  86.        $response = Json::decode($rawResponse, true); 
  87.        if (isset($response['error'])) { 
  88.          throw new Exception('Response error: ' . $response['error']); 
  89.        } 
  90.        break; 
  91.      } 
  92.      case self::CONTENT_TYPE_URLENCODED: { 
  93.        $response = []; 
  94.        parse_str($rawResponse, $response); 
  95.        break; 
  96.      } 
  97.      case self::CONTENT_TYPE_XML: { 
  98.        $response = $this->convertXmlToArray($rawResponse); 
  99.        break; 
  100.      } 
  101.      default: { 
  102.        throw new Exception('Unknown response type "' . $contentType . '".'); 
  103.      } 
  104.    } 
  105.    return $response; 
  106.  } 
  107. } 

更改 config/main.php 文件,在components中增加,大致如下

  1. 'components' => [ 
  2.  'authClientCollection' => [ 
  3.    'class' => 'yii\authclient\Collection', 
  4.    'clients' => [ 
  5.      'qq' => [ 
  6.       'class'=>'common\components\QqOAuth', 
  7.       'clientId'=>'your_qq_clientid', 
  8.       'clientSecret'=>'your_qq_secret' 
  9.     ], 
  10.    ], 
  11.  ] 
  12. ] 

SiteController.php 就按官方那样子

  1. public function successCallback($client) 
  2. { 
  3.  $attributes = $client->getUserAttributes(); 
  4.  // 用户的信息在$attributes中,以下是您根据您的实际情况增加的代码 
  5.  // 如果您同时有QQ互联登录,新浪微博等,可以通过 $client->id 来区别。 
  6. } 

最后在登录的视图文件中 增加QQ登录链接

<a href="/site/auth?authclient=qq">使用QQ快速登录</a>

Tags: Yii2 OAuth

分享到: