3
votes

I am using FB Ads API, following steps described in documentation and created my PHP file as bellow. It gives me

Fatal error: Uncaught exception 'FacebookAds\Http\Exception\AuthorizationException' with message 'Invalid OAuth access token.' in /project/root/vendor/facebook/php-ads-sdk/src/FacebookAds/Http/Exception/RequestException.php on line 137

and

FacebookAds\Http\Exception\AuthorizationException: Invalid OAuth access token. in /project/root/vendor/facebook/php-ads-sdk/src/FacebookAds/Http/Exception/RequestException.php on line 137

My PHP code snippet is

<?php

require_once DIR . '/vendor/autoload.php';

use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
use FacebookAds\Api;
use FacebookAds\Object\AdUser;

// Init PHP Sessions
session_start();

$fb = new Facebook([
    'app_id' => 'your-app-id',
    'app_secret' => 'your-app-secret',
        ]);

$helper = $fb->getRedirectLoginHelper();

if (!isset($_SESSION['facebook_access_token'])) {
    $_SESSION['facebook_access_token'] = null;
}

if (!$_SESSION['facebook_access_token']) {
    $helper = $fb->getRedirectLoginHelper();
    try {
        $_SESSION['facebook_access_token'] = (string) $helper->getAccessToken();
    } catch (FacebookResponseException $e) {
// When Graph returns an error
        echo 'Graph returned an error: ' . $e->getMessage();
        exit;
    } catch (FacebookSDKException $e) {
// When validation fails or other local issues
        echo 'Facebook SDK returned an error: ' . $e->getMessage();
        exit;
    }
}

if ($_SESSION['facebook_access_token']) {
    echo "You are logged in!";
    $app = Api::init(
                    'your-app-id', // App ID
                    'your-app-secret', $_SESSION['facebook_access_token'] // Your user access token
    );
    $me = new AdUser('me');
    $my_adaccount = $me->getAdAccounts()->current();
    print_r($my_adaccount->getData());
} else {
    $permissions = ['ads_management'];
    $loginUrl = $helper->getLoginUrl('http://localhost:8888/marketing-api/', $permissions);
    echo 'Log in with Facebook';
}
1
did you list your ad account under the developer settings?Paul Bain

1 Answers

0
votes

You should also check that the access token you have has not expired as this will also cause an authentication exception to be thrown. This access token object has the function isExpired which you can use to test this.

You can extend the access token by using Oauth2Client and calling getLongLivedAccessToken.

$long_lived_token = 
  $fb->getOauth2Client()->getLongLivedAccessToken($access_token);

If you want to see why the token has become invalid, you can use the Developer Debug Tool: https://developers.facebook.com/tools/debug/