Is Facebook long-lived access token usable on multiple users? - php

I'm experimenting with Facebook's long-live access token and I found that the long-lived access token is usable in different users. Is this normal?
I'm using the Facebook PHP SDK v3.2.2 and Yii. Here's my code to generate the long-lived access token from App_User_1
Yii::import('application.vendors.facebook.Facebook');
$facebook = new Facebook(
array(
'appId' => Yii::app()->params['facebookApi'],
'secret' => Yii::app()->params['facebookSecretCode'],
'cookie' => true,
)
);
$loginUrl = $facebook->getLoginUrl(array('display' => 'touch', 'scope' => 'publish_actions'));
$fbUser = $facebook->getUser();
if(!empty($fbUser))
{
$facebook->setExtendedAccessToken(); //long-live access_token 60 days
$access_token = $facebook->getAccessToken();
exit(print_r($access_token));
}
Here's my code to test posting to App_User_1's Facebook wall.
$message = "A message";
$link = "http://www.alink.com";
$picture = "http://www.alink/image.png";
$sendTo = "`**App_User_1**`";
$access_token = "xxxxxxxxxx";
Yii::import('application.vendors.facebook.Facebook');
$facebook = new Facebook(
array(
'appId' => Yii::app()->params['facebookApi'],
'secret' => Yii::app()->params['facebookSecretCode'],
'cookie' => true,
)
);
$attachment = array('message' => $message, 'link' => $link, 'picture' => $picture );
$api = "/$sendTo/feed/?access_token='.$access_token,";
$result = $facebook->api($api,'post', $attachment);
I have 2 test app user. If I substitute the App_User_1's access token, I can also post into App_User_2's Facebook Wall. Is this normal?

I think I may have been doing this the wrong way. Using the PHP SDK, the api method does not recognize the access_token as part of its path parameter. (e.g. /me/feed/?access_token=blah)
Instead, the access token should be specified under optional parameters in an array format.
Here's how I got mine to work.
$facebook_uid = '1234567890';
//Initialize array for the params parameter
$fb_data = array();
$fb_data['access_token'] = 'xxxxxxxxxx';
$fb_data['message'] = 'A test message';
$facebook->api('/'.$facebook_uid.'/feed/', 'post', $fb_data);
Tried swapping the access token with other app user's access token and not specifying access_token at all. Both will result in error (#200) The user hasn't authorized the application to perform this action.
I would also recommend using this tool by Facebook to verify that the access_token is generated correctly by your app. https://developers.facebook.com/tools/debug

Related

OAuthException: Error validating access token: The session is invalid because the user logged out

I have followed the steps from.
Facebook Access Token for Pages
And generated a page access token, then used the following code
<?php
include 'includes/facebook.php';
$app_id = "XXXXXXXXXXXX";
$app_secret = "XXXXXXXXXXXX";
$page_id = "XXXXXXXXXXXX";
$my_url = "http://XXXXXXXXXXXX.com";
$page_access_token = "XXXXXXXXXXXX";
//Create the facebook object
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
//Write to the Page wall
try {
$attachment = array(
'access_token' => $page_access_token,
'message'=> "Hello World"
);
$result = $facebook->api('page_id/feed', 'post', $attachment);
} catch (FacebookApiException $e) {
error_log($e);
echo $e;
}
?>
It works for the first time but whenever the admin logged out, it's showing the error.
"OAuthException: Error validating access token: The session is invalid because the user logged out."
I tried a lot of suggestions but failed.
Try and replace
'page_id/feed'
with
$page_id.'/feed'
this should provide facebook api with correct destination page id

Conversion Personal Account to a Facebook Page: which token use to upload photo on that page?

this is my situation: I converted my personal account in a Facebook page (https://www.facebook.com/nextdoorhelp). Now when I logged in FB as the same account I have only a page adminstration panel for that page (that I call pageX).
I created an app for my website http://nextdoorhelp.it/ndh to allow login with Facebook account.
I want to use my FB app to allow to upload a user photo to a specific pageX's photo album.
My problem is that I don't know which access token I have to use to do it!
This is my code:
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $app_secret,
'cookie' => true,
'fileUpload' => true
));
$accessToken = ????;
$post_login_url = "http://nextdoorhelp.it/ndh";
// Facebook Photo Album ID = 123456789
$album_id = "123456789";
// Enable Facebook Upload Support
$facebook->setFileUploadSupport(true);
// Share url
$uri = 'http://nextdoorhelp.it/ndh/pages/share?item=' . $shareurl;
// Data
$attachment = array(
'message' => $msg . ' - '.$uri ,
'image' => '#' .realpath($photo_path),
'access_token' => $accessToken
);
$data = $facebook->api('/'.$album_id.'/photos', 'post', $attachment);
$loaded_photo_id = $data['id'];
return $loaded_photo_id;
Moreover, I'm admin for the pageX and I tried to use my access token retrieved by a graph-api call to "me/accounts" for pageX but Facebook answered me with an error message "Error: [FacebookApiException] (#120) Invalid album id".
How can I obtain right access token to upload photo from every users (Facebook users and not)?
Please help me, I'm becoming crazy!

How to post an image to a facebook page from a PHP app?

I'm trying to post an image to a facebook page from a PHP app. I check many resources, the documentation, some demo codes and several questions in this site, but cannot finish a working app.
Here is my code:
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $appSecret
));
$fbuser = $facebook->getUser();
$facebook->setFileUploadSupport(true);
$post_url = '/443513955707619/photos';
$msg_body = array(
'source' => '#/www/www.gbart.hu/public_html/facebook/megosztos_app/img/winner/winner_'.(int)$round[0].'.jpg',
//'image' => 'http://www.gbart.hu/facebook/megosztos_app/img/winner/winner_'.(int)$round[0].'.jpg',
'message' => 'http://www.facebook.com/WangMesterKinaiKonyhaja/app_322145727882829',
'access_token' => $access_token
);
try {
$postResult = $facebook->api($post_url, 'post', $msg_body);
}
catch (FacebookApiException $e) {
echo $e->getMessage();
}
Here are my permissions for the app:
$fbPermissions = 'email, publish_actions, publish_stream, photo_upload, manage_pages';
I have the appID, app_secret, access_token parameters as required (the other parts of the app is working).
I got some different error messages, like invalid album id or invalid access tokens. I solved these, and now there isn't any error messages, but the photo does not appear anywhere.
In a previous version of this code I tried to post the image to the page walls not to the album, but that made a weird result: posted the image to my user profile's wall.
Try to post something like below
$url = "https://graph.facebook.com/443513955707619/photos?access_token=".$token."&message=hello&url=http://imagetopost.com/hi.jpg&method=post";
$response = file_get_contents($url);

PHP API FACEBOOK - Users post to facebook page and personal wall

I created a contest where a submitted form will:
write a comment on the wall of Facebook staff and
write a comment on the wall of my page
I had no problems with step 1, but step 2 does not work. My code is as follows:
connect.php
<?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' => 'CRYPT FOR THIS FORUM',
'secret' => 'CRYPT FOR THIS FORUM',
'cookie' => true
));
//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', 'read_stream');
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,read_stream',
'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
//id pag sposiamo รจ 494659577226200
$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: manage.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' => 'publish_stream,read_stream',
'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();
}
?>
newpost.php
<?php
//include the Facebook PHP SDK
include_once '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' => 'CRYPT',
'secret' => 'CRYPT',
'cookie' => true
));
//get the info from the form
$parameters = array(
'message' => $_POST['message'],
'picture' => $_POST['picture'],
'link' => $_POST['link'],
'name' => $_POST['name'],
'caption' => $_POST['caption'],
'description' => $_POST['description']
);
//add the access token to it
$parameters['access_token'] = $_SESSION['active']['access_token'];
//build and call our Graph API request
$newpost = $facebook->api(
'/494659577226200/feed',
'/me/feed',
'POST',
$parameters
);
//redirect back to the manage page
header('Location: manage.php');
exit();
494659577226200 = FBPAGEID
PROBLEM IS '/494659577226200/feed', and error AuthCode 200...
You need to ask your user's to give your app manage_pages permission to post to their pages they manage on behalf of them. Check out their permissions doc here, See Page Permissions section.
Quoted from docs:
manage_pages
Enables your application to retrieve access_tokens for Pages and Applications that the user administrates. The access tokens can be queried by calling //accounts via the Graph API. This permission is only compatible with the Graph API, not the deprecated REST API.
See here for generating long-lived Page access tokens that do not expire after 60 days.
Once you get this permission, you can then make a wall post using page access token

FQL returns "Requires valid signature"

I am having a wierd problem, things that worked before stopped working today, maybe it was bad before but now after the oAUTH 2 change, I am having troubles with a near production app
this is what I try
$params = array('method'=>'fql.query','query' => 'SELECT uid2 FROM friend WHERE uid1 = me()');
$result = $facebook->api($params);
I get:
Exception: 104: Requires valid signature
or more elaborated :
$config = array(
'appId' => 'XXXXXXXXXXXXXXXX',
'secret' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX',
);
$facebook = new Facebook($config);
$uid = $facebook->getUser();
if ($uid){
try {
$access_t = $facebook->getAccessToken();
$fql = 'SELECT uid2 FROM friend WHERE uid1 = '.$uid;
$params = array('method' => 'fql.query', 'query' => 'SELECT uid2 FROM friend WHERE uid1 = '.$uid);
$result = $facebook->api($params);
echo $result;
$friends = $facebook->api(array('method' => 'fql.query', 'query' => $fql, 'access_token' => $access_t));
var_dump($friends);
} catch (FacebookApiException $e) {
echo $e;
}
this is the code I am using to validate the user and get the login info and permissions allowed:
$canvas_base_url = "https://apps.facebook.com/myapp/index.php?from=allow";
$params = array('scope' => 'publish_stream,email,offline_access,user_status,friends_status,friends_photos,user_photos,xmpp_login,user_online_presence,friends_online_presence',
'redirect_uri' => $canvas_base_url
);
$loginUrl = $facebook->getLoginUrl($params);
what am I doing wrong ?
This means the access token you are using is invalid. It has probably expired.
Here's a quote from the docs at http://developers.facebook.com/docs/authentication/:
In addition to the access token (the access_token parameter), the
response contains the number of seconds until the token expires (the
expires parameter). Once the token expires, you will need to re-run
the steps above to generate a new code and access_token, although if
the user has already authorized your app, they will not be prompted to
do so again. If your app needs an access token with an infinite expiry
time (perhaps to take actions on the user's behalf after they are not
using your app), you can request the offline_access permission.
So you should re-run the steps to generate an access token, or require the offline_access permission.

Categories