How to get images from FB to website - facebook

I'm working on publishing posts from our FB page on our website. Each new post and photos we added into our FB page I need to show in our website too.
I have this code, but don't working as I need.
require 'php-graph-sdk-5.x/src/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => '...',
'app_secret' => '{app-secret}', // don't know where to find app_secret for my page, I've found that just for apps, not pages
'default_graph_version' => 'v2.10'
]);
$access_token = '...'; // generated in developers, but with just for 12 hours, than this token is expired... :-(
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('me?fields=id,name,feed,data', $access_token);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$graphNode = $response->getGraphNode();
foreach ($graphNode as $node) {
foreach ($node as $items) {
print_r($items);
// when access token was valid, I got posts from out FB page. But with no images, didn't find how to get add images to this feed...
}
}
So, my questions are:
where I can find app-secret for FB page? I'm not able to connect to my FB page without that, I think
how to generate permanent access token, or if it's not possible, how to make i other way?
how to add images (new, shared, etc.) to my feed?
Thanks.

There is no App Secret per Page, there is only the App Secret per App. You can find it in your App Settings.
Extended/Permanent Tokens: https://developers.facebook.com/docs/facebook-login/access-tokens/ or http://www.devils-heaven.com/facebook-access-tokens/ - for getting the feed entries of unrestricted Page, you can just use an App Access Token and you can hardcode it in your PHP code.
Getting images in the feed, not just messages: You need to specify which fields you want to get, or you will only get default ones. It is called "Declarative Fields": https://developers.facebook.com/docs/graph-api/changelog#v2_4 - also, check out the API reference: https://developers.facebook.com/docs/graph-api/reference/post

Related

Graph API Facebook SDK for PHP Permissions Error

I am working on Auto Posting on facebook page or group by using graph api. But i get error of permissions but i allow permissions But i face this error. Any one who know about this error.
Code given below.
I share some images Which error showing me or how to allow permissions.
<?php
require_once ('vendor/autoload.php');
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.10',
]);
$pageAccessToken = '{page-access-token}';
$MsgData = [
'message' => 'Hi, My name is Zaheer'
];
try {
$response = $fb->post('/me/feed/' , $MsgData , $pageAccessToken );
}
catch ( \Facebook\Exceptions\FacebookResponseException $e ) {
echo 'Graph returned an error ' . $e->getMessage();
exit;
}
$GraphNode = $response->getGraphNode();
echo 'ID :' . $GraphNode['id'];
?>
[![enter image description here][2]][2]
Debug your Token: https://developers.facebook.com/tools/debug/accesstoken
You can see that it is a User Token, not a Page Token. Page Tokens can be generated by using a User Token with the following endpoints:
/me/accounts?fields=access_token
/page-id?fields=access_token
Make sure to use page token. You can easily get one from the the graphi api explorer on the right panel. I was having permissions error. My app type was business and to remove it, I just added all the permissions from the given list and after I added all permissions, facebook asked me to review permissions, I simply kept clicking on OK and everything worked, the error went :D

Ask facebook to re-scrape URL automatically

how can I make a php code for facebook to automatically update the cache of a single url
I saw something similar in other threads, but did not manage to make it work:
Is there an API to force Facebook to scrape a page again?
Ask facebook to re-scrape URL
For example use this php code, adding the url of my web www.tolchx.net, but it still appears the same GIF when I go to debugging:
<?php
try {
$params = [
'id' => 'https://www.tolchx.net',
'scrape' => 'true',
];
$response = $fb->post('/', $params);
print_r($response);
} catch(\Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
}
?>
With that enough to automatically update the link cache www.tolchx.net?
thanks for the reply

FaceBook PHP API SDK: suddenly the argument 'link' is not published and /me/feed is not working

I completed this script, that was working fine till this morning, when launching it, suddenly I noticed that the argument "link" of the array $linkData, is not published any longer, (no error returned) while "message" is published.
I also noticed that if I put /me/feed into the object $fb->post, it doesn't work (see the commented line). No errors returned.
While, if I put the code of a group (the code you see is a test group I created to test the script), the argument "message" is published (not the "link")
The scopes are:
user_managed_groups,
user_events,
user_friends,
user_posts,
publish_actions,
user_actions.music,
user_actions.video,
public_profile
The link is referred to the link for which the application is written. the www.example.com URL, is written here for this example. In the real code, I use the URL of the site of the App (that till yesterday was working fine).
Please here the code:
<?php
session_start();
define(__APP_ID__, XXXXXXXXXXXXXXX);
define(__APP_SECRET__, 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY');
define(__APP_TOKEN__, 'ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ');
define(__APP_ACCESS_TOKEN__, 'WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW');
require_once '../include/setup.php';
require_once $root_dir.'/include/Facebook/autoload.php';
// Creates the object
$fb = new Facebook\Facebook([
'app_id' => __APP_ID__,
'app_secret' => __APP_SECRET__,
'default_graph_version' => 'v2.2',
]);
$linkData = [
'link' => 'http://www.example.com',
'message' => 'The link above, is not any longer published',
];
$group_id = "1041863359178529";
try {
//$response = $fb->post("/me/feed", $linkData, __APP_ACCESS_TOKEN__); // SUDDENLY it doesn't work any longer
$response = $fb->post("/{$group_id}/feed", $linkData, __APP_ACCESS_TOKEN__);
} catch (Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$graphNode = $response->getGraphNode();
echo 'Posted with id: ' . $graphNode['id']."\r\n";
?>
EDIT:
Is there anything I can do? Is id depending from the App settings? I changed many parameters to find a solution but I still have the issue.
I did verified that the block, is due FB.
In other words: probably of security reasons (mainly Anti-Spam), FB block repetitive use of the function in short time.
I did try also to wait more than 15 seconds among the iterations, but if I employ it for more than 20-25 time in one day, FB suspends all the required authorizations.
At the time I did post the thread, FB was enabling only the post of the text, and deactivated OpenGraph.
Now, instead, it blocks any kind of sending, including text.

Redirect to Index page when Facebook PHP SDK Access Token is Expired

I'm working on a site that uses the Facebook PHP SDK. It is working great, and after 2 hours, whenever I try to get onto one of the general pages on the site, I get...
Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user.
If I go back to the index page, I get a new access token and everything works properly again...for 2 hours.
What code can I put on my webpages to redirect to the index page when the access token has expired?
Thanks for helping this noob.
You must redirect user to page that has authorized code.
If your user not deauthorized app , the Oauth dialog isn't appear.
For more information go to
Access Token & Handling
You can put a try / catch block in your code.
Put each Facebook API call in such block and if an exception occurs you can redirect the user to the right resource by header('Location: <url>');:
try {
# FB API call
}
catch(OAuthException e) {
header('Location: <url>');
}
Have a file that goes like this and include it in your webpages.
$facebook = new Facebook(array(
'appId' => "app id",
'secret' => "app secret",
));
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl();
if ($user) {
try {
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
else {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
}

Facebook iFrame app - how to fetch Preload FQL result using PHP SDK?

since few years I have an FBML app (a small Flash game) which I'm now trying to convert to an iFrame app. Unfortunately there aren't many docs for Facebook iFrame apps yet.
For my game I need the user's first name, picture, gender and the city.
In my old version I had this preload FQL (created once by a PHP script):
$fql = array('info' => array('pattern' => 'facebook',
'query' => 'SELECT first_name, sex, pic_big, current_location
FROM user WHERE uid={*user*}'));
$fb->api_client->admin_setAppProperties(
array('preload_fql' => json_encode($fql)));
and then my FBML app script had been as simple as:
<?php
require_once('facebook.php');
define('FB_API_ID', 'XXX');
define('FB_AUTH_SECRET', 'YYY');
$fb = new Facebook(FB_API_ID, FB_AUTH_SECRET);
$viewer_id = $fb->require_login();
$data = json_decode($fb->fb_params['info'], true);
$first_name = $data[0][0];
$last_name = $data[0][2];
$female = ($data[0][3] != 'male');
$avatar = $data[0][3];
$city = $data[0][4]['city'];
# and then I'd just construct flashvars attribute
# for the <fb:swf ...> tag and print it
?>
Does anybody please have hints on how to recreate the same script for the iFrame version - i.e. how can I fetch the result of Preload FQL by my iFrame app?
According to an older Facebook blog entry Preload FQL should be accessible by the iFrame apps.
Thank you!
Alex
My own answer after long searching is that Preload FQL results aren't sent to iframe Facebook apps.
That is why Facebook performance doc says:
"Preload FQL Query and Multiquery.
This section applies to FBML canvas pages, but not to websites or IFrame canvas pages."
As Facebook said for Preload FQL
"Facebook will send the result of these FQL queries as JSON-encoded POST parameters to your Canvas URL"
print_r your $_POST and see which variable is the "json-encoded results". You convert json into php object using json_decode
JSON looks like this: {"var":"val","var":"val"}
Also, Facebook already has great docs for iframes. Then you might have missed these great docs:
Facebook Docs Home
http://developers.facebook.com/docs/
Authentication
http://developers.facebook.com/docs/authentication/
Signed Request
http://developers.facebook.com/docs/authentication/signed_request/
iFrame Canvas Apps
http://developers.facebook.com/docs/guides/canvas/
PHP SDK
https://github.com/facebook/php-sdk
Graph API
http://developers.facebook.com/docs/reference/api/
You don't need to call any FQL for the information you are getting. For iFrame you just need to do following steps
Download the PHP SDK of graph api https://github.com/facebook/php-sdk/
Create the object and authorize the app from user
$fbconfig['appid' ] = "your application id";
$fbconfig['api' ] = "your application api key";
$fbconfig['secret'] = "your application secret key";
try{
include_once "facebook.php";
}
catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
// User location extended permission allow you to get user's current location
$loginparams = array('canvas' => 1,'fbconnect' => 0,'req_perms' => 'user_location');
$loginUrl = $facebook->getLoginUrl($loginparams);
// We may or may not have this data based on a $_GET or $_COOKIE based session.
// If we get a session here, it means we found a correctly signed session using
// the Application Secret only Facebook and the Application know. We dont know
// if it is still valid until we make an API call using the session. A session
// can become invalid if it has already expired (should not be getting the
// session back in this case) or if the user logged out of Facebook.
$session = $facebook->getSession();
$fbme = null;
// Session based graph API call.
if ($session) {
try {
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
} catch (FacebookApiException $e) {
d($e);
}
}
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}
// You can found all the data in this array.
print_r($fbme);
For more detail you can follow this tutorial http://thinkdiff.net/facebook/php-sdk-graph-api-base-facebook-connect-tutorial/
Hope it works for you