Facebook Ad API PHP : Invalid OAuth access token

1.5k Views Asked by At

I am working on the Facebook Ads API and I am totally new for this. I am getting an error to fetch the Ads account. The error is Invalid OAuth access token. After getting this error I came to google and searched a lot like First Link Another one another one. But didn't find any solution so I decided to come to Stackoverflow so this question is not duplicate

Here is the code how I used the Facebook Ads API

public function login() {

        $helper = $this->facebook->getRedirectLoginHelper();
        $this->request->session()->write('fb_access_token', false);
        $access_token =  $this->request->session()->read('fb_access_token');

        if ($access_token) {
            echo "You are logged in!";
          } else {
            $permissions = ['email', 'ads_management', 'pages_show_list', 'publish_pages', 'manage_pages', 'ads_read'];
            $loginUrl = $helper->getLoginUrl('http://localhost/FacebookManager/Adsmanagement/authenticate', $permissions);
            echo '<a href="' . $loginUrl . '">Log in with Facebook</a>';
          }
    }

    public function authenticate() {
        if (isset($_GET['state'])) {
            $helper = $this->facebook->getRedirectLoginHelper();
            $helper->getPersistentDataHandler()->set('state', $_GET['state']);
            $accessToken = $helper->getAccessToken();
            if($accessToken) {
                echo "got the token";
                $this->request->session()->write('fb_access_token', $accessToken);
                //echo $accessToken; 
                $oAuth2Client = $this->facebook->getOAuth2Client();
                $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);

                $this->facebook->setDefaultAccessToken($longLivedAccessToken);


            }
        }
    }

And I am getting the adaccount like this

public function getAdsAccount() {
        $accesstoken = $this->request->session()->read('fb_access_token');
        //$accesstoken = "AQwfmuNgKZCZCiZBuhAMGB8xZBty5dgNR7J9ZBO2ZCDl1SWYxnBLn9ahIn5FQTWxkJ0FPKbemeG0vUAwPsZCN2FFxOFey9BQr8CZBW07IwlZB0FK81SH8ozOil2GllR35BCyxQGhQ7JrtuCdNE6kjEOU0FZCAZDZD";
        Api::init(
            $this->app_id, // App ID
            $this->appsecret,
            $accesstoken // Your user access token
          );
        //*****************
        $account = new AdAccount('****************');
        $contracts = $account->read();

        echo "<pre>"; print_r($contracts->getData());
    }

So I am using a developer account, Trying to fetch this with the facebook test user from the APP dashboard-> Roles->Test User. I am setting the proper permissions etc. Don't know where I am wrong.

Update Now the issue is if I create access token from Graph Explorar It works but if i create with SDK its giving me the error "invalid aouth Tokan"

Please help me. Thanks in advance.

2

There are 2 best solutions below

8
On

Hello @manoj Kumar Please check with below URL with administrator login for app debug your AccessToken.

https://developers.facebook.com/tools/explorer/

Please check below code from facebook PHP SDK for getting the valid access token with permission ads_management.

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

use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;

// 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!";
} else {
  $permissions = ['ads_management'];
  $loginUrl = $helper->getLoginUrl('http://localhost:8888/marketing-api/', $permissions);
  echo '<a href="' . $loginUrl . '">Log in with Facebook</a>';
}

After that, You have to get AdAccount so use below code

use FacebookAds\Object\AdUser;

// Add after Api::init()
$me = new AdUser('me');
$my_adaccount = $me->getAdAccounts()->current();
0
On

It was actually my mistake. Facebook API return us an protect object. If you print the variable it will display it as string.

<?php
echo $longLivedAccessToken;
var_dump($longLivedAccessToken);
?>

The output is something like enter image description here

I tried $longLivedAccessToken->getValue();

$oAuth2Client = $this->facebook->getOAuth2Client();
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
$accesstoken = $longLivedAccessToken->getValue();
$this->request->session()->write('fb_access_token', $accesstoken);
$this->facebook->setDefaultAccessToken($longLivedAccessToken);