Twitter access to resource error after first connection - php

I successfully setup twitteroauth and posted a message. Now, when I try to post again, and every time AFTER THE FIRST successful message post, I get an error Your credentials do not allow access to this resource. (code 220);
Here's my code:';
$message = 'Test';
$apiKey = Ranger_Application_Util::getConfig('twitter_app_api_key');
$apiSecret = Ranger_Application_Util::getConfig('twitter_app_api_secret');
$consumerToken = Ranger_Application_Util::getStorageData('twitter_oauth_token');
$consumerSecret = Ranger_Application_Util::getStorageData('twitter_oauth_secret');
$twitterOauthVerifier = Ranger_Application_Util::getStorageData('twitter_oauth_verifier');
$_SESSIOM['oauth_token'] = $consumerToken;
$_SESSION['oauth_token_secret'] = $consumerSecret;
require_once 'twitter/twitteroauth.php';
$connection = new TwitterOAuth($apiKey,$apiSecret,$consumerToken,$consumerSecret);
$connection->host = "https://api.twitter.com/1.1/";
$accessToken = $connection->getAccessToken($twitterOauthVerifier);
$_SESSION['access_token'] = $accessToken;
$parameters = array('status' => $message);
$status = $connection->post('statuses/update',$parameters);
Core::dump($status);
die();
The data I retrieve from getStorageData is values stored in the database that pertain to that specific user.

Unless you are storing the information from $accessToken to your database in a piece of code you have not posted, I believe the issue may be that you are getting the access token after your initial connection, but not using the permanent access information from the access token when trying to post to the connection. So any future requests will not be using the permanent credentials and are therefore rejected. Try something like this:
$message = 'Test';
$apiKey = Ranger_Application_Util::getConfig('twitter_app_api_key');
$apiSecret = Ranger_Application_Util::getConfig('twitter_app_api_secret');
$twitterOauthVerifier = Ranger_Application_Util::getStorageData('twitter_oauth_verifier');
require_once 'twitter/twitteroauth.php';
$hasAccessToken = (
array_key_exists('oauth_token', $_SESSION) &&
array_key_exists('oauth_token_secret', $_SESSION));
if ($hasAccessToken)
{
$consumerToken = $_SESSION['oauth_token'];
$consumerSecret = $_SESSION['oauth_token_secret'];
}
else
{
$consumerToken = Ranger_Application_Util::getStorageData('twitter_oauth_token');
$consumerSecret = Ranger_Application_Util::getStorageData('twitter_oauth_secret');
$connection = new TwitterOAuth($apiKey, $apiSecret, $consumerToken, $consumerSecret);
$connection->host = "https://api.twitter.com/1.1/";
$accessToken = $connection->getAccessToken($twitterOauthVerifier);
$consumerToken = $accessToken['oauth_token'];
$consumerSecret = $accessToken['oauth_token_secret'];
$_SESSION['oauth_token'] = $consumerToken;
$_SESSION['oauth_token_secret'] = $consumerSecret;
}
$connection = new TwitterOAuth($apiKey, $apiSecret, $consumerToken, $consumerSecret);
$connection->host = "https://api.twitter.com/1.1/";
$parameters = array('status' => $message);
$status = $connection->post('statuses/update', $parameters);
Core::dump($status);
die();
You may want to store the oauth token information in your database after receiving it from getAccessToken() rather than using sessions. Maybe you have a method like Ranger_Application_Util::setStorageData('twitter_oauth_token', $consumerToken)?

This
$_SESSIOM['oauth_token'] = $consumerToken;
^
should be
$_SESSION['oauth_token'] = $consumerToken;

Related

how to set the oauth_verifier in the header twitteroauth php

I'm getting the following error:
Error processing your OAuth request: Invalid oauth_verifier parameter
I keep reading that the issue is that in the library TwitterOAuth by Abraham we need to set the oauth_verifier in the header and not the body.
I don't know how to do this.
Here is my code:
// twitterlogin.php
session_start();
$twitterKey = 'xxx';
$twitterSecret = 'xxx';
$callback = "https://xxx/socialmedia/twittercallback.php";
require_once("/xxx/twitteroauth/vendor/autoload.php");
use Abraham\TwitterOAuth\TwitterOAuth;
$twitter = new TwitterOAuth($twitterKey,$twitterSecret);
$result = $twitter->oauth('oauth/request_token', ['oauth_callback' => $callback]);
$_SESSION['oauth_token'] = $result['oauth_token'];
$_SESSION['oauth_token_secret'] = $result['oauth_token_secret'];
$url = $twitter->url('oauth/authorize', array('oauth_token' => $result['oauth_token']));
header("Location: $url");
// twittercallback.php
session_start();
require_once("/xxx/api");
$twitterKey = 'xxx';
$twitterSecret = 'xxx';
require_once("/xxx/twitteroauth/vendor/autoload.php");
$twitter = new \Abraham\TwitterOAuth\TwitterOAuth($twitterKey,$twitterSecret,$_SESSION['oauth_token'],$_SESSION['oauth_token_secret']);
try {
$access_token = $twitter->oauth("oauth/access_token", ["oauth_verifier" => $_GET['oauth_verifier']]);
$_SESSION['access_token'] = $access_token;
} catch(\Exception $e){
print "<pre>".print_r($e,true)."</pre>";
}
var_dump($access_token);
How do I set the oauth_verifier in the header?
Thanks!

Twitter returns [code] => 89 I just trying to use second time the tookens

Hi im using this code for getting the oauth_token and oauth_token_secret
require 'autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => OAUTH_CALLBACK));
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
$url = $connection->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token']));
echo $url;
header('Location: '.$url);
and on my call back url it is:
$request_token = [];
$request_token['oauth_token'] = $_REQUEST['oauth_token'];
$request_token['oauth_token_secret'] = 'JeVDKh0rSfBozrJ65p1lG4HaDmBtLkqF';
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_REQUEST['oauth_token'], $request_token['oauth_token_secret']);
$access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $_REQUEST['oauth_verifier']));
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$user = $connection->get("account/verify_credentials");
$add = "INSERT INTO users SET
name = '".$user->name."',
username = '".$user->screen_name."',
oauth_token = '".$_REQUEST['oauth_token']."',
oauth_token_secret = '".$_SESSION['oauth_token_secret']."',
oauth_verifier = '".$_REQUEST['oauth_verifier']."',
id_string = '".$user->id_str."',
status = '1' ";
but when after that from database when i try to login it gives me
[code] => 89
[message] => Invalid or expired token.
on every access token im getting this error. i'm using this code for relogin
$oauth_token = 'token from db';
$oauth_token_secret = 'token_secrete from db';
$oauth_verifier = 'aoth verifier from db that i stored';
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $oauth_token, $oauth_token_secret );
$access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $oauth_verifier ));
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $oauth_token, $oauth_token_secret);
$user = $connection->get("account/verify_credentials");
Please help me whats the issue with my code. I have read tw don't expire the access token. so whats wrong with my current scenario..
You don't have to manually assigning access_token_secret as they are generated. First, inside your callback you may wish to add an expression just in case the oauth_token given in URL doesn't same with saved oauth_token on session on the time you're doing a request.
if ($_SESSION['oauth_token'] !== $_REQUEST['oauth_token']) {
echo 'Oauth token does not match!';
exit();
}
Assuming they're match, now, create a connection with oauth_token and oauth_token_secret that stored on session.
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
Above connection is only created for verifying your access token. Now, verify it with $_REQUEST['oauth_verifier'] that appears on your callback URL param.
$access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $_REQUEST['oauth_verifier']));
Afterward, your access token has now verified. You may store it to session (overwrite session beforehand or create a new one) or to database as you do.
//Verified access token
$oauth_token = $access_token['oauth_token'];
$oauth_token_secret = $access_token['oauth_token_secret'];
As it's been verified, now you should create another connection to playing around with. Just like what you do, looking up account's credentials.
$newConnection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $oauth_token, $oauth_token_secret);
$user = $newConnection->get("account/verify_credentials");
$add = "INSERT INTO users SET
name = '".$user->name."',
username = '".$user->screen_name."',
oauth_token = '".$oauth_token."',
oauth_token_secret = '".$oauth_token_secret."',
id_string = '".$user->id_str."',
status = '1' ";
Notice that I remove oauth_verifier as you don't need it. The use of it is only to verify unverified access token, just like you create a new request for the first time.
And last, you may follow last snippet to open another connection from access token that stored on database.
$oauth_token = $row['oauth_token_from_db'];
$oauth_token_secret = $row['oauth_token_secret_from_db'];
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $oauth_token, $oauth_token_secret);

How do you get user OAuth for the Tumblr API in PHP?

Using the default Tumblr v2 API, I'm able to connect to my application, and retrieve posts from my own account. However, I'd like users to be able to connect their own accounts. I've tried to figure this out but I'm not entirely sure how to use OAuth (im using this class). How is this done?
The code I'm using to retrieve dashboard posts is:
$consumerKey = 'xxx';
$consumerSecret = 'xxx';
$tumblr = new Tumblr\API\Client(
$consumerKey,
$consumerSecret
);
var_dump( $tumblr->getDashboardPosts() ); // using var_dump for testing purposes only
This code works, but it's only returning the code for my PERSONAL account.
I figured it out, thanks to Github user seejohnrun.
require_once 'include/util.php';
$consumerKey = 'XXX';
$consumerSecret = 'XXX';
$client = new Tumblr\API\Client($consumerKey, $consumerSecret);
$requestHandler = $client->getRequestHandler();
$requestHandler->setBaseUrl('https://www.tumblr.com/');
// If we are visiting the first time
if (!$_GET['oauth_verifier']) {
// grab the oauth token
$resp = $requestHandler->request('POST', 'oauth/request_token', array());
$out = $result = $resp->body;
$data = array();
parse_str($out, $data);
// tell the user where to go
echo ' GO ';
$_SESSION['t']=$data['oauth_token'];
$_SESSION['s']=$data['oauth_token_secret'];
} else {
$verifier = $_GET['oauth_verifier'];
// use the stored tokens
$client->setToken($_SESSION['t'], $_SESSION['s']);
// to grab the access tokens
$resp = $requestHandler->request('POST', 'oauth/access_token', array('oauth_verifier' => $verifier));
$out = $result = $resp->body;
$data = array();
parse_str($out, $data);
// and print out our new keys we got back
$token = $data['oauth_token'];
$secret = $data['oauth_token_secret'];
echo "token: " . $token . "<br/>secret: " . $secret;
// and prove we're in the money
$client = new Tumblr\API\Client($consumerKey, $consumerSecret, $token, $secret);
$info = $client->getUserInfo();
echo "<br/><br/>congrats " . $info->user->name . "!";
}

Using twitterOAuth for login scripts

I recently started working with twitteroauth login, which seems to be working in the examples (found here) but not when I amalgamate the redirect.php and callback.php
Based on the script below (which is integrated in a bit of login script I've been working on) the second portion works fine (which is based on redirect.php), returning an oauth_token and oauth_verifier, but the first part (based on callback.php) isn't even initiating it seems. Which it should when Twitter redirects the user to the homepage.
Any ideas/suggestions folks?
session_start();
require_once('socialCodes.php'); //where I keep my app ID and Secret
require_once('twitteroauth/twitteroauth.php');
if (isset($_GET['oauth_token'])) {
$connection = new TwitterOAuth($twAppID, $twAppSec, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$connection->host = "https://api.twitter.com/1.1/";
$access_token = $connection->getAccessToken($_GET['oauth_verifier']);
$_SESSION['access_token'] = $access_token;
unset($_SESSION['oauth_token']);
unset($_SESSION['oauth_token_secret']);
if (200 == $connection->http_code) {
$userAccessToken = $access_token['oauth_token'];
$userSecretToken = $access_token['oauth_token_secret'];
$userID = $access_token['user_id'];
$userName = $access_token['screen_name'];
}
} else {
$connection = new TwitterOAuth($twAppID, $twAppSec);
$connection->host = "https://api.twitter.com/1.1/";
$request_token = $connection->getRequestToken('myhomepage');
$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
switch ($connection->http_code) {
case 200:
$url = $connection->getAuthorizeURL($token);
header('Location: ' . $url);
break;
default:
echo 'Could not connect to Twitter. Refresh the page or try again later.';
}
}
Turns out this was a caching issue, and the script now works.

twitter oauth authentication and posting tweet not working

So I'm trying to post tweets of a user through my application. Whenever I freshly get the oauth_token and oauth_secret, I can post a tweet no problem, However, if I try to save them for later and then post a tweet, I get the error:
object(stdClass)#5 (2) {
["error"]=>
string(27) "Could not authenticate you."
["request"]=>
string(23) "/1/statuses/update.json"
}
Here is the script I use to get the tokens initially:
<?php
require("config.php");
require("twitterOAuth.php");
session_start();
if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token']) && !empty($_SESSION['oauth_token_secret'])){
// We've got everything we need
} else {
// Something's missing, go back to square 1
//header('Location: new_index.php');
}
// TwitterOAuth instance, with two new parameters we got in twitter_login.php
$twitteroauth = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
// Let's request the access token
$oauth_token = $_SESSION['oauth_token'];
$oauth_secret = $_SESSION['oauth_token_secret'];
$access_token = $twitteroauth->getAccessToken($_GET['oauth_verifier']);
//post tweet
$result = $twitteroauth->post('statuses/update', array('status' => 'asd '));
// Save it in a session var
$_SESSION['access_token'] = $access_token;
// Let's get the user's info
$user_info = $twitteroauth->get('account/verify_credentials');
?>
And here is the script where I just try to tweet it using the tokens:
<?php
require("config.php");
require_once('twitterOAuth.php');
$oAuthToken = $argv[1];
$oAuthSecret = $argv[2];
$message = $argv[3];
$post_id = $argv[4];
// create a new instance
$tweet = new TwitterOAuth($consumerKey, $consumerSecret, "$oAuthToken", "$oAuthSecret");
//send a tweet
$result = $tweet->post('statuses/update', $message);//array('status' => "$message"));
$tweet_id = $result['id_str'];
?>
Any ideas? I could really use some help here. It worked fine last night and now all the sudden it's not working at all :/
Could the tokens expire and not work after they're not session variables?
/*Try this one it will work proper*/
session_start();
require("config.php");
require_once("twitterOAuth.php");
$access_token = $_SESSION['access_token'];//which you got from callback
/* Create a TwitterOauth object with consumer/user tokens. */
$tweet = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$tweet->post('direct_messages/new', array('text' => $messageBody, 'screen_name' => $screenName))
Try to use this code (in the second part of your code):
<?php
session_start();
require("config.php");
require_once("twitterOAuth.php");
$oAuthToken = $_SESSION['oauth_token'];
$oAuthSecret = $_SESSION['oauth_token_secret'];
and so on. Does this code work for you?

Categories