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
Answers
It was actually my mistake. Facebook API return us an protect object. If you print the variable it will display it as string.
The output is something like
I tried
$longLivedAccessToken->getValue();
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
.After that, You have to get AdAccount so use below code