Error Logging In & Getting Facebook OAUTH Token

44 Views Asked by At

Using the Facebook SDK to get a user token and then convert it into a page access token. However I'm getting the Unauthorised Access or error occurred.

Here is my code

$fb = new Facebook\Facebook([
  'app_id' => 'YOUR_APP_ID',
  'app_secret' => 'YOUR_APP_SECRET',
  'default_graph_version' => 'v10.0',
]);

$helper = $fb->getRedirectLoginHelper();

$permissions = ['manage_pages']; // Add additional permissions if needed

$loginUrl = $helper->getLoginUrl('https://your-callback-url/', $permissions); // Replace 'https://your-callback-url/' with your actual callback URL

try {
    $accessToken = $helper->getAccessToken();
} catch(Facebook\Exception\FacebookResponseException $e) {
    // When Graph returns an error
    echo 'Graph returned an error: ' . $e->getMessage();
    exit;
} catch(Facebook\Exception\FacebookSDKException $e) {
    // When validation fails or other local issues
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
    exit;
}

if (isset($accessToken)) {
    // Logged in successfully
    $_SESSION['access_token'] = (string) $accessToken;

    // Get user access token
    $userAccessToken = $_SESSION['access_token'];

    // Get page access token
    $response = $fb->get('/me/accounts', $userAccessToken);
    $pages = $response->getGraphEdge()->asArray();

    foreach ($pages as $page) {
        if ($page['id'] == 'YOUR_PAGE_ID') {
            $pageAccessToken = $page['access_token'];
            break;
        }
    }

    // Use the generated page access token
    echo "Page Access Token: " . $pageAccessToken;

} else {
    // Unable to log in
    echo 'Unauthorized access or error occurred.';
}

?>

But yet if I define the $accessToken then the page access token is generated fine. Any help would be appreciated because having to get the page token via the graph explorer manually multiple times daily is really bugging me

0

There are 0 best solutions below