当前位置:首页 > 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.  ... 

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

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

在登录的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.  public $authUrl = 'https://graph.qq.com/oauth2.0/authorize'
  31.  public $tokenUrl = 'https://graph.qq.com/oauth2.0/token'
  32.  public $apiBaseUrl = 'https://graph.qq.com'
  33.  public function init() 
  34.  { 
  35.  parent::init(); 
  36.  if ($this->scope === null) { 
  37.   $this->scope = implode(',', [ 
  38.   'get_user_info'
  39.   ]); 
  40.  } 
  41.  } 
  42.  protected function initUserAttributes() 
  43.  { 
  44.  $openid = $this->api('oauth2.0/me''GET'); 
  45.  $qquser = $this->api("user/get_user_info"'GET', ['oauth_consumer_key'=>$openid['client_id'], 'openid'=>$openid['openid']]); 
  46.  $qquser['openid']=$openid['openid']; 
  47.  return $qquser
  48.  } 
  49.  protected function defaultName() 
  50.  { 
  51.  return 'qq'
  52.  } 
  53.  protected function defaultTitle() 
  54.  { 
  55.  return 'Qq'
  56.  } 
  57.  /** 
  58.  * 该扩展初始的处理方法似乎QQ互联不能用,应此改写了方法 
  59.  * @see \yii\authclient\BaseOAuth::processResponse() 
  60.  */ 
  61.  protected function processResponse($rawResponse$contentType = self::CONTENT_TYPE_AUTO) 
  62.  { 
  63.    if (emptyempty($rawResponse)) { 
  64.      return []; 
  65.    } 
  66.    switch ($contentType) { 
  67.      case self::CONTENT_TYPE_AUTO: { 
  68.        $contentType = $this->determineContentTypeByRaw($rawResponse); 
  69.        if ($contentType == self::CONTENT_TYPE_AUTO) { 
  70.    //以下代码是特别针对QQ互联登录的,也是与原方法不一样的地方  
  71.          if(strpos($rawResponse"callback") !== false){ 
  72.            $lpos = strpos($rawResponse"("); 
  73.            $rpos = strrpos($rawResponse")"); 
  74.            $rawResponse = substr($rawResponse$lpos + 1, $rpos - $lpos -1); 
  75.            $response = $this->processResponse($rawResponse, self::CONTENT_TYPE_JSON); 
  76.            break
  77.          } 
  78.    //代码添加结束 
  79.          throw new Exception('Unable to determine response content type automatically.'); 
  80.        } 
  81.        $response = $this->processResponse($rawResponse$contentType); 
  82.        break
  83.      } 
  84.      case self::CONTENT_TYPE_JSON: { 
  85.        $response = Json::decode($rawResponse, true); 
  86.        if (isset($response['error'])) { 
  87.          throw new Exception('Response error: ' . $response['error']); 
  88.        } 
  89.        break
  90.      } 
  91.      case self::CONTENT_TYPE_URLENCODED: { 
  92.        $response = []; 
  93.        parse_str($rawResponse$response); 
  94.        break
  95.      } 
  96.      case self::CONTENT_TYPE_XML: { 
  97.        $response = $this->convertXmlToArray($rawResponse); 
  98.        break
  99.      } 
  100.      default: { 
  101.        throw new Exception('Unknown response type "' . $contentType . '".'); 
  102.      } 
  103.    } 
  104.    return $response
  105.  } 

更改 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.  ] 

SiteController.php 就按官方那样子

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

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

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

Tags: Yii2 OAuth

分享到: