Zend_Oauth-GettingStarted.xml 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- Reviewed: no -->
  3. <sect2 id="zend.oauth.introduction.getting-started">
  4. <title>Getting Started</title>
  5. <para>
  6. With the OAuth protocol explained, let's show a simple example of it with
  7. source code. Our new Consumer will be handling Twitter Status submissions.
  8. To do so, it will need to be registered with Twitter in order to receive
  9. an OAuth Consumer Key and Consumer Secret. This are utilised to obtain
  10. an Access Token before we use the Twitter API to post a status message.
  11. </para>
  12. <para>
  13. Assuming we have obtained a key and secret, we can start the OAuth workflow
  14. by setting up a <classname>Zend_Oauth_Consumer</classname> instance as
  15. follows passing it a configuration (either an array or <classname>
  16. Zend_Config</classname> object).
  17. </para>
  18. <programlisting language="php"><![CDATA[
  19. $config = array(
  20. 'callbackUrl' => 'http://example.com/callback.php',
  21. 'siteUrl' => 'http://twitter.com/oauth',
  22. 'consumerKey' => 'gg3DsFTW9OU9eWPnbuPzQ',
  23. 'consumerSecret' => 'tFB0fyWLSMf74lkEu9FTyoHXcazOWpbrAjTCCK48A'
  24. );
  25. $consumer = new Zend_Oauth_Consumer($config);
  26. ]]></programlisting>
  27. <para>
  28. The callbackUrl is the URI we want Twitter to request from our server
  29. when sending information. We'll look at this later. The siteUrl is the
  30. base URI of Twitter's OAuth API endpoints. These utilise a convention
  31. which maps to the three OAuth endpoints (as standard) for requesting a
  32. request token, access token or authorization. If the actual endpoints of
  33. any service differ from the standard set, these three URIs can be separately
  34. set using the methods <methodname></methodname>,
  35. <methodname></methodname>,
  36. and <methodname></methodname>.
  37. </para>
  38. <para>
  39. The consumerKey and consumerSecret are retrieved from Twitter when your
  40. application is registered for OAuth access. These also apply to any OAuth
  41. enabled service, so each one will provide a key and secret for your
  42. application.
  43. </para>
  44. <para>
  45. All of these configuration options may be set using method calls simply
  46. by converting from, e.g. callbackUrl to setCallbackUrl().
  47. </para>
  48. <para>
  49. The first part of the OAuth workflow is obtaining a request token. This
  50. is accomplished using:
  51. </para>
  52. <programlisting language="php"><![CDATA[
  53. $config = array(
  54. 'callbackUrl' => 'http://example.com/callback.php',
  55. 'siteUrl' => 'http://twitter.com/oauth',
  56. 'consumerKey' => 'gg3DsFTW9OU9eWPnbuPzQ',
  57. 'consumerSecret' => 'tFB0fyWLSMf74lkEu9FTyoHXcazOWpbrAjTCCK48A'
  58. );
  59. $consumer = new Zend_Oauth_Consumer($config);
  60. // fetch a request token
  61. $token = $consumer->getRequestToken();
  62. ]]></programlisting>
  63. <para>
  64. The new request token (an instance of <classname>Zend_Oauth_Token_Request
  65. </classname>) is unauthorized. In order to exchange it for an authorized
  66. token with which we can access the Twitter API, we need the user to authorize
  67. it. We accomplish this by redirecting the user to Twitter's authorize endpoint
  68. via:
  69. </para>
  70. <programlisting language="php"><![CDATA[
  71. $config = array(
  72. 'callbackUrl' => 'http://example.com/callback.php',
  73. 'siteUrl' => 'http://twitter.com/oauth',
  74. 'consumerKey' => 'gg3DsFTW9OU9eWPnbuPzQ',
  75. 'consumerSecret' => 'tFB0fyWLSMf74lkEu9FTyoHXcazOWpbrAjTCCK48A'
  76. );
  77. $consumer = new Zend_Oauth_Consumer($config);
  78. // fetch a request token
  79. $token = $consumer->getRequestToken();
  80. // persist the token to storage
  81. $_SESSION['TWITTER_REQUEST_TOKEN'] = serialize($token);
  82. // redirect the user
  83. $consumer->redirect();
  84. ]]></programlisting>
  85. <para>
  86. The user will now be redirected to Twitter. They will be asked to authorize
  87. the request token attached to the redirect URI's query string. Assuming they
  88. agree, and complete the authorization, they will be again redirected, this
  89. time to our Callback URL as previously set (note that the callback URL is
  90. also registered with Twitter when we registered our application).
  91. </para>
  92. <para>
  93. Before redirecting the user, we should persist the request token to storage.
  94. For simplicity I'm just using the user's session, but you can easily use a
  95. database for the same purpose, so long as you tie the request token to the
  96. current user so it can be retrieved when they return to our application.
  97. </para>
  98. <para>
  99. The redirect URI from Twitter will contain an authorized Access Token. We
  100. can include code to parse out this access token as follows - this source
  101. code would exist within the executed code of our callback URI. Once parsed
  102. we can discard the previous request token, and instead persist the access
  103. token for future use with the Twitter API. Again, we're simply persisting
  104. to the user session, but in reality an access token can have a long lifetime
  105. so it should really be stored to a database.
  106. </para>
  107. <programlisting language="php"><![CDATA[
  108. $config = array(
  109. 'callbackUrl' => 'http://example.com/callback.php',
  110. 'siteUrl' => 'http://twitter.com/oauth',
  111. 'consumerKey' => 'gg3DsFTW9OU9eWPnbuPzQ',
  112. 'consumerSecret' => 'tFB0fyWLSMf74lkEu9FTyoHXcazOWpbrAjTCCK48A'
  113. );
  114. $consumer = new Zend_Oauth_Consumer($config);
  115. if (!empty($_GET) && isset($_SESSION['TWITTER_REQUEST_TOKEN'])) {
  116. $token = $consumer->getAccessToken($_GET, unserialize($_SESSION['TWITTER_REQUEST_TOKEN']));
  117. $_SESSION['TWITTER_ACCESS_TOKEN'] = serialize($token);
  118. // Now that we have an Access Token, we can discard the Request Token
  119. $_SESSION['TWITTER_REQUEST_TOKEN'] = null;
  120. } else {
  121. // Mistaken request? Some malfeasant trying something?
  122. exit('Invalid callback request. Oops. Sorry.');
  123. }
  124. ]]></programlisting>
  125. <para>
  126. Success! We have an authorized access token - so it's time to actually
  127. use the Twitter API. Since the access token must be included with every
  128. single API request, Zend_Oauth_Consumer offers a ready-to-go HTTP client
  129. (a subclass of <classname>Zend_Http_Client</classname>) to use either
  130. by itself or by passing it as a custom HTTP Client to another library or
  131. component. Here's an example of using it standalone. This can be done
  132. from anywhere in your application, so long as you can access the OAuth
  133. configuration and retrieve the final authorized access token.
  134. </para>
  135. <programlisting language="php"><![CDATA[
  136. $config = array(
  137. 'callbackUrl' => 'http://example.com/callback.php',
  138. 'siteUrl' => 'http://twitter.com/oauth',
  139. 'consumerKey' => 'gg3DsFTW9OU9eWPnbuPzQ',
  140. 'consumerSecret' => 'tFB0fyWLSMf74lkEu9FTyoHXcazOWpbrAjTCCK48A'
  141. );
  142. $statusMessage = 'I'm posting to Twitter using Zend_Oauth!';
  143. $token = unserialize($_SESSION['TWITTER_ACCESS_TOKEN']);
  144. $client = $token->getHttpClient($configuration);
  145. $client->setUri('http://twitter.com/statuses/update.json');
  146. $client->setMethod(Zend_Http_Client::POST);
  147. $client->setParameterPost('status', $statusMessage);
  148. $response = $client->request();
  149. $data = Zend_Json::decode($response->getBody());
  150. $result = $response->getBody();
  151. if (isset($data->text)) {
  152. $result = 'true';
  153. }
  154. echo $result;
  155. ]]></programlisting>
  156. </sect2>