oauth0 oauth2
Welcome back to Understanding OAuth – Tweeting from Scratch. This is Part 2 of the two-part series and picks up right where we left off in Part 1 with your returned Access Credentials. Since obtaining the credentials is the grueling part of the process, there’s not much more left to do except posting a tweet on the user’s behalf. Hopefully you’ll find the final steps to be a lot easier to follow and more fun to implement.
欢迎回到了解OAuth –从头开始推文。 这是由两部分组成的系列文章的第2部分,从我们在第1部分中使用您返回的访问凭据结束的地方开始。 由于获取凭据是过程的艰苦部分,因此除了代表用户发布推文外,别无他法。 希望您会发现最终步骤更容易遵循且实现起来更有趣。
First things first, you should at least store the user specific details and credentials from Part 1 in $_SESSION
so they can be used later, though most likely you’ll want to store the information in a database so you can retrieve them whenever you like to send tweets on behalf of others.
首先,您至少应将第1部分中特定于用户的详细信息和凭据存储在$_SESSION
以便以后可以使用,尽管您很可能希望将信息存储在数据库中,以便您可以随时检索它们代表他人发送推文。
<?php
//...
$response = file_get_contents($requestUrl);
parse_str($response, $values);
$_SESSION["accessToken"] = $values["oauth_token"];
$_SESSION["accessTokenSecret"] = $values["oauth_token_secret"];
$_SESSION["twitterUserId"] = $values["user_id"];
$_SESSION["twitterUsername"] = $values["screen_name"];
// Redirect the user to the application's form
header("Location: /postTweet.php");
Since your application has the necessary Access Credentials and you’ve tucked them away safely for future use, you can redirect the user to a form where he can enter the text of his tweet.
由于您的应用程序具有必要的访问凭据,并且已将它们安全地藏起来以备将来使用,因此您可以将用户重定向到一个表单,在该表单中,他可以输入其推文的文本。
<form action="/postTweet.php" method="post">
<textarea name="tweet" rows="3" cols="50"></textarea>
<br>
<input type="submit" value="Send">
</form>
发布到Twitter (Posting to Twitter)
There is plenty you can do with the Twitter API once you have Access Credentials (full API documentation can be found at dev.twitter.com/docs/api). For this article I’m showing just the use of statuses/update to to post a tweet. You can request many of the API calls to respond with XML or JSON formatted data simply by adding .xml
or .json
to the end of the URL. Personally I find JSON far easier to deal with than XML.
拥有访问凭据后,Twitter API可以做很多事情(完整的API文档可在dev.twitter.com/docs/api上找到)。 对于本文,我仅展示了使用状态/更新来发布推文。 您只需向URL末尾添加.xml
或.json
,即可请求许多API调用以XML或JSON格式的数据进行响应。 我个人认为JSON比XML更容易处理。
statuses/update
requires an HTTP POST
to be made sending your OAuth parameters in the HTTP header. Previously you only used GET
in the conversations with Twitter.
statuses/update
要求进行HTTP POST
,以在HTTP标头中发送OAuth参数。 以前,您仅在与Twitter的对话中使用GET
。
All OAuth v1 Twitter API resource URLs begin with “http://api.twitter.com/1/” and end with the resource name followed by .xml
or .json
. The only credentials you need from now on are your Consumer Credentials and the Access Credentials; the Request Credentials are discarded since they were only necessary for the authorization process.
所有OAuth v1 Twitter API资源URL均以“ http://api.twitter.com/1/”开头,并以资源名称结尾,后跟.xml
或.json
。 从现在开始,您唯一需要的凭证是“使用者凭证”和“访问凭证”。 请求凭证被丢弃,因为它们仅是授权过程所必需的。
Building the signature is performed the same as before except you now include the Access Token Secret in $sigKey
.
生成签名的过程与之前相同,只是现在您在$sigKey
包括了访问令牌密钥。
<?php
$oauthVersion = "1.0";
$apiResourceUrl = "http://api.twitter.com/1/statuses/update.json";
$nonce = md5(mt_rand());
$oauthSignatureMethod = "HMAC-SHA1";
$oauthTimestamp = time();
$accessToken = $_SESSION["accessToken"];
$accessTokenSecret = $_SESSION["accessTokenSecret"];
$tweetText = trim($_POST["tweet"]);
$sigBase = "POST&" . rawurlencode($apiResourceUrl) . "&"
. rawurlencode("oauth_consumer_key=" . rawurlencode($consumerKey)
. "&oauth_nonce=" . rawurlencode($nonce)
. "&oauth_signature_method=" . rawurlencode($oauthSignatureMethod)
. "&oauth_timestamp=" . $oauthTimestamp
. "&oauth_token=" . rawurlencode($accessToken)
. "&oauth_version=" . rawurlencode($oauthVersion)
. "&status=" . rawurlencode($tweetText));
$sigKey = rawurlencode($consumerSecret) . "&" . rawurlencode($accessTokenSecret);
$oauthSig = base64_encode(hash_hmac("sha1", $sigBase, $sigKey, true));
OAuth POST
transactions can (and are required to by Twitter) have the OAuth parameters included in a special Authorization
HTTP header. It’s worth noting that besides the typical OAuth parameters, $sigBase
also includes the API resource parameter status above. Non-OAuth parameters are needed in the signature but are excluded from the HTTP header. They are used in the POST
body instead.
OAuth POST
事务可以(并且是Twitter必需的)具有OAuth参数,该参数包含在特殊的Authorization
HTTP标头中。 值得注意的是,除了典型的OAuth参数之外, $sigBase
还包括上面的API资源参数状态。 签名中需要非OAuth参数,但这些参数将从HTTP标头中排除。 而是在POST
正文中使用它们。
<?php
$authHeader = "OAuth oauth_consumer_key=" . rawurlencode($consumerKey) . ","
. "oauth_nonce=" . rawurlencode($nonce) . ","
. "oauth_signature_method=" . rawurlencode($oauthSignatureMethod) . ","
. "oauth_signature=" . rawurlencode($oauthSig) . ","
. "oauth_timestamp=". rawurlencode($oauthTimestamp) . ","
. "oauth_token=" . rawurlencode($accessToken) . ","
. "oauth_version=" . rawurlencode($oauthVersion);
$httpPostDataUrl = "status=" . $tweetText;
$context = stream_context_create(array("http" => array(
"method" => "POST",
"header" => "Content-Type: application/x-www-form-urlencodedrnAuthorization: " . $authHeader . "rn",
"content" => $httpPostDataUrl)));
$result = file_get_contents($apiResourceUrl, false, $context);
If everything went smoothly you should have just posted to twitter on behalf of an authorized user. Twitter sends the success or failure status along with a very large amount of information regarding the transaction, which you can with print_r(json_decode($result))
if you like.
如果一切顺利,您应该代表授权用户发布到Twitter。 Twitter发送成功或失败状态以及有关交易的大量信息,您可以根据需要使用print_r(json_decode($result))
。
摘要 (Summary)
Now that you have a fair understanding of how Oauth works, implementing a third party library or troubleshooting OAuth in general should be a lot easier. In summary, you’ve learned how to:
既然您对Oauth的工作方式有了一个很好的了解,那么一般来说,实现第三方库或对OAuth进行故障排除要容易得多。 总之,您已经了解了如何:
- Create a new Twitter application and obtain the Consumer Credentials 创建一个新的Twitter应用程序并获取使用者凭证
- Obtain the Request Credentials which are necessary for requesting Access Credentials 获取请求访问凭证所需的请求凭证
- Authorize your application with a user and obtain Access Credentials 向用户授权您的应用程序并获取访问凭据
- Post a tweet on another user’s behalf using the Access Credentials 使用访问凭据代表其他用户发布推文
Today some of the most popular web applications provide access to an API – Flickr, Facebook, foursquare, Netflix, Last.fm, and GetGlue to name a few. Having an intimate knowledge of how to seamlessly communicate with these applications is a very desirable skill! Some of what you have learned here regarding the hashing of signatures and exchange of tokens can also be well applied to non-Oauth v1.0 APIs, such as Flickr’s pre-OAuth interface and the much easier to understand OAuth v2. Good luck and have fun!
今天,一些最受欢迎的Web应用程序提供了对API的访问权限-Flickr , Facebook , foursquare , Netflix , Last.fm和GetGlue等 。 非常了解如何与这些应用程序无缝通信是一项非常可取的技能! 您在此处了解到的有关签名哈希和令牌交换的一些知识也可以很好地应用于非Oauth v1.0 API,例如Flickr的pre-OAuth接口以及更容易理解的OAuth v2 。 祝好运并玩得开心点!
Code for this series can be found on GitHub.
该系列的代码可以在GitHub上找到。
Image via Photosani / Shutterstock
图片来自Photosani / Shutterstock
oauth0 oauth2