Twitter OAuth Error 220 - php

I have an application that Authenticates a user using OAuth and gets all of the permissions needed to post an update for a twitter user but when i try to actually do the post I get this response:
stdClass Object ( [errors] => Array ( [0] => stdClass Object ( [code] => 220 [message] => Your credentials do not allow access to this resource. ) ) )
here is my code for the authentication when they first link twitter:
// The TwitterOAuth instance
$twitteroauth = new TwitterOAuth(TWITTER_KEY, TWITTER_SECRET);
// Requesting authentication tokens, the parameter is the URL we will be redirected to
$request_token = $twitteroauth->getRequestToken(TWITTER_CALLBACK_URL);
// Saving them into the session
$_SESSION['twitter_oauth_token'] = $request_token['oauth_token'];
$_SESSION['twitter_oauth_token_secret'] = $request_token['oauth_token_secret'];
// If everything goes well..
if($twitteroauth->http_code==200){
// Let's generate the URL and redirect
$url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);
header('Location: '. $url);
} else {
// Remember to adds script for error handling and reporting but for now kill the script
die('Something wrong happened.');
}
And here is what happend when they get to the callback:
if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['twitter_oauth_token']) && !empty($_SESSION['twitter_oauth_token_secret'])){
// TwitterOAuth instance, with two new parameters we got in twitter_login.php
$twitteroauth = new TwitterOAuth(TWITTER_KEY, TWITTER_SECRET, $_SESSION['twitter_oauth_token'], $_SESSION['twitter_oauth_token_secret']);
// Let's request the access token
$access_token = $twitteroauth->getAccessToken($_GET['oauth_verifier']);
// 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');
if(isset($user_info->error)){
// Something's wrong, go back to square 1
header('Location: networks.php?connect=2');
} else {
// Let's find the user by its ID
$query = mysql_query("SELECT * FROM connected_accounts WHERE oauth_provider = 'twitter' AND oauth_uid = ". $user_info->id);
$result = mysql_fetch_array($query);
// If not, let's add it to the database
if(empty($result)){
$query = mysql_query("INSERT INTO connected_accounts (user_id, account_id, oauth_provider, acct_usr_id, oauth_uid, username, token, secret) VALUES ('".${'User'}['id']."', '2', 'twitter', ".$user_info->id.", ".$user_info->id.", '".$user_info->screen_name."', '".$access_token['oauth_token']."', '".$access_token['oauth_token_secret']."')");
$query = mysql_query("SELECT * FROM connected_accounts WHERE id = " . mysql_insert_id());
$result = mysql_fetch_array($query);
} else {
// Update the tokens
$query = mysql_query("UPDATE connected_accounts SET token = '".$access_token['oauth_token']."', secret = '".$access_token['oauth_token_secret']."' WHERE oauth_provider = 'twitter' AND oauth_uid = ".$user_info->id);
}
$_SESSION['id'] = $result['id'];
$_SESSION['username'] = $result['username'];
$_SESSION['oauth_uid'] = $result['oauth_uid'];
$_SESSION['oauth_provider'] = $result['oauth_provider'];
$_SESSION['oauth_token'] = $result['token'];
$_SESSION['oauth_secret'] = $result['secret'];
header('Location: manage_accounts.php');
}
} else {
// Something's missing, go back to square 1
header('Location: networks.php?connect=2');
}
// Get our permenant token
$response = $twitter_client->getAccessToken($_GET['oauth_verifier']);
// If we did not receive a permenant token, notify the user
if (!$response['oauth_token']) {
$message = '<center><div class="error">An error occurred while linking your Twitter account. Please try again later.</div></center>';
// Otherwise
} else {
// Update our info
mysql_query('UPDATE `connected_accounts` SET `token` = "'.$response['oauth_token'].'", `acct_usr_id` = "'.$response['user_id'].'", `secret` = "'.$response['oauth_token_secret'].'" WHERE `account_id` = 2 AND `user_id` = '.${'User'}['id']) or die(mysql_error());
// Send the user to the post page
header('Location: manage_accounts.php'); exit;
}
I am using the Library from https://github.com/abraham/twitteroauth
Everything used to work just fine but now it isn't working.
It seems that it has something to do with application only authentication but I am using OAuth which is supposed to allow posting to statuses/update

Related

Trying to use referesh tokens with google PHP api

This is my first time implementing login via google and I am a beginner programmer. I have been stuck on implementing refresh tokens using google api and outh 2.
Here is the code I am using to implement the login
<?php
ob_start();
session_start();
require_once 'init.php';
require('vendor/autoload.php');
//Details for setting up the google login
$client = new Google_Client();
$client->setAccessType("offline");
$client->setAuthConfigFile('client_secrets.json');
$client->setScopes(array('https://www.googleapis.com/auth/plus.login','https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/plus.me'));
$oauth2 = new Google_Service_Oauth2($client);
/************************************************
Logout function
************************************************/
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
header('Location:http://localhost:1234/trial/log-inlogic/');
}
/************************************************
Get the code back from the OAuth 2.0 flow,
exchange that with the authenticate()
function.
************************************************/
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
/************************************************
If we have an access token, I make
requests, else I generate an authentication URL.
************************************************/
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
else {
$authUrl = $client->createAuthUrl();
}
/************************************************
In case the token is expired, this is where i have a problem
************************************************/
if ($client->getAccessToken()) {
//Check if our token has expired.
if ($client->isAccessTokenExpired()) {
// create this function to store the referesh token in the database
$refreshToken = getRefreshToken();
$client->refreshToken($refreshToken);
}
//Basic User Information
$user = $oauth2->userinfo->get();
try {
google_login( $user );
}catch (Exception $e) {
$error = $e->getMessage();
}
$_SESSION['token']=$client->getAccessToken();
//Save the refresh token on our database.
}
//Simple function to store a given refresh_token on a database
function setRefreshToken () {
if (isset($_SESSION['k_id'])) {
$k_id=$_SESSION['k_id'];
$accesstoken=$_SESSION['token'];
$token=json_decode($_SESSION['token']);
echo $token->refresh_token;
$result =query("UPDATE users SET refreshtoken=$token WHERE k_id='$k_id'");
}
}
//Retrieves the refresh_token from our database.
function getRefreshToken () {
if (isset($_SESSION['k_id'])) {
$k_id=$_SESSION['k_id'];
$result = query("SELECT refresh_token FROM users WHERE k_id='$k_id'");
if(count($result)==0){
}
else{
return $result[0]['refresh_token'];
}
}
}
function google_login($user )
{
// escape variables for security
$name = $user['name'];
$email = $user['email'] ;
$social_id = $user['id'] ;
$picture = $user['picture'] ;
$result = query("SELECT k_id FROM users where email = '$email'");
$count = count($result);
if( $count == 1){
$_SESSION['logged_in'] = true;
$_SESSION['k_id']=$result[0]['k_id'];
$result = query("SELECT gog_id FROM users where email = '$email'");
if($result[0]['gog_id']){
setRefreshToken();
}
else{
$add_user = query("INSERT INTO users (gog_id) VALUES(?)", $social_id);
}
}else{
$add_user = query("INSERT INTO users (gog_id, email, name, pic) VALUES(?, ?, ?, ?)", $social_id, $email, $name, $picture);
if( $add_user === false)
{
apologize("Whoops! There was an error at our end. We deeply apologisze.");
}
//the new user has been added
$return_id = query("SELECT k_id FROM users WHERE gog_id = ?", $social_id);
//storing the user id in session superglobal
$_SESSION["k_id"]=$return_id[0]["k_id"];
}
}
?>
<?php ob_end_flush(); ?>
The problem I have is in the setRefreshToken() function. This the error I get
Notice: Undefined property: stdClass::$refresh_token in C:\xampp\htdocs\trial\log-inlogic\config.php on line 88
Catchable fatal error: Object of class stdClass could not be converted to string in C:\xampp\htdocs\trial\log-inlogic\config.php on line 89
Can someone tell me what might be the problem, I have researched online and all the people are recommending the same solution.
The error in
Notice: Undefined property: stdClass::$refresh_token in C:\xampp\htdocs\trial\log-inlogic\config.php on line 88
is because the server didn't return a refresh token in the response. You can solve this by revoking the access and granting it again by using $client->revokeToken()
Catchable fatal error: Object of class stdClass could not be converted to string in C:\xampp\htdocs\trial\log-inlogic\config.php on line 89
This is because you are trying to write an object as a string
$result =query("UPDATE users SET refreshtoken=$token WHERE k_id='$k_id'");
try this instead
$result =query("UPDATE users SET refreshtoken='$token->refresh_token' WHERE k_id='$k_id'");

PHP Facebook SDK, Get Albums

I know there are tons of questions about facebook and php sdk, grabbing and taking some infos. but i got different question.
imagine that i already did everything.
authorized user by fb javascript sdk + php and ajax, stored basic infos in database and forgot facebook. now my user can login with my database with facebook information.
in my database i have:
id user_fb say_smth access register mail limitTime count
notice there is user_fb, which is facebook id.
when user logs in, i create session and get it with jquery/ajax/json parse
// Cache hit
// $start = microtime(true);
$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT fb_id, email, password FROM sp_signup WHERE email = '{$email}' AND password = '{$passw}' LIMIT 1");
$check_row = $res->num_rows;
$check_array = $res->fetch_assoc();
$res->free();
if ($check_row == 0)
{
print json_encode( array("status" => "user does not exists", "code" => 10) );
} else {
if ( ! isset($_SESSION) )
{
session_start();
$_SESSION[ "dh_user_fb" ] = $check_array["fb_id"];
print json_encode( array("status" => "", "code" => 4, "session" => $_SESSION[ "dh_user_fb" ]) );
} else {
print json_encode( array("status" => "", "code" => 4, "session" => null) );
}
} // endcode
and jquery ajax success method
var gotJson = jQuery.parseJSON(jsonR);
var code = gotJson['code'];
var status = gotJson['status'];
var session = gotJson['session'];
if ( session == null ){
if ( code == 11 ){
$("#email_try").html(status).fadeIn(600);
$("#email_try").html(status).fadeOut(2200);
} else if ( code == 12 || code == 10 ) {
$("#passw_try").html(status).fadeIn(600);
$("#passw_try").html(status).fadeOut(2200);
} else {
//
}
}
so when user enters, there is $_SESSION["fb_id"];
I need to get logged in users photo albums by php and copy it on my local ftp or take src from facebook. it is not neccessery.
i'm only interested, if there is any chance to do this without access tokens and logins and so on, i want to do this only by fb_id;
Thanks...
you can't get it directly without calling api.
get user permission to access his photos
$loginLink = $facebook->getLoginUrl(array(
'scope' => 'user_photos,user_photo_video_tags'
));
then use this api to get user photos :
$photos = $facebook->api('/me/photos?access_token=' . $token);

Twitter OAuth returning blank array if there is no tweet

I spent my last 5 hours in this issue and finally I came here for the solution.
I am doing log-in using twitter functionality in my site (Zend Framework + PHP) and everything is working fine. But I am facing the following issue in it:
If the user has no tweets (0 tweets) in his account then the
$tweets = json_decode($response->getBody());
echo "<pre>";
print_r($tweets);
exit;
Its showing me blank array. i.e. : Array(); :-(
And if I am adding some tweets there in twitter account then its showing me the complete array along with user information like display name, image, etc...like this:
Array
(
//other data
[0] => stdClass Object
(
[user] => stdClass Object
....
....
so on..
)
)
Following is my code :
public function twitterregisterAction() {
$path = realpath(APPLICATION_PATH . '/../library/');
set_include_path($path);
session_start();
require $path . "/Zend/Oauth/Consumer.php";
$config = array(
"callbackUrl" => "http://" . $_SERVER['HTTP_HOST'] . "/register/twittercallback",
"siteUrl" => "http://twitter.com/oauth",
"consumerKey" => "xxxxxxxxxxxxx",
"consumerSecret" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
);
$consumer = new Zend_Oauth_Consumer($config);
// fetch a request token
$token = $consumer->getRequestToken();
// persist the token to storage
$_SESSION["TWITTER_REQUEST_TOKEN"] = serialize($token);
// redirect the user
$consumer->redirect();
}
/*
* Ticket id #16
* twittercallbackAction method
*/
public function twittercallbackAction() {
$config = array(
"callbackUrl" => "http://" . $_SERVER['HTTP_HOST'] . "/register/twittercallback",
"siteUrl" => "http://twitter.com/oauth",
"consumerKey" => "xxxxxxxxxxxxxxxxxx",
"consumerSecret" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
);
$consumer = new Zend_Oauth_Consumer($config);
if (!$this->_getParam("denied")) {
if (!empty($_GET) && isset($_SESSION['TWITTER_REQUEST_TOKEN'])) {
$token = $consumer->getAccessToken($_GET, unserialize($_SESSION['TWITTER_REQUEST_TOKEN']));
} else {
// Mistaken request? Some malfeasant trying something?
exit('Invalid callback request. Oops. Sorry.');
}
// save token to file
// file_put_contents('token.txt', serialize($token));
$client = $token->getHttpClient($config);
$client->setUri('https://api.twitter.com/1/statuses/user_timeline.json?');
$client->setMethod(Zend_Http_Client::GET);
$client->setParameterGet('name');
$client->setParameterGet('profile_image_url');
$response = $client->request();
$tweets = json_decode($response->getBody());
$session = new Zend_Session_Namespace("userIdentity");
Zend_Session::rememberMe(63072000); //2years
$session->tw_id = $tweets[0]->user->id;
$session->tw_name = $tweets[0]->user->name;
$session->tw_image = $tweets[0]->user->profile_image_url;
if ($session->tw_id != "") {
$tw_id = $session->tw_id;
//Calling the function twitterAuthAction for email authentication
$twAuthArr = $this->twitterAuthAction($tw_id);
if ($twAuthArr['socialId'] == $tw_id) {
$session->userId = $twAuthArr['id'];
$session->email = $twAuthArr['emailId'];
$this->_redirect('/profile/showprofile');
} else {
$user = new UserRegistration();
$firstname = "";
$lastname = "";
$password = "";
$socialtype = "twitter";
$email = "";
$socialid = $session->tw_id;
$result = $user->registerUser($firstname, $lastname, $socialid, $socialtype, $email, $password);
$session->userId = $result;
$this->_redirect('/register');
}
}
$this->_redirect("/register");
} else {
$this->_redirect("/register");
}
}
My Questions are :
1) Why its not providing user array if there is no any tweet in my twitter account (or newly created twitter account)
2) I want user profile details from twitter account. How can I get it?
Need Help. Thanks
I think as per david's answer you need to use users/show url there instead of using statuses/user_timeline. You can use curl for requesting url so you'll get the response which contains the users information.
Try with following code:
$user_id = $client->getToken()->getParam('user_id');
$trends_url = "http://api.twitter.com/1/users/show.json?user_id=".$user_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $trends_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlout = curl_exec($ch);
curl_close($ch);
$response = json_decode($curlout, true);
$session = new Zend_Session_Namespace("userIdentity");
Zend_Session::rememberMe(63072000); //2years
$session->tw_id = $response['id'];
$session->tw_name = $response['name'];
$session->tw_image = $response['profile_image_url'];
Try this. Hope it will help you.
I think you are misreading the Twitter API docs for the statuses/user_timeline endpoint.
The field user that you identify is one of the fields within a returned tweet. If the user id to which you point has no tweets, then there will be no entries in the returned array, hence no user field.
If you need the user information even in the absence of any tweets, then you probably need to hit the users/show endpoint.

Posting to Twitter from any page after login/approval with PHP

Users on my website can login to Twitter and post their status on my website and twitter at once. I'm using https://github.com/abraham/twitteroauth to connect to Twitter. Login and posting is performed on different pages of website.
This is login script:
public function loginTwitter() {
$twitter = new TwitterOAuth(
$this->getContext()->params['social']['twitter']['consumerKey'],
$this->getContext()->params['social']['twitter']['consumerSecret']
);
$request_token = $twitter->getRequestToken($this->link('//User:connectFromTwitter'));
// Saving to session (Nette Framework)
$twitterSession = $this->getContext()->session->getSection('twSes');
$twitterSession->oauth_request_token = $token = $request_token['oauth_token'];
$twitterSession->oauth_request_token_secret = $request_token['oauth_token_secret'];
if ($twitter->http_code == 200) {
$requestLink = $twitter->getAuthorizeURL($token);
$this->redirectUrl($requestLink);
} else {
echo 'Error';
}
}
This is callback script (posting works right after user has been logged in):
public function twitterOauth() {
// $_GET parameter oauth_verifier
$oauthVerifier = $this->getParam('oauth_verifier');
// Session section
$twitterSession = $this->getContext()->session->getSection('twSes');
$twitter = new TwitterOAuth(
$this->getContext()->params['social']['twitter']['consumerKey'],
$this->getContext()->params['social']['twitter']['consumerSecret'],
$twitterSession->oauth_request_token,
$twitterSession->oauth_request_token_secret
);
$access_token = $twitter->getAccessToken($oauthVerifier);
$twitterSession->access_token = $access_token;
$user_info = $twitter->get('account/verify_credentials');
// Saving to DB to be able to post without login
$tm = new TwitterUserManager();
if (!$tm->isInDatabase($this->getUser()->getId())) {
$tu = new TwitterUser();
$tu->setUser($this->loggedUser);
$tu->setOauthProvider('twitter');
$tu->setOauthUid("'".$user_info->id."'");
$tu->setUsername("'".$user_info->screen_name."'");
$tu->setOauthToken("'".$access_token['oauth_token']."'"); // Saving the access token for further posting
$tu->setOauthSecret("'".$access_token['oauth_token_secret']."'");
$tm->persist($tu);
}
$twitter->post('statuses/update', array('status' => 'Hello ' . date('d.m.Y H:i:s'))); // <== HERE IT WORKS
$this->redirect('User:socialConnect'); // Redirect to another page
}
This is posting function (User posts from any page):
public function postToTwitter() {
$twitterSession = $this->getContext()->session->getSection('twitter');
$twitter = new TwitterOAuth(
$this->getContext()->params['social']['twitter']['consumerKey'],
$this->getContext()->params['social']['twitter']['consumerSecret'],
$twitterSession->access_token['oauth_token'],
$twitterSession->access_token['oauth_token_secret']
);
return $twitter->post('statuses/update', array('status' => 'Hello' . date('d.m.Y H:i:s')));
}
When I use posting function I get this error:
stdClass(2) {
request => "/1/statuses/update.json" (23)
error => "Could not authenticate you." (27)
}
Thanks for help in advance.
EDIT: Solution:
Use this to connect to Twitter (save all info into DB):
http://framework.zend.com/manual/1.12/en/zend.oauth.introduction.html
Use this to post from any page:
http://framework.zend.com/manual/1.12/en/zend.service.twitter.html
Nice example:
http://www.joeyrivera.com/2010/twitter-api-oauth-authentication-and-zend_oauth-tutorial/
I always used the Zend-Framework-Component: http://framework.zend.com/manual/1.12/en/zend.service.twitter.html
I think it's simple and I could confirm, that it works. You just have to read through the tutorial (see link above).

TwitterOAuth Store Tokens for offline use

Hi sorry for my bad english, i have writed simple app for update status in twitter account.
Twitter Login:
require("twitteroauth.php");
session_start();
$twitteroauth = new TwitterOAuth('*******', '***********');
$request_token = $twitteroauth->getRequestToken('http://127.0.0.1/twitter_oauth.php');
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
if($twitteroauth->http_code==200)
{
$url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);
header('Location: '. $url);
}
else
{
die('error');
}
twitter_oauth.php:
require("twitteroauth.php");
session_start();
if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token']) && !empty($_SESSION['oauth_token_secret']))
{
require("config.php");
$twitteroauth = new TwitterOAuth('****', '********', $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$access_token = $twitteroauth->getAccessToken();
$_SESSION['access_token'] = $access_token;
$user_info = $twitteroauth->get('account/verify_credentials');
$username= $user_info->screen_name;
$followerInit= $user_info->followers_count;
$oauth_token=$_SESSION['oauth_token'];
$oauth_token_secret=$_SESSION['oauth_token_secret'];
$update=query("SELECT 1 FROM connect WHERE id_user=(SELECT id FROM user WHERE user='$username' )");
if(mysql_num_rows($update)>0)
{
query("UPDATE connect set oauth_token='$oauth_token', oauth_token_secret='$oauth_token_secret' WHERE id_user=(SELECT id FROM user WHERE user='$username' ) ");
}
else
{
query("INSERT INTO connect(id_user,followerInit,oauth_token,oauth_token_secret) VALUES((SELECT id FROM user WHERE user='$username' ),$followerInit,'$oauth_token','$oauth_token_secret' ) ");
}
header('Location: index.php');
}
else
{
header('Location: twitter_login.php');
}
I save oauth_token,oauth_token_secret and in index.php, when user have the oauth_token,oauth_token_secret i would like update status:
session_start();
require("twitterbot/twitterbot/twitteroauth.php");
require("twitterbot/config.php");
$query=query("SELECT oauth_token,oauth_token_secret FROM connect WHERE id_user=8");
if(mysql_num_rows($query)>0)
{
$row=mysql_fetch_row($query);
}
else
{
header('Location: twitter_login.php');
}
$twitteroauth = new TwitterOAuth('bSMnfSsk3CTcSV85jKWz1w', 'HeNAG1v2sgxhkq1QyfZDd029JUDdRNGAaO85Nsg', $row[0], $row[1]);
print_r($twitteroauth);
print_r($twitteroauth->OAuthRequest('https://twitter.com/statuses/update.xml',
array('status' => "Hey! I'm posting via #OAuth!"), 'POST'));
but in index.php i have error, "Could not authenticate you. /statuses/update.xml" and i can't update status...
$access_token = $twitteroauth->getAccessToken();
$_SESSION['access_token'] = $access_token;
$user_info = $twitteroauth->get('account/verify_credentials');
$username= $user_info->screen_name;
$followerInit= $user_info->followers_count;
$oauth_token=$_SESSION['oauth_token'];
$oauth_token_secret=$_SESSION['oauth_token_secret'];
In this code you are getting an access oauth_token but saving the temporary request oauth_token in the database. You need to save the access_token instead.

Categories