問題描述
我正在使用 Twitter 將用戶登錄到一個網站,在我嘗試獲取有效的訪問令牌之前,該網站似乎一直在工作.
require("twitteroauth.php");需要'twconfig.php';session_start();$twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET);$request_token = $twitteroauth->getRequestToken('http://****/tw_response.php');$oauth_token = $request_token['oauth_token'];$_SESSION['oauth_token'] = $oauth_token;$oauth_token_secret = $request_token['oauth_token_secret'];$_SESSION['oauth_token_secret'] = $oauth_token_secret;如果($twitteroauth->http_code == 200){url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);header('位置:'.$url);} 別的 {die('發生了一些錯誤.');}
這似乎工作正常,將我重定向到 Twitter 以登錄并確認訪問,然后它返回到 tw_response.php(我的回調 URL),在 URL 中包含以下變量:
http://example.com/login.php?oauth_token=sO3X...yj0k&oauth_verifier=Ip6T...gALQ
在 tw_response.php 中,我嘗試獲取訪問令牌,但它報告為無效.我嘗試使用 var_dump
查看訪問令牌的內容如下:
require("twitteroauth.php");需要'twconfig.php';session_start();$oauth_verifier = $_REQUEST['oauth_verifier'];$oauth_token = $_SESSION['oauth_token'];$oauth_token_secret = $_SESSION['oauth_token_secret'];$twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET, $oauth_token, $oauth_token_secret);$access_token = $twitteroauth->getAccessToken($data['oauth_verifier']);var_dump($access_token);
var_dump
的結果以無效/過期令牌"結尾:
array(8) {[oauth_url"] =>string(104) ""1.0" encoding="UTF-8"?>/oauth/access_token?oauth_consumer_key=ceE...9Dg"[oauth_nonce"]=>字符串(32)c52...d07"[oauth_signature"]=>字符串(28)ry7...Fcc="[oauth_signature_method"]=>字符串(9)HMAC-SHA1"[oauth_timestamp"]=>字符串(10)1359031586"[oauth_token"]=>字符串(40)sO3...j0k"[oauth_verifier"]=>字符串(43)IP6...ALQ"[oauth_version"]=>string(63) "1.0 無效/過期令牌 "}
$access_token = $twitteroauth->getAccessToken($data['oauth_verifier']);var_dump($access_token);
$data
神奇地來自哪里?您有變量 $oauth_verifier
,但請記住,如果這是您注冊的回調 URL,則您不需要它.
由于您在 getAccessToken
中使用了無效變量,它將返回無效值.
正確使用 TwitterOAuth 的方法:
if (!isset($_GET["oauth_token"])) {//在某處的配置文件中設置這些值.$twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);//附加一個 ?.如果您指定某些內容,這就是您的回調 URL.$credentials = $twitter->getRequestToken("http://example.com/test.php?");//嘗試讓 URL 更優雅一些...這是一個最小的例子$url = $twitter->getAuthorizeUrl($credentials);回聲 $url;//這些是必須用于獲取新令牌的臨時令牌,//永久訪問令牌.以某種方式存儲這些,//session 是一個不錯的選擇.$_SESSION["token"] = $credentials["oauth_token"];$_SESSION["secret"] = $credentials["oauth_token_secret"];} 別的 {//在這里使用用戶之前存儲的臨時憑證$twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,$_SESSION["token"], $_SESSION["secret"]);//已經使用了 oauth_token(來自請求).//您將這些憑據存儲在您的數據庫中(見下文).$credentials = $twitter->getAccessToken($_GET["oauth_verifier"]);//只是憑據的打印輸出.存儲這些,不要顯示它們.echo "";var_dump($credentials);//有效憑據,前提是您授予應用訪問權限.echo "</pre>";}
為了便于使用,我只使用單個腳本進行回調;如果您愿意(您可能應該這樣做),您可以將相關部分拆分為多個腳本.
對于您的數據庫來說,憑據還包括 Twitter 用戶的用戶名.
編輯:Twitter 現在為用戶 ID 分配 64 位整數.如果您無法在應用程序的每個部分都處理 64 位整數,您應該將其存儲為字符串,以確保不會以損壞的用戶 ID 和沖突結束.
array(4) {[oauth_token"]=>字符串(50)7041...wYupkS"[oauth_token_secret"]=>string(42) "O9ENq...21B2fk"[user_id"]=>//用戶身份.始終相同,永不改變(將其存儲為 ID)字符串(9)..."[屏幕名稱"]=>//用戶名.可以換.字符串(11)..."}
因此,如果您想通過 Twitter 登錄用戶,而無需明確授予他們登錄您網站的權限,您可以使用 $_SESSION
(我使用數據庫進行登錄,如果您想保存那個狀態)在上面的腳本中,您將把它添加到 else
塊的末尾:
$_SESSION["token"] = $credentials["oauth_token"];$_SESSION["secret"] = $credentials["oauth_secret"];$_SESSION["username"] = $credentials["screen_name"];
您還可以從 GET account/verify_credentials<獲取用戶的屏幕名稱等信息/code>,如果你想給他們一個用戶頁面(如果你使用javascript,通過這里的
id_str
獲取他們的用戶ID):
$user_array = $twitter->get("account/verify_credentials");
I am using Twitter to log users into to a website, which seems to be working up until I attempt to obtain a valid Access Token.
require("twitteroauth.php");
require 'twconfig.php';
session_start();
$twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET);
$request_token = $twitteroauth->getRequestToken('http://****/tw_response.php');
$oauth_token = $request_token['oauth_token'];
$_SESSION['oauth_token'] = $oauth_token;
$oauth_token_secret = $request_token['oauth_token_secret'];
$_SESSION['oauth_token_secret'] = $oauth_token_secret;
if ($twitteroauth->http_code == 200) {
url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);
header('Location: '.$url);
} else {
die('Something wrong happened.');
}
This seems to be working correctly, redirecting me to twitter to sign in and confirm access, after which it returns me to tw_response.php (my Callback url), with the following variables in the url:
http://example.com/login.php?oauth_token=sO3X...yj0k&oauth_verifier=Ip6T...gALQ
In tw_response.php I then try to get the Access Token, but it reports as invalid. I tried using var_dump
to view the content of the access token as follows:
require("twitteroauth.php");
require 'twconfig.php';
session_start();
$oauth_verifier = $_REQUEST['oauth_verifier'];
$oauth_token = $_SESSION['oauth_token'];
$oauth_token_secret = $_SESSION['oauth_token_secret'];
$twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET, $oauth_token, $oauth_token_secret);
$access_token = $twitteroauth->getAccessToken($data['oauth_verifier']);
var_dump($access_token);
The result of the var_dump
ends in "invalid / expired Token":
array(8) {
["oauth_url"] => string(104) ""1.0" encoding="UTF-8"?>/oauth/access_token?oauth_consumer_key=ceE...9Dg"
["oauth_nonce"]=> string(32) "c52...d07"
["oauth_signature"]=> string(28) "ry7...Fcc="
["oauth_signature_method"]=> string(9) "HMAC-SHA1"
["oauth_timestamp"]=> string(10) "1359031586"
["oauth_token"]=> string(40) "sO3...j0k"
["oauth_verifier"]=> string(43) "Ip6...ALQ"
["oauth_version"]=> string(63) "1.0 Invalid / expired Token "
}
$access_token = $twitteroauth->getAccessToken($data['oauth_verifier']);
var_dump($access_token);
Where did $data
magically come from? You have the variable $oauth_verifier
, but keep in mind you don't need this if this is your registered callback URL.
Since you used an invalid variable inside getAccessToken
, it will return an invalid value back.
The correct way to use TwitterOAuth:
if (!isset($_GET["oauth_token"])) {
// set these values in a config file somewhere.
$twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
// append a ?. This is your callback URL if you specify something.
$credentials = $twitter->getRequestToken("http://example.com/test.php?");
// try and be a bit more elegant with the URL... This is a minimal example
$url = $twitter->getAuthorizeUrl($credentials);
echo $url;
// these are temporary tokens that must be used to fetch the new,
// permanent access tokens. store these in some way,
// session is a decent choice.
$_SESSION["token"] = $credentials["oauth_token"];
$_SESSION["secret"] = $credentials["oauth_token_secret"];
} else {
// use the user's previously stored temporary credentials here
$twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,
$_SESSION["token"], $_SESSION["secret"]);
// uses the oauth_token (from the request) already.
// you store these credentials in your database (see below).
$credentials = $twitter->getAccessToken($_GET["oauth_verifier"]);
// just a printout of credentials. store these, don't display them.
echo "<pre>";
var_dump($credentials);
// valid credentials, provided you give the app access to them.
echo "</pre>";
}
I just use a single script for callbacks for ease of use; you can split the relevant sections into multiple scripts if you like (and you probably should).
Handily for your database, the credentials include the twitter user's username, too.
Edit: Twitter is now allocating 64bit integers for user IDs. You should store this as a string to ensure that you don't end up with mangled user IDs and collisions if you can't handle 64bit integers in every part of your application.
array(4) {
["oauth_token"]=>
string(50) "7041...wYupkS"
["oauth_token_secret"]=>
string(42) "O9ENq...21B2fk"
["user_id"]=> // user ID. always the same, never changes (store this as ID)
string(9) "..."
["screen_name"]=> // username. can change.
string(11) "..."
}
So, if you want to log users in through twitter, without explicitly giving them a login to your site, you could use $_SESSION
(I use databases for my logins, which is recommended if you want to save that state)
In the above script you would add this to the end of the else
block:
$_SESSION["token"] = $credentials["oauth_token"];
$_SESSION["secret"] = $credentials["oauth_secret"];
$_SESSION["username"] = $credentials["screen_name"];
You can also get the user's screen name and more from GET account/verify_credentials
, if you want to give them a user page (if you use javascript, grab their userid through id_str
here):
$user_array = $twitter->get("account/verify_credentials");
這篇關于為什么我的 twitter oauth 訪問令牌無效/過期的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!