I'm having troubles posting to twitter with codebird.
This is the error message that I get when I log $reply.
[code] => 89
[message] => Invalid or expired token.
This is my code
require_once __DIR__ . '/includes/codebird/src/codebird.php';
\Codebird\Codebird::setConsumerKey($consumer_key, $consumer_secret);
$cb = \Codebird\Codebird::getInstance();
$cb->setToken($access_token, $access_token_secret);
$reply = $cb->statuses_update('status=Whohoo, I just tweeted!');
For the oAuth I have "read and write" option selected and for callback URL I have http://127.0.0.1
Any help is much appreciated.
Related
I have generated tokens and code and everything and i am able to login and authorize the user but somehow I am getting error. Two error has been spotted.
First One
(
[error] => invalid_grant
[error_description] => Authorization code doesn't exist or is invalid for the client
)
Sometimes authorization code is not generating so I am getting above error. And sometimes when I am able to generate auth_code I am getting below error
{"error":"invalid_token","error_description":"The access token provided is invalid"}
I am developer of the site abcd.com and now I have a platform where I need to develop my abcd.com for that platform. To implement login I have to use OAuth2.0 and this is the requirement of the platform. I have read a lot of documents on OAuth2.0 and build the app. I am using codeigniter though.
server.php
$dsn = 'mysql:dbname=my_oauth2_db;host=localhost';
$username = 'root';
$password = '';
// error reporting (this is a demo, after all!)
ini_set('display_errors',1);error_reporting(E_ALL);
// Autoloading (composer is preferred, but for this example let's just do this)
require_once('oauth2-server-php/src/OAuth2/Autoloader.php');
OAuth2\Autoloader::register();
// $dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost"
$storage = new OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));
// Pass a storage object or array of storage objects to the OAuth2 server class
$server = new OAuth2\Server($storage);
// Add the "Client Credentials" grant type (it is the simplest of the grant types)
$server->addGrantType(new OAuth2\GrantType\ClientCredentials($storage));
// Add the "Authorization Code" grant type (this is where the oauth magic happens)
$server->addGrantType(new OAuth2\GrantType\AuthorizationCode($storage));
$scope = new OAuth2\Scope(array(
'supported_scopes' => array('email')
));
$server->setScopeUtil($scope);
Here is my authorize.php
require_once __DIR__.'/server.php';
$request = OAuth2\Request::createFromGlobals();
$client_id = $request->query['client_id'];
$response = new OAuth2\Response();
if (!$server->validateAuthorizeRequest($request, $response)) {
$response->send();
die;
}
if (empty($_POST)) {
exit('<form method="post">
<label>Do You Authorize '.$client_id.'?</label><br />
<input class="yes_authorize" type="submit" name="authorized" value="Yes">
<input class="no_authorize" type="submit" name="authorized" value="No">
</form>');
}
$is_authorized = ($_POST['authorized'] === 'Yes');
$server->handleAuthorizeRequest($request, $response, $is_authorized);
if ($is_authorized) {
$code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=')+5, 40);
$client_secret = $_GET['state'];
$token_value = shell_exec("curl -u CLIENT_ID:CLIENT_SECRET https://abcd.com/api/token.php -d 'grant_type=authorization_code&code=$code'");
$token = json_decode($token_value);
$access_token = $token->access_token;
$expires_in = $token->expires_in;
$state = $_GET['state'];
$resource_result = shell_exec("curl https://abcd.com/api/resource.php -d 'access_token=$code'");
$redirect_url = $_GET['redirecturi']."?code=$access_token&state=".$_GET['state'];
exit(header("location: $redirect_url"));
}
$response->send();
resource.php
require_once __DIR__.'/server.php';
if (!$server->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
$server->getResponse()->send();
die;
}
echo json_encode(array('success' => true, 'message' => 'You accessed my APIs!'));
token.php
require_once __DIR__.'/server.php';
$server->handleTokenRequest(OAuth2\Request::createFromGlobals())->send();
If you see authorize.php, After generating access_token through token.php, If I pass that to resource.php, I am getting second error. AND I have passed auth_code as well as access_token both to my redirect url, but I am getting not able to get through.
I am trying to get access token from twitter using codebird, first getting user to authorize use of my application works perfectly using this code
require_once('lib/codebird.php');
\Codebird\Codebird::setConsumerKey("xxx", "xxxx");
$cb = \Codebird\Codebird::getInstance();
session_start();
// get the request token
$reply = $cb->oauth_requestToken(array(
'oauth_callback' => 'http://lifetanstic.co.ke/AppRegister'));
// store the token
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
$_SESSION['oauth_verify'] = true;
// redirect to auth website
$auth_url = $cb->oauth_authorize();
?>
<script type="text/javascript">
window.location = "<?php echo $auth_url; ?>";
</script>
<?php
//header('Location: ' . $auth_url);
?>
This is where I am redirected here:
When then I get redirected to the window in where I am supposed to get the access token and access token secret and that also works.
Here is where using $_GET[] I get the following codes http://lifetanstic.co.ke/AppRegister?oauth_token=zzzzz&oauth_verifier=zzzz
Now in that page when I run the following code, it does not work, but produces the following error:
require_once('lib/codebird.php');
session_start();
\Codebird\Codebird::setConsumerKey("xxxx", "xxxx");
$cb = \Codebird\Codebird::getInstance();
// get the access token
$reply = $cb->oauth_accessToken(array(
'oauth_verifier' => $_GET['oauth_verifier']
));
var_dump($reply);
When I dump the reply, it has the following error in it:
object(stdClass)#1 (3) { ["message"]=> string(21) "Invalid request token" ["httpstatus"]=> int(401) ["rate"]=> NULL }
So how am I supposed to get the aouth_accessToken, with this oauth_token=zzzzz&oauth_verifier=zzzz url parameters provide and a user has authorised use of my application?
so let me answer my own question, the part of the code that did not work was this:
require_once('lib/codebird.php');
session_start();
\Codebird\Codebird::setConsumerKey("xxxx", "xxxx");
$cb = \Codebird\Codebird::getInstance();
// get the access token
$reply = $cb->oauth_accessToken(array(
'oauth_verifier' => $_GET['oauth_verifier']
));
var_dump($reply);
And i realized why, in the tutorial for codebird here https://github.com/jublonet/codebird-php there is something i thought it was not a necessary but the moment is reinstated it, it worked miracurously, this line of code
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
So the final code will be like this:
require_once('lib/codebird.php');
session_start();
\Codebird\Codebird::setConsumerKey("xxxx", "xxxxx");
$cb = \Codebird\Codebird::getInstance();
// get the access token
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
/*$reply = $cb->oauth_requestToken(array(
'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
));*/
$reply = $cb->oauth_accessToken(array(
'oauth_verifier' => $_GET['oauth_verifier']
));
//var_dump($reply);
uncomment the last line to show the results in greater details
to confirm the results, i posted to twitter successfully using this code:
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
$params = array(
'status' => '1Auto Post on Twitter with PHP http://goo.gl/OZHaQD #php #twitter #Maina_Wycliffe'
);
$reply = $cb->statuses_update($params);
//var_dump($reply);
and here is the evidence, tweet url-> https://twitter.com/Maina_Wycliffe/status/595995951132712960
and tweets itself
Hope this will assist you
This is really weird because
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
should not work. the first variable is not OAuth access token. You need to get this token from authorization URL - this is what was this invented for. Maybe other users may want to use your app.
Even if I have this line of code in my script I cannot tweet because I got "invalid token" error, so for me whole codebird library is a mess with no proper documentation :(
Can anyone help me to solve this issue, I am breaking my head for the past 48 hours on this.
Objective:
I am trying to post some information to my friends facebook wall through my website.
Everything was working fine before but I am getting an error now:
Fatal error: Uncaught OAuthException: (#200) The user hasn't authorized the application to perform this action thrown in /home/abcd/public_html/front_apps/controllers/src/base_facebook.php on line 1039
Also what I am trying to do is, to post it on my friends Facebook wall when I am offline, using cron and to post daily by 12.00 am.
I am using PHP code here is the code:
<?php
$message = "Message goes here";
$link = "http://link.com/";
$picture = "http://link.com/1.jpg";
$sendTo = "my friend id";
$access_token = "access tocken";
require 'src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'appId',
'secret' => 'secret_ID',
)); <br>
$attachment = array('message' => $message, 'link' => $link, 'picture' => $picture );
$api = "/$sendTo/feed/?access_token='.$access_token,";
$result = $facebook->api($api,'post', $attachment);
?>
Since facebook deprecated Offline Acces, you have to get long lived token (valid for 60 days) and store it on your server! Here is what I'm using.
To Get the long lived token right away use server side login flow
$code = $_REQUEST["code"];
//get acces token from user
$token_url = "https://graph.facebook.com/oauth/access_token?"."client_id=".$config[‘appId’]."&redirect_uri=".urlencode($my_url)."&client_secret=".$config[‘secret’]."&code=".$code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$token = $params['access_token']; //long live the token
and for posting to users wall
//construct the image URL
$url ="https://".$_SERVER['SERVER_NAME'].$event_data['path'];
$img_url = urlencode($url); //encode the URL
$text= urlencode($event_data['text']);
//post to user wall - picture and text
$post_url= "https://graph.facebook.com/".$user_data['uid']."/photos?url=".$img_url."&message=".$text."&access_token=".$user_data['token']."&method=post";
$upload_photo = file_get_contents($post_url);
Hope it helps ;)
Check out this link and follow the steps.
http://eagerfish.eu/using-facebook-off-line-access-to-post-on-users-wall/enter link description here
Check the below link also,
Uncaught OAuthException: (#200), when trying to post on wallenter link description here
I am currently trying to integreate twitter into a php web app that I am working on with OAuth.
I have an HTML page which provides a link to the twitter app authentication url which appears to be working fine and is showing the authentication screen.
Below is the code that calls the function.
if (!isset($_GET['oauth_token']))
{
//include("phpHandler/twitterLib/secret.php");
getTwitterURL($consumer_key, $consumer_secret);
}
The consumer_key and consumer_secret are included within a php file.
Below is the code that gets the twitter authorisation url.
function getTwitterUrl($consumer_key, $consumer_secret)
{
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$url = $twitterObj->getAuthorizationUrl();
echo '<a class="linkButtons" href="'.$url.'">Add Twitter</a>';
}
This redirect back to the page fine and then I call the authentication method to retrieve info like twitter username. Below is the function that does the authentication
function authenticate($consumer_key, $consumer_secret)
{
require ("twitterLib/EpiCurl.php");
require ("twitterLib/EpiOAuth.php");
require ("twitterLib/EpiTwitter.php");
require ("twitterLib/secret.php");*/
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$twitterObj->setToken($_GET['oauth_token']);
$token = $twitterObj->getAccessToken();
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
$token = $twitterObj->getAccessToken();
$twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
$_SESSION['ot'] = $token->oauth_token;
$_SESSION['ots'] = $token->oauth_token_secret;
$twitterInfo= $twitterObj->get_accountVerify_credentials();
echo '<pre>';
print_r($twitterInfo->response);
}
The echo and print_r is to show the response return from twitter.
I am getting the following error printed out in the array
Array (
[error] => Invalid / expired Token
[request] => /account/verify_credentials.json )
How can I fix this error. I don't know why its invalid or expired, I have closed the browser and started again but get the same error appear.
Thanks for any help you can provide.
Your access token will be invalid if a user explicitly rejects your application from their settings or if a Twitter admin suspends your application. If your application is suspended there will be a note on your application page saying that it has been suspended.
Many users trust an application to read their information but not necessarily change their name or post new statuses. Updating information via the Twitter API - be it name, location or adding a new status - requires and HTTP POST. We stuck with the same restriction when implementing this. Any API method that requires an HTTP POST is considered a write method and requires read & write access.
Whatever your storage system may be, you'll need to begin storing an oauth_token and oauth_token_secret (collectively, an "access token") for each user of your application. The oauth_token_secret should be stored securely. Remember, you'll be accessing these values for every authenticated request your application makes to the Twitter API, so store them in a way that will scale to your user base. When you're using OAuth, you should no longer be storing passwords for any of your users.
require '../tmhOAuth.php';
require '../tmhUtilities.php';
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => 'YOUR_CONSUMER_KEY',
'consumer_secret' => 'YOUR_CONSUMER_SECRET',
'user_token' => 'AN_ACCESS_TOKEN',
'user_secret' => 'AN_ACCESS_TOKEN_SECRET',
));
// we're using a hardcoded image path here. You can easily replace this with an uploaded image-see images.php example)
// 'image = "#{$_FILES['image']['tmp_name']};type={$_FILES['image']['type']};filename={$_FILES['image']['name']}",
$image = "./dickvandyke.jpg';
$code = $tmhOAuth->request('POST', 'https://upload.twitter.com/1/statuses/update_with_media.json',
array(
'media[]' => "#{$image}",
'status' => "Don't slip up" // Don't give up..
),
true, // use auth
true // multipart
);
if ($code == 200) {
tmhUtilities::pr(json_decode($tmhOAuth->response['response']));
} else {
tmhUtilities::pr($tmhOAuth->response['response']);
}
I've managed to find the problem. I always creating two new EpiTwitter objects in the authenticate function.
I worked on new Twitter API. It is working fine for me with following code I did.
<?php
require "vendor/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
$consumer_key = "XXXXXXX";
$consumer_secret = "XXXXXXX";
$connection = new TwitterOAuth($consumer_key, $consumer_secret);
$request_token= $connection->oauth('oauth/request_token', array('oauth_callback' => "http://callbackurlhere.com/callback.php"));
$url = $connection->url("oauth/authorize", array("oauth_token" => $request_token['oauth_token']));
header('Location: '. $url);
?>
callback.php code below to obtain the permanent oauthToken and save it in database for further use:
<?php
require "vendor/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
// session_start();
if(isset($_REQUEST['oauth_verifier'])){
$oauth_access_token = $_REQUEST['oauth_token'];
$oauth_access_token_secret = $_REQUEST['oauth_verifier'];
$consumer_key = "XXXXXXXXXXXXXXXX";
$consumer_secret = "XXXXXXXXXXXXXXX";
$connection = new TwitterOAuth($consumer_key, $consumer_secret,$oauth_access_token , $oauth_access_token_secret );
$access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $oauth_access_token_secret));
var_dump($access_token); die("--success here--");// Obtain tokens and save it in database for further use.
}
?>
I have spent a ton of hours on this and cannot for the life of me figure out what the problem is here. I am writing my own twitter web app. I downloaded the OAuth PHP Library which is what I am using. Everything was setup correctly.
I did Step 1 and "Acquire a Request Token". I got a correct response back with a token, token secret and callback confirmed of TRUE.
Now I proceeded to the next step of "Send User to Authorization" and passed along the oauth_token parameter to the request. The request got sent and redirects to the Twitter page, but when it gets there is is showing an error message of :
Exception Request failed with code 403:
Woah there!
This page requires some information that was not provided. Please return to the site that sent you to this page and try again … it was probably an honest mistake.
What is the problem?? The error message is not very helpful. According to Twitter 403 means the request was understood but denied. I am really stuck here and would appreciate the help with this one.
Here is what the code looks like (I have obviously replaces my token and secret keys with ########, so if anyone wanted to test this locally with their own keys, just replace the ######### values:
<?php
include_once "scripts/OAuth/OAuthStore.php";
include_once "scripts/OAuth/OAuthRequester.php";
// register at http://twitter.com/oauth_clients and fill these two
define("TWITTER_CONSUMER_KEY", "#############");
define("TWITTER_CONSUMER_SECRET", "#############");
define("TWITTER_OAUTH_HOST","https://api.twitter.com");
define("TWITTER_REQUEST_TOKEN_URL", TWITTER_OAUTH_HOST . "/oauth/request_token");
define("TWITTER_AUTHORIZE_URL", TWITTER_OAUTH_HOST . "/oauth/authorize");
define("TWITTER_ACCESS_TOKEN_URL", TWITTER_OAUTH_HOST . "/oauth/access_token");
define("TWITTER_PUBLIC_TIMELINE_API", TWITTER_OAUTH_HOST . "/statuses/public_timeline.json");
define("TWITTER_UPDATE_STATUS_API", TWITTER_OAUTH_HOST . "/statuses/update.json");
define('OAUTH_TMP_DIR', function_exists('sys_get_temp_dir') ? sys_get_temp_dir() : realpath($_ENV["TMP"]));
// Twitter test
$options = array('consumer_key' => TWITTER_CONSUMER_KEY, 'consumer_secret' => TWITTER_CONSUMER_SECRET);
OAuthStore::instance("2Leg", $options);
try
{
// Obtain a request object for the request we want to make
$request = new OAuthRequester(TWITTER_REQUEST_TOKEN_URL, "POST");
$result = $request->doRequest(0);
parse_str($result['body'], $params);
list($token, $secret, $status) = explode('&', $result['body']);
// now make the request.
$request = new OAuthRequester(TWITTER_AUTHORIZE_URL, 'POST', $token);
$result = $request->doRequest();
}
catch(OAuthException2 $e)
{
echo "Exception " . $e->getMessage();
}
?>