search
HomeBackend DevelopmentPHP TutorialQQ login PHP OAuth sample code_PHP tutorial

QQ login PHP OAuth sample code_PHP tutorial

Jul 21, 2016 pm 03:26 PM
httpoauthphpcodecopyofficialdocumentApplyLog inExamplewrite

Written according to official documents

Copy code The code is as follows:

/**
* Apply http://connect.opensns.qq.com/apply
* List http://connect.opensns.qq.com/my
*/
session_start();
$qq_oauth_config = array(
'oauth_consumer_key'=>'*******',//APP ID
'oauth_consumer_secret'=>'******************',//APP KEY
'oauth_callback'=>"http://www.955.cc/qq.php?action=reg",//这里修改为当前脚本,但是要保留?action=reg
'oauth_request_token_url'=>"http://openapi.qzone.qq.com/oauth/qzoneoauth_request_token",
'oauth_authorize_url'=>'http://openapi.qzone.qq.com/oauth/qzoneoauth_authorize',
'oauth_request_access_token_url'=>'http://openapi.qzone.qq.com/oauth/qzoneoauth_access_token',
'user_info_url' => 'http://openapi.qzone.qq.com/user/get_user_info',
);
$action = isset($_GET['action']) ? $_GET['action'] : '';
$qq = new qq_oauth($qq_oauth_config);
switch($action){
//用户登录 Step1:请求临时token
case 'login':
$token = $qq->oauth_request_token();
$_SESSION['oauth_token_secret'] = $token['oauth_token_secret'];
$qq->authorize($token['oauth_token']);
break;
//Step4:Qzone引导用户跳转到第三方应用
case 'reg':
$qq->register_user();
$access_token = $qq->request_access_token();
if($token = $qq->save_access_token($access_token)){
//保存,一般发给用户cookie,以及用户入库
//var_dump($token);
$_SESSION['oauth_token'] = $token['oauth_token'];
$_SESSION['oauth_token_secret'] = $token['oauth_token_secret'];
$_SESSION['openid'] = $token['openid'];
header('Content-Type: text/html; charset=utf-8');
$user_info = json_decode($qq->get_user_info());
if($user_info->ret!=0){
exit("获取头像昵称时发生错误".$user_info->msg);
} else {
echo 'QQ昵称:',$user_info->nickname,
'QQ login PHP OAuth sample code_PHP tutorialfigureurl,'" />',
'QQ login PHP OAuth sample code_PHP tutorialfigureurl_1,'" />',
'QQ login PHP OAuth sample code_PHP tutorialfigureurl_2,'" />';
}
}
break;
default :
}
class qq_oauth{
private $config;
function __construct($config){
$this->config = $config;
}
/**
* Return configuration
* @param string $name
*
*/
function C($name){
return isset($this->config[$name]) ? $this->config[$name] : FALSE;
}
/**
* Build request URL
* @param string $url
* @param array $params
* @param string $oauth_token_secret
*
*/
function build_request_uri($url,$params=array(),$oauth_token_secret=''){
$oauth_consumer_key = $this->C('oauth_consumer_key');
$oauth_consumer_secret = $this->C('oauth_consumer_secret');
$params = array_merge(array(
'oauth_version'=>'1.0',
'oauth_signature_method'=>'HMAC-SHA1',
'oauth_timestamp'=>time(),
'oauth_nonce'=>rand(1000,99999999),
'oauth_consumer_key'=>$oauth_consumer_key,
),$params);
$encode_params = $params;
ksort($encode_params);
$oauth_signature = 'GET&'.urlencode($url).'&'.urlencode(http_build_query($encode_params));
$oauth_signature = base64_encode(hash_hmac('sha1',$oauth_signature,$oauth_consumer_secret.'&'.$oauth_token_secret,true));
$params['oauth_signature'] = $oauth_signature;
return $url.'?'.http_build_query($params);
}
/**
* Verify whether the callback returns the agreed parameters
*/
function check_callback(){
if(isset($_GET['oauth_token']))
if(isset($_GET['openid']))
if(isset($_GET['oauth_signature']))
if(isset($_GET['timestamp']))
if(isset($_GET['oauth_vericode']))
return true;
return false;
}
function get_contents($url){
$curl = curl_init();
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_URL,$url);
return curl_exec($curl);
}
/**
* Step1: Request temporary token, Step2: Generate unauthorized temporary token
*/
function oauth_request_token(){
$url = $this->build_request_uri($this->C('oauth_request_token_url'));
$tmp_oauth_token = $this->get_contents($url);
parse_str($tmp_oauth_token);
/*
oauth_token 未授权的临时token
oauth_token_secret token的密钥,该密钥仅限于临时token
error_code 错误码
*/
if(isset($error_code)) exit($error_code);
return array(
'oauth_token'=>$oauth_token,
'oauth_token_secret'=>$oauth_token_secret
);
}
/**
* Step3: Guide the user to the Qzone login page
* @param string $oauth_token Unauthorized temporary token
*/
function authorize($oauth_token){
$str = "HTTP/1.1 302 Found";
header($str);
$url = $this->C('oauth_authorize_url');
$query_strings = http_build_query(array(
'oauth_consumer_key'=>$this->C('oauth_consumer_key'),
'oauth_token'= >$oauth_token,
'oauth_callback'=>$this->C('oauth_callback'),
));
header('Location: '.$url.'?'.$ query_strings);
}
/**
* Step4: Qzone guides users to jump to third-party applications
* @return bool Verify whether it is valid
*/
function register_user(){
/*
* oauth_token authorized temporary token
* openid Tencent user external Unified ID, the OpenID corresponds one-to-one with the user's QQ number
* oauth_signature signature value, which facilitates third parties to verify the reliability of the openid and source.
* Use HMAC-SHA1 algorithm:
* Source string: openid+timestamp (do not add the '+' symbol in the middle of the string)
* Key: oauth_consumer_secret
* timestamp timestamp of openid
* oauth_vericode authorization verification code.
*/
if($this->check_callback()){
//Verify signature
$signature = base64_encode(hash_hmac('sha1',$_GET['openid']. $_GET['timestamp'],$this->C('oauth_consumer_secret'),true));
if(!emptyempty($_GET['oauth_signature']) && $signature==$_GET['oauth_signature ']){
$_SESSION['oauth_token'] = $_GET['oauth_token'];
$_SESSION['oauth_vericode'] = $_GET['oauth_vericode'];
return;
}
}
//Verification failed
exit('UNKNOW REQUEST');
}
/**
* Step5: Request access token
*/
function request_access_token(){
$url = $this->build_request_uri($this->C('oauth_request_access_token_url'),array(
'oauth_token'=>$_SESSION['oauth_token'],
'oauth_vericode'=> ;$_SESSION['oauth_vericode']
),$_SESSION['oauth_token_secret']);
return $this->get_contents($url);
}
/**
* Step6: Generate access token (save access token)
*
* About access_token
* Currently access_token (and its secret) is valid for a long time and corresponds to a certain openid. It can currently support online Get the openid information below.
* Of course, the user has the authority to delete the authorization to the third party on Qzone. At this time, the access_token will become invalid and the entire process needs to be re-authorized by the user.
* In the future, the validity of access_token will be gradually enriched, including long-term validity, short-term validity, validity only when the user logs in, etc.
*/
function save_access_token($access_token_str){
parse_str($access_token_str,$access_token_arr);
if(isset($access_token_arr['error_code'])){
return FALSE;
} else {
return $access_token_arr;
}
}
/**
* Currently, Tencent only opens this API.
* Obtain logged-in user information. Currently, user nickname and avatar information can be obtained.
* http://openapi.qzone.qq.com/user/get_user_info
*/
function get_user_info(){
$url = $this->build_request_uri( $this->C('user_info_url'),array(
'oauth_token'=>$_SESSION['oauth_token'],
'openid'=>$_SESSION['openid'],
),$_SESSION['oauth_token_secret']);
return $this->get_contents($url);
}
}

File package download qq_php.rar
Reprinted from: http://dev.meettea.com

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/323931.htmlTechArticleWrite the copy code according to the official document as follows: ?php /*** Apply http://connect.opensns.qq.com/apply * List http://connect.opensns.qq.com/my*/ session_start(); $ qq_oauth_conf...
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 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

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.