我正在使用 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模板网!