_php example of implementation method of OAuth extension and QQ interconnection login in Yii2

Source: Internet
Author: User
Tags auth oauth openid php programming smarty template yii

This article is an example of YII2 OAuth expansion and QQ Internet login implementation method. Share to everyone for your reference, specific as follows:

Copy Code code as follows:
PHP Composer.phar require--prefer-dist yiisoft/yii2-authclient "*"

Quick Start

Change the Yii2 profile config/main.php, add the following in components

' Components ' => ['
 authclientcollection ' => ['
 class ' => ' yii\authclient\collection ', ' clients '
 => ['
  Google ' => ['
  class ' => ' Yii\authclient\clients\googleopenid '
  ],
  ' Facebook ' => [
  ' class ' => ' Yii\authclient\clients\facebook ', '
  clientId ' => ' facebook_client_id ',
  ' Clientsecret ' => ' Facebook_client_secret ',],], ...
]

Change the entry file, typically app/controllers/sitecontroller.php, add code to the function actions, and increase the callback function Successcallback, roughly as follows

Class Sitecontroller extends Controller
{public
 function actions ()
 } {return
 [
  ' auth ' => [
  ' Class ' => ' yii\authclient\authaction ', '
  successcallback ' => [$this, ' Successcallback '],
  ]
 }
 Public Function Successcallback ($client)
 {
 $attributes = $client->getuserattributes ();
 User login or signup comes here
 }
}

In the views of the login, add the following code

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

Above is the official instruction document, below we will access QQ interconnection

Add QQ Login Components I am here in the common/components/qqoauth.php, the source code is as follows

<?php namespace 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 ' => ' Qq_client_secret ', *], *], *] * ~ ~ ~ ~ * * @see http://connect.qq.com/* * @author Easypao <admin@easypao.com> * @since 2.0/class Qqoauth extends OAuth2 {public $authUrl = ' https://g
 Raph.qq.com/oauth2.0/authorize ';
 Public $tokenUrl = ' Https://graph.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 of this extension seems to be that QQ interconnect can not be used, should this rewrite the method * @see \yii\authclient\baseoauth::p rocessresponse () * * protected function process
   Response ($rawResponse, $contentType = Self::content_type_auto) {if (empty ($rawResponse)) {return []; Switch ($contentType) {case Self::content_type_auto: {$contentType = $this->determinecontenttypebyra
       W ($rawResponse); if ($contentType = = Self::content_type_auto) {//The following code is specifically for QQ Internet login and is not the same place as the original method if (Strpos ($rawResponse, "callb
           Ack ")!== 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;

 }
}

Change the config/main.php file, add in components, roughly as follows

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


Sitecontroller.php, just like the crown.

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

Finally add the QQ login link in the login view file

<a href= "/SITE/AUTH?AUTHCLIENT=QQ" > Use QQ fast login </a>

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

PHP Code online Format Landscaping tool:Http://tools.jb51.net/code/phpformat

More about Yii related content readers can view the site topics: "Yii framework Introduction and common skills Summary", "PHP Excellent Development Framework Summary", "Smarty Template Primer Tutorial", "PHP date and Time usage summary", "PHP object-oriented Programming Program", " Summary of PHP string usage, Introduction to PHP+MYSQL database operations, and a summary of PHP common database operations Tips

I hope this article will help you with the PHP program design based on the YII framework.

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.