facebook auth code becomes invalidate after hours? - facebook

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!"));

Related

Facebook: Permanent Page Access Token?

I work on a project that has Facebook pages as one of its data sources. It imports some data from it periodically with no GUI involved. Then we use a web app to show the data we already have.
Not all the information is public. This means I have to get access to the data once and then keep it. However, I don't know the process and I haven't found a good tutorial on that yet. I guess I need an access_token, how can I get it from the user, step by step? The user is an admin of a facebook page, will he have to add some FB app of ours to the page?
EDIT: Thanks #phwd for the tip. I made a tutorial how to get a permanent page access token, even with offline_access no longer existing.
EDIT: I just found out it's answered here: Long-lasting FB access-token for server to pull FB page info
Following the instructions laid out in Facebook's extending page tokens documentation I was able to get a page access token that does not expire.
I suggest using the Graph API Explorer for all of these steps except where otherwise stated.
0. Create Facebook App
If you already have an app, skip to step 1.
Go to My Apps.
Click "+ Add a New App".
Setup a website app.
You don't need to change its permissions or anything. You just need an app that wont go away before you're done with your access token.
1. Get User Short-Lived Access Token
Go to the Graph API Explorer.
Select the application you want to get the access token for (in the "Application" drop-down menu, not the "My Apps" menu).
Click "Get Token" > "Get User Access Token".
In the pop-up, under the "Extended Permissions" tab, check "manage_pages".
Click "Get Access Token".
Grant access from a Facebook account that has access to manage the target page. Note that if this user loses access the final, never-expiring access token will likely stop working.
The token that appears in the "Access Token" field is your short-lived access token.
2. Generate Long-Lived Access Token
Following these instructions from the Facebook docs, make a GET request to
https://graph.facebook.com/v2.10/oauth/access_token?grant_type=fb_exchange_token&client_id={app_id}&client_secret={app_secret}&fb_exchange_token={short_lived_token}
entering in your app's ID and secret and the short-lived token generated in the previous step.
You cannot use the Graph API Explorer. For some reason it gets stuck on this request. I think it's because the response isn't JSON, but a query string. Since it's a GET request, you can just go to the URL in your browser.
The response should look like this:
{"access_token":"ABC123","token_type":"bearer","expires_in":5183791}
"ABC123" will be your long-lived access token. You can put it into the Access Token Debugger to verify. Under "Expires" it should have something like "2 months".
3. Get User ID
Using the long-lived access token, make a GET request to
https://graph.facebook.com/v2.10/me?access_token={long_lived_access_token}
The id field is your account ID. You'll need it for the next step.
4. Get Permanent Page Access Token
Make a GET request to
https://graph.facebook.com/v2.10/{account_id}/accounts?access_token={long_lived_access_token}
The JSON response should have a data field under which is an array of items the user has access to. Find the item for the page you want the permanent access token from. The access_token field should have your permanent access token. Copy it and test it in the Access Token Debugger. Under "Expires" it should say "Never".
Here's my solution using only Graph API Explorer & Access Token Debugger:
Graph API Explorer:
Select your App from the top right dropdown menu
Select "Get User Access Token" from dropdown (right of access token field) and select needed permissions
Copy user access token
Access Token Debugger:
Paste copied token and press "Debug"
Press "Extend Access Token" and copy the generated long-lived user access token
Graph API Explorer:
Paste copied token into the "Access Token" field
Make a GET request with "PAGE_ID?fields=access_token"
Find the permanent page access token in the response (node "access_token")
(Optional) Access Token Debugger:
Paste the permanent token and press "Debug"
"Expires" should be "Never"
(Tested with API Version 2.9-2.11, 3.0-3.1)
In addition to the recommended steps in the Vlasec answer, you can use:
Graph API explorer to make the queries, e.g. /{pageId}?fields=access_token&access_token=THE_ACCESS_TOKEN_PROVIDED_BY_GRAPH_EXPLORER
Access Token Debugger to get information about the access token.
Another PHP answer to make lives easier. Updated for Facebook Graph API 2.9 . Just fill 'er up and load.
<?php
$args=[
/*-- Permanent access token generator for Facebook Graph API version 2.9 --*/
//Instructions: Fill Input Area below and then run this php file
/*-- INPUT AREA START --*/
'usertoken'=>'',
'appid'=>'',
'appsecret'=>'',
'pageid'=>''
/*-- INPUT AREA END --*/
];
echo 'Permanent access token is: <input type="text" value="'.generate_token($args).'"></input>';
function generate_token($args){
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.9/oauth/access_token?grant_type=fb_exchange_token&client_id={$args['appid']}&client_secret={$args['appsecret']}&fb_exchange_token={$args['usertoken']}")); // get long-lived token
$longtoken=$r->access_token;
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.9/me?access_token={$longtoken}")); // get user id
$userid=$r->id;
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.9/{$userid}?fields=access_token&access_token={$longtoken}")); // get permanent token
if($r->id==$args['pageid']) $finaltoken=$r->access_token;
return $finaltoken;
}
?>
Addendum: (alternative)
Graph 2.9 onwards , you can skip much of the hassle of getting a long access token by simply clicking Extend Access Token at the bottom of the Access Token Debugger tool, after having debugged a short access token. Armed with information about pageid and longlivedtoken, run the php below to get permanent access token.
<?php
$args=[
/*-- Permanent access token generator for Facebook Graph API version 2.9 --*/
//Instructions: Fill Input Area below and then run this php file
/*-- INPUT AREA START --*/
'longlivedtoken'=>'',
'pageid'=>''
/*-- INPUT AREA END --*/
];
echo 'Permanent access token is: <input type="text" value="'.generate_token($args).'"></input>';
function generate_token($args){
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.9/{$args['pageid']}?fields=access_token&access_token={$args['longlivedtoken']}"));
return $r->access_token;
}
?>
Although the second code saves you a lot of hassle, I recommend running the first php code unless you are in a lot of hurry because it cross-checks pageid and userid. The second code will not end up working if you choose user token by mistake.
Thanks to dw1 and Rob
I made a PHP script to make it easier. Create an app. In the Graph API Explorer select your App and get a user token with manage_pages and publish_pages permission. Find your page's ID at the bottom of its About page. Fill in the config vars and run the script.
<?php
$args=[
'usertoken'=>'',
'appid'=>'',
'appsecret'=>'',
'pageid'=>''
];
echo generate_token($args);
function generate_token($args){
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/oauth/access_token?grant_type=fb_exchange_token&client_id={$args['appid']}&client_secret={$args['appsecret']}&fb_exchange_token={$args['usertoken']}")); // get long-lived token
$longtoken=$r->access_token;
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/me?access_token={$longtoken}")); // get user id
$userid=$r->id;
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/{$userid}/accounts?access_token={$longtoken}")); // get permanent token
foreach($r->data as $d) if($d->id==$args['pageid']) return $d->access_token;
}
I tried these steps:
https://developers.facebook.com/docs/marketing-api/access#graph-api-explorer
Get Permanent Page Access Token
Go to Graph API Explorer
Select your app in Application
Paste the long-lived access token into Access Token
Next to Access Token, choose the page you want an access token for. The access token appears as a new string.
Click i to see the properties of this access token
Click “Open in Access Token Tool” button again to open the “Access Token Debugger” tool to check the properties
One Tip, it only worked for me when the page language is english.
As all the earlier answers are old, and due to ever changing policies from facebook other mentioned answers might not work for permanent tokens.
After lot of debugging ,I am able to get the never expires token using following steps:
Graph API Explorer:
Open graph api explorer and select the page for which you want to obtain the access token in the right-hand drop-down box, click on the Send button and copy the resulting access_token, which will be a short-lived token
Copy that token and paste it in access token debugger and press debug button, in the bottom of the page click on extend token link, which will extend your token expiry to two months.
Copy that extended token and paste it in the below url with your pageId, and hit in the browser url
https://graph.facebook.com/{page_id}?fields=access_token&access_token={long_lived_token}
U can check that token in access token debugger tool and verify Expires field , which will show never.
Thats it
Most of the answers above now doesn't give permanent token, they only extend it to 2 months. Here's how I got it:
From Graph Explorer tool, select the relevant permissions and get the short lived page access token.
Go to debugger tool and paste your access token. Then, click on 'Extend Token' button at the bottom of the page.
Copy the the extended token and use it in this API:
https://graph.facebook.com/v2.10/me?fields=access_token&access_token=<extended_access_token>
This should return you the permanent access token. You can verify it in debugger tool, the expires at field should say 'Never'.
If you are requesting only page data, then you can use a page access token. You will only have to authorize the user once to get the user access token; extend it to two months validity then request the token for the page. This is all explained in Scenario 5. Note, that the acquired page access token is only valid for as long as the user access token is valid.
While getting the permanent access token I followed above 5 steps as Donut mentioned. However in the 5th step while generating permanent access token its returning the long lived access token(Which is valid for 2 months) not permanent access token(which never expires). what I noticed is the current version of Graph API is V2.5. If you trying to get the permanent access token with V2.5 its giving long lived access token.Try to make API call with V2.2(if you are not able to change version in the graph api explorer,hit the API call https://graph.facebook.com/v2.2/{account_id}/accounts?access_token={long_lived_access_token} in the new tab with V2.2) then you will get the permanent access token(Which never expires)
In addition to mentioned methods it is worth mentioning that for server-to-server applications, you can also use this form of permanent access token:
app_id|app_secret
This type of access token is called App Token. It can generally be used to call Graph API and query for public nodes within your application back-end.
It is mentioned here: https://developers.facebook.com/docs/facebook-login/access-tokens
If you have facebook's app, then you can try with app-id & app-secret.
Like :
access_token={your-app_id}|{your-app_secret}
it will don't require to change the token frequently.
Thanks to #donut I managed to get the never expiring access token in JavaScript.
// Initialize exchange
fetch('https://graph.facebook.com/v3.2/oauth/access_token?grant_type=fb_exchange_token&client_id={client_id}&client_secret={client_secret}&fb_exchange_token={short_lived_token}')
.then((data) => {
return data.json();
})
.then((json) => {
// Get the user data
fetch(`https://graph.facebook.com/v3.2/me?access_token=${json.access_token}`)
.then((data) => {
return data.json();
})
.then((userData) => {
// Get the page token
fetch(`https://graph.facebook.com/v3.2/${userData.id}/accounts?access_token=${json.access_token}`)
.then((data) => {
return data.json();
})
.then((pageToken) => {
// Save the access token somewhere
// You'll need it at later point
})
.catch((err) => console.error(err))
})
.catch((err) => console.error(err))
})
.catch((err) => {
console.error(err);
})
and then I used the saved access token like this
fetch('https://graph.facebook.com/v3.2/{page_id}?fields=fan_count&access_token={token_from_the_data_array}')
.then((data) => {
return data.json();
})
.then((json) => {
// Do stuff
})
.catch((err) => console.error(err))
I hope that someone can trim this code because it's kinda messy but it was the only way I could think of.
Application request limit reached (#4) - FB API v2.1 and greater
This answer led me to the "ultimate answer for us" and so it is very much related so I am appending it here. While it's related to the above it is different and it seems FB has simplified the process some.
Our sharing counts on our site stopped worked when FB rolled over the api to v 2.1. In our case we already had a FB APP and we were NOT using the FB login. So what we needed to do was get a FB APP Token to make the new requests. This is as of Aug. 23 2016.
Go to: https://developers.facebook.com/tools/explorer
Select the api version and then use GET and paste the following:
/oauth/access_token?client_id={app-id}&client_secret={app-secret}&grant_type=client_credentials
You will want to go grab your app id and your app secret from your app page. Main FB Apps developer page
Run the graph query and you will see:
{
"access_token": "app-id|app-token",
"token_type": "bearer"
}
Where "app-id" and "app-token" will be your app id from your FB app page and the generated FB App HASH you just received.
Next go test your new APP access token: FB Access Token tester
You should see, by pasting the "app-token" into the token tester, a single app based token without an expiration date/time.
In our case we are using the FB js sdk so we changed our call to be like so (please note this ONLY gets the share count and not the share and comment count combined like it used to be):
FB.api(
'/','GET',{
// this is our FB app token for our FB app
access_token: FBAppToken,
"id":"{$shareUrl}","fields":"id,og_object{ engagement }"
}
This is now working properly. This took a lot of searching and an official bug report with FB to confirm that we have to start making tokenized requests to the FB api. As an aside I did request that they (FB) add a clue to the Error code (#4) that mentions the tokenized request.
I just got another report from one of our devs that our FB comment count is broken as well due to the new need for tokenized requests so I will update this accordingly.
Many of these examples do not work, not sure if it's because of 2.9v coming out but I was banging my head. Anyways I took #dw1 version and modified it a little with the help of #KFunk video and got this working for me for 2.9. Hope this helps.
$args=[
/*-- Permanent access token generator for Facebook Graph API version 2.9 --*/
//Instructions: Fill Input Area below and then run this php file
/*-- INPUT AREA START --*/
'usertoken'=>'',
'appid'=>'',
'appsecret'=>'',
'pageid'=>''
/*-- INPUT AREA END --*/
];
echo 'Permanent access token is: <input type="text" value="'.generate_token($args).'"></input>';
function generate_token($args){
$r = json_decode(file_get_contents("https://graph.facebook.com/v2.9/oauth/access_token?grant_type=fb_exchange_token&client_id={$args['appid']}&client_secret={$args['appsecret']}&fb_exchange_token={$args['usertoken']}")); // get long-lived token
$longtoken=$r->access_token;
$r=json_decode(file_get_contents("https://graph.facebook.com/{$args['pageid']}?fields=access_token&access_token={$longtoken}")); // get user id
$finaltoken=$r->access_token;
return $finaltoken;
}
As of April 2020, my previously-permanent page tokens started expiring sometime between 1 and 12 hours. I started using user tokens with the manage_pages permission to achieve the previous goal (polling a Page's Events). Those tokens appear to be permanent.
I created a python script based on info found in this post, hosted at github.com/k-funk/facebook_permanent_token, to keep track of what params are required, and which methods of obtaining a permanent token are working.
I created a small NodeJS script based on donut's answer. Store the following in a file called get-facebook-access-token.js:
const fetch = require('node-fetch');
const open = require('open');
const api_version = 'v9.0';
const app_id = '';
const app_secret = '';
const short_lived_token = '';
const page_name = '';
const getPermanentAccessToken = async () => {
try {
const long_lived_access_token = await getLongLivedAccessToken();
const account_id = await getAccountId(long_lived_access_token);
const permanent_page_access_token = await getPermanentPageAccessToken(
long_lived_access_token,
account_id
);
checkExpiration(permanent_page_access_token);
} catch (reason) {
console.error(reason);
}
};
const getLongLivedAccessToken = async () => {
const response = await fetch(
`https://graph.facebook.com/${api_version}/oauth/access_token?grant_type=fb_exchange_token&client_id=${app_id}&client_secret=${app_secret}&fb_exchange_token=${short_lived_token}`
);
const body = await response.json();
return body.access_token;
};
const getAccountId = async (long_lived_access_token) => {
const response = await fetch(
`https://graph.facebook.com/${api_version}/me?access_token=${long_lived_access_token}`
);
const body = await response.json();
return body.id;
};
const getPermanentPageAccessToken = async (
long_lived_access_token,
account_id
) => {
const response = await fetch(
`https://graph.facebook.com/${api_version}/${account_id}/accounts?access_token=${long_lived_access_token}`
);
const body = await response.json();
const page_item = body.data.find(item => item.name === page_name);
return page_item.access_token;
};
const checkExpiration = (access_token) => {
open(`https://developers.facebook.com/tools/debug/accesstoken/?access_token=${access_token}&version=${api_version}`);
}
getPermanentAccessToken();
Fill in the constants and then run:
npm install node-fetch
npm install open
node get-facebook-access-token.js
After running the script a page is opened in the browser that shows the token and how long it is valid.
I found this answer which refers to this tool which really helped a lot.
I hope this answer is still valid when you read this.

Getting the right access token

I'd like my application could read the posts from a group.
To do it, I got the access token in the following url:
https://developers.facebook.com/tools/explorer?method=GET&path=404425692946289%2Ffeed
and I call que following url:
https://graph.facebook.com/404425692946289/feed?access_token=debug_token_generated_from_above_url
And it works like a charm.
But I can't get any results when I call the url above with the token that was generated using my application id and secret:
https://graph.facebook.com/oauth/access_token?client_id=myid&client_secret=mysecret&grant_type=client_credentials <--- The token generated by this url does not work! =(
I am receiving the following data:
{
"data": [
]
}
I supposedly have the read_stream extended permission configured on my application.
One way to check for your self what permissions the token in the API explorer has, is to call /me/permissions
In addition grant_type=client_credentials is for app tokens. You need a user token most likely. Please review the documentation where you got that information from.

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 get value of "expires" parameter of access_token using Facebook PHP SDK?

My Facebook PHP SDK application logged in to Facebook and received access_token.
How to get the value of "expires" parameter later time using PHP SDK?
Facebook API provides the expires parameter along with the access_token in its response as stated here: https://developers.facebook.com/docs/authentication/
In addition to the access token (the access_token parameter), the response contains the number of seconds until the token expires (the expires parameter). Once the token expires, you will need to re-run the steps above to generate a new code and access_token, although if the user has already authorized your app, they will not be prompted to do so again. If your app needs an access token with an infinite expiry time (perhaps to take actions on the user's behalf after they are not using your app), you can request the offline_access permission.
If you're trying to get the time remaining for an access token, I don't believe Facebook even has a method via the API for you to do this. It's easier to just request a new access token, or to request an "offline_access" token which is also documented in the above reference.
To retrieve the "expires" parameter with the Facebook PHP SDK, you need to add a few lines to the base_facebook.php script provided inside the SDK:
//base_facebook.php
//At Line 728
if (!isset($response_params['access_token'])) {
return false;
}
//Add these two lines here
$_SESSION['token_created_time'] = time();
$_SESSION['token_expires'] = $response_params['expires'];
return $response_params['access_token'];
Once your are connected with your application, you can access your "expires" parameter and the remaining time before your token expires with the following :
//Your "expires" parameter :
echo $_SESSION['token_expires'];
//The remaining time before your token expires :
echo $_SESSION['token_expires'] + $_SESSION['token_created_time'] - time();
I hope it would help.

How to make a post to a Facebook page?

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