Yii2's OAuth extension and QQ login implementation method, yii2oauth

Source: Internet
Author: User
Tags openid

Yii2's OAuth extension and QQ login implementation method, yii2oauth

This article describes how to implement OAuth extension and QQ Internet login in yii2. We will share this with you for your reference. The details are as follows:
Copy codeThe Code is as follows: php composer. phar require -- prefer-dist yiisoft/yii2-authclient "*"

Quick start

Change the configuration file config/main. php of Yii2 and add the following content to 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, which is generally app/controllers/SiteController. php. Add code in function actions and add the callback function successCallback, which is 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 }}

Add the following code to the login Views:

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

The above is an official instruction document. Next we will connect to QQ

Add the QQ login component. I am here in common/components/QqOAuth. php. The source code is as follows:

<? Phpnamespace common \ components; use yii \ authclient \ oau2; use yii \ base \ Exception; use yii \ helpers \ Json ;/****~~~ * 'Components' => [* 'authclientcollect' => [* 'class' => 'yii \ authclient \ collect ', * '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 oau2{ public $ authUrl = 'https: // export 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 ('oss. 0/me ', 'get'); $ qquser = $ this-> api ("user/get_user_info", 'get ', ['oss _ 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 this extension seems to be unavailable for Qq interconnection, The method * @ see \ yii \ authclient \ BaseOAuth: processResponse () */protected function processResponse ($ rawResponse, $ contentType = self: CONTENT_TYPE_AUTO) should be rewritten here) {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 especially applicable to QQ Internet login, it is also different from the original method. if (strpo S ($ rawResponse, "callback ")! = False) {$ lpos = strpos ($ rawResponse, "("); $ rpos = strrpos ($ rawResponse, ")"); $ rawResponse = substr ($ rawResponse, $ lpos + 1, $ rpos-$ lpos-1); $ response = $ this-> processResponse ($ rawResponse, self: CONTENT_TYPE_JSON); break ;} // 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 :: decode ($ 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 and add it to components as follows:

'components' => [ 'authClientCollection' => [   'class' => 'yii\authclient\Collection',   'clients' => [     'qq' => [      'class'=>'common\components\QqOAuth',      'clientId'=>'your_qq_clientid',      'clientSecret'=>'your_qq_secret'    ],   ], ]]

SiteController. php is official.

Public function successCallback ($ client) {$ attributes = $ client-> getUserAttributes (); // The user information is in $ attributes, the following code is added based on your actual situation. // if you have a logon via QQ or Sina Weibo, you can use $ client-> id to differentiate between them .}

Add the QQ logon link to the logon View File.

<A href = "/site/auth? Authclient = qq "> use QQ to log on quickly </a>

PS: I recommend a php formatting and formatting typographical tool on this site to help you typeset code in future PHP programming:
 
Php code online formatting and beautification tools:Http://tools.jb51.net/code/phpformat

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.