Yii2 OAuth extension and QQ interconnection login Implementation method, yii2oauth_php tutorial

Source: Internet
Author: User
Tags getting started with php oauth openid smarty template yii

Yii2 OAuth extension and QQ interconnection login implementation method, Yii2oauth


In this paper, the implementation method of OAuth extension and QQ interconnection login in Yii2 is described. Share to everyone for your reference, as follows:
Copy the Code code as follows: PHP Composer.phar require--prefer-dist yiisoft/yii2-authclient "*"

Quick Start

To change the configuration file for Yii2 config/main.php, add the following to the components

' Components ' = [' authclientcollection ' and ' = ' class ' = ' yii\authclient\collection ', ' clients ' and ' = '  goo Gle ' = ' + ['  class ' = ' Yii\authclient\clients\googleopenid '  ],  ' Facebook ' + [  ' class ' = ' = ' Yii\authclient\clients\facebook ',  ' clientId ' = ' facebook_client_id ',  ' clientsecret ' = ' facebook_ ' Client_secret ',  ],], [...]

Changing the entry file, typically app/controllers/sitecontroller.php, increases the code in the function actions, while adding the callback function Successcallback, roughly as follows

Class Sitecontroller extends controller{public Function actions () {return [  ' auth ' = = [  ' class ' = ' = ' Yii\au Thclient\authaction ',  ' successcallback ' = [$this, ' Successcallback '],  ], '} public function Successcallback ($client) {$attributes = $client->getuserattributes ();//user login or signup comes here}}

In the login views, add the following code

<?= yii\authclient\widgets\authchoice::widget ([' Baseauthurl ' = [' Site/auth ']]?>

The above is the official documentation, below we come to connect QQ

Added QQ login Components I am here to put in the common/components/qqoauth.php, the source code is as follows

<?phpnamespace common\components;use yii\authclient\oauth2;use yii\base\exception;use yii\helpers\Json;/** * ~ ~ ~  * ' components ' + = [* ' authclientcollection ' + = [* ' class ' = ' yii\authclient\collection ', * ' clients ' = [ * ' QQ ' = [* ' class ' = ' Common\components\qqoauth ', * ' clientId ' = ' qq_client_id ', * ' Clientsecret ' =& Gt ' Qq_client_secret ', *], *], *] * ... * * ~ ~ ~ * @see http://connect.qq.com/* * @author Easypao * @since 2.0 */CL Qqoauth extends oauth2{public $authUrl = ' https://graph.qq.com/oauth2.0/authorize ', public $tokenUrl = ' Https://grap H.qq.com/oauth2.0/token '; Public $apiBaseUrl = ' https://graph.qq.com '; Public Function init () {parent::init (), if ($this->scope = = = null) {$this->scope = implode (', ', [' Get_user_info ',  ]); }} protected function Inituserattributes () {$openid = $this->api (' oauth2.0/me ', ' GET '); $qquser = $this->api ("User /get_user_info ", ' Get ', [' oauth_consumer_key ' = = $openid [' client_id'], ' OpenID ' = $openid [' OpenID ']]; $qquser [' OpenID ']= $openid [' OpenID ']; return $qquser; } protected function DefaultName () {return ' QQ ';} protected function Defaulttitle () {return ' QQ ';}/** * The initial processing method of the extension seems to be Q Q Interconnect can not be used, should this rewrite the method * @see \yii\authclient\baseoauth::p rocessresponse () */protected function ProcessResponse ($rawResponse   , $contentType = Self::content_type_auto) {if (empty ($rawResponse)) {return []; } switch ($contentType) {case Self::content_type_auto: {$contentType = $this->determinecontenttypebyraw ($       Rawresponse); if ($contentType = = Self::content_type_auto) {//The following code is specifically for the QQ Internet login, but also the original method is not the same place if (Strpos ($rawResponse, "Callbac           K ")!== false) {$lpos = Strpos ($rawResponse," (");           $rpos = Strrpos ($rawResponse, ")");           $rawResponse = substr ($rawResponse, $lpos + 1, $rpos-$lpos-1);           $response = $this->processresponse ($rawResponse, Self::content_type_json);         Break        }//Code add end throw new Exception (' Unable to determine response content type automatically. ');       } $response = $this->processresponse ($rawResponse, $contentType);     Break       } case Self::content_type_json: {$response = JSON::d ecode ($rawResponse, true);       if (Isset ($response [' Error '])) {throw new Exception (' Response error: '. $response [' ERROR ']);     } break;       } case self::content_type_urlencoded: {$response = [];       Parse_str ($rawResponse, $response);     Break       } case self::content_type_xml: {$response = $this->convertxmltoarray ($rawResponse);     Break } default: {Throw new Exception (' Unknown response type '. $contentType.   '".');     }   } return $response; }}

Changes to the config/main.php file, added in components, are outlined below

' Components ' = [' authclientcollection ' and ' = '   class ' = ' yii\authclient\collection ', ' clients ' and '   = ' [     ' qq ' = [      ' class ' = ' Common\components\qqoauth ',      ' clientId ' = ' your_qq_clientid ',      ' Clientsecret ' = ' Your_qq_secret '    ],   [],]

Sitecontroller.php just as the official.

Public Function Successcallback ($client) {$attributes = $client->getuserattributes ();//user's information in $attributes, The following is the code you add according to your actual situation//If you have QQ interconnection login, Sina Weibo, etc., can be distinguished by $client->id. }

Finally add the QQ login link in the login view file.

Use QQ Quick Login

PS: Small series here recommend a site of the PHP format of the beautification of the layout tools to help you in the future of PHP programming code layout:

PHP Code online format beautification tool:Http://tools.jb51.net/code/phpformat

For more information on YII related content readers can view this site topic: "YII framework Introduction and common skills Summary", "PHP Excellent Development Framework Summary", "Smarty Template Primer Basic Tutorial", "PHP date and Time usage summary", "PHP object-oriented Programming introduction Tutorial", " PHP String Usage Summary, "Getting Started with Php+mysql database operations" and "PHP Common Database Operations Skills Summary"

It is hoped that this article is helpful to the PHP program design based on YII framework.

http://www.bkjia.com/PHPjc/1127882.html www.bkjia.com true http://www.bkjia.com/PHPjc/1127882.html techarticle The implementation method of OAuth extension and QQ interconnection login in Yii2, Yii2oauth the implementation method of OAuth extension and QQ interconnection login in Yii2 in this paper. Share to everyone for your reference, as follows: Complex ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.