facebook php api multiple users one computer force logout - php

I am working on an application that is basically going to operate in a Kiosk, the point is to allow users while they are at a business to be able to login to facebook and after logging in it posts a message saying they are there, afterwords they are given a coupon.
The problem has arisen that after they have logged in and then logged out, the next person logs in with their account ends up posting as the previous user, this continues adnauseum.
After getting their coupon the script automatically logs them out after 15 seconds and returns the application to the home screen for the next user. When they login, which they are able to do it returns them to the page asking for permission to post, but it is pulling all of the previous users information. This is the code being called in the page after being sent to logging in on facebook.
<?php
//include the Facebook PHP SDK
include_once 'couponGenerator/facebook.php';
//start the session if necessary
if( session_id() ) {
} else {
session_start();
}
//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
'appId' => '00000000000',
'secret' => '000000000000000000000',
'cookie' => true,
'status' => true,
'oath' => true
));
$access_token = $facebook->getAccessToken();
$_SESSION['active'][$access_token];
//get the news feed of the active page using the page's access token
$page_feed = $facebook->api(
'/me/feed',
'GET',
array(
'access_token' => $_SESSION['active']['access_token']
)
);
$fbuser = $facebook->api('/me');
//var_dump($page_feed); exit;
?>
I have attempted on the homepage of of deleting facebook cookies and sessions and this has not solved anything, I am just trying to figure out what I am doing wrong and any advice would be very welcome.
$facebook->destroySession();
$facebook->_killFacebookCookies();
public function _killFacebookCookies()
{
// get your api key
$apiKey = $this->getAppId();
// get name of the cookie
$cookie = $this->getSignedRequestCookieName();
$cookies = array('user', 'session_key', 'expires', 'ss');
foreach ($cookies as $name)
{
setcookie($apiKey . '_' . $name, false, time() - 3600);
unset($_COOKIE[$apiKey . '_' . $name]);
}
setcookie($apiKey, false, time() - 3600);
unset($_COOKIE[$apiKey]);
$this->clearAllPersistentData();
}
Here is the updated connection class
`
<?php
//include the Facebook PHP SDK
include_once 'facebook.php';
//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
'appId' => '122628977190080',
'secret' => '123123123123123123123123',
'cookie' => true
));
$access_token = $facebook->getAccessToken();
unset ($_SESSION['active'][$access_token]);
session_unregister ($_SESSION['active'][$access_token]);
//Get the FB UID of the currently logged in user
$user = $facebook->getUser();
//if the user has already allowed the application, you'll be able to get his/her FB UID
if($user) {
//start the session if needed
if( session_id() ) {
} else {
session_start();
}
//do stuff when already logged in
//get the user's access token
$access_token = $facebook->getAccessToken();
//check permissions list
$permissions_list = $facebook->api(
'/me/permissions',
'GET',
array(
'access_token' => $access_token
)
);
//check if the permissions we need have been allowed by the user
//if not then redirect them again to facebook's permissions page
$permissions_needed = array('publish_stream', 'email');
foreach($permissions_needed as $perm) {
if( !isset($permissions_list['data'][0][$perm]) || $permissions_list['data'][0][$perm] != 1 ) {
$login_url_params = array(
'scope' => 'publish_stream,email',
'fbconnect' => 1,
'display' => "page",
'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
);
$login_url = $facebook->getLoginUrl($login_url_params);
header("Location: {$login_url}");
exit();
}
}
//if the user has allowed all the permissions we need,
//get the information about the pages that he or she managers
$accounts = $facebook->api(
'/me/accounts',
'GET',
array(
'access_token' => $access_token
)
);
//save the information inside the session
$_SESSION['access_token'] = $access_token;
$_SESSION['accounts'] = $accounts['data'];
//save the first page as the default active page
$_SESSION['active'] = $accounts['data'][0];
//redirect to manage.php
header('Location: ../facebook_result.php');
} else {
//if not, let's redirect to the ALLOW page so we can get access
//Create a login URL using the Facebook library's getLoginUrl() method
$login_url_params = array(
'scope' => 'read_stream,email',
'fbconnect' => 1,
'display' => "page",
'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
);
$login_url = $facebook->getLoginUrl($login_url_params);
//redirect to the login URL on facebook
header("Location: {$login_url}");
exit();
}
?>`
After calling the logoff script, I am run this piece of code on the homepage to see if everything is set.
<?php
try {
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
echo "$uid";
} catch (FacebookApiException $e) {
print_r($e);
}
?>
it gives me this result
FacebookApiException Object ( [result:protected] =>
Array ( [error] => Array ( [message] =>
An active access token must be used to query information about the current user.
[type] => OAuthException [code] => 2500 ) )
[message:protected] => An active access token must be
used to query information about the current user.
[string:private] => [code:protected] => 0 [file:protected] =>
/home/m3dev/public_html/couponsite/couponGenerator/base_facebook.php
[line:protected] => 1046 [trace:private] => Array ( [0] => Array ( [file] => /home/m3dev/public_html/couponsite/couponGenerator/base_facebook.php [line] => 751 [function] => throwAPIException [class] => BaseFacebook [type] => -> [args] => Array ( [0] => Array ( [error] => Array ( [message] => An active access token must be used to query information about the current user. [type] => OAuthException [code] => 2500 ) ) ) ) [1] => Array ( [function] => _graph [class] => BaseFacebook [type] => -> [args] => Array ( [0] => /me ) ) [2] => Array ( [file] => /home/m3dev/public_html/couponsite/couponGenerator/base_facebook.php [line] => 560 [function] => call_user_func_array [args] => Array ( [0] => Array ( [0] => Facebook Object ( [appId:protected] => 162628977190080 [apiSecret:protected] => **SECRET KEY REMOVED ** [user:protected] => 0 [signedRequest:protected] => Array ( [algorithm] => HMAC-SHA256 [code] => 961628b1ca0354544541d58e.1-34319949|p3D3pSNoawlC1wBllhiN7zoEpJY [issued_at] => 1331218933 [user_id] => 34319949 ) [state:protected] => [accessToken:protected] => 162628977190080|**SECRET KEY REMOVED** [fileUploadSupport:protected] => ) [1] => _graph ) [1] => Array ( [0] => /me ) ) ) [3] => Array ( [file] => /home/m3dev/public_html/couponsite/index.php [line] => 71 [function] => api [class] => BaseFacebook [type] => -> [args] => Array ( [0] => /me ) ) ) )

You may be destroying a Facebook session but you don't seem to be destroying your own session.
Clear out
$_SESSION['active'][$access_token];

You need to force Facebook Re-Authentication for each user.
I'm not sure if the PHP API you're using supports this, but the OAuth dialog can receive a auth_type that when valued to reauthenticate forces the user to provide his credentials:
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. '&auth_type=reauthenticate&auth_nonce=' . $auth_nonce;
This can be done useg the Javascript API as well.

Related

Save values after redirect

I am saving values into $_SESSiON variable, but after I submit form, which redirect me to the same page, $_SESSION variable is empty.
include 'googleauthorize.php';
include 'googleTransfer.php';
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (isset($_REQUEST['logout']))
unset($_SESSION['auth']);
if(isset($_REQUEST['auth'])){
//Initialize google client
$_SESSION['auth'] = new GoogleAuthorize(__DIR__ . '/../oauth-credentials.json', 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']."?auth", "https://www.googleapis.com/auth/drive");
//Get authorize URL
$authUrl = $_SESSION['auth']->obtainAuthorizeUrl();
//Redirect
if(!isset($_GET['code'])){
$_SESSION['auth']->redirect($authUrl);
}
//Authentificate and return token
$_SESSION['token'] = $_SESSION['auth']->obtainAccessToken();
if(!isset($_SESSION['refreshToken']))
{
$_SESSION['refreshToken'] = $_SESSION['auth']->getRefreshToken();
//Call method to save token into DB
}
}elseif(isset($_REQUEST['upload'])){
if(isset($_SESSION['auth']))
{
//Initialize google client
$_SESSION['auth'] = new GoogleAuthorize(__DIR__ . '/../oauth-credentials.json', 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], "https://www.googleapis.com/auth/drive");
}
//Here is undefined index 'token'
$_SESSION['auth']->setAccessToken($_SESSION['token']);
//Initialize new object for file transfer
new googleTransfer($_SESSION['auth']->getGoogleClient());
}
This is content of $_SESSION variable in elseif statement. Which makes me confused because there is only auth saved inside, which doesn't have anything set inside.
Array
(
[auth] => GoogleAuthorize Object
(
[client:GoogleAuthorize:private] => Google_Client Object
(
[auth:Google_Client:private] => Google\Auth\OAuth2 Object
(
[authorizationUri:Google\Auth\OAuth2:private] => GuzzleHttp\Psr7\Uri Object
(
[scheme:GuzzleHttp\Psr7\Uri:private] => https
[userInfo:GuzzleHttp\Psr7\Uri:private] =>
[host:GuzzleHttp\Psr7\Uri:private] => accounts.google.com
[port:GuzzleHttp\Psr7\Uri:private] =>
[path:GuzzleHttp\Psr7\Uri:private] => /o/oauth2/auth
[query:GuzzleHttp\Psr7\Uri:private] =>
[fragment:GuzzleHttp\Psr7\Uri:private] =>
)
[tokenCredentialUri:Google\Auth\OAuth2:private] => GuzzleHttp\Psr7\Uri Object
(
[scheme:GuzzleHttp\Psr7\Uri:private] => https
[userInfo:GuzzleHttp\Psr7\Uri:private] =>
[host:GuzzleHttp\Psr7\Uri:private] => www.googleapis.com
[port:GuzzleHttp\Psr7\Uri:private] =>
[path:GuzzleHttp\Psr7\Uri:private] => /oauth2/v4/token
[query:GuzzleHttp\Psr7\Uri:private] =>
[fragment:GuzzleHttp\Psr7\Uri:private] =>
)
[redirectUri:Google\Auth\OAuth2:private] => http://localhost:81/FileTransfer/src/testik.php?auth
[clientId:Google\Auth\OAuth2:private] => 108715515230-g8e7tjh2d7luiggtfes6fsdv17n794hu.apps.googleusercontent.com
[clientSecret:Google\Auth\OAuth2:private] => Ab-DiaYYRnVSFf8JGay-TIMN
[username:Google\Auth\OAuth2:private] =>
[password:Google\Auth\OAuth2:private] =>
[scope:Google\Auth\OAuth2:private] =>
[state:Google\Auth\OAuth2:private] =>
[code:Google\Auth\OAuth2:private] =>
[issuer:Google\Auth\OAuth2:private] => 108715515230-g8e7tjh2d7luiggtfes6fsdv17n794hu.apps.googleusercontent.com
[audience:Google\Auth\OAuth2:private] =>
[sub:Google\Auth\OAuth2:private] =>
[expiry:Google\Auth\OAuth2:private] => 3600
[signingKey:Google\Auth\OAuth2:private] =>
[signingAlgorithm:Google\Auth\OAuth2:private] =>
[refreshToken:Google\Auth\OAuth2:private] =>
[accessToken:Google\Auth\OAuth2:private] =>
[idToken:Google\Auth\OAuth2:private] =>
[expiresIn:Google\Auth\OAuth2:private] =>
[expiresAt:Google\Auth\OAuth2:private] =>
[issuedAt:Google\Auth\OAuth2:private] =>
[grantType:Google\Auth\OAuth2:private] =>
[extensionParams:Google\Auth\OAuth2:private] => Array
(
)
)
[http:Google_Client:private] =>
[cache:Google_Client:private] =>
[token:Google_Client:private] =>
[config:Google_Client:private] => Array
(
[application_name] =>
[base_path] => https://www.googleapis.com
[client_id] => 108715515230-g8e7tjh2d7luiggtfes6fsdv17n794hu.apps.googleusercontent.com
[client_secret] => Ab-DiaYYRnVSFf8JGay-TIMN
[redirect_uri] => http://localhost:81/FileTransfer/src/testik.php?auth
[state] =>
[developer_key] =>
[use_application_default_credentials] =>
[signing_key] =>
[signing_algorithm] =>
[subject] =>
[hd] =>
[prompt] =>
[openid.realm] =>
[include_granted_scopes] =>
[login_hint] =>
[request_visible_actions] =>
[access_type] => offline
[approval_prompt] => auto
[retry] => Array
(
)
[cache_config] => Array
(
)
[token_callback] =>
)
[logger:Google_Client:private] =>
[deferExecution:Google_Client:private] =>
[requestedScopes:protected] => Array
(
[0] => https://www.googleapis.com/auth/drive
)
)
[authUrl:GoogleAuthorize:private] =>
https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=offline&client_id=108715515230-g8e7tjh2d7luiggtfes6fsdv17n794hu.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A81%2FFileTransfer%2Fsrc%2Ftestik.php%3Fauth&state&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive&approval_prompt=auto
[token:GoogleAuthorize:private] =>
)
)
include 'googleauthorize.php';
include 'googleTransfer.php';
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (isset($_REQUEST['logout']))
unset($_SESSION['auth']);
if(isset($_REQUEST['auth']) || isset($_REQUEST['upload'])){
if(!isset($_SESSION['auth']){
$_SESSION['auth'] = new GoogleAuthorize(__DIR__ . '/../oauth-credentials.json', 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']."?auth", "https://www.googleapis.com/auth/drive");
//Get authorize URL
$authUrl = $_SESSION['auth']->obtainAuthorizeUrl();
//Redirect
if(!isset($_GET['code'])){
$_SESSION['auth']->redirect($authUrl);
}
//Authentificate and return token
$_SESSION['token'] = $_SESSION['auth']->obtainAccessToken();
if(!isset($_SESSION['refreshToken']))
{
$_SESSION['refreshToken'] = $_SESSION['auth']->getRefreshToken();
//Call method to save token into DB
}
}
if(isset($_REQUEST['upload'])){
new googleTransfer($_SESSION['auth']->getGoogleClient());
}
}
include 'googleauthorize.php';
include 'googleTransfer.php';
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (isset($_REQUEST['logout']))
unset($_SESSION['auth']);
if(isset($_REQUEST['auth'])){
// You have initialize the session variable auth here.
$_SESSION['auth'] = new GoogleAuthorize(__DIR__ . '/../oauth-credentials.json', 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']."?auth", "https://www.googleapis.com/auth/drive");
//Get authorize URL
$authUrl = $_SESSION['auth']->obtainAuthorizeUrl();
//Redirect
if(!isset($_GET['code'])){
$_SESSION['auth']->redirect($authUrl);
}
$_SESSION['token'] = $_SESSION['auth']->obtainAccessToken();
if(!isset($_SESSION['refreshToken']))
{
$_SESSION['refreshToken'] = $_SESSION['auth']->getRefreshToken();
//Call method to save token into DB
}
}elseif(isset($_REQUEST['upload'])){
// but how will it set here? when not having value? You have put the //session initialize here also.
$_SESSION['auth'] = new GoogleAuthorize(__DIR__ . '/../oauth-credentials.json', 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], "https://www.googleapis.com/auth/drive");
if(isset($_SESSION['auth']))
{
$_SESSION['auth']->setAccessToken($_SESSION['token']);
}
//Initialize new object for file transfer
new googleTransfer($_SESSION['auth']->getGoogleClient());
}

Fitbit API response handling in PHP

I am using a PHP library (https://github.com/djchen/oauth2-fitbit) to retreive a users Fitbit data via Oauth2. I am getting the data correctly but I am not sure how to grab a specific item from the multidimensional array response.
I am using code below but doesnt work
$response = $provider->getResponse($request);
var_dump($response['encodedId'][0]);
Full PHP code
$provider = new djchen\OAuth2\Client\Provider\Fitbit([
'clientId' => 'xxx',
'clientSecret' => 'xxx',
'redirectUri' => 'http://xxx-env.us-east-1.elasticbeanstalk.com/a/fitbitapi'
]);
// start the session
session_start();
// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {
// Fetch the authorization URL from the provider; this returns the
// urlAuthorize option and generates and applies any necessary parameters
// (e.g. state).
$authorizationUrl = $provider->getAuthorizationUrl();
// Get the state generated for you and store it to the session.
$_SESSION['oauth2state'] = $provider->getState();
// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit;
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
exit('Invalid state');
} else {
try {
// Try to get an access token using the authorization code grant.
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// We have an access token, which we may use in authenticated
// requests against the service provider's API.
echo $accessToken->getToken() . "\n";
echo $accessToken->getRefreshToken() . "\n";
echo $accessToken->getExpires() . "\n";
echo ($accessToken->hasExpired() ? 'expired' : 'not expired') . "\n";
// Using the access token, we may look up details about the
// resource owner.
$resourceOwner = $provider->getResourceOwner($accessToken);
var_export($resourceOwner->toArray());
// The provider provides a way to get an authenticated API request for
// the service, using the access token; it returns an object conforming
// to Psr\Http\Message\RequestInterface.
$request = $provider->getAuthenticatedRequest(
'GET',
'https://api.fitbit.com/1/user/-/profile.json',
$accessToken
);
// Make the authenticated API request and get the response.
$response = $provider->getResponse($request);
var_dump($response['encodedId'][0]);
Response data
eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0NjAzNzgxOTYsInNjb3BlcyI6InJ3ZWkgcnBybyByaHIgcmxvYyByc2xlIHJzZXQgcmFjdCByc29jIiwic3ViIjoiNEg4NU5WIiwiYXVkIjoiMjI3UUNXIiwiaXNzIjoiRml0Yml0IiwidHlwIjoiYWNjZXNzX3Rva2VuIiwiaWF0IjoxNDYwMzc0NTk2fQ.NN9OOx--3YLvwai0hl0ZRJ4MNWXlaMwcEJ_xxxxxb2382a930144c3a76e69567dcbf0d9834c574919fff8c268b378e635735f1bbf 1460378196 not expired array ( 'encodedId' => '4545NV', 'displayName'
=> 'dan', )...
I am using the same PHP library for FitBit API integration. The response you have pasted with the question is the data that is coming because of the following part of your code:
// requests against the service provider's API.
echo $accessToken->getToken() . "\n";
echo $accessToken->getRefreshToken() . "\n";
echo $accessToken->getExpires() . "\n";
echo ($accessToken->hasExpired() ? 'expired' : 'not expired') . "\n";
// Using the access token, we may look up details about the
// resource owner.
$resourceOwner = $provider->getResourceOwner($accessToken);
var_export($resourceOwner->toArray());
When you try to get the user profile from FitBit, you make the below request :
$request = $provider->getAuthenticatedRequest(
'GET',
'https://api.fitbit.com/1/user/-/profile.json',
$accessToken
);
// Make the authenticated API request and get the response.
$response = $provider->getResponse($request);
The $response comes in the below format and you can see there that "encodeId" is not the direct key there. Below is the example of var_dump($response); -
Array(
[user] => Array
(
[age] => 27
[avatar] => https://static0.fitbit.com/images/profile/defaultProfile_100_male.gif
[avatar150] => https://static0.fitbit.com/images/profile/defaultProfile_150_male.gif
[averageDailySteps] => 3165
[corporate] =>
[dateOfBirth] => 1991-04-02
[displayName] => Avtar
[distanceUnit] => METRIC
[encodedId] => 478ZBH
[features] => Array
(
[exerciseGoal] => 1
)
[foodsLocale] => en_GB
[fullName] => Avtar Gaur
[gender] => MALE
[glucoseUnit] => METRIC
[height] => 181
[heightUnit] => METRIC
[locale] => en_IN
[memberSince] => 2016-01-17
[offsetFromUTCMillis] => 19800000
[startDayOfWeek] => MONDAY
[strideLengthRunning] => 94.2
[strideLengthRunningType] => default
[strideLengthWalking] => 75.1
[strideLengthWalkingType] => default
[timezone] => Asia/Colombo
[topBadges] => Array
(
[0] => Array
(
)
[1] => Array
(
)
[2] => Array
(
)
)
[waterUnit] => METRIC
[waterUnitName] => ml
[weight] => 80
[weightUnit] => METRIC
)
)
In order to access anything in there you need to access it in this manner -
$encodedId = $response['user']['encodedId];
I hope this was helpful to you. You can ask more questions related to fitbit API as I have got it all working, including the Fitbit Subscriver API and Notifications.

Twitter Codebird Error

I am trying to use codebird to tweet using PHP. Initially I was unable to get Access Token but after I defined CallbackURL in settings that issue seems to be resolved. Now it is returning oauth token:
Codebird\Codebird Object ( [_oauth_token:protected] => codehere [_oauth_token_secret:protected] => codehere [_return_format:protected] => 0 [_supported_media_files:protected] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [_version:protected] => 3.0.0-dev [_use_curl:protected] => 1 [_timeout:protected] => 10000 [_connectionTimeout:protected] => 3000 )
But when i try to tweet i get following error:
stdClass Object ( [errors] => Array ( [0] => stdClass Object ( [code]
=> 89 [message] => Invalid or expired token. ) ) [httpstatus] => 401 [rate] => )
Following is my code
Codebird\Codebird::setConsumerKey('copy+paste from twitter', 'copy+paste from twitter'); // I changed it to my settings
$cb = \Codebird\Codebird::getInstance();
if (! isset($_SESSION['oauth_token'])) {
// get the request token
$reply = $cb->oauth_requestToken(array(
'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
));
// 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();
header('Location: ' . $auth_url);
die();
} elseif (isset($_GET['oauth_verifier']) && isset($_SESSION['oauth_verify'])) {
// verify the token
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
unset($_SESSION['oauth_verify']);
// get the access token
$reply = $cb->oauth_accessToken(array(
'oauth_verifier' => $_GET['oauth_verifier']
));
// store the token (which is different from the request token!)
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
// send to same URL, without oauth GET parameters
header('Location: ' . basename(__FILE__));
die();
}
// assign access token on each page load
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
print_r($cb);
$params = array(
'status' => 'Auto Post on Twitter with PHP http://goo.gl/OZHaQD #php #twitter'
);
$reply = $cb->statuses_update($params);
print_r($reply);
Thanks in advance for the assistance.
Is your callback address the one registered with Twitter in the app definition?
Do you have "read and write" access in the app definition?
Have you exceeded the rate limit for posting?
I'd check those things first, as I don't see anything obviously missing from your code snippet.

getting 200 ok code but image not uploaded on twitter using codebird

i am using codebird-php to post images on twitter, when i do that i get 200 ok http code but the image is not uploaded. Here is my code:
<?php
session_start();
require_once ('./src/codebird.php');
\Codebird\Codebird::setConsumerKey('74AFitlDilqB2HlFQ8Cjszz6I', 'tDlVndY7iJG8loFGG1sq3gJaj59CwNx6UV5o6wEtV0LJebNJ0y'); // static, see 'Using multiple Codebird instances'
$cb = \Codebird\Codebird::getInstance();
$access_token = $_SESSION['access_token'];
$cb->setToken($access_token['oauth_token'], $access_token['oauth_token_secret']);
//$reply = $cb->statuses_update('status=Whohoo, I just again tweeted!');
// send tweet with these medias
$reply = $cb->media_upload(array(
'media' => 'http://www.bing.com/az/hprichbg/rb/BilbaoGuggenheim_EN-US11232447099_1366x768.jpg'
));
print_r($reply);
?>
This is what i am getting on running it in my browser:
stdClass Object ( [media_id] => 540134777223790592 [media_id_string] => 540134777223790592 [size] => 179801 [image] => stdClass Object ( [w] => 1366 [h] => 768 [image_type] => image/jpeg ) [httpstatus] => 200 [rate] => )
PS: I am running it on localhost, tweeting text works but not image and i am using Abrahams oAuth for getting oAuth token.
i fixed it by changing
$reply = $cb->media_upload(array(
'media' => 'http://www.bing.com/az/hprichbg/rb/BilbaoGuggenheim_EN-US11232447099_1366x768.jpg'
));
to
$params = array(
'status' => 'Auto Post on Twitter with PHP http://goo.gl/OZHaQD #php #twitter',
'media[]' => 'http://www.bing.com/az/hprichbg/rb/BilbaoGuggenheim_EN-US11232447099_1366x768.jpg'
);
// send tweet with these medias
/*$reply = $cb->media_upload(array(
'media[]' => "#http://www.bing.com/az/hprichbg/rb/BilbaoGuggenheim_EN-US11232447099_1366x768.jpg"
));*/
$reply = $cb->statuses_updateWithMedia($params);

Error:#200 The user hasn't authorized the application to perform this action

Facebook Login URL Code :
$this->set("facebookUrl",$this->facebook->getLoginUrl(
array(
'scope' => 'email,publish_actions',
'redirect_uri' =>"http://redirected_url"
'display'=>"popup"
)
));
Post story on facebook code :
$params = array(
"access_token" => "access_token_of_logged_in_user",
"message" => "Testing facebook post",
"picture" => "http://i.stack.imgur.com/Og6yH.jpg?s=128&g=1",
"caption" => "www.pontikis.net",
"description" => "Description of post."
);
$myProfile = $this->facebook->api('/me');
$permissions = $this->facebook->api('/me/permissions');
pr($permissions);
try {
$ret = $this->facebook->api('/'.$myProfile['id'].'/feed', 'POST', $params);
echo 'Successfully posted to Facebook';
}
catch(Exception $e) {
echo $e->getMessage();
}
Permission Displayed here :
Array
(
[data] => Array
(
[0] => Array
(
[permission] => public_profile
[status] => granted
)
[1] => Array
(
[permission] => email
[status] => granted
)
)
)
I got following Error when I post on facebook :
(#200) The user hasn't authorized the application to perform this action
If you're using Graph API >=v2.0, then you need to pass Login Review for non admin/tester/developer users before you can use this permission in your app:
See
https://developers.facebook.com/docs/apps/review/login#do-you-need-review

Categories