I have been stumped for a while now. I'm attempting to write myself a small app to automatically post to a number of groups that I am members of in FB. I'm a PHP novice, but this is about my strongest skill set for what FB allows in terms of access that I can tell. So far, I CAN post to my own wall no problem but once I try and post to my own FB testing group I'm stumped. Here is my code so far...
<?php
require_once __DIR__ . '/vendor/autoload.php';
require 'src/config.php';
require 'src/facebook.php';
$fb = new Facebook\Facebook([
'app_id' => $config['App_ID'],
'app_secret' => $config['App_Secret'],
'default_graph_version' => 'v2.8',
]);
$linkData = [
'link' => 'http://www.example.com',
'message' => 'Test post to my feed.',
];
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->post('/{group_id}/feed', $linkData, $config['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;
}
?>
Currently the error that this is generating is:
Graph returned an error: (#200) Insufficient permission to post to target on behalf of the viewer
I have made the app Public and generated the access token with manage_pages and publish_pages. Unfortunately I'm out of ideas as of this point. Any help would be greatly appreciated. Thanks in advance.
OK. I figured out my problem at this point. It was that I had to go into the App Settings in my FB user account and change my App from "Only Me" to Public. Once I did that I was able to post to my groups. Next will be to figure out how to post into the proper fields for a "Sell Something" type of post and then to test it in groups that I'm not an admin of.
I figure it has to be possible to post into non-admin groups since there are a number of services out there for FB auto-posting and they have to get around it somehow.
Related
I would like to get images from my Instagram account to my web page. So I try to use FB php sdk and get accessToken first according this documentation. But it returns null. I don't know what is wrong with the code.
public function getMedia()
{
$fb = new \Facebook\Facebook([
'app_id' => self::APP_ID,
'app_secret' => self::APP_SECRET,
'default_graph_version' => 'v2.10',
//'default_access_token' => '{access-token}', // optional
]);
$helper = $fb->getRedirectLoginHelper(); // Whichever helper I use access-token is null
dd($helper->getAccessToken());
}
I need help with it. It could be so simple.
EDIT:
After few hours I have this, but the last command throws an Facebook\Exceptions\FacebookResponseException Invalid OAuth access token signature. As I see the token is app id and app secret joined with pipe. "733163597544229|xxxxxxxxxxxxx9d14362xxxx3a6". This should work but does not work.
public function getMedia()
{
$fb = new \Facebook\Facebook([
'app_id' => self::APP_ID_FB,
'app_secret' => self::APP_SECRET_FB,
'default_graph_version' => 'v2.10',
//'default_access_token' => '{access-token}', // optional
]);
$token = $fb->getApp()->getAccessToken();
$response = $fb->get('https://graph.instagram.com/me/media?fields=media_url,media_type', $token->getValue());
}
If I've understood the docs correctly, if you want to get an access token dynamically, according to https://developers.facebook.com/docs/facebook-login/web, you need enable fb-login for your app
https://developers.facebook.com/apps/
select your app
add fb-login & follow the tips.
Otherwise you should just be able to get an access token for your app from the web interface and use that over and over.
See also : https://developers.facebook.com/docs/facebook-login/access-tokens#apptokens
There's also:
https://developers.facebook.com/tools/explorer/?method=GET&path=me%3Ffields%3Did%2Cname&version=v9.0
Which enables you to generate an access token, and test out a call to the graph api, AND allows you to export code you can copy/paste:
try {
// Returns a `FacebookFacebookResponse` object
$response = $fb->get(
'/me',
'{access-token}'
);
} catch(FacebookExceptionsFacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$graphNode = $response->getGraphNode();
EDIT:
I see in your original question you state:
As I see the token is app id and app secret joined with pipe. "733163597544229|xxxxxxxxxxxxx9d14362xxxx3a6". This should work but does not work.
According to the docs, if you want to supply an access token as {app_id}|{client-token} (not sure what secret you're using here) you should append this to the URL, which is not in the URL you're using.
See example here: https://developers.facebook.com/docs/facebook-login/access-tokens#clienttokens
The URL they use is:
curl -i -X GET "https://graph.facebook.com/{your-user-id}/accounts?access_token={user-access-token}
So for you this be:
$response = $fb->get('https://graph.instagram.com/me/media?fields=media_url,media_type&access_token=733163597544229|{client_token}');
EDIT 2:
I managed to get your sample working so perhaps these screen shots will help:
PHP Code:
<?php
$accessToken="EAAJIZAj**************************************************************************************************************************************************************************ZD";
require_once __DIR__ . '/Facebook/autoload.php'; // change path as needed
//echo __DIR__ . '/Facebook/autoload.php';
$fb = new \Facebook\Facebook([
'app_id' => '642**********502',
'app_secret' => '0185*****************f743',
'default_graph_version' => 'v2.10',
'default_access_token' => "{$accessToken}"
]);
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');
} 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 took the source code from https://github.com/facebookarchive/php-graph-sdk and copied the src/Facebook dir into my project. I amended the path location in my code
require_once __DIR__ . '/Facebook/autoload.php'; // change path as needed
//echo __DIR__ . '/Facebook/autoload.php'; //<< comment out everything else and check the path is correct with this.
Working code: (same as above) with successful output shown at the bottom of the screen shot.
If you need to get the app secret go to the apps settings to uncover it:
Seems you were right - the access token does have an expiry and I had to refresh mine since using it yesterday.
As far as I know this will probably not work to get the access token .
To get access token you need to implement the login with facebook in your app to get the access token . If your app is only used by limited user then you can get access token on this link https://developers.facebook.com/tools/explorer/ but if your app is used by wide range of user and each user has their own data then you need to implement oauth2 in your app
I followed these instructions and some others to create an app and get tokens: facebook: permanent Page Access Token?
I used the following php code to post using the app:
<?php
require_once 'src/Facebook/autoload.php'; $fb = new \Facebook\Facebook([ 'app_id' => 'apkey', 'app_secret' => 'appsecret', 'default_graph_version' => 'v2.10', //'default_access_token' => '{access-token}', // optional ]);
$linkData = [
"message" => "Wonderful message.",
]; $pageAccessToken ='pageaccesstoken';
try { $response = $fb->post('/targetfeed/feed', $linkData, $pageAccessToken); } 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();
?>
I replace the keys and specific data with description.
My issue is that when I run this script it posts to the feed, but it posts as the app owner. I created the app in my personal account, and went through the token process using that account. I was granted admin access to the account that I want to post to, but when I post to that account it is posting as my person page and I instead want it to post as if I am posting as the account that I am posting to.
I am sure it some access token setting or permissions things, but I cannot figure it out. Any suggestions?
I am struggling going round in circles getting an Facebook App to post to a Page's Wall, as that Page.
** Note: I put out a 300 point bounty to update an outdated answer of a related, well-viewed, existing question. Happy to award anyone who also answers there with the updated, working, solution
In brief:
I have the App Secret and ID
I have Page ID
I am relying on an in-code approach to generating the token I need.
It is based on a solution I saw posted on the SDK GitHub page but it does not work
I am using API v 2.9
I am using the latest PHP SDK
It's just been hard.
The solution I used is purely based on the one below:
<?php
define('FACEBOOK_SDK_V4_SRC_DIR', __DIR__ . '/Facebook');
require_once __DIR__ . '/Facebook/autoload.php';
use Facebook\FacebookRequest;
$app_id = {{your app-id}};
$app_secret = {{your app-secret}};
$fb = new Facebook\Facebook([
'app_id' => $app_id,
'app_secret' => $app_secret,
'default_graph_version' => '{{your app-version}}',
]);
$token = $fb->get(
'/oauth/access_token?client_id=' . $app_id . '&'.
'client_secret=' . $app_secret . '&'.
'grant_type=client_credentials');
$get_token = $token -> getdecodedBody();
$access_token = $get_token['access_token'];
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/{{your facebook name}}', $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;
}
$body = $response->getBody();
print_r($body);
?>
I am certainly not lazy. I have been stuck on this issue for weeks.
I have tried the following different solutions and have gotten stuck in either a permissions related issue that was also related to depracated functionality and API calls or getting the right token to do it.
Posting to a facebook page from a website using curl (using a pure CURL approach - "The user hasn't authorized the application to perform this action")
Facebook SDK returned an error: You must provide an access token. Php Facebook Api - (suggests that I support login and redirection callback - yet I do not want any user intervention everytime when posting onto the page)
Graph returned an error: Invalid appsecret_proof provided in the API argument - Previous attempt was based on this example but the appsecret-proof issue
Simple example to post to a Facebook fan page via PHP? - Another CURL-based approach that failed me
https://stackoverflow.com/a/14212125/919426 - Best explained step by
step process for permissions and tokens, but still failed
Update:
Tried the following and got the error "Invalid appsecret_proof provided in the API argument"
$fb = new Facebook([
'app_id' => 'APP_ID',
'app_secret' => 'APP_SECRET',
'default_graph_version' => 'v2.9',
]);
$postData = [
'message' => "Test Message",
'picture' => 'https://www.website.com/image.jpg'
];
try
{
// 'LONG_LIVED_PAGE_ACCESS_TOKEN' obtained by going to https://developers.facebook.com/tools/debug/accesstoken and clicking
// "Extend Access Token"
$response = $fb->post('/' . 'PAGE_ID' . '/feed', $postData,"LONG_LIVED_PAGE_ACCESS_TOKEN");
}
catch (FacebookResponseException $e)
{
var_dump("Facebook Response Exception occured: \n" . $e);
exit;
}
catch(FacebookSDKException $e)
{
var_dump("Generic Facebook SDK Exception occured: \n" . $e);
exit;
}
catch(Exception $e)
{
var_dump("Uknown Exception occured while attempting to call the Facebook SDK API: \n" . $e);
exit;
}
There are countless more that I have tried and failed.
I try to get the total number of likes for different Facebook pages, like this one for example : https://www.facebook.com/LeoMessi/
I have implemented the following code :
<?php
// Pass session data over.
session_start();
// Include the required dependencies.
require_once( 'vendor/autoload.php' );
// Initialize the Facebook PHP SDK v5.
$fb = new Facebook\Facebook([
'app_id' => '**********',
'app_secret' => '**********',
'default_graph_version' => 'v2.9',
]);
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/176063032413299?fields=likes.limit(0).summary(true)', $_SESSION['access_token']);
var_dump($response);
} 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;
}
It works, but it does not return the total_count property. I don'to how to access this property for any Facebook Page. Could you help me ?
Ok everybody, I just founded the solution just after having posted my question. And the solution is just here : Request to get total count of Facebook page likes in v2.3 API
To get the number of fans, you now need to use fields=fan_count.
So I just replace
/176063032413299?fields=likes.limit(0).summary(true)
With
/176063032413299?fields=fan_count
And it returns
["fan_count"]=> int(88899488)
Hope this can help someone else.
Modify field as :
{page-id}?fields=fan_count
I've created a Facebook App using the latest version of the PHP SDK (version 5) which publishes posts to my Facebook page when ran.
This is working...however the posts are going onto the page as 'private', so only I can see the posts when logged in to my personal Facebook page. the public cannot see them.
Does anyone know why this may be? Am I right in assuming I need to 'submit the App to Facebook for review' before it can send public posts to my page?
Here's my code below:
define('FACEBOOK_SDK_V4_SRC_DIR', __DIR__.'/src/facebook-sdk-v5/');
require_once(__DIR__.'/src/facebook-sdk-v5/autoload.php');
//Set your Facebook API settings
$fb = new Facebook\Facebook([
'app_id' => 'apptoken',
'app_secret' => 'appsecrettoken',
'default_graph_version' => 'v2.2',
]);
//Post property to Facebook
$linkData = [
'link' => 'http://www.google.co.uk',
'message' => 'Test message'
];
try {
$response = $fb->post('/me/feed', $linkData, 'thepageaccesstokenhere');
} 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();
One solution is to make the app public. By default, I believe it's in development mode.
To do this, please follow below steps:
1. Go to https://developers.facebook.com
2. From the left sidebar, select "App Review"
3. Set "Make your app public?" to "Yes"
Page post made by your app should be available even if you're not logged in.
You are Facebook app & page admin. That's why you are able to post as page, but it's for test purposes only so hidden from other users. You have to apply for permission (post_as_page) to achieve this.