medo ampir
medo ampir

Reputation: 1920

why can't get user access token (offline) to manage pages?

i'm trying to write a script to post to a page while the admin is offline. my application has the manage_pages extended permission of the admin user. here is my code:

require('php-sdk/src/facebook.php');
$facebook = new Facebook(array(
'appId'  => 'MY_APP_ID', // YOUR APP ID
'secret' => 'MY_SECRET', // YOUR API SECRET
'cookie' => true
));

$user_admin_id = 'MY_ADMIN_ID';
$page_id = 'MY_PAGE_ID';

//get the access token to post to my page via the graph api
$accounts = $facebook->api("/" . $user_admin_id  . "/accounts");

foreach ($accounts['data'] as $account)
{
    if ($account['id'] == $page_id)
    {

    //found the access token, now we can break out of the loop
    $page_access_token = $account['access_token'];
    break;
    }
}

but I always get this message:

"Fatal error: Uncaught OAuthException: A user access token is required to request this resource. thrown in /home/itrade10/public_html/khodiersoftware/php-sdk/src/base_facebook.php on line 1033"

Upvotes: 0

Views: 832

Answers (3)

andyrandy
andyrandy

Reputation: 74014

You forgot to authorize the User, that´s how you get a User Access Token:

https://developers.facebook.com/docs/reference/php/facebook-getLoginUrl/

Don´t forget to add the "manage_pages" permission in the scope Parameter. You will also have to use the Function "setExtendedAccessToken" of the PHP SDK to extend the User Token. After that, you will get a Page Access Token that is valid forever with the /me/accounts endpoint.

If you used getLoginUrl already, then there´s something wrong with that code, you may want to add it to the question.

Before getting the accounts (with /me/accounts, not with your id), get the User ID:

$user = $facebook->getUser();

If you got a valid User Token, your ID will be in the $user Variable.

Upvotes: 1

Stephen Atty
Stephen Atty

Reputation: 336

The error message is telling you exactly what the problem is... you need to get a user access token to access your page tokens

Upvotes: 0

Related Questions