search
HomeBackend DevelopmentPHP Tutorialphp QQ third-party login SDK program code_PHP tutorial

php QQ third-party login SDK program code_PHP tutorial

Jul 20, 2016 am 11:12 AM
phpsdkcodeofficialLoginofprogramthird partyOwn

I rewrote a PHP QQ third-party login SDK program code. The official one couldn’t praise it, so I wrote another one


Mainly because I considered that QQ’s PHP SDK was really poorly written. It was purely Popularize API knowledge, rather than ready-to-deploy class libraries. . Anyway, I’ve written one myself, so I’ll share it. .

Don’t say anything more, just go straight to the code.

Qq_sdk.php

The code is as follows Copy code
 代码如下 复制代码

/**

* QQ开发平台 SDK

* 作者:偶尔陶醉

* blog: www.stutostu.com

*/ 

 

class Qq_sdk{ 

 

//配置APP参数

private $app_id = 你的APP ID; 

private $app_secret = ‘你的APP_secret’; 

private $redirect = 你的回调地址;

 

function __construct() 

 

 

/**

* [get_access_token 获取access_token]

* @param [string] $code [登陆后返回的$_GET['code']]

* @return [array] [expires_in 为有效时间 , access_token 为授权码 ; 失败返回 error , error_description ]

*/ 

function get_access_token($code) 

//获取access_token

$token_url = ‘https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&’

. ‘client_id=’ . $this->app_id . ‘&redirect_uri=’ . urlencode($this->redirect)//回调地址

. ‘&client_secret=’ . $this->app_secret . ‘&code=’ . $code; 

$token = array(); 

//expires_in 为access_token 有效时间增量 

parse_str($this->_curl_get_content($token_url), $token); 

 

return $token; 

 

/**

* [get_open_id 获取用户唯一ID,openid]

* @param [string] $token [授权码]

* @return [array] [成功返回client_id 和 openid ;失败返回error 和 error_msg]

*/ 

function get_open_id($token) 

$str = $this->_curl_get_content(‘https://graph.qq.com/oauth2.0/me?access_token=’ . $token);

if (strpos($str, “callback”) !== false) 

$lpos = strpos($str, “(“); 

$rpos = strrpos($str, “)”); 

$str = substr($str, $lpos + 1, $rpos – $lpos -1); 

$user = json_decode($str, TRUE); 

 

return $user; 

 

/**

* [get_user_info 获取用户信息]

* @param [string] $token [授权码]

* @param [string] $open_id [用户唯一ID]

* @return [array] [ret:返回码,为0时成功。msg为错误信息,正确返回时为空。...params]

*/ 

function get_user_info($token, $open_id) 

 

//组装URL

$user_info_url = ‘https://graph.qq.com/user/get_use
r_info?’

. ‘access_token=’ . $token 

. ‘&oauth_consumer_key=’ . $this->app_id 

. ‘&openid=’ . $open_id 

. ‘&format=json’; 

 

$info = json_decode($this->_curl_get_content($user_info_url), TRUE); 

 

return $info; 

 

private function _curl_get_content($url) 

$ch = curl_init(); 

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 

curl_setopt($ch, CURLOPT_URL, $url); 

//设置超时时间为3s

curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 3); 

$result = curl_exec($ch); 

curl_close($ch); 

 

return $result; 

 

 

/* end of Qq_sdk.php */ 

 

 

/*** QQ Development Platform SDK* Author: Occasionally Intoxicated* blog: www.stutostu.com*/ class Qq_sdk{ //Configure APP parametersprivate $app_id = your APP ID; private $app_secret = 'Your APP_secret'; private $redirect = your callback address; function __construct() { } /*** [get_access_token Get access_token]* @param [string] $code [$_GET['code'] returned after login]* @return [array ] [expires_in is the validity time, access_token is the authorization code; error is returned on failure, error_description ]*/ function get_access_token($code) { //Get access_token$token_url = 'https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&'. ' client_id=' . $this->app_id . '&redirect_uri=' . urlencode($this->redirect)//Callback address. '&client_secret=' . $this->app_secret . '&code =' . $code; $token = array(); //expires_in is the access_token valid time increment parse_str($this->_curl_get_content($ token_url), $token); return $token; } /*** [get_open_id Get the user's unique ID, openid]* @param [string] $token [Authorization code]* @return [array] [Return client_id successfully and openid; failure returns error and error_msg]*/ function get_open_id($token) { $str = $this->_curl_get_content('https://graph.qq.com/oauth2.0/ me?access_token=' . $token);if (strpos($str, “callback”) !== false) { $lpos = strpos( $str, “(“); $rpos = strrpos($str, “)”); $str = substr($str, $lpos + 1, $rpos – $ lpos -1); } $user = json_decode($str, TRUE); return $user; } /*** [get_user_info Get user information]* @param [string] $token [Authorization code]* @param [string] $open_id [User’s unique ID] * @return [array] [ret: Return code, success when it is 0. msg is the error message and will be empty when returned correctly. ...params]*/ function get_user_info($token, $open_id) { //Assembly URL$user_info_url = 'https://graph.qq.com/user/get_user_info?'. 'access_token=' . $token . '&oauth_consumer_key=' . $this->app_id . '&openid=' . $open_id . '&format=json'; $info = json_decode($this->_curl_get_content($user_info_url), TRUE); return $info; } private function _curl_get_content($url) { $ch = curl_init(); curl_setopt($ ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_URL, $url); //Set the timeout to 3scurl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 3); $result = curl_exec($ch); curl_close($ch); return $result; } } /* end of Qq_sdk.php */

How to use: Place a hyperlink on your website, the address is: https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=your APP_ID&redirect_uri=your callback address

Just call my qq_sdk above on the callback address.

The demo is as follows:

The code is as follows
 代码如下 复制代码

 

if(empty($_GET['code'])) 

exit(‘参数非法’); 

 

include(‘qq_sdk’); 

$qq_sdk = new Qq_sdk(); 

$token = $qq_sdk->get_access_token($_GET['code']); 

print_r($token); 

 

$open_id = $qq_sdk->get_open_id($token['access_token']); 

print_r($open_id); 

 

 

$user_info = $qq_sdk->get_user_info($token['access_token'], $open_id['openid']); 

print_r($user_info); 

Copy code

if(empty($_GET['code']))

{ exit( 'Illegal parameter'); } include('qq_sdk'); $qq_sdk = new Qq_sdk(); $token = $qq_sdk->get_access_token($_GET['code']);
print_r($token);
$open_id = $qq_sdk ->get_open_id($token['access_token']); print_r($open_id); $user_info = $qq_sdk- >get_user_info($token['access_token'], $open_id['openid']); print_r($user_info); http://www.bkjia.com/PHPjc/444589.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/444589.htmlTechArticleA php QQ third-party login SDK program code that I rewrote. The official one couldn’t compliment it, so I wrote it myself. I made one mainly because QQ’s PHP SDK is really poorly written and is purely for popularization of AP...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools