Facebook PHP SDK - How to get access token? - php

I'm trying to post on user's Facebook wall from my app. The user granted the permissions to the app to post on his wall, and I have userid in db. I need to send the post automatically, without the user logging in again.
My code is:
try{
require_once(dirname(__FILE__) . '\lib\facebook-php\src\facebook.php' );
}
catch(Exception $o){
print_r($o);
}
$config = array(
'appId' => '123456',
'secret' => '454544',
'allowSignedRequest' => false // optional but should be set to false for non-canvas apps
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
$user_id = '123456';
if($user_id) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$ret_obj = $facebook->api('/me/feed', 'POST',
array(
'access_token' => $facebook->getAccessToken(),
'link' => 'www.example.com',
'message' => 'Posting with the PHP SDK!'
));
echo '<pre>Post ID: ' . $ret_obj['id'] . '</pre>';
// Give the user a logout link
echo '<br />logout';
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
var_dump($e);
$login_url = $facebook->getLoginUrl( array(
'scope' => 'publish_stream'
));
echo 'Please login.';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, so print a link for the user to login
// To post to a user's wall, we need publish_stream permission
// We'll use the current URL as the redirect_uri, so we don't
// need to specify it here.
$login_url = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
echo 'Please login.';
}
This throws An active access token must be used to query information about the current user. error and asks for login. After I click login, the post is sucesfully posted.
How can I get the access token with userid without the user logging in?

This happens when the active access token is not available while calling the API end point /me
There are two solutions to get rig of this
use the userid instead of /me
set the access-token prior sending the api call
For the first you can make the call as
ret_obj = $facebook->api('/'.$user_id.'/feed', 'POST',
array(
'link' => 'www.example.com',
'message' => 'Posting with the PHP SDK!'
));
You dont need to send 'access_token' => $facebook->getAccessToken(),
The Second option is to do as
$access_token = $facebook->getAccessToken();
$facebook->setAccessToken($access_token);
ret_obj = $facebook->api('/me/feed', 'POST',
array(
'link' => 'www.example.com',
'message' => 'Posting with the PHP SDK!'
));
NOTE: publish_stream scope must be send while doing the login
Deprecation Notice :publish_stream was replaced by publish_actions, check the facebook doc for permission

you have to get permission .
Check it out here
https://developers.facebook.com/docs/reference/login/

Related

How to fix "(#200) The user hasn't authorized the application to perform this action" error while posting on facebook wal

I am getting "(#200) The user hasn't authorized the application to perform this action" error when posting message on user's facebook wall. I am using facebook graph API. I have also set the "publish_actions" permission in the scope, but didn't working. My code is
require 'facebook/facebook.php';
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
));
$user = $facebook->getUser();
if ($user) {
$accessToken = $facebook->getAccessToken();
try {
//create message with token gained before
$post = array(
'access_token' => $accessToken,
'message' => 'Test message'
);
$res = $facebook->api('/me/feed', 'POST', $post);
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
} else {
# There's no active session, let's generate one
$login_url = $facebook->getLoginUrl(array(
'scope' => 'publish_actions'
));
header("Location: " . $login_url);
}
Can you please suggest me what i am missing in the code or in the app?
Since you mentioned that it does work for Admins, but not for anyone else, it´s very clear what the problem is: You need to go through Login Review with publish_actions - else, that permission will only work for users with a role in the App.
All the information you need about Login Review is in the docs: https://developers.facebook.com/docs/facebook-login/review

Post on Facebook without Share Prompt in PHP

Is there a possibility where I can make a button on which when I click, the contents directly get shared on facebook without showing our user the share prompt dialog box?
I referred it online and found that its possible through mobile devices:
http://www.mindfiresolutions.com/How-to-post-message-on-your-facebook-wall-without-using-Facebook-dialog-Box-1419.php
The question is can we make some sort of ajax call and get this done on web apps.
We used Following code
<?php
require_once('php-sdk/facebook.php');
$config = array(
'appId' => 'My app ID', /*Your APP ID*/
'secret' => 'My Secret ID', /*Your APP Secret Key*/
'allowSignedRequest' => false
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if($user_id) {
try {
$user_profile = $facebook->api('/me','GET');
} catch(FacebookApiException $e) {
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, print a link for the user to login
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
}
$response = $facebook->api(
"/me/feed",
"POST",
array (
'message' => 'This is a test message',
'link' => 'www.google.com'
/* 'picture' => '{picture}',
'caption' => '{caption}',
'description' => '{description}'*/
)
);
?>
But its returns : " Fatal error: Uncaught OAuthException: (#200) The user hasn't authorized the application to perform this action throw in file"
Any help would be highly appreciated.
Thanks in advance.
Of course you can using the Graph API. On the button click you just have to make a \POST call to /me/feed.
Learn more about publishing a feed via Graph API and what all parameters are available here.
Permission required: publish_stream
Using PHP SDK:
$response = $facebook->api(
"/me/feed",
"POST",
array (
'message' => 'This is a test message',
'link' => '{link}',
'picture' => '{picture}',
'caption' => '{caption}',
'description' => '{description}'
)
);
Direct HTTP Request-
POST /me/feed
Host: graph.facebook.com
message=This+is+a+test+message
...
You can check your calls in Graph API Explorer
Edit:
To ask for the required permissions:
$params = array(
'scope' => 'publish_stream'
);
$login_url = $facebook->getLoginUrl($params);
You can read more about permissions here.
Try this way: https://developers.facebook.com/docs/reference/php/
When coding the wep app, you only have to provide the App Id and the App Secret, then you should have to specify the content to be posted.
You should try also the Javascript Facebook SDK, you'll find it here: https://developers.facebook.com/docs/javascript or you could go further and try the C# SDK, this one is a little bit more complex, but you will be able to do so much more.
Have fun coding!!!
Just go to https://developers.facebook.com/docs/opengraph/
Review it and place what kind of share you want.
This is the long process to be handle so. you need to study it.

Post to FB Page as User

So I have a Facebook Page (let's call it X), which has app Y on it. The user can ask a question via Y, and it gets posted to X as the user (not as the app).
My permissions for the app are currently set to publish_stream.
I can grab a token via
$token_url = "https://graph.facebook.com/oauth/access_token?" .
"client_id=" . $this -> data["environment"] -> fb_appid .
"&client_secret=" . $this -> data["environment"] -> fb_appsecret .
"&grant_type=client_credentials";
$app_token = file_get_contents($token_url);
which gives me a token just fine.
Now, if I try to POST via an APi call, I get two results:
When I do not pass the token and simply call
$post_id = $this ->Facebook->fb_api("/PAGE_ID/feed", "POST", array("message"=>"This is a post from PHP."));
I get a response back in the form of JSON
{
"id": "PAGEID_someOtherID"
}
but I do not see the post on the wall.
When I do pass the access token, ala
$post_id = $this ->Facebook->fb_api("/PAGE_ID/feed", "POST", array("access_token"=>$app_token,"message"=>"This is a post from PHP."));
my response comes back empty.
What am I doing wrong with such a simple concept?
Sample from Facebook docs
https://developers.facebook.com/docs/reference/php/facebook-api/
<?php
// Remember to copy files from the SDK's src/ directory to a
// directory in your application on the server, such as php-sdk/
require_once('php-sdk/facebook.php');
$config = array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
?>
<html>
<head></head>
<body>
<?
if($user_id) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$ret_obj = $facebook->api('/'.$pageid.'/feed', 'POST',
array(
'link' => 'www.example.com',
'message' => 'Posting with the PHP SDK!'
));
echo '<pre>Post ID: ' . $ret_obj['id'] . '</pre>';
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl( array(
'scope' => 'publish_stream'
));
echo 'Please login.';
error_log($e->getType());
error_log($e->getMessage());
}
// Give the user a logout link
echo '<br />logout';
} else {
// No user, so print a link for the user to login
// To post to a user's wall, we need publish_stream permission
// We'll use the current URL as the redirect_uri, so we don't
// need to specify it here.
$login_url = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
echo 'Please login.';
}
?>
</body>
</html>
Well you are not able to post something on a page wall without access_token Cause without access token facebook can not realize Who is The user who wants to post & about the time you are trying to post via access_token i think you are doing something wrong please check permissions you have (you need publish_stream not stream_publish) i will put a sample code for you soon

How to request scope/permission from Facebook during user registration

I am using the information on http://developers.facebook.com/docs/plugins/registration/ to register, and login users with Facebook. How would I request this permission? I've tried to use
&scope=permission,permission,etc,etc
before fields, and then after fields. Regardless, the system still says
The user hasn't authorized the application to perform this action
Any help on this issue would be much appreciated!
After registration, I try as follows and it still spit out the same error:
if ($_REQUEST) {
require 'facebook.php';
$facebook = new Facebook(array('appId' => APP_ID,'secret' => APP_SECRET));
$user = $facebook->getUser();
if ($user) {
$loginUrl = $facebook->getLoginUrl(array('scope' => 'email,publish_stream'));
$statusUpdate = $facebook->api('/me/feed', 'post', array('message'=> 'Testing posting to may wall', 'cb' => ''));
} else {
$loginUrl = $facebook->getLoginUrl(
array('scope' => 'email,publish_stream','redirect_uri' => REDIRECT_URL )
);
}
}
You need to request permissions after registration seperately. There is no way to request permissions through registration plugin at the moment.
This feature is on the wishlist:
http://bugs.developers.facebook.net/show_bug.cgi?id=14733

Facebook App - auto login so can update status (php SDK)

I have built an app that allows users to update their status' externally. It uses the PHP SDK.
Is it possible to automatically login for registered users once they have initially authorised their facebook account via the app? I do not want them to have to login for every new session. Id like that once they have been authenticated the first time, they are always connected and not asked to login multiple times. Possibly by storing the access token in a database and this using this to connect somehow. Is this possible? I have noticed other apps that do this, but have no idea how they do this eg. ping.fm
Below is what I have so far, but this requires the user to select the "login" link when the session expires.
//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
'appId' => 'appid',
'secret' => 'secret',
'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', 'offline_access');
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,offline_access',
'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',
'GET',
array(
'access_token' => $access_token
)
);
//save the information inside the session
$_SESSION['access_token'] = $access_token;
$_SESSION['accounts'] = $accounts['data'];
$facebookAuth = TRUE;
} 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,offline_access',
'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
$facebook_login = $login_url;
}
if (isset($_GET['submit'])){
if ($_GET['facebook']){
//get the info from the form
$parameters = array(
'message' => $_GET['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(
'/me/feed',
'POST',
$parameters
);
if ($newpost){
echo 'posted to facebook';
} else {
echo 'not posted to facebook :0( ';
}
}
I did not check how ping.fm does it.
But after looking at the extended permissions list here:
http://developers.facebook.com/docs/reference/api/permissions/
xmpp_login (Provides applications that integrate with Facebook Chat the ability to log in users.)
Otherwise, i dont think its possible.
Even desktop Apps need to redirect the user to a browser for authentication.
This also may depend on whether the user has the "keep me logged in" checkbox marked on log-in.
Since you have the offline_access, then you basically can perform the actions regardless if the user is logged in or not.

Categories