How to use setExtendedAccessToken() - php

i am using Graph api to create a facebook app with PHP .
require_once("facebook.php");
$config = array();
$config[‘appId’] = 'xxxxxxxxxxx';
$config[‘secret’] = 'xxxxxxxxxxxxxxxxxxxxx'; // NEVER USED THIS , JUST INCLUDED IT !
$config[‘fileUpload’] = true; // optional
$facebook = new Facebook($config);
$app_id = "xxxxxxxxx";
$app_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$my_url = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token']; // The acess call :)
$at = $params['access_token']; // I USE THIS ACCESS TOKEN
I now use that access token ($at) to make requests . But i need to store the access_token for much longer time (60 days) .
So
1)how do i use setExtendedAccessToken() method &
2) where i should put that in my code &
3) where can i obtain the output from
I am including the PHP SDK too , even though i am not using it .

You can exachange temporary Token for Extended Token. check below code.
try {
$graph_url = "https://graph.facebook.com/oauth/access_token?";
$graph_url .= "client_id=".$FB_APP_ID;
$graph_url .= "&client_secret=".$FB_APP_SECRET;
$graph_url .= "&grant_type=fb_exchange_token";
$graph_url .= "&fb_exchange_token=".$fb_temp_access_token;
$response = #file_get_contents($graph_url);
$params = null;
parse_str($response, $params);
$new_token =$params['access_token'];
} catch (Exception $e) {
//DO NOTHING
}

You can extend an access_token, read about it here: https://developers.facebook.com/docs/howtos/login/extending-tokens/
Put it at the end, after you have already have an acces_token from the login.
You get the output in the same manner you would with other API calls.

The code I am using to get access token is:
$access_token=$facebook->getAccessToken();
I just put this code like this.
if($userid){
try{
$access_token = $facebook->getAccessToken();
echo $access_token;
}
catch(FacebookApiException $e){
//catch error here
}
else{
$loginUrl=$facebook->getLoginUrl(array('redirect_uri'=>'your_url','scope'=>'publish_stream,read_stream,manage_pages');
exit("<script>window.top.location.replace('$loginUrl');</script>");
}
It does store access token that will expire about 2 month ( I use this tool to check).

Related

Facebook server login doesn't retrieve info if user refreshes page

the code is according to fb manual, and i ve noticed that if the user refreshes the page, i can't retrieve the id of the user..the user will need to clear from the address bar the entire string after my url, in order to be able to obtain user info..
<?php
$app_id = "myid";
$app_secret = "mysecretkey";
$my_url = "http://myurl.php";
session_start();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); // CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'] . "&scope=publish_actions";
header("Location: " . $dialog_url);
}
if($_SESSION['state'] && ($_SESSION['state'] === $_REQUEST['state'])) {
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$_SESSION['access_token'] = $params['access_token'];
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
echo var_dump($user);
else {
echo("The state does not match. You may be a victim of CSRF.");
}
var_dump returns to me all necessary information after first redirect, but if i refresh the page it returns null..
perhaps i need to "destroy" any session cookies??
This happens cause the $code that you are using is no longer valid and has been consumed.
Also might I suggest you to use Facebook's PHP SDK. It would reduce time to develop your app and take care of these errors for you.
i altered the code a little bit, in order to by pass the problem..
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
if ($params['access_token'] == NULL) {
header("Location: " . $my_url);
}
$user = json_decode(file_get_contents($graph_url));
}
so, if the access_token is not valid, then the page is "forced" to be reloaded without any string query and retrieves a new one.. :)
there was a usefull reference over here as well https://developers.facebook.com/blog/post/2011/05/13/how-to--handle-expired-access-tokens/
and many thanks to #Anvesh Saxena for his contribution

How can i pull a user's facebook status message using the Graph API

I've tried to use this method using the Graph API, but it doesn't return the status messages ... Is there anyway I can pull those ? How can I also get the feeds of the Facebook pages that a user's follow .. Like for example coca cola's page .. how can I retrieve its feeds if I like it ?? answers would be appreciated !!!
$status = $facebook->api("/690196511");
Try this code :
<?php
$facebook_appid = "facebook_appid"; // Facebook appplication id
$facebook_secret = "facebook_secret"; // Facebook secret id
$facebook_pageid = "facebook_pageid"; // Facebook secret id
$redirect_uri = "https://localhost/facebook_page/events.php"; // return url to our application after facebook login ## should be SAME as in facebook application
//$redirect_uri = "https://localhost/facebook_page/fb_login.php"; // return url to our application after facebook login ## should be SAME as in facebook application
$scope = "user_photos,email,user_birthday,user_online_presence,offline_access,manage_pages,publish_stream,user_events,friends_events"; // User permission for facebook
$code = $_REQUEST["code"]?$_REQUEST["code"]:"";
if(empty($code)) {
$_SESSION['state'] = time(); // CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id=". $facebook_appid . "&redirect_uri=" . urlencode($redirect_uri) . "&state=". $_SESSION['state'] . "&scope=".$scope;
header("location:".$dialog_url);
}
if($_SESSION['state'] && ($_SESSION['state'] == $_REQUEST['state'])) {
$token_url = "https://graph.facebook.com/oauth/access_token?". "client_id=" . $facebook_appid . "&redirect_uri=" . urlencode($redirect_uri). "&client_secret=" . $facebook_secret . "&code=" . $code;
$response = #file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$account_url = "https://graph.facebook.com/".$facebook_pageid."?fields=access_token&access_token=".$params['access_token'];
$resp = #file_get_contents($account_url);
$dt = json_decode($resp);
echo $dt->access_token;
echo "<br>";
echo $dt->id;
$offer_url = "https://graph.facebook.com/".$dt->id."/feed?access_token=".$dt->access_token;
$off = #file_get_contents($offer_url);
$dto = json_decode($off);
echo "<pre>";
print_r($dto);
}
?>

App_access_token Always Returns False

According to the Facebook docs, using App_access_token is as simple as:
$appid = 'xxx';
$secret = 'yyyyyyyyy';
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $secret,
'cookie' => true,
));
$session = $facebook->getUser()>0;
if($session){
$access_token = 'access_token='.$facebook->getAccessToken();
$app_access_token = file_get_contents("https://graph.facebook.com/oauth/access_token?client_id=$appid&client_secret=$secret&grant_type=client_credentials");
}
My problem is that $access_token is fine but $app_access_token always returns false, what am I doing wrong?
-EDIT-
If I open the app_access_token URL in my browser I can see the access token! It seems to fail the file_get_contents... ?
The file_get_contents could be creating problems, may be due to some php config settings. (Discussion here: file_get_contents returns empty string)
I'll recommend you to use cURL instead, something like that-
function get_content($URL){
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $URL);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
echo get_content('http://example.com');
If the problem persists, re-check the values of app_id and secret in the url.
I file_get_contents not working try this :
Enable php ini setting for allow_url_fopen, then restart the server.
Here is the working code :
<?php
$facebook_appid = "facebook_appid"; // Facebook appplication id
$facebook_secret = "facebook_secret"; // Facebook secret id
$redirect_uri = "https://192.168.75.44/facebook_login/fb_login.php"; // return url to our application after facebook login ## should be SAME as in facebook application
//$cancel_url = ""; // redirect url if user denies the facebook login ## should be SAME as in facebook application
$scope = "user_photos,email,user_birthday,user_online_presence,offline_access"; // User permission for facebook
$code = $_REQUEST["code"]?$_REQUEST["code"]:"";
if(empty($code)) {
$_SESSION['state'] = time(); // CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id=". $facebook_appid . "&redirect_uri=" . urlencode($redirect_uri) . "&state=". $_SESSION['state'] . "&scope=".$scope;
header("location:".$dialog_url);
}
if($_SESSION['state'] && ($_SESSION['state'] == $_REQUEST['state'])) {
$token_url = "https://graph.facebook.com/oauth/access_token?". "client_id=" . $facebook_appid . "&redirect_uri=" . urlencode($redirect_uri). "&client_secret=" . $facebook_secret . "&code=" . $code;
$response = #file_get_contents($token_url);
$params = null;
parse_str($response, $params);
echo $params['access_token'];
}
?>

Facebook: Post on Page as Page issue (access token / php)

I'm totally frustrated with my first facebook app project. I'm having major issues with what seems to be a simple task.
I want to setup a cron job on my server (easy) that will post something smart on a facebook page (not my profile), and it should be posted as page. I coded myself into a corner and am totally confused now... Can anyone help, please?
I've been thru pretty much every error message and am now stuck on
"OAuthException: Error validating application."
Here's what I have now:
First php -> Gets a new Access Token for my page access. This part seems to work fine, as I get the next page called and receive a new access token.
<?php
require_once 'facebook.php';
$app_id = "1234....";
$app_secret = "5678....";
$my_url = "http://.../next.php";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
// known valid access token stored in a database
$access_token = "abc....";
$code = $_REQUEST["code"];
// If we get a code, it means that we have re-authed the user
//and can get a valid access_token.
if (isset($code)) {
$token_url="https://graph.facebook.com/oauth/access_token?
client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code . "&display=popup";
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
}
// Attempt to query the graph:
$graph_url = "https://graph.facebook.com/me?"
. "access_token=" . $access_token;
$response = curl_get_file_contents($graph_url);
$decoded_response = json_decode($response);
//Check for errors
if ($decoded_response->error) {
// check to see if this is an oAuth error:
if ($decoded_response->error->type== "OAuthException") {
// Retrieving a valid access token.
$dialog_url= "https://www.facebook.com/dialog/oauth?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode($my_url);
echo("<script> top.location.href='" . $dialog_url
. "'</script>");
} else {
echo "other error has happened";
}
} else {
// success
echo("success" . $decoded_response->name);
}
function curl_get_file_contents($URL) {
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c);
$err = curl_getinfo($c,CURLINFO_HTTP_CODE);
curl_close($c);
if ($contents) return $contents;
else return FALSE;
}
?>
Next php -> Read the access token and post on the wall. I get the access token from my query string, but then why do I receive the error message. My id, secret and page id are all in order...
<?php
require_once 'facebook.php';
$app_id = "1234....";
$app_secret = "5678....";
$page_id = "0909....";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
$access_token = $_GET['code'];
echo($access_token);
try {
$attachment = array(
'access_token' => $access_token,
'message'=> "Hello World"
);
$result = $facebook->api('/'.$page_id.'/feed','POST',
$attachment);
var_dump($result);
} catch(Exception $e) {
echo $e;
}
?>
I'm sure there is a simpler way to do so.... and a way to actually make it work!
Any help is appreciated!
I followed this script
Update facebook page status from that page itself
and this
https://developers.facebook.com/blog/post/500
Thank you.
// firstly include the fb sdk
$facebook = new Facebook(array(
'appId' => 'your app id',
'secret' => 'your app secret',`enter code here`
'cookie' => true,
));
$session = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'user_status,publish_stream,email,user_location,user_birthday,friends_birthday,manage_pages',
'redirect_uri' => 'http://www.example.com/'
)
);
$logoutUrl = $facebook->getLogoutUrl(
array(
// any url u want to redirsct onto
'redirect_uri' => 'http://www.example.com/'
)
);
// when redirected from facebook get the code
$code = $_GET['code'];
//
$my_url = 'http://www.example.com/';
$app_id = 'your app id ';
$app_secret = 'your app secret ';
// here we have the access token so we will play with it
if (isset($code)) {
$token_url="https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code ;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$user_access_token = $params['access_token'];
}
// here we got the access token of user over here in $user_access_token
// now we will get for our page
//------ get PAGE access token
$attachment_1 = array(
'access_token' => $user_access_token
);
$page_id = 'your page id ';
$result = $facebook->api("/me/accounts", $attachment_1);
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {
$page_access_token = $page["access_token"];
break;
}
}
// write to page wall
try {
$attachment = array(
'access_token' => $page_access_token,
'message'=> 'hello world posting like admin!',
'page_id'=> $page_id
);
$result = $facebook->api('/'.$page_id.'/feed','POST',$attachment);
//$result = $facebook->api('/me/feed','POST', $attachment);
var_dump($result);
} catch(Exception $e) {
echo $e;
}
From your code, it appears you are not getting a PAGE access token which you need, but instead you're using a USER access token, hence why the API doesn't like it. For more information on how to get a PAGE access token from a USER one, please see the Page login section of https://developers.facebook.com/docs/authentication/
After many hours of trial and error, here's my solution that works so far.
<?php
require_once 'facebook.php';
//------ vars
$app_id = "123...";
$app_secret = "abc...";
$page_id = "999...";
$my_url = "http://exactly the same as defined /";
//------ fb object
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
//------ verification CODE
// this is not pretty -> the code should be received with a another graph query...
// but I couldn't get this to work. Thus I'm using my last known Verification Code
$code = "ABC123...";
//------ get USER access token
if (isset($code)) {
$token_url="https://graph.facebook.com/oauth/access_token?client_id=" . $app_id
. "&client_secret=" . $app_secret
. "&code=" . $code
. "&redirect_uri=" . $my_url;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$user_access_token = $params['access_token'];
} else {
echo("No code");
}
//------ get PAGE access token
$attachment_1 = array(
'access_token' => $user_access_token
);
$result = $facebook->api("/me/accounts", $attachment_1);
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {
$page_access_token = $page["access_token"];
break;
}
}
//------ write to page wall
try {
$attachment = array(
'access_token' => $page_access_token,
'message'=> 'hello world!'
);
$result = $facebook->api('/me/feed','POST', $attachment);
var_dump($result);
} catch(Exception $e) {
echo $e;
}
?>

How to parse the authentication code in the Facebook API? Getting MySQL errors

What's the right way to parse the code when authenticating your app during a user login? I'm using PHP for my app.
The reason I'm asking is because I keep getting weird queries in MySQL whenever I try to do inserts into my database. The API calls are all working, but if I try to put in user details (name, email, access_token) then three or four other queries will also run after that with empty values, each in different rows. This only happens when I try to get the authentication code via $_REQUEST['code'] or $_SERVER['QUERY_STRING'] after the dialog url.
What's weird though is that I don't get any issues with MySQL at all if I simply try calling the same page with $code hard-coded to the right value. Obviously, I can't leave it like that since the authentication code is always changing, but it's weird because only then do my MySQL work normally. Has anyone else experienced this? Is the code response encoded in a different format maybe?
Any help would be greatly appreciated, here's my code:
$code = $_REQUEST['code'];
if (empty($code)) {
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=" . $app_id .
"&redirect_uri=" . urlencode($redirect) . "&scope=offline_access,email";
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
$response = urldecode($_SERVER['QUERY_STRING']);
$code = substr($response,5);
$token_url = "https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($redirect) . "&client_secret=" .
$app_secret . "&code=" . $code;
$access_token = file_get_contents($token_url);
$user_url = "https://graph.facebook.com/me?" . $access_token;
$user = json_decode(file_get_contents($user_url));
$user_id = $user->id;
$email = $user->email;
// MYSQL insert queries into database
Are you using the facebook php sdk file? or are you making your own authorization callback?
because its much easyer, example:
////////////////////////////////////////////////////////
require_once('facebook.php');
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'cookie' => true,
));
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
// login or logout url will be needed depending on current user state.
if ($me) {
$logoutUrl = $facebook->getLogoutUrl();
$sql=my_sql_fetch_array(mysql_query("SELECT * from mytable where id='".$me['id']."'"));
if($sql)
{
$_SESSION["usr_id"] =$me['id'];
$_SESSION["usr_name"]=$me['name'];
}
else{
mysql_query("insert into mytable (id,fbid,name) values(NULL,'".$me['id']."','".$me['name']."'");
$_SESSION["usr_id"] =$me['id'];
$_SESSION["usr_name"]=$me['name'];
}
} else {
$loginUrl = $facebook->getLoginUrl();
}
//i set sessions here or maybe some mysql commands like check if the user is already in the database and then set the sessions.

Categories