I'm using the Facebook php-sdk and the batch request API to send AppRequests with the following code:
$facebook = new Facebook(array(
'appId' => $FB_APP_ID,
'secret' => $FB_APP_SECRET,
'cookie' => true
));
// get app token before it's overwritten
$FB_APP_TOKEN = $facebook->getAccessToken();
$res = $facebook->api('<USER ID>/apprequests', 'POST', array(
'message' => 'Test message..'
), $FB_APP_TOKEN);
This appears to work and returns the ID of the request, which I can then see has been stored when looking back with the graph explorer. My problem is that nothing appears on my test user's facebook account, no notification and no number appears next to the app name in the sidebar as described here.
Does anyone have any idea why this might be?
getAccessToken() sometimes don't return user access token. It only returns facebook application key. Use the following code to get the access token.
$token_url = "https://graph.facebook.com/oauth/access_token?" .
"client_id=" . $app_id .
"&client_secret=" . $app_secret .
"&grant_type=client_credentials";
$app_access_token = file_get_contents($token_url);
Turns out I was looking at the App's page instead of the App itself, app requests are working fine!
Related
I have a really strange problem in PHP with the Facebook API. All this code is working in my testing server (shared hosting). But when I run it in the production server (Heroku) I get an error.
What I am trying to do is to receive realtime updates from Facebook when my app users likes (or unlikes) a new page.
This is the documentation that Facebook provides: https://developers.facebook.com/docs/graph-api/real-time-updates
My code to subscribe:
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
$facebook->api(
"/" . $app_id . "/subscriptions", "POST", array(
'object' => 'user',
'callback_url' => 'http://' . $url . '/rtu/callback',
'fields' => 'likes',
'verify_token' => $rtu_verify_token,
'access_token' => $app_id . "|" . $app_secret
)
);
My code in the callback:
if (isset($_GET['hub_verify_token']) && isset($_GET['hub_challenge'])) {
$rtu_verify_token = Config::get('variables.rtu_verify_token');
if (($_GET['hub_verify_token'] == $rtu_verify_token)) {
echo $_GET['hub_challenge'];
die();
}
}
$data = file_get_contents("php://input");
$json = json_decode($data);
The error:
FacebookApiException (#2200) callback verification failed: Operation
timed out after 6001 milliseconds with 0 bytes received
I have already verify the app_id, url and the app_secret variables.
Again, this works in my testing server, but not in Heroku.
I even tried not to use the Facebook API and make a cURL call, but I got the same error.
I'm thinking that maybe has something to do with Heroku, but i couldn't find any evidence.
Thanks
Your server must be reachable from the internet, and be able to process concurrent requests, because facebook sends verification requests simultaneously.
I would like to post to my own Facebook page's wall from my website using PHP.
I have the following:
Facebook Application with AppID, AppSecret, ApiKey
Facebook Page with PageID
my own Facebook account - I'm the admin and the creator of the application and page mentioned above.
E.g. I write a blog post, and I'd like to get the name, the short description and a picture on my Facebook page's wall. Or I would like to publish some articles on the Facebook page every day automatically as a cron job.
Could you provide a step-by-step tutorial how to accomplish this?
I've read this article about Facebook Login:
https://developers.facebook.com/docs/facebook-login/
but I still don't know what to write in my code.
UPDATE 1
This is how I send a request for an App Access Token:
$url = 'https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id='
.Yii::app()->params['FacebookAppID']
.'&client_secret='
.Yii::app()->params['FacebookSecret'];
The response is similar to this (fake symbols):
access_token=326584076429|ax3-D39YbpDcR9rMRQn_fMvNu_s
What access_token is it? Application Access Token? How to get a User Access Token?
I tried to use the access token from here:
https://developers.facebook.com/tools/explorer?method=GET&path=me%2Faccounts
but I got the following error message:
An active access token must be used to query information about the current user
So how should I obtain the right access token?
UPDATE 2:
How can I get the right Facebook tokens in my application without any client interaction?
I'm the admin and the creator of the Facebook Application and the Facebook Page.
Step by step
Authenticate a user that is a page admin (yourself)
Request an extended access token (to get a 60 day variety as offline_access is gone). See https://developers.facebook.com/docs/offline-access-deprecation/
Call Graph API me/accounts and search thru the resulting list to find the page you're interested in
Take the page access token from the page and start using that for the calls to post
It might be possible to get an extended access token for a page access token like described in step 2, please try and let us know if that can be done for page access token too.
You can experiment with the above at https://developers.facebook.com/tools/explorer
Happy Coding!
EDIT
For getting an access token without dialogs for any user, you can use https://developers.facebook.com/tools/access_token/ to get an access token.
Steps:
Request For manage_pages permission ( Allow this process ) :
https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&scope=manage_pages&response_type=token
Get Access token from URL :
If the administrator allows this permission. You should be redirected to URL below:
http://YOUR_URL/#access_token=AAABY5jBXQz0BAEzNKkb6FZC22D7aOoKIfFuozIjoOpkGHRJ6SyzBvqx24JGooMc31374EdRFNXkOyLZCBzETRD9vhZAZC8MZD&expires_in=0
Use Access token in the URL and you should get this:
AAABY5jBXQz0BAEzNKkb6FZC22D7aOoKIfFuozIjoOpkGHRJ6SyzBvqx24JGooMc31374EdRFNXkOyLZCBzETRD9vhZAZC8MZD
Check Access token using Graph API:
https://graph.facebook.com/me/accounts?access_token=TOKEN_FROM_ABOVE
Connection will return information and access token for each page.
Implement it in your code:
You can use App access token while call a Facebook Graph API method.
Update:
If you want use API method in Facebook SDK, DEPRECATED REST API or FQL Query...
You have to use users_accesstoken this way:
Method 1:
Use your account or users to login to your Facebook page with offline_access permissions and grab access_token while login success using $facebook->getAccessToken(), and save it in database so you can use it anytime.
You can check the expiration time of the token here, token with offline_access permissions never expire except when the user changes his password or maybe anything else.
Method 2:
You can update your access_token dynamically using the code below (say goodbye to expire token). Facebook shows this solution here, it's a sample code for executing an FQL Query:
Code:
<?php
$app_id = 'YOUR_APP_ID';
$app_secret = 'YOUR_APP_SECRET';
$my_url = 'POST_AUTH_URL';
$code = $_REQUEST["code"];
//auth user
if(empty($code)) {
$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>");
}
//get user access_token
$token_url = 'https://graph.facebook.com/oauth/access_token?client_id='
. $app_id . '&redirect_uri=' . urlencode($my_url)
. '&client_secret=' . $app_secret
. '&code=' . $code;
$access_token = file_get_contents($token_url);
Try this simple function to post onto a wall:
function doWallPost($postName = '', $postMessage = '', $postLink = '', $postCaption = '', $postDescription = '') {
$FB_APP_ID = 'xxxxxxxxxxxxxxxxxxxxxxxx';
$FB_APP_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx';
$APP_RETURN_URL = ((substr($_SERVER['SERVER_PROTOCOL'], 0, 4) == "HTTP") ? "http://" : "https://") . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'];
$code = $_REQUEST["code"];
if (empty($code)) {
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=" . $FB_APP_ID . "&redirect_uri=" . $APP_RETURN_URL . "&scope=publish_stream";
header("Location:$dialog_url");
}
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=" . $FB_APP_ID . "&redirect_uri=" . urlencode($APP_RETURN_URL) . "&client_secret=" . $FB_APP_SECRET . "&code=" . $code;
$access_token = file_get_contents($token_url);
$param1 = explode("&", $access_token);
$param2 = explode("=", $param1[0]);
$FB_ACCESS_TOKEN = $param2[1];
$url = "https://graph.facebook.com/me/feed";
$attachment = array(
'access_token' => $FB_ACCESS_TOKEN,
'name' => $postName,
'link' => $postLink,
'description' => $postDescription,
'message' => $postMessage,
'caption' => $postCaption
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
$result = curl_exec($ch);
header('Content-type:text/html');
curl_close($ch);
return $result;
}
So I have been tearing my hair out trying to make this work. I have been all over stack overflow looking at existing questions and found this: Facebook: Post on Page as Page issue (access token / php) but it still doesn't seem to solve my problem.
I'm trying to post to my facebook page every day using a cron job. I am having problems with the authentication. Here's my code:
//Post to Facebook
//Variables
$app_id = "...";
$app_secret = "...";
$page_id = "...";
$my_url = "http://.../";
$access_token = "taken from page access token (developers.facebook.com/tools/explorer/)";
//Create the facebook object
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
//Get the access token using Facebook Graph API
//This gives permission to post to the wall
$token_url="https://graph.facebook.com/oauth/access_token?client_id=" . $app_id
. "&client_secret=" . $app_secret
. "&code=" . $access_token
. "&redirect_uri=" . $my_url;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$user_access_token = $params['access_token'];
//Get a list of pages and loop through
//If one matches one in the variables above, that's the one
//We're posting to
$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 the Page wall
try {
$attachment = array(
'access_token' => $page_access_token,
'message'=> "Hello World"
);
$result = $facebook->api('/me/feed','POST', $attachment);
} catch(Exception $e) {
//Send me an email
...
mail($to, $subject, $message, $headers);
}
This works if I access the script in a browser (I assume it is using my facebook session then), but not when it is triggered by the cron job.
I would really appreciate any help. Thanks.
//Get the access token using Facebook Graph API
//This gives permission to post to the wall
If you already have a page access token, then this step is wrong at this point – it’s for exchanging the code that the Auth dialog passes back to your app for a user access token.
But since you already have your page access token, you can skip that step (everything from the above comments up to //Write to the Page wall).
All you have to do, is to use your page access token in your API call, instead of the user access token you are giving there right now.
I have a facebook iframe app which correctly logs in and authorizes the app, but getUser() only works on the first page. As soon as a user clicks a link to a new page within the iframe, getUser() returns 0.
What's strange is that this same code works for another app... I do all the clicking I want and getUser() returns a valid ID.
The app that doesn't work: https://apps.facebook.com/celestial_glory/
The one that does (same codebase): https://apps.facebook.com/uprisingstlouis/
Here's the code I am using:
require_once ('fb/facebook.php');
// snip... set $app_id, $secret, and $canvas_page
// first, try normal facebook getUser(). If that works, awesome.
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $secret,
));
$signed_request = $_REQUEST['signed_request'];
// Get User ID
$user = $facebook->getUser();
if ($user != '0') return 'fb=' . $user; // works once
// getUser() didn't work. Try oAuth. Maybe user needs to log in or
// authorize the game?
$auth_url = 'http://www.facebook.com/dialog/oauth?client_id='
. $app_id . '&redirect_uri=' . urlencode($canvas_page);
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if (empty($data["user_id"])) {
echo '<a target="_top" href="' . $auth_url . '">Login to Facebook</a>';
exit;
// normally we would auto-redirect, but with a uid of 0, this just auto-redirects
// echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
return 'fb=' . $data['user_id'];
}
any ideas? I have triple-checked app ids and secrets and canvas pages. If those were wrong, I expect no page, not even the first, would work.
Change Facebook PHP-SDK initialization to:
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $secret,
'cookie' => true // this!
));
getUser works on the first page because it can get the user from signed_request (POST'ed by Facebook to your canvas page URL). Thus you need some way to track your user once he starts navigation deeper within your application. You could pass signed_request somehow all by yourself or simply enable built-in PHP-SDK cookie support as suggested above.
I'm unable to get custom parameters send to my facebook fan page tab.
I'm using php and is passing like this:
http://www.facebook.com/pages/{page-name}/?sk=APP_ID&pass=1
but I'm unable to read the parameter pass
Sreejith
Facebook passes in your data as part of the signed_Request data.
Here is how you would retrieve it using PHP:
<?php
require 'facebook.php';
$app_id = "YOUR APP ID HERE";
$app_secret = "YOUR SECRET KEY HERE";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
// THE MAGIC SAUCE
$signed_request = $facebook->getSignedRequest();
$page_id = $signed_request["page"]["id"];
$like_status = $signed_request["page"]["liked"];
// HERE IS A STRING OF YOUR APP DATA.
$app_data = $signed_request["app_data"];
echo '$app_data = '.$app_data;
?>
This example requires the Facebook PHP api and will write your app_data into the browser window where you can marvel in all its glory.
Oh wow, I didn't know about the app_data parameter.Here's another method for whatever it's worth:
http://iamskwerl.com/tech/2011/11/passing-query-variables-to-facebook-fan-page-tabs/
There is a solution available although I have not tried it but hope it works
http://ikorolchuk.blogspot.com/2011/03/facebook-fan-page-pass-parameter-to.html