I have the below snippet and it works and posts to a Facebook page as my own user account on Facebook.
The values FACEBOOK_* are defined earlier in the codebase.
// SDK Version 5.0
$fb = new Facebook\Facebook([
'app_id' => FACEBOOK_APP_ID,
'app_secret' => FACEBOOK_APP_SECRET,
'default_graph_version' => 'v2.4',
]);
// Returns a `Facebook\FacebookResponse` object
$response = $fb->post('/'.FACEBOOK_PAGE_ID.'/feed', $postData, FACEBOOK_ACCESS_TOKEN);
$postId = $response->getGraphNode();
Now my question is how can I get it to post as the actual page and not my account which is the admin of the page.
I've had a look at the SDK documentation and I've been going around in circles, there are many examples of v4 but as it's deprecated I'm trying to use v5 and just can't seem to figure it out, any links to post attribution or impersonation I find are dead links in v5 of the SDK.
From what I can see I need to make a call to /{user-id}/accounts to get an access token for the page from my user, https://developers.facebook.com/docs/facebook-login/access-tokens#pagetokens
But to get a {user-id} I have to query the user, with something like the below example from the SDK documentation:
// Make sure to load the Facebook SDK for PHP via composer or manually
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
if($session) {
try {
$user_profile = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
echo "Name: " . $user_profile->getName();
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
The issue here is that I have no idea how to get a session which I need to get the user data for which gives me the access token to allow me pass the access token into my code snippet above that works, that's if I understand it all correctly!?
Any help greatly appreciated!
I work with classes, so I adapted my code to your examples above. Tested and working code.
After getting your user access token using the method you use (see the guide here), we have to obtain a long-lived access token. Add this to your code :
session_start();
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// There was an error communicating with Graph
echo $e->getMessage();
exit;
}
if (isset($accessToken)) {
$client = $fb->getOAuth2Client();
try {
$accessToken = $client->getLongLivedAccessToken($accessToken);
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo $e->getMessage();
exit;
}
$response = $fb->get('/me/accounts', (string) $accessToken);
foreach ($response->getDecodedBody() as $allPages) {
foreach ($allPages as $page ) {
if (isset($page['id']) && $page['id'] == $pageId) { // Suppose you save it as this variable
$appAccessToken = (string) $page['access_token'];
break;
}
}
}
$response = $fb->post(
'/'.$pageId.'/feed',
array(
"message" => "Message",
"link" => "http://www.example.com",
"picture" => "http://www.example.net/images/example.png",
"name" => "Title",
"caption" => "www.example.com",
"description" => "Description example"
),
$appAccessToken
);
// Success
$postId = $response->getGraphNode();
echo $postId;
} elseif ($helper->getError()) {
var_dump($helper->getError());
var_dump($helper->getErrorCode());
var_dump($helper->getErrorReason());
var_dump($helper->getErrorDescription());
exit;
}
Explanations : You have to know which pages you are administrator :
$response = $fb->get('/me/accounts', (string) $accessToken);
Then search the table to retrieve the access token of the page that interests us (I have chosen to take the id of the page referenced).
Finally, simply run the post function provided by the SDK :
$response = $fb->post(
'/'.$pageId.'/feed',
array(
"message" => "Message",
"link" => "http://www.example.com",
"picture" => "http://www.example.net/images/example.png",
"name" => "Title",
"caption" => "www.example.com",
"description" => "Description example"
),
$appAccessToken
);
Related
Last week i installed facebook SDK via composer on CODEIGNITER 3 ,it work fine and return name email and token until this day , When I try login the page loads for 1 minute and then an empty page apears with the error:
Empty Error
Facebook SDK returned an error:
and Return This URI
https://www.mywebsite.com/en/fbcallback?code=AQCCasdfSAD35L-3iABFbT5zntYQ4jJHVcko9ekG-6k-jn5aERodXoasdf7jHWEgSxxqze_K-nyAYSmcASDFaskde6wPasdfD8WHBEFUEO5gNpgLU0RJqnvVGCdYKNfT2Qm5U1pcWCvVE_YkJ6sQyUL0RrcONrqMbb7bpPv0KDUQjaO_XMAwvKEo2Jasdf31PCjxoHBGoogupX8VF5Gx6WaT4b7ZlsYkPhbQPTCdJaWrzwvfJ1So27Wsdt1Ub9WPUO07io3vxmX-P-rmzsxnk3qDSKCPJX9ks0eBtNwXA-83&state=8cbe21da648d832fcd2b34aceb8dfe62#=
im using 2 action in my controller for login :
function fblogin(){
$fb = new Facebook\Facebook([
'app_id' => 'my app id ',
'app_secret' => 'my app secret',
'default_graph_version' => 'v3.2',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email'];
// For more permissions like user location etc you need to send your application for review
$loginUrl = $helper->getLoginUrl('https://www.example.com/en/fbcallback', $permissions);
header("location: ".$loginUrl);
}
this where it should return token info :
function fbcallback(){
$fb = new Facebook\Facebook([
'app_id' => 'myid',
'app_secret' => 'myscretapp',
'default_graph_version' => 'v3.2',
]);
$helper = $fb->getRedirectLoginHelper();
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;
}
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?fields=id,name,email,first_name,last_name',$accessToken);
// print_r($response);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'ERROR: Graph ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'ERROR: validation fails ' . $e->getMessage();
exit;
}
// User Information Retrival begins................................................
$me = $response->getGraphUser();
echo "First Name: ".$me->getProperty('first_name')."<br>";
echo "Last Name: ".$me->getProperty('last_name')."<br>";
echo "Email: ".$me->getProperty('email')."<br>";
echo "Facebook ID: <a href='https://www.facebook.com/".$me->getProperty('id')."' target='_blank'>".$me->getProperty('id')."</a>"."<br>";
$profileid = $me->getProperty('id');
echo "</br><img src='//graph.facebook.com/$profileid/picture?type=large'> ";
echo "</br></br>Access Token : </br>".$accessToken;
}
the same question was asked 2 years ago but no answers :
link
My problem was on server side :
This feature allows you to specify certain IPs or IP ranges to which you will be able to open outgoing connections.
Just go to your server and check if it block outgoing connections....
I added it to white list and work fine ! ... hope that can save your time .
Using this example from fb-sdk:
require_once 'fb-sdk/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => '123456',
'app_secret' => 'abc1233',
'default_graph_version' => 'v2.6',
]);
$data = [
'message' => 'Testupload',
'source' => $fb->fileToUpload('image.jpg'),
];
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->post('/PageID/photos', $data, 'XXXXXXYYYYYY');
} 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 'Photo ID: ' . $graphNode['id'];
i am able to post as myself to the wall of my facebook-page.
'app_id' and 'app_secret' come from the app i created for this.
If i set $response = $fb->post('/me/photos', $data, 'XXXXXXYYYYYY'); the post shows up on my timeline.
What do i need to change, so get a photo, posted by "Page" on the feed of "Page"?
You need to use a Page Token with the publish_pages permission to post "as Page". You can get a Page Token with the following API call, after authorizing with manage_pages and publish_pages:
/page-id?fields=access_token
More information:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
I have created a facebook app and approved the app to access manage_pages.I am looking for php code to get page access from page to get the page information.
For getting reviews and rating I am using the below code
require 'facebook-php-sdk-master/src/facebook.php';
$config = array();
$config['appId'] = '1489047331XXXXX';
$config['secret'] = '6ac210360aad27ab1044e4201XXXX';
$facebook = new Facebook($config);
print_r($facebook);
try {
// 466400200079875 is Facebook id of Fan page https://www.facebook.com/pontikis.net
$ret = $facebook->api("/page_id/ratings?field=open_graph_story", 'GET');
print_r($ret);
} catch(Exception $e) {
echo $e->getMessage();
}
I am getting the below error
(#210) This call requires a Page access token.
Any help will be highly appreciated.
Create new object like this and set access_token if not exists:
$fb = new Facebook([
'app_id' => FB_APP_ID,
'app_secret' => FB_APP_SECRET,
'default_graph_version' => 'v2.5',
'default_access_token' => isset($_SESSION['facebook_access_token']) ?
$_SESSION['facebook_access_token'] : FB_APP_ID . '|'. FB_APP_SECRET
]);
Change FB_APP_ID and FB_APP_SECRET, only with yours. Now you have access token, after that you can make requests and get data that u need access token for it like this (for the example):
$request = $fb->request('GET', '/'.$page_id.'/');
// Send the request to Graph
try {
$response = $fb->getClient()->sendRequest($request);
} 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;
}
$graphNode = $response->getGraphPage();
var_dump($graphNode->all());
Where $page_id is id of some page, where you can find it with its FB page URL .
I'm having a lot of trouble getting the Facebook API to work at all. Any example code I use gives me Server Error 500. I'm trying to post a link to my facebook page (this code is from the example code Facebook gives in its documentation). To clarify as well, I do have an app-id, secret-id, and I believe I got the right access token from the Graph API. I know I need a public_action permission to post a link, but the way I read it, I think the access token defaults with public_action.
<?php
$appid = '{app-id}';
$appsecret = '{app-secret}';
$redirect_uri = 'http://mywebsite.com';
// Define the root directoy
define( 'ROOT', dirname( __FILE__ ) . '/' );
// Autoload the required files
require_once( ROOT . 'facebook-php-sdk-v4-4.0-dev/autoload.php' );
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.2',
]);
$linkData = [
'link' => 'http://www.example.com',
'message' => 'User provided message',
];
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->post('/me/feed', $linkData, '{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'];
?>
I really do not know what I am doing wrong. Likewise, where it says "me" should that be my facebook user id? Thank you.
I try to post simple message on my facebook post wall, I try to use PHP SDK v5. The documentation about sdk witch is on Facebook Developers is not so clear for me, and I don't understand what I'm doing wrong.
When i try run this script with posting a message a get an error message " Graph returned an error: Invalid parameter"
This is my code:
<?php
session_start();
require_once __DIR__ . '/vendor/facebook-php-sdk-v4-5.0-dev/src/Facebook/autoload.php';
//use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\Authentication\AccessToken;
//use Facebook\GraphUser;
//use Facebook\FacebookRequestException;
$fb = new Facebook\Facebook([
'app_id' => '************',
'app_secret' => '****************************',
'default_graph_version' => 'v2.4',
]);
$page_id = '****************';
// HERE IS LONG LIVED ACCESS TOKEN WITCH I GENERATED MANUALY
$access_token = '*********************************';
// HERE IS A CODE WITH GET A POSTS FROM MY WALL AND PRINT IT IN A MY WEBSITE
$object = $fb->get('.$page_id.'/feed', $access_token);
$posts_array = $object->getDecodedBody();
print_r($posts_array['data']);
$linkData = [
'link' => 'http://www.example.com',
'message' => 'User provided message',
];
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->post('/'.$page_id.'/feed', $linkData, $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'];
Thank you for your help !
I found the problem. In the $linkData array the link parameter is a problem. When i deleted it, every think works. Topic to close.