How to check offline if two FB user are mutual friends - facebook-fql

I need a query running in a CRONJOB that check if 2 FBuser are mutual friends:
something like the following, but I get this error:
Warning: file_get_contents(https://graph.facebook.com/fql?q=SELECT......) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in...
on the FBtool I get the following error:
{
"error": {
"message": "(#601) Parser error: unexpected '+' at position 6.",
"type": "OAuthException",
"code": 601
}
} )
This is the script:
// get App AccessToken
$app_token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $appId
. "&client_secret=" .$secret
. "&grant_type=client_credentials";
$response = file_get_contents($app_token_url);
$params = null;
parse_str($response, $params);
$App_access_token = $params['access_token'];
try { $permissions = $facebook->api('/'.$user1.'/permissions');
} catch(Exception $o){ $log[] = "//*** error on $user1/permissions > $o"; }
$permessi=$permissions[data][0];
if(array_key_exists('read_stream', $permessi) or array_key_exists('read_friendlists', $permessi) ) {
$fql_q = "SELECT 'uid1','uid2' FROM friend WHERE 'uid1'='$user1' AND 'uid2'='$user2'";
$fql_q = urlencode($fql_q);
$fql_query_url = "https://graph.facebook.com"
."/fql?q=$fql_q"
."&access_token=$App_access_token";
$fql_query_result = file_get_contents($fql_query_url);
$fql_query_obj = json_decode($fql_query_result, true);
if(is_array($fql_query_obj)){
$CountFriends = $CountFriends + 1;
}

Facebook offline access has been deprecated
Follow this link:
offline-access-removal

Here the solution
https://developers.facebook.com/docs/graph-api/reference/v2.0/user/friends#readmodifiers
I hope could be helpfull
thanks

Related

Facebook login: url cannot be loaded

I have the following code and get the following error (it is in Dutch):
Graph returned an error: URL kan niet worden geladen: Het domein van deze URL is niet toegevoegd aan de domeinen van deze app. Voeg alle domeinen en subdomeinen van je app toe aan het veld Appdomeinen in de instellingen van je app om deze URL te kunnen laden.
What may be wrong?
ini_set('display_errors', true);
$host = "m.****.com"; // Your Sub domain
$host2 = "www.m.****.com"; // Your Sub domain
if ($_SERVER['HTTP_HOST'] == $host || $_SERVER['HTTP_HOST'] == $host2) {
$root_doc = $_SERVER['DOCUMENT_ROOT'];
$root_doc = str_replace("/m","",$root_doc);
} else {
$root_doc = $_SERVER['DOCUMENT_ROOT'];
}
include_once("$root_doc/php-graph-sdk-5.x/src/Facebook/autoload.php");
//require_once __DIR__ . '/vendor/autoload.php'; // change path as needed
$fb = new \Facebook\Facebook([
'app_id' => '*****',
'app_secret' => '****',
'default_graph_version' => 'v2.10',
//'default_access_token' => '{access-token}', // optional
]);
// Use one of the helper classes to get a Facebook\Authentication\AccessToken entity.
// $helper = $fb->getRedirectLoginHelper();
// $helper = $fb->getJavaScriptHelper();
// $helper = $fb->getCanvasHelper();
// $helper = $fb->getPageTabHelper();
//BEGIN
$helper = $fb->getRedirectLoginHelper();
//$helper = $fb->getRedirectLoginHelper();
if (isset($_GET['state'])) {
$helper->getPersistentDataHandler()->set('state', $_GET['state']);
}
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}
// Logged in
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());
// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();
// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
//echo '<h3>Metadata</h3>';
//var_dump($tokenMetadata);
// Validation (these will throw FacebookSDKException's when they fail)
$tokenMetadata->validateAppId("152670682069405");
// If you know the user ID this access token belongs to, you can validate it here
//$tokenMetadata->validateUserId('123');
$tokenMetadata->validateExpiration();
if (! $accessToken->isLongLived()) {
// Exchanges a short-lived access token for a long-lived one
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo "<p>Error getting long-lived access token: " . $e->getMessage() . "</p>\n\n";
exit;
}
echo '<h3>Long-lived</h3>';
var_dump($accessToken->getValue());
}
$_SESSION['fb_access_token'] = (string) $accessToken;
//END
try {
// Get the \Facebook\GraphNodes\GraphUser object for the current user.
// If you provided a 'default_access_token', the '{access-token}' is optional.
$response = $fb->get('/me', '{access-token}');
} catch(\Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$me = $response->getGraphUser();
echo 'Logged in as ' . $me->getName();
I hope i will get an answer.
Regards,
Jeroen
Translated from Dutch to English:
URL can not be loaded: The domain of this URL has not been added to the domains of this app. Add all domains and subdomains of your app to the App domains field in your app's settings to load this URL.

Requesting page insight for Facebook getting error "Graph returned an error: An unknown error has occurred. "

$helper = $fb->getRedirectLoginHelper();
$permissions = ['email','manage_pages','pages_manage_cta','publish_pages','publish_actions'];
giving permissions.
$loginUrl = $helper->getLoginUrl('http://localhost/Facebook/insight.php', $permissions);
echo 'Log in with Facebook!';
facebook Insight code.
$fb->setDefaultAccessToken($accessToken);
Get user groups detail
$requestPageInsights = $fb->request('GET', '/1364467436924381/insights/, $accessToken');
//Make a batch request
$batch = ['page-insights' => $requestPageInsights];
try {
$responses = $fb->sendBatchRequest($batch);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
Graph returned an error: An unknown error has occurred.
Just experienced the same issue.
The error seems to be with batched requests - The solution for us was to change the code to do the requests individually.

Facebook Graph API: Create/Update Event Picture not working

I want to update an event's picture as described in the Event API.
$eventId = '291145580981541';
$accessToken = $facebook->getAccessToken(); // have tested, is correct
$data = array('source' => '#'.realpath($file));
try {
$result = $facebook->api('/$eventId/picture?access_token=$accessToken', 'POST', $data);
echo $result;
} catch(Exception $e) {
echo "Exception: $e";
}
The result I get:
Exception: OAuthException: (#200)
What am I doing wrong?
Error #200 is a permissions error. You most likely don't have the create_event permission
https://developers.facebook.com/docs/reference/api/event/#picture

Facebook cannot send notification

The user is logged in successful via fosfacebookbundle in symfony2.1
Related to this topic: "A user access token is required to request this resource." Facebook graph for notifications
I want to send a notification to a user. The access token looks like this ...234|asdf....
$token_url = 'https://graph.facebook.com/oauth/access_token?grant_type=
client_credentials&client_id=' . $app_id . '&
client_secret=' . $app_secret;
$access_token = file_get_contents($token_url);
//After that I do a preg_split. Or for testing I print out the access token
and I define it manual in the php file `$access_token = '...234|asdf...';`
$userid = 12345;
$inviteMessage = 'Test_message';
$inviteMessage = urlencode($inviteMessage);
$url = "https://graph.facebook.com/" . $userid . "/notifications?access_token=" .
$access_token . "&template=" . $inviteMessage;
$c = curl_init($url);
// necessary so CURL doesn't dump the results on your page
curl_setopt($c, CURLOPT_POST, true);
$result = curl_exec($c);
curl_close($c);
$r = json_decode($result);
print_r($r);
print_r gives me this: Sorry, something went wrong! Facebook Inc.
If I am directly put this in the address line:
https://graph.facebook.com/12345/notifications?access_token=access_token=...234|asdf...&template=Test_message
Error message:
{
"error": {
"message": "Invalid OAuth access token signature.",
"type": "OAuthException",
"code": 190
}
}
What is wrong?
Update
What is the meaning of href in developers.facebook.com/docs/concepts/notifications?

Read Facebook page post and token expiration

I need to read, from a server, the stream of a specific fan page.
I tried to read the graph api
https://graph.facebook.com//feed?access_token=&limit=100
and it works.
What I need is to understand if the token will expire and how to renew it programmatically.
Now I generate my token through the http://developers.facebook.com/tools/explorer/ app.
Can you please help me?
I'm using the PHP sdk
thanks,
a.
You can read the facebook page using below codes and you can also get the specified fields
https://graph.facebook.com/$page_id/?fields=link,etc&access_token=page_access_token
or
$response = $fb->api($page_id . '/?fields=link,etc&'. $access_token, 'GET')
Below is the solution for four scenarios
1.The token expires after expires time (2 hours is the default).
2.The user changes her password which invalidates the access token.
3.The user de-authorizes your app.
4.The user logs out of Facebook.
To ensure the best experience for your users, your app needs to be prepared to catch errors for the above scenarios. The following PHP code shows you how to handle these errors and retrieve a new access token.
When you redirect the user to the auth dialog, the user is not prompted for permissions if the user has already authorized your application. Facebook will return you a valid access token without any user facing dialog. However if the user has de-authorized your application then the user will need to re-authorize your application for you to get the access_token.
<?php
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$my_url = "YOUR_POST_LOGIN_URL";
// known valid access token stored in a database
$access_token = "YOUR_STORED_ACCESS_TOKEN";
$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);
echo($access_token);
}
// note this wrapper function exists in order to circumvent PHP’s
//strict obeying of HTTP error codes. In this case, Facebook
//returns error code 400 which PHP obeys and wipes out
//the response.
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;
}
?>
for more details info you can visit this link
Thanks