搜尋
首頁後端開發php教程QQ登录 PHP OAuth示例代码_PHP教程

QQ登录 PHP OAuth示例代码_PHP教程

Jul 21, 2016 pm 03:26 PM
httpoauthphp程式碼複製官方文件申請登入範例編寫

根据官方文档编写

复制代码 代码如下:

/**
* 申请http://connect.opensns.qq.com/apply
* 列表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登录 PHP OAuth示例代码_PHP教程figureurl,'" />',
'QQ登录 PHP OAuth示例代码_PHP教程figureurl_1,'" />',
'QQ登录 PHP OAuth示例代码_PHP教程figureurl_2,'" />';
}
}
break;
default :
}
class qq_oauth{
private $config;
function __construct($config){
$this->config = $config;
}
/**
* 返回配置
* @param string $name
*
*/
function C($name){
return isset($this->config[$name]) ? $this->config[$name] : FALSE;
}
/**
* 构建请求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);
}
/**
* 校验回调是否返回约定的参数
*/
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:请求临时token、Step2:生成未授权的临时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:引导用户到Qzone的登录页
* @param string $oauth_token 未授权的临时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引导用户跳转到第三方应用
* @return bool 验证是否有效
*/
function register_user(){
/*
* oauth_token 已授权的临时token
* openid 腾讯用户对外的统一ID,该OpenID与用户QQ号码一一对应
* oauth_signature 签名值,方便第三方来验证openid以及来源的可靠性。
* 使用HMAC-SHA1算法:
* 源串:openid+timestamp(串中间不要添加'+'符号)
* 密钥:oauth_consumer_secret
* timestamp openid的时间戳
* oauth_vericode 授权验证码。
*/
if($this->check_callback()){
//校验签名
$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;
}
}
//校验未通过
exit('UNKNOW REQUEST');
}
/**
* Step5:请求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:生成access token (保存access token)
*
* 关于access_token
* 目前access_token(及其secret)是长期有效的,和某一个openid对应,目前可以支持线下获取该openid的信息。
* 当然,用户有权限在Qzone这边删除对第三方的授权,此时该access_token会失效,需要重新走整个流程让用户授权。
* 以后会逐步丰富access_token的有效性,长期有效、短期有效、用户登录时才有效等。
*/
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;
}
}
/**
* 目前腾讯仅开放该API
* 获取登录用户信息,目前可获取用户昵称及头像信息。
* 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);
}
}

文件打包下载 qq_php.rar
转自: http://dev.meettea.com

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/323931.htmlTechArticle根据官方文档编写 复制代码 代码如下: ?php /** * 申请http://connect.opensns.qq.com/apply * 列表http://connect.opensns.qq.com/my */ session_start(); $qq_oauth_confi...
陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何使PHP應用程序更快如何使PHP應用程序更快May 12, 2025 am 12:12 AM

tomakephpapplicationsfaster,關注台詞:1)useopcodeCachingLikeLikeLikeLikeLikePachetoStorePreciledScompiledScriptbyTecode.2)MinimimiedAtabaseSqueriSegrieSqueriSegeriSybysequeryCachingandeffeftExting.3)Leveragephp7 leveragephp7 leveragephp7 leveragephpphp7功能forbettercodeefficy.4)

PHP性能優化清單:立即提高速度PHP性能優化清單:立即提高速度May 12, 2025 am 12:07 AM

到ImprovephPapplicationspeed,關注台詞:1)啟用opcodeCachingwithapCutoredUcescriptexecutiontime.2)實現databasequerycachingingusingpdotominiminimizedatabasehits.3)usehttp/2tomultiplexrequlexrequestsandreduceconnection.4 limitesclection.4.4

PHP依賴注入:提高代碼可檢驗性PHP依賴注入:提高代碼可檢驗性May 12, 2025 am 12:03 AM

依赖注入(DI)通过显式传递依赖关系,显著提升了PHP代码的可测试性。1)DI解耦类与具体实现,使测试和维护更灵活。2)三种类型中,构造函数注入明确表达依赖,保持状态一致。3)使用DI容器管理复杂依赖,提升代码质量和开发效率。

PHP性能優化:數據庫查詢優化PHP性能優化:數據庫查詢優化May 12, 2025 am 12:02 AM

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

簡單指南:帶有PHP腳本的電子郵件發送簡單指南:帶有PHP腳本的電子郵件發送May 12, 2025 am 12:02 AM

phpisusedforsenderemailsduetoitsbuilt-inmail()函數andsupportivelibrariesLikePhpMailerAndSwiftMailer.1)usethemail()functionForbasiceMails,butithasimails.2)butithasimail.2)

PHP性能:識別和修復瓶頸PHP性能:識別和修復瓶頸May 11, 2025 am 12:13 AM

PHP性能瓶颈可以通过以下步骤解决:1)使用Xdebug或Blackfire进行性能分析,找出问题所在;2)优化数据库查询并使用缓存,如APCu;3)使用array_filter等高效函数优化数组操作;4)配置OPcache进行字节码缓存;5)优化前端,如减少HTTP请求和优化图片;6)持续监控和优化性能。通过这些方法,可以显著提升PHP应用的性能。

PHP的依賴注入:快速摘要PHP的依賴注入:快速摘要May 11, 2025 am 12:09 AM

依賴性注射(DI)InphpisadesignPatternthatManages和ReducesClassDeptions,增強量強制性,可驗證性和MATIALWINABIOS.ItallowSpasspassingDepentenciesLikEdenciesLikedAbaseConnectionStoclasseconnectionStoclasseSasasasasareTers,interitationAseTestingEaseTestingEaseTestingEaseTestingEasingAndScalability。

提高PHP性能:緩存策略和技術提高PHP性能:緩存策略和技術May 11, 2025 am 12:08 AM

cachingimprovesphpermenceByStorcyResultSofComputationsorqucrouctationsorquctationsorquickretrieval,reducingServerLoadAndenHancingResponsetimes.feftectivestrategiesinclude:1)opcodecaching,whereStoresCompiledSinmememorytssinmemorytoskipcompliation; 2)datacaching datacachingsingMemccachingmcachingmcachings

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。