Reputation: 108
My overall goal is to simply display posts from my Facebook page onto a website, but I feel like I'm missing something important, making this seemingly simple task quite difficult!
I have set up my app in Facebook Developer and generated a test access token via the Graph API Explorer to test out the example set out on https://developers.facebook.com/docs/reference/php/examples, shown below, which uses the PHP SDK. This works fine.
<?php
require_once __DIR__ . '/vendor/autoload.php';
$fb = new \Facebook\Facebook([
'app_id' => '{your-app-id}',
'app_secret' => '{your-app-secret}',
'graph_api_version' => 'v5.0',
]);
try {
$response = $fb->get('/me?fields=name,hometown', '{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;
}
$me = $response->getGraphUser();
echo 'All the data returned from the server: ' . $me;
echo 'My name is ' . $me->getName();
$hometown = $me->getHometown();
$hometown_name = $hometown->getName();
echo 'My hometown is ' . $hometown_name;
?>
However, given that the access token will expire, I am under the impression I should therefore request a new token when someone visits the website (assuming the previous one has expired, and assuming I store it for use during the period it is active). Is this correct? If so, I am failing to figure out how to generate a token in these circumstances. There are posts like this one from 7 years ago ( Facebook PHP SDK dealing with Access Tokens ) but can't seem to make anything work with the example I'm using (presumably because it is an older version of the SDK).
Can anyone assist with how I generate a new token to allow my basic feed to work without manual creation of an access token? Surely this is just basic stuff but it is baffling me. I have seen references to using the format '{your-app-id}|{your-app-secret}' to create an access token but this seems to create an app token that doesn't do the job.
Any help would be much appreciated!
Thank you!
Upvotes: 1
Views: 128
Reputation: 2007
I've been struggling with this in the past as well. So don't worry :) The relevant part what you're looking for is a "Long-Lived Access Tokens". Here is the documentation to it:
https://developers.facebook.com/docs/facebook-login/access-tokens/refreshing/
Upvotes: 1