Partage
  • Partager sur Facebook
  • Partager sur Twitter

Pb avec l'Oauth de Tumblr

Sujet résolu
4 août 2012 à 16:19:39

Bonjour,

Je viens de télécharger un fichier sur le forum de tumblr pour pouvoir utiliser certaines partie de leur API qui necessite une autorisation Oauth de l'utilisateur pour pouvoir accéder aux données.

Le problème c'est que dans l'exemple, il faut demander à chaque fois l'autorisation à l'utilisateur pour avoir les informations voulues.

J'aimerai savoir les modifications, à apporter pour ne plus avoir à le faire constamment (Juste une fois au début). Après ça stocke dans un cookie ou dans la bdd.

J'ai déja essayé d'enlever ces 2 lignes :

<?php 
unset($_SESSION['request_token']);
unset($_SESSION['request_token_secret']);
?>


dans le fichier callback.php mais ça ne marche pas.

Connect.php
<?php
// This script is a simple example of how to send a user off to authentication using Tumblr's OAuth

// Start a session.  This is necessary to hold on to  a few keys the callback script will also need
session_start();

// Include the TumblrOAuth library
require_once('tumblroauth/tumblroauth.php');

// Define the needed keys
$consumer_key = "YOUR CONSUMER KEY GOES HERE";
$consumer_secret = "PUT THE SECRET KEY HERE";

// The callback URL is the script that gets called after the user authenticates with tumblr
// In this example, it would be the included callback.php
$callback_url = "PUT A CALLBACK URL HERE";

// Let's begin.  First we need a Request Token.  The request token is required to send the user
// to Tumblr's login page.

// Create a new instance of the TumblrOAuth library.  For this step, all we need to give the library is our
// Consumer Key and Consumer Secret
$tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret);

// Ask Tumblr for a Request Token.  Specify the Callback URL here too (although this should be optional)
$request_token = $tum_oauth->getRequestToken($callback_url);

// Store the request token and Request Token Secret as out callback.php script will need this
$_SESSION['request_token'] = $token = $request_token['oauth_token'];
$_SESSION['request_token_secret'] = $request_token['oauth_token_secret'];

// Check the HTTP Code.  It should be a 200 (OK), if it's anything else then something didn't work.
switch ($tum_oauth->http_code) {
  case 200:
    // Ask Tumblr to give us a special address to their login page
    $url = $tum_oauth->getAuthorizeURL($token);
	
	// Redirect the user to the login URL given to us by Tumblr
    header('Location: ' . $url);
	
	// That's it for our side.  The user is sent to a Tumblr Login page and
	// asked to authroize our app.  After that, Tumblr sends the user back to
	// our Callback URL (callback.php) along with some information we need to get
	// an access token.
	
    break;
default:
    // Give an error message
    echo 'Could not connect to Tumblr. Refresh the page or try again later.';
}
exit();

?>


Callback.php
<?php
// Start a session, load the library
session_start();
require_once('tumblroauth/tumblroauth.php');

// Define the needed keys
$consumer_key = "YOUR CONSUMER KEY GOES HERE";
$consumer_secret = "PUT THE SECRET KEY HERE";

// Once the user approves your app at Tumblr, they are sent back to this script.
// This script is passed two parameters in the URL, oauth_token (our Request Token)
// and oauth_verifier (Key that we need to get Access Token).
// We'll also need out Request Token Secret, which we stored in a session.

// Create instance of TumblrOAuth.
// It'll need our Consumer Key and Secret as well as our Request Token and Secret
$tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $_SESSION['request_token'], $_SESSION['request_token_secret']);

// Ok, let's get an Access Token. We'll need to pass along our oauth_verifier which was given to us in the URL. 
$access_token = $tum_oauth->getAccessToken($_REQUEST['oauth_verifier']);

// We're done with the Request Token and Secret so let's remove those.
unset($_SESSION['request_token']);
unset($_SESSION['request_token_secret']);

// Make sure nothing went wrong.
if (200 == $tum_oauth->http_code) {
  // good to go
} else {
  die('Unable to authenticate');
}

// What's next?  Now that we have an Access Token and Secret, we can make an API call.

// Any API call that requires OAuth authentiation will need the info we have now - (Consumer Key,
// Consumer Secret, Access Token, and Access Token secret).

// You should store the Access Token and Secret in a database, or if you must, a Cookie in the user's browser.
// Never expose your Consumer Secret.  It should stay on your server, avoid storing it in code viewable to the user.

// I'll make the /user/info API call to get some baisc information about the user

// Start a new instance of TumblrOAuth, overwriting the old one.
// This time it will need our Access Token and Secret instead of our Request Token and Secret
$tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $access_token['oauth_token'], $access_token['oauth_token_secret']);

// Make an API call with the TumblrOAuth instance.  There's also a post and delete method too.
$userinfo = $tum_oauth->get('http://api.tumblr.com/v2/user/info');

// You don't actuall have to pass a full URL,  TukmblrOAuth will complete the URL for you.
// This will also work: $userinfo = $tum_oauth->get('user/info');

// Check for an error.
if (200 == $tum_oauth->http_code) {
  // good to go
} else {
  die('Unable to get info');
}

// find primary blog.  Display its name.
$screen_name = $userinfo->response->user->name;
for ($fln=0; $fln<count($userinfo->response->user->blogs); $fln=$fln+1) {
	if ($userinfo->response->user->blogs[$fln]->primary==true) {
		echo("Your primary blog's name: " .($userinfo->response->user->blogs[$fln]->title));
		break;
	}
}

echo("<br/>");
echo("Your user name (the part before tumblr.com of your primary blog): ".$userinfo->response->user->name);

// And that's that.  Hopefully it will help.
?>


Merci d'avance.
  • Partager sur Facebook
  • Partager sur Twitter
10 septembre 2012 à 23:45:26

ReBonjour,

J'apporte la solution à mon problème :)

Donc pour régler ce problème, il faut utiliser un script php Oauth pour Tumblr

Cliquer pour télécharger le script

Ce script a été réaliser pour montrer l'essentiel, il marche très bien mais il faut l'améliorer stockant, lors de l'inscription (de préférence), l' "access_token" dans la base de donnée afin de ne pas avoir a demander à l'utilisateur de se reconnecter à Tumblr à chaque fois que la session expire.

Je mets à disposition mon script qui permet "S'abonner" à des gens très facilement, le script va chercher des noms automatiquement sur un site nommé tumblrplug.com. Il est ensuite possible de suivre 150 personnes (maximum/jour) en 2 ou 3 min à la place de 2h (c'est super mal codé mais ça marche :) )

Cliquer pour télécharger le script et cliquer ici si vous voulez voir une démo

Pour pouvoir ce servir du premier comme du 2 eme script

- Il faut s'enregistrer sur Tumblr et créer une application http://www.tumblr.com/oauth/apps
- Il faut ensuite remplir le fichier config.php avec les cle qu'on vous a donné.
- (Pour le second script) Aller dans le fichier include et remplir le fichier db.class.php avec vos identifiants SQL et penser à ajouter la table SQL fourni

Et voici la documentation pour le premier script, mais je reste disposition s'il y a des questions, je pense pouvoir répondre.

Citation : Guide d'utilisation

TumblrOAuth documentation.



GET THE CODE
====================
You can pull the latest development version using git:
git clone git://github.com/nquinlan/Tumblr-OAuth.git

Or you can download the latest release by visiting:
http://github.com/nquinlan/Tumblr-OAuth/downloads


FLOW OVERVIEW
====================
1) Build TumblrOAuth object using client credentials.
2) Request temporary credentials from Tumblr.
3) Build authorize URL for Tumblr.
4) Redirect user to authorize URL.
5) User authorizes access and returns from Tumblr.
6) Rebuild TumblrOAuth object with client credentials and temporary credentials.
7) Get token credentials from Tumblr.
8) Rebuild TumblrOAuth object with client credentials and token credentials.
9) Query Tumblr API.


TERMINOLOGY
====================
The terminology has changed since 0.1.x to better match the draft-hammer-oauth IETF
RFC. You can read that at http://tools.ietf.org/html/draft-hammer-oauth. Some of the
terms will differ from those Tumblr uses as well.

client credentials - Consumer key/secret you get when registering an app with Tumblr.
temporary credentials - Previously known as the request token.
token credentials - Previously known as the access token.


PARAMETERS
====================
There are a number of parameters you can modify after creating a TumblrOAuth object.

Stop auto decoding JSON.
$connection->decode_json = FALSE;

Decode JSON to Associative Array
$connection->assoc = TRUE;

There are several more you can find in TumblrOAuth.php.



EXTENDED FLOW USING EXAMPLE CODE
====================
To use TumblrOAuth with the Tumblr API you need TumblrOAuth.php, OAuth.php and
client credentials. You can get client credentials by registering your application at
https://tumblr.com/oauth/apps.

The example files are explained below.

0) Users start out on connect.php which displays the "Sign in with Tumblr" image hyperlinked
to redirect.php. This button should be displayed on your homepage in your login section. The
client credentials are saved in config.php as CONSUMER_KEY and CONSUMER_SECRET. You can
save a static callback URL in the app settings page, in the config file or use a dynamic
callback URL later in step 2. In example use http://example.com/callback.php.

1) When a user lands on redirect.php we build a new TumblrOAuth object using the client
credentials. If you have your own configuration method feel free to use it instead of config.php.
$connection = new TumblrOAuth(CONSUMER_KEY, CONSUMER_SECRET);// Use config.php client credentials
$connection = new TumblrOAuth('abc890', '123xyz');

2) Using the built $connection object you will ask Tumblr for temporary credentials. If you
wish to have a dynamic callback URL for each user you can do pass a URL as a parameter.
$temporary_credentials = $connection->getRequestToken(); // Use applications registered callback.
$temporary_credentials = $connection->getRequestToken('http://example.com/callback.php?');

3) Now that we have temporary credentials the user has to go to Tumblr and authorize the app
to access and updates their data. You can also pass a second parameter of FALSE to not use Sign
in with Tumblr: http://apiwiki.tumblr.com/Sign-in-with-Tumblr.
$redirect_url = $connection->getAuthorizeURL($temporary_credentials); // Use Sign in with Tumblr
$redirect_url = $connection->getAuthorizeURL($temporary_credentials, FALSE);

4) You will now have a Tumblr URL that you must send the user to. You can add parameters and
they will return with the user in step 5.
http://www.tumblr.com/oauth/authorize?oauth_token=xyz123
http://www.tumblr.com/oauth/authorize? [...] z123&info=abc // info will return with user

5) The user is now on tumblr.com and may have to login. Once authenticated with Tumblr they will
will either have to click on allow/deny, or will be automatically redirected back to the callback.

6) Now that the user has returned to callback.php and allowed access we need to build a new
TumblrOAuth object using the temporary credentials.
$connection = new TumblrOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'],
$_SESSION['oauth_token_secret']);

7) Now we ask Tumblr for long lasting token credentials. These are specific to the application
and user and will act like password to make future requests. If a dynamic callback URL was used
you will also have to pass the oauth_varifier parameter. Normally the token credentials would
get saved in your database but for this example we are just using sessions.
$token_credentials = $connection->getAccessToken(); // Used applications registered callback URL
$token_credentials = $connection->getAccessToken($_REQUEST['oauth_verifier']);

7a) After getting the token credentials we redirect the user to index.php.

8) With the token credentials we build a new TumblrOAuth object.
$connection = new TumblrOAuth(CONSUMER_KEY, CONSUMER_SECRET, $token_credentials['oauth_token'],
$token_credentials['oauth_token_secret']);

9) And finally we can make requests authenticated as the user. You can GET, POST, and DELETE API
methods. Directly copy the path from the API documentation and add an array of any parameter
you wish to include for the API method such as curser or in_reply_to_status_id.
$content = $connection->get('user/info');
$connection->post('blog/nquinlan/post', array('type' => 'text', 'body' => 'Text of post here'));



Voila, en espérant aider qqun d'entre vous :)
  • Partager sur Facebook
  • Partager sur Twitter