How to make a post to a Facebook page? - facebook

I have a Facebook page at https://www.facebook.com/xxxx and a web site at http://xxxx.com. How do I make a status update to the facebook page to correspond with every new posting on the actual web site? That update should be authored by the page, and not by my personal Facebook account.
I know it might seem like this is a duplicate question, but hear me out. I have been working on this for hours. I've found a lot of help on this topic, but all of it is incomplete or out of date. Most answers tell me what I need to do, but not how to do it.
The closest thing I could find to what I'm looking for is this note in the official docs.
https://developers.facebook.com/docs/opengraph/#publishing
Here's what I've been able to do so far. I created the facebook page. I created a facebook application. I added the app to the page. I added the app to my personal account and granted it the manage_pages permission. I tried to grant it manage_pages permission from the perspective of the page user, but that doesn't seem to be possible.
I can use this to get an access key for the application:
curl -s -F grant_type=client_credentials -F client_id=APPID -F client_secret=APPSECRET https://graph.facebook.com/oauth/access_token
Then I try to do this to actually make a status update.
curl -s -F access_token=ACCESS_TOKEN -F message='test' https://graph.facebook.com/xxxx/feed
This returns a message that the user hasn't authorized the application to perform this action. I assume that's because I'm trying to post as the page user and not as my personal user.
How can I get the correct access key to make a post on the page as the page user? Also, how can I be sure that access key won't expire? Once I have the access key, how do I actually make the post so that it shows up in the right place?

Here's how the manage_pages permission works.
Bob has a page called Awesemo.
Bob wants UltraPageManager5000 to
manage his page.
Bob goes to a page that UltraPageManager5000 has setup that grants UltraPageManager5000 the manage_pages, publish_stream, and offline_access permissions (just like a normal connect app). You must make sure you ask for offline_access, otherwise the access token will expire.
UltraPageManager5000 now has an access token for Bob, but not for his pages.
Now, when UltraPageManager5000 wants to do anything with one of his pages, they go to https://graph.facebook.com/uid/accounts/?access_token=bobs_access_token and look for the "Awesome-O" page to get the proper access token.
I've made a method that simplifies this a little bit for you.
function get_page_access_token($page_id, $access_token, $user_id) {
$data = file_get_contents('https://graph.beta.facebook.com/'.$user_id.'/accounts?access_token='.$access_token);
$pages = json_decode($data,true);
foreach($pages['data'] as $page) {
if($page['id'] == $page_id) {
return $page['access_token'];
}
}
}
Once you have the actual access token, the following HTTP POST will actually create the status update.
curl -F access_token="the token you got for the page from the command above" \
-F message="the status update you want to post" \
https://graph.facebook.com/PAGE_ID/feed

Related

Post to Instagram via Facebook Graph API - unable to get the correct ig-user-id permission

I need to create a Meta application that posts scheduled content on the Instagram page of the company. The app is now in dev mode, and used through the Graph API and cURL.
After getting an Instagram user token on the Graph Explorer with all the required permissions (email, pages_show_list, ads_management, business_management, instagram_basic, instagram_content_publish, publish_to_groups, pages_read_engagement, pages_manage_posts, public_profile) and getting the ig-user-id through the GET /v13.0/me?fields=id,name API call, i make the container generation call, as described in the docs:
curl -i -X POST https://graph.facebook.com/{{ig-user-id}}/media?
image_url=https://{{image-url}}&caption={{text}}&access_token={{token}}
To which I get as a response:
Unsupported post request. Object with ID '{{ig-user-id}}' does not exist, cannot be
loaded due to missing permissions, or does not support this operation.
I tried to generate a Page token in spite of an User token, to use the Page ID in spite of the Used scoped app ID provided by the Graph API but the result has always been the same. One thing I noticed is, trying to get the IG user ID as described on the getting started page, point 5, to my request:
curl -i -X GET "https://graph.facebook.com/v13.0/{{page-id}}?
fields=instagram_business_account&access_token={{token}}"
The response is just {"id":"{{page-id}}"} in spite of the expected
{
"instagram_business_account": {
"id": "17841405822304914" // Connected IG User ID
},
"id": "134895793791914" // Facebook Page ID
}
So it appears it might be a permissions issue. Now, on the Business Settings for the business the app is related:
I'm listed under Users -> People as Administrator and Developer
I'm listed under Account -> Instagram Account -> People with all the permissions (Content, Community Activity, etc.) granted but messages (Impossible to assign - Available only on Instagram)
I'm listed onder Account -> Apps -> {{App Name}} -> People twice with all permissions granted.
Could anyone help me solve the issue? Thanks in advance.

Get facebook public page rating and review

I am not the owner of some page but i want access the pages reviews and ratings,Each access time i am getting empty data set
> http="https://graph.facebook.com/102227700571/tabs/reviews?access_token=fb_oauth"
> content=callAPIInfo(http,fb_oauth)
> content
$data
list()
I saw some of the similar12 question but didnt get my answer,I dont wanna collect page access tokens from the admin of each pages,Is it possible to fetch review and rating.thanks.
EDIT
Finally i find a very detailed answer by ifaour for access pages token by admin and its necessary to take page access token so here is how to get page access token and review and rating
Go to the Graph API Explorer
Choose your app from the dropdown menu
Click "Get Access Token"
Choose the manage_pages permission (you may need the user_events permission too, not sure)
Now access the me/accounts connection and copy your page's access_token Click on
your page's id Add the page's access_token to the GET fields Call
the connection you want (e.g.: PAGE_ID/events)
access_token="xxx" #[what u find above]
> content=callAPIInfo(http,access_token)
> content
$data
$data[[1]]
$data[[1]]$created_time
[1] "2014-04-13T11:37:26+0000"
$data[[1]]$reviewer
$data[[1]]$reviewer$name
[1] "abc"
$data[[1]]$reviewer$id
[1] "100000579606903"
$data[[1]]$rating
[1] 4
$data[[1]]$review_text
[1] "Enjoy having coffee here...:)"
See, all-most all the graph API calls needs an access token for access else you'll not get the result.
The different APIs require different kinds of access tokens, some required current user's access token, some requires page access token and some require app access token. And there are also some APIs that can use either of these tokens.
You want to get the rating/reviews of a page. If you read the official documentation for the same (/{page-id}/ratings), it clearly says-
A page access token is required to retrieve this data.
So you have to have the page access token to get the ratings/reviews of that page. (and for that you should add manage_pages permission and get the page access token with /{page-id}?fields=access_token)

Facebook PHP SDK: getting "long-lived" access token now that "offline_access" is deprecated

BASIC PROBLEM: I want my app to be able to make calls to the Facebook graph api about authorized users even while the user is away.
For example, I want the user (A) to authorize the app, then later I want user (B) to be able to use the app to view info about user (A)'s friends. Specifically: the "work" field. Yes, I am requesting those extended permissions (user_work_history, friends_work_history, etc). Currently my app has access to the logged-in user's friends work history, but not to any of the friends' work history of other users of the app.
Here's what I know already:
Adding offline_access to the scope parameter is the old way and it
no longer works.
The new way is with "long-lived" access tokens,
described here. These last for 60 days.
I need to exchange a normal access token to get the new extended token. The FB documentation says:
https://graph.facebook.com/oauth/access_token?
client_id=APP_ID&
client_secret=APP_SECRET&
grant_type=fb_exchange_token&
fb_exchange_token=EXISTING_ACCESS_TOKEN
Here's what I don't know (and I'm hoping you can tell me):
How do I get the extended (aka "long-lived") access token using the Facebook PHP SDK? Currently, my code looks like this:
$facebook->getAccessToken();
Is there such a thing as this?:
$facebook->getExtendedAccessToken();
If not, is this what I should be doing?
$accessToken = $facebook->getAccessToken();
$extendedAccessToken = file_get_contents("https://graph.facebook.com/oauth/access_token?
client_id={$appId}&
client_secret={$secret}&
grant_type=fb_exchange_token&
fb_exchange_token={$accessToken}"
);
I've tried it and it doesn't work. I get this error:
Warning: file_get_contents(https://graph.facebook.com/oauth/access_token? client_id=#######& client_secret=#########& grant_type=fb_exchange_token& fb_exchange_token=##########) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in /...
Does it work any differently if I switch to FQL instead of the graph api? I've read through the Facebook documentation many times, but the PHP sdk is not thoroughly documented and I can't find any examples of how this should work.
I finally figured this out on my own. The answer is pretty anti-climactic. It appears that newly created apps get 60 day access tokens automatically. I'm not sure if this is dependent on enabling the "depricate offline_access" setting in the Migrations section of the app settings. Leave it on to be safe.
So at the time of writing this, you can use the PHP SDK as follows: $facebook->getAccessToken();
(The reason my app wasn't working as expected was unrelated to the expiration of the access token.)
Just one more thing, to get long-lived access token using PHP SDK you should call $facebook->setExtendedAccessToken(); before $facebook->getAccessToken();
In the last Facebook PHP SDK 3.2.0 you have a new function setExtendedAccessToken()
that you have to call before getAccessToken();
Like this:
$user = $facebook->getUser();
$facebook->setExtendedAccessToken(); //long-live access_token 60 days
$access_token = $facebook->getAccessToken();
Actually newly created apps only get a 60 day access token automatically if you are using a server side call. If you are using the client-side endpoint as shown above in the question, even new apps will still receive a short-term token initially. see: https://developers.facebook.com/docs/roadmap/completed-changes/offline-access-removal/
I had the same HTTP/1.1 400 Bad Request error that you had when using the New Endpoint and the problem was if you copy the code Facebook gives you exactly and paste it into your app, there are actually spaces in between the params, meaning there's unnecessary spaces in the url and it won't get called correctly when passed into file_get_contents() even though it works okay when pasted in the browser. This took me way too long to figure out. Hope this helps somebody! Here is my complete working code to get the extended access token out of the new endpoint (replace x's with your values):
$extend_url = "https://graph.facebook.com/oauth/access_token?client_id=xxxxxxxxxxxx&client_secret=xxxxxxxxxxxxxxxxxxxxxx&grant_type=fb_exchange_token&fb_exchange_token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$resp = file_get_contents($extend_url);
parse_str($resp,$output);
$extended_token = $output['access_token'];
echo $extended_token;
The selected answer is now outdated. Here are Facebook's instructions to swap a short-term token (provided in front-end) for a long-term token (server only):
https://developers.facebook.com/docs/facebook-login/access-tokens/refreshing/
Generate a Long-lived User or Page Access Token
You will need the following:
A valid User or Page Access Token
Your App ID
Your App Secret
Query the GET oath/access_token endpoint.
curl -i -X GET "https://graph.facebook.com/{graph-api-version}/oauth/access_token?
grant_type=fb_exchange_token
client_id={app-id}&
client_secret={app-secret}&
fb_exchange_token={your-access-token}"
Sample Response
{
"access_token":"{long-lived-access-token}",
"token_type": "bearer",
"expires_in": 5183944 //The number of seconds until the token expires
}

How to post to a Facebook Page (how to get page access token + user access token)

I am trying to work out how to post to a Facebook page wall, when using my app as a different Facebook User (who is not the Page Administrator).
I get a range of error messages while testing:
Exception: 200: The user hasn't authorized the application to perform this action
The page administrator has visited the app and accepted the following permissions: publish_stream, manage_pages, offline_access
Here is the code I plan to use:
// Insert Page Administrators ID here
// This user is not the same user that is currently logged in and using the app
// This user is the page administrator who has authorised:
// - manage_pages
// - offline_access
// - publish_stream
$user_id = '123456789';
// Insert Page ID here
$page_id = '123456789';
$accounts = $facebook->api('/'.$user_id.'/accounts');
foreach($accounts['data'] as $account)
{
if($account['id'] == $page_id)
{
$page_access_token = $account['access_token'];
echo "<p>Page Access Token: $page_access_token</p>";
}
}
// publish to the wall on your page
try
{
$result = $facebook->api(array( "uid" => $page_id,
"method" => "stream.publish",
"access_token" => $page_access_token,
"message" => $message, ));
}
catch (FacebookApiException $e)
{
error_log('FB Error: Could not post on Page Wall. Page ID: ' . $page_id);
error_log('FB Error Message: ' . $e);
}
Note: There may be PHP errors in the code above, as I just spliced it on the fly, but its not so much the PHP errors I need correcting, but more my logically understanding of how I am meant to go about this process.
PROBLEM:
I can't access the $user_id/accounts information without an active user access token for the Page Administrator.
The end result that I'm trying to achieve is:
1.) A normal FB user goes to the app and submits a form
2.) The app posts a message on a FB Page wall, which is not owned by the FB user, but has previously been authorized by the Page Administrator with the following permissions manage_pages, publish_stream and offline_access
Q1. Since the Page Administrator has accepted the appropriate permissions, why can't I just generate an active user access token, without the actual Page Administrator user logging into the website?
Q2. Is there a way I can get the equivalent of /$user_id/accounts for the Page Administrator user_id, when logged into Facebook as a different user (which is why I do not use /me/accounts)?
Q3. Please confirm that my understanding of needing the page access token to post to the page wall is correct (or do I need the user access_token for the Page Administrator - see Q1)?
Q4. Anyone have a handy resource on what each type of access_token can actually access?
If you need any more information, please let me know.
I've spent the last few days working on this and I'm stuck.
Thanks!
You can ask the page admin for manage_pages along with offline_access. I do this in my production app to be able to post scheduled postings onto the pages' walls.
Nope. Not possible. That's what asking permissions is all about. And why not everyone gets to administer everyone else's pages. Could you image if you could administer anyone's page without them granting you access?!?
To post to the page as the page, you need a page access token. To post to page's wall as a user, you need a user access token.
Yes, please see: https://developers.facebook.com/docs/reference/api/permissions and https://developers.facebook.com/docs/authentication/
If you have further questions about any one of these, please start a new question. It's not really fair to users of stackoverflow to be hit with 4 questions in one and then to be asked followup questions to each of those.
I have done in Django:
Step to get Page_access_token:
facebook_page_id=360729583957969
graph = GraphAPI(request.facebook.user.oauth_token.token)
page_access_token=graph.get(facebook_page_id+'?fields=access_token')
This way you can get Page access token.
You can check this thing on Fb GraphAPIexplorer:
http://developers.facebook.com/tools/explorer
GET URL: fb_page_id?fields=access_token
for example: 360729583957969?fields=access_token
that will give you page_access_token

facebook auth code becomes invalidate after hours?

I've a simple application in facebook. To change user's facebook status, I need to get code via
https://www.facebook.com/dialog/oauth?
client_id=YOUR_APP_ID&redirect_uri=YOUR_URL
Then I use that code to generate a auth token. With the token I can update user's stauts. It works for one or two days. After that, when trying to generate auth token with code, I got an error like:
{
"error":{
"type":"OAuthException",
"message":"Code was invalid or expired."
}
}
So how long can a code be validate?
There is a way to get an infinite token from facebook. Use the offline_access parameter in requesting permissions, and you will never lose the token.
You just need to grant the publish_stream the first time and get the user id, after that no need to go through this process again and you can just use:
curl -F 'message=Hello World.' \
https://graph.facebook.com/USERID/feed
or in PHP-SDK:
$facebook->api("/USER_ID/feed", "post", array("message"=>"Hello World!"));