Im using abrahams oauth twitter library. but Im having some difficulty posting to twitter from php on my site.
I am receiving zero errors, but nothing is happening. Has anyone been able to solve this very simple issue? Can you share you knowledge?
Thx
/* Load required lib files. */
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('twitteroauth/config.php');
$connection = new TwitterOAuth ('myprivatecode', myprivatecode', 'myprivatecode','myprivatecode');
$content = $connection->get('account/verify_credentials');
$connection->post('statuses/update', array('status' => $myTweet));
Try this,
<?PHP
require_once 'twitteroauth.php';
define("CONSUMER_KEY", "....");
define("CONSUMER_SECRET", "...");
define("OAUTH_TOKEN", "...");
define("OAUTH_SECRET", "...");
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET);
$content = $connection->get('account/verify_credentials');
$connection->post('statuses/update', array('status' => 'test'));
?>
After requesting Read & Write permissions, you have to RECREATE your access tokens to reflect the new permissions.
A working example for Post to twitter using PHP Oauth API
Hope it helps..
" /* Load required lib files. */ session_start();
require_once('twitteroauth/twitteroauth.php'); require_once('twitteroauth/config.php');
$connection = new TwitterOAuth ('myprivatecode', myprivatecode' 'myprivatecode','myprivatecode');
$content = $connection->get('account/verify_credentials'); $connection->post('statuses/update', array('status' => $myTweet)); "
Have you set a variable via a form post or anything for
$mytweet
Without any more information it is hard to tell. I assume the files are correct in the require_once since the file actually processes.
Make sure the form is sent via post, not much else we can help with with so little information.
Related
I had a problem with updating user cover pic using php(zend framework) and Oauth.
I have added to my composer.json the following lines:
"require" : {
"google/auth": "0.7",
"google/apiclient" : "^2.0.0#RC"
}
After that I made composer-install + composer-update using and oppp I get the library inside my vendor.
I have configured my application inside google developing console, following the official tutorial by google :D
Now inside my controller I could easily request google web service using this method :
public function googleplusAction()
{
Zend_Loader::loadFile("HttpPost.class.php");
$client_id = "id_here";
$client_secret = "secret_here";
$application_name = "application_name_here";
$redirect_uri = "redirection_uri_here";
$oauth2_server_url = 'https://accounts.google.com/o/oauth2/auth';
$query_params = array(
'response_type' => 'code',
// The app needs to use Google API in the background
'client_id' => $client_id,
'redirect_uri' => $redirect_uri,
'scope' => 'https://www.googleapis.com/auth/userinfo.profile'
);
$forward_url = $oauth2_server_url . '?' . http_build_query($query_params);
header('Location: ' . $forward_url);
}
After that I get redirected to my redirection URI , and in the bar address I get a new variable 'code'.
Until now, I hope everything is fine , coming to the most important part , the controller of the redirection URI page , using the 'code' variable that I have talked about it before I tried to get an access token, but I was failed.
This is the method that should set a new cover picture on google plus :
$client_id = "client-id";
$client_secret = "g+-secret";
$application_name = "my-app-name";
$redirect_uri = "my-uri-on-g+";
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$service = new Google_Service_Oauth2($client);
$client->addScope(Google_Service_Oauth2::USERINFO_PROFILE);
$client->authenticate($_GET['code']); // I have the right code, and I am being authenticated
$plus = new Google_Service_Plus($client);
$person = $plus->people->get('me');
var_dump($person);
$pic = $this->session->image['generatedAbs'];
$gimg = new Google_Service_Plus_PersonCover();
$source = new Google_Service_Plus_PersonCoverCoverPhoto();
$source ->setUrl("$photo-that-i-wanted-to-put-on-g+");
$gimg->setCoverPhoto($source);
$person->setCover($gimg);}
So my questions are :
How can I change my google plus cover picture to a new png or JPEG picture that I have already in my project ?
inside the G+ library I found this method :
Google_Service_Plus_PersonCoverCoverPhoto();
inside a class called
Google_Service_Plus_PersonCover();
But how can I use it ?
I think that methods Google_Service_Plus_PersonCoverCoverPhoto() and Google_Service_Plus_PersonCover() are used by the client library to set it when the information is retrieved. It is not meant for you to be able to update the users cover on Google+, if that does work it will only update the class object which really there is no point in doing (IMO).
var_dump($person->Cover);
If you check the Plus.People documentation you will notice there are no update or patch methods. This is because its not possible to update a users information programmatically at this time.
Answer: Your inability to update the users cover picture has nothing to do with Oauth it has to do with the fact that this is not allowed by the API. Unfortunately it looks like you have done a lot of work for nothing this is why it is good to always consult the documentation before you begin you would have seen that it was not possible, and could have avoided a lot of unnecessary stress on yourself.
I was wondering is there any method to upload the files directly to our own Google drive by using php , Currently i am using a method like this.
$drive = new Google_Client();
$drive->setClientId($client_id);
$drive->setClientSecret($client_secret);
$drive->setRedirectUri($redirect_uri);
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$gdrive = new Google_DriveService($drive);
$_GET['code'] = 'ya2-------------------------OZXiA';
//file_put_contents('token.json', $drive->authenticate());
$drive->setAccessToken(file_get_contents('token.json'));
$doc = new Google_DriveFile();
$doc->setTitle('Test Document');
$doc->setDescription('Test description');
$doc->setMimeType('text/plain');
$content = file_get_contents('/assets/new--detils.txt');
$output = $gdrive->files->insert($doc, array(
'data' => $content,
'mimeType' => 'text/plain',
));
print_r($output);
But this shows an error as
Fatal error: Uncaught exception Google_AuthException with message 'Error fetching OAuth2 access token, message: 'invalid_grant'' in /var/www/path/src/auth/Google_OAuth2.php:115
Here i am using $_GET['code'] = 'ya2-------------------------OZXiA' generated for that app,
Can anyone please suggest a method to do this, thanks in advance.
Not sure if it helps but I found this looking through Google Code...
"You'll get the invalid_grant error when you try to use the same authorization code."
I found it here: https://code.google.com/p/google-api-php-client/issues/detail?id=94
Not sure if that will help you or not...
Also found this tutorial: http://25labs.com/tutorial-implementing-google-api-using-oauth-2-0-in-php/
$drive = new Google_Client();
$drive->setClientId($client_id);
$drive->setClientSecret($client_secret);
$drive->setRedirectUri($redirect_uri);
**$drive->setAccessType('offline');**
$authUrl = $client->createAuthUrl();
echo $authUrl;
Now go the auth url and get the refresh token and other things.
Make sure this is the first time you are asking for permission, if you aren't then you wont get the refreshtoken which is necessary to make authtokens in the future.
If you have already give permissions just go to your google account and revoke the permissions of the app.
This is what you should have in the file which you are redirecting too.
$tokeninfo = $drive->getAccessToken();
print_r($tokeninfo);
Now save the tokeninfo in a file like "token.json".
Now go back to the original file which will contain the code for upload.
$drive = new Google_Client();
$drive->setClientId($client_id);
$drive->setClientSecret($client_secret);
$drive->setRedirectUri($redirect_uri);
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$drive->setAccessType('offline');
$service = new Google_Service_Drive($drive);
$refreshToken = "Your refresh token";
/* get it from token.json and it will look some like this 1**\/**asasfasfsfsd
remove the \ since this is actually json encoded.*/
$tokens = file_get_contents(TOKEN); /*TOKEN = the token.json file*/
$drive->setAccessToken($tokens);
if ($drive->isAccessTokenExpired()) {
$drive->refreshToken($refreshToken);
file_put_contents(TOKEN,$drive->getAccessToken());
}
Now you have done the authentication and just need to upload the file.
if ($drive->getAccessToken()) {
$file = new Google_Service_Drive_DriveFile();
$file->title ="the file name";
/*the upload code can be found in the examples*/
}
Note
The file you upload cannot be downloaded by other ppl, you need to set googlepermissions to make the file shared.
Just drop a comment if you need to code to add permissions.
Before i make a call to twitter, I check for the chache version of data. If there is no cache, then i create a connection with twitter.
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token);
This is how i have planned to do. I haven't started it yet.
The question is :
Which is best way to do this?
1) Check for the cache, if there is no cache create a new connection and get details from twitter.
2) Create a new connection in top of every file ( or in a header ) check for cache, if there is no cache, (connection is already exists. so) get the details from twitter.
And, How do i check whether the connection ($connection) is active?
The below would roughly do what you're asking for. The example below uses APC
//define cache key
$cacheKey = "twitterResponse[" . md5($endpoint, implode("&", $parameters) . "]";
//attempt to grab from cache
$foundCachedResponse = false;
$twitterResponse = apc_fetch($cacheKey, $foundCachedResponse);
//only when needed
if(!foundCachedResponse){
//twitter connection
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token);
//make the call
$twitterResponse = $connection->getTweetsOrWhatever($parameters);
//cache the response
apc_store($cacheKey, $twitterResponse, 600);
}
//return
return $twitterResponse;
To see if APC is enabled:
if(!extension_loaded('apc')){
die('no APC');
}
I want to post some text automatically to my application twitter account. I create an account for that and take all the needed information and write a php code for it. it is simple code:
I made it just to test the post ability :
<?php
require_once 'oauth/twitteroauth.php';
$message = "hiiiiiii"; #actual message to twitter
define("CONSUMER_KEY", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
define("CONSUMER_SECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
define("OAUTH_TOKEN", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
define("OAUTH_SECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET);
print_r($connection);
$content = $connection->get('account/verify_credentials');
//print_r($content);
$connection->post('statuses/update', array('status' => $message));
?>
I get the information from the account so i think the connection is working but why i can not post any thing? i tried to post this message but after executing this code nothing happened on my twitter no new tweet is shown????
$connection->post is a method :
/**
* POST wrapper for oAuthRequest.
*/
function post($url, $parameters = array()) {
$response = $this->oAuthRequest($url, 'POST', $parameters);
if ($this->format === 'json' && $this->decode_json) {
return json_decode($response);
}
return $response;
}
My first port of call if you are able to receive information from the account using those credentials, would be that your app has read AND write (posting) permissions:
Go to dev.twitter.com/apps. Select your app, then under 'settings' -->
'application type' you will find what you need.
Although that didn't work, no matter what you changed in your code posting to your account through this app wouldn't work as that functionality was outside the permissions you set yourself. So now we know that you're able to post:
Change
$connection->post('statuses/update', array('status' => $message));
To
$result = $connection->post('statuses/update', array('status' => $message));
Then see what the value of $result is. This might provide some clues
Ok so the response is telling you, you still don't have permissions, you need to regenerate your token and access credentials then update your code with them:
define("CONSUMER_KEY", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
define("CONSUMER_SECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
define("OAUTH_TOKEN", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
define("OAUTH_SECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
Those credentials still have the previous permissions attached to them, when you request new token, it will reference the new permissions and allow you to post.
Im using the following code to read to consumer_key and consumer_secret from config.php, pass it to twitter and retrieve some bits of information back from them.
What the script below attempts to do is 'cache' the request_token and request_secret. So in theory I should be able to reuse those details (all 4 of them to automatically tweet when required).
<?php
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
$consumer_key = CONSUMER_KEY;
$consumer_secret = CONSUMER_SECRET;
if (isset($_GET["register"]))
{
// If the "register" parameter is set we create a new TwitterOAuth object
// and request a token
/* Build TwitterOAuth object with client credentials. */
$oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request = $oauth->getRequestToken();
$request_token = $request["oauth_token"];
$request_token_secret = $request["oauth_token_secret"];
// At this I store the two request tokens somewhere.
file_put_contents("request_token", $request_token);
file_put_contents("request_token_secret", $request_token_secret);
// Generate a request link and output it
$request_link = $oauth->getAuthorizeURL($request);
echo "Request here: " . $request_link . "";
die();
}
elseif (isset($_GET["validate"]))
{
// This is the validation part. I read the stored request
// tokens.
$request_token = file_get_contents("request_token");
$request_token_secret = file_get_contents("request_token_secret");
// Initiate a new TwitterOAuth object. This time we provide them with more details:
// The request token and the request token secret
$oauth = new TwitterOAuth($consumer_key, $consumer_secret,
$request_token, $request_token_secret);
// Ask Twitter for an access token (and an access token secret)
$request = $oauth->getAccessToken();
// There we go
$access_token = $request['oauth_token'];
$access_token_secret = $request['oauth_token_secret'];
// Now store the two tokens into another file (or database or whatever):
file_put_contents("access_token", $access_token);
file_put_contents("access_token_secret", $access_token_secret);
// Great! Now we've got the access tokens stored.
// Let's verify credentials and output the username.
// Note that this time we're passing TwitterOAuth the access tokens.
$oauth = new TwitterOAuth($consumer_key, $consumer_secret,
$access_token, $access_token_secret);
// Send an API request to verify credentials
$credentials = $oauth->oAuthRequest('https://twitter.com/account/verify_credentials.xml', 'GET', array());
// Parse the result (assuming you've got simplexml installed)
$credentials = simplexml_load_string($credentials);
var_dump($credentials);
// And finaly output some text
echo "Access token saved! Authorized as #" . $credentials->screen_name;
die();
}
?>
When i run /?verify&oauth_token=0000000000000000 - It works however trying to resuse the generated tokens etc... I get a 401
Here is the last bit of code where I attempt to reuse the details from Twitter combined with my consumer_key and consumer_secret and get the 401:
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
// Read the access tokens
$access_token = file_get_contents("access_token");
$access_token_secret = file_get_contents("access_token_secret");
// Initiate a TwitterOAuth using those access tokens
$oauth = new TwitterOAuth($consumer_key, $consumer_key_secret,
$access_token, $access_token_secret);
// Post an update to Twitter via your application:
$oauth->OAuthRequest('https://twitter.com/statuses/update.xml',
array('status' => "Hey! I'm posting via #OAuth!"), 'POST');
Not sure whats going wrong, are you able to cache the details or do i need to try something else?
You can't store the OAuth tokens in cache and to more than 1 request with it, as OAuth is there to help make the system secure, your "oauth_token" will contain some unique data, this token will only be able to make one call back to twitter, as soon as the call was made, that "oauth_token" is no longer valid, and the OAuth class should request a new "oauth_token", thus making sure that every call that was made is secure.
That is why you are getting an "401 unauthorized" error on the second time as the token is no longer valid.
twitter is still using OAuth v1 (v2 is still in the draft process even though facebook and google already implemented it in some parts)
The image below describes the flow of the OAuth authentication.
Hope it helps.
A while ago I used this to connect to twitter and send tweets, just note that it did make use of some Zend classes as the project was running on a zend server.
require_once 'Zend/Service/Twitter.php';
class Twitter {
protected $_username = '<your_twitter_username>';
protected $_token = '<your_twitter_access_token>';
protected $_secret = '<your_twitter_access_token_secret>';
protected $_twitter = NULL;
//class constructor
public function __construct() {
$this->getTwitter();
}
//singleton twitter object
protected function getTwitter() {
if (null === $this->_twitter) {
$accessToken = new Zend_Oauth_Token_Access;
$accessToken->setToken($this->_token)
->setTokenSecret($this->_secret);
$this->_twitter = new Zend_Service_Twitter(array(
'username' => $this->_username,
'accessToken' => $accessToken,
));
$response = $this->_twitter->account->verifyCredentials();
if ($response->isError()) {
throw new Zend_Exception('Provided credentials for Twitter log writer are wrong');
}
}
return $this->_twitter;
}
//send a status message to twitter
public function update( $tweet ) {
$this->getTwitter()->status->update($tweet);
}
}
In your second script, it looks like you aren't setting the Consumer Key and Consumer Secret when you create your TwitterOAuth instance.
// Initiate a TwitterOAuth using those access tokens
$oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token_secret);