Search code examples
phpapitumblraccess-token

PHP- Save Access Tokens for Tumblr API


So I've been up all night trying to figure this out (literally). But Im stumped. What I want to do is, simply, to save access tokens for future use and to allow users to not have to "Allow" the app each time. When I use the access tokens in "done.php" that I stored and retrieved, the "GET" action works but the "POST" doesnt.

addblogs.php (This script, ran right after registration, snags the access tokens and stores them... right now it isn't salted, but it will be)

include('functions.php');
require_once('tumblroauth/tumblroauth.php');
require_once('config.php');
session_start();
sec_session_start();
$tumblrblog = $_SESSION['tumblrblog'];

$connection = new TumblrOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);

$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);

unset($_SESSION['oauth_token']);
unset($_SESSION['oauth_token_secret']);

if (200 == $connection->http_code) {
$at = implode(",",$access_token);

$insert_stmt = $mysqli->prepare("INSERT INTO tumblogs (tumblrblog, access_token) VALUES ( ?, ?)");
   $insert_stmt->bind_param('ss', $tumblrblog, $at); 
   $insert_stmt->execute();
print_r ($access_token);

} else {
  header('Location: ./clearsessions.php');
}

done.php (Retreive and Use the saved access tokens)

include('functions.php');
session_start();
sec_session_start();
require_once('tumblroauth/tumblroauth.php');
require_once('config.php');
$tumblrblog = $_SESSION['tumblrblog'];

$stmt = $mysqli->prepare('SELECT access_token FROM `tumblogs` WHERE tumblrblog=? LIMIT 1');
$stmt->bind_param("s", $tumblrblog);
$stmt->execute();
$stmt->bind_result($at);
$stmt->fetch();

$access_token = explode(",", $at);

$connection = new TumblrOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['0'], $access_token['1']);

print_r($access_token['0']);

$hostname = "$tumblrblog.tumblr.com";
$connection = new TumblrOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['0'], $access_token['1']);
$userinfo = $connection->get('http://api.tumblr.com/v2/user/info');
print_r($userinfo);
$pic_path = "dir/$tumblrblog/good/icon.png";
$pic = file_get_contents($pic_path);
$connection->post('api.tumblr.com/v2/blog/$hostname/post', array('type' => 'text', 'body' => 'this is a test of Tumbloadr v2'));

Thank you all for taking a look!

Brandon


Solution

  • In done.php I would verify that you're also retrieving the correct access token secret by printing $access_token[1] as well. Also, I would remove one of the $connections, theres no need to do it twice. To be a bit more dynamic, you can get the $hostname using this $hostname = parse_url($blog->url,PHP_URL_HOST); This clearly isn't a fix, but hopefully it helps a bit.