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';
}
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/
Related
how to post on users timeline using php sdk
i search about that issue on stackoverflow i got nothing plx help
i need to do this for my client
<?php
namespace App;
use Facebook\Facebook;
class FacebookClass{
private $fb;
private $appiD = 3073019182770120;
private $appSecret = "6360e1540e1add2b6fc93fce07fcb61a";
public function __construct()
{
$this->fb = new Facebook([
'app_id' => $this->appiD, // Replace {app-id} with your app id
'app_secret' => $this->appSecret,
'default_graph_version' => 'v4.0',
]);
}
public function getLoginUrl() {
$helper = $this->fb->getRedirectLoginHelper();
$permissions = ['email']; // Optional permissions
$loginUrl = $helper-
>getLoginUrl('http://localhost/social_platform/',$permissions);
return $loginUrl;
}
public function loginWithFacebook() {
$helper = $this->fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
if(isset($accessToken))
{
$_SESSION['facebook']['access_token'] = (string) $accessToken;
header("index.php");
}
} catch (\Throwable $th) {
// var_dump($th);
}
}
public function postOnUserTimeLine() {
// posting on user timeline using publish_actins permission
try {
// message must come from the user-end
$data = ['message' => 'testing...'];
$request = $this->fb->post('/me/feed', $data,
$_SESSION['facebook']['access_token']);
$response = $request->getGraphNode()->asArray;
} catch (Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch (Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
echo $response['id'];
}
}
?>
Fatal error: Uncaught Facebook\Exceptions\FacebookAuthorizationException: (#200) If posting to a group, requires app being installed in the group, and \ either publish_to_groups permission with user token, or both manage_pages \ and publish_pages permission with page token; If posting to a page, \ requires both manage_pages and publish_pages as an admin with \ sufficient administrative permission in E:\xampp\htdocs\Social_Platform\vendor\facebook\graph-sdk\src\Facebook\Exceptions\FacebookResponseException.php:137 Stack trace: #0 E:\xampp\htdocs\Social_Platform\vendor\facebook\graph-sdk\src\Facebook\FacebookResponse.php(210): Facebook\Exceptions\FacebookResponseException::create(Object(Facebook\FacebookResponse)) #1 E:\xampp\htdocs\Social_Platform\vendor\facebook\graph-sdk\src\Facebook\FacebookResponse.php(255): Facebook\FacebookResponse->makeException() #2 E:\xampp\htdocs\Social_Platform\vendor\facebook\graph-sdk\src\Facebook\FacebookResponse.php(82): Facebook\FacebookResponse->deco in E:\xampp\htdocs\Social_Platform\vendor\facebook\graph-sdk\src\Facebook\Exceptions\FacebookResponseException.php on line 137
Posting to the user wall is not possible anymore. The required permission "publish_actions" got deprecated a while ago:
https://developers.facebook.com/docs/graph-api/changelog/breaking-changes#login-4-24
Use the Share Dialog instead: https://developers.facebook.com/docs/sharing/reference/share-dialog
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 'Log in with Facebook';
}
}
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.
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 'Log in with Facebook';
}
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();
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
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);
This is my controller and it's working fine.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->library('session');
}
function index(){
$this->load->view("welcome_message");
}
function fblogin(){
$fb = new Facebook\Facebook([
'app_id' => '213234637467346734',
'app_secret' => '7346762476374673647',
'default_graph_version' => 'v2.8',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email','user_location','user_birthday','publish_actions'];
// For more permissions like user location etc you need to send your application for review
$loginUrl = $helper->getLoginUrl('http://localhost/facebooklogin/welcome/fbcallback', $permissions);
header("location: ".$loginUrl);
}
function fbcallback(){
$fb = new Facebook\Facebook([
'app_id' => '1767865763452676',
'app_secret' => '2454f5b88ea788b407297f39400b796b',
'default_graph_version' => 'v2.5',
]);
$helper = $fb->getRedirectLoginHelper();
$this->session->set_userdata('state',$_GET['state']);
try {
$accessToken = $helper->getAccessToken();
}catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
try {
// Get the Facebook\GraphNodes\GraphUser object for the current user.
// If you provided a 'default_access_token', the '{access-token}' is optional.
$response = $fb->get('/me?fields=id,name,email,first_name,last_name,birthday,location,gender', $accessToken);
// print_r($response);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'ERROR: Graph ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'ERROR: validation fails ' . $e->getMessage();
exit;
}
// User Information Retrieval begins................................................
$data['me'] = $response->getGraphUser();
$data['accessToken'] =$accessToken;
$this->load->view("home",$data);
}
}
When I refresh the home page its give me this error
Facebook SDK returned an error: Cross-site request forgery validation failed. Required param "state" missing from persistent data.
Here I changed the app_id and app_secret for security reason.and i also load the session library in autload file
I have solve the problem.I just add this code in try block where i get the access token
if(!$this->session->userdata('token')){
$accessToken = $helper->getAccessToken();
$this->session->set_userdata('token',$accessToken);
}
else{
$accessToken = $this->session->userdata('token');
}
I have tried to following way
but i got Error "The access token does not belong to application "
i have checked lot of time in my app id and secrt id, app id is correct but This error shown again and again I didn't peridict this Error? and also i have tried following way also
https://graph.facebook.com/v2.2/oauth/access_token?grant_type=fb_exchange_token&client_id=CLIENT_ID
&client_secret=SECRED CODE&fb_exchange_token=EAACEdEose0cBAJRZCZBIaDmW3oOO6SHaOkQLKdgyjp1evGoQ19mYcZCXu5wWLwZABJUbV77tjPjiE2pac2fDEmjM1tZAZB8hflSyERXFWIZB2DtzZAGSgVX6Ukb0ZAZAzd6pohnZBXU0T2aqYwf1umUxsfgHQXBNmM15yhdZBG2Br
PHPsdk 5 and v2.8
$fb = new Facebook\Facebook([
'app_id' => 'xxxxxxxxx',
'app_secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
'default_graph_version' => 'v2.8',
]);
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// There was an error communicating with Graph
echo $e->getMessage();
exit;
}
$client = $fb->getOAuth2Client();
try {
// Returns a long-lived access token
$accessTokenLong = $client->getLongLivedAccessToken($accessToken);
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// There was an error communicating with Graph
echo $e->getMessage();
exit;
}
if (isset($accessTokenLong)) {
// Logged in.
$_SESSION['facebook_access_token'] = (string) $accessTokenLong;
}
Reference url :https://www.sammyk.me/upgrading-the-facebook-php-sdk-from-v4-to-v5
I am use this code from Facebook
https://developers.facebook.com/docs/php/gettingstarted/5.0.0
But now its show Facebook SDK returned an error: Cross-site request forgery validation failed. The "state" param from the URL and session do not match.
I cant understand whats wrong
my login callback page code
session_start();
require_once __DIR__ . '/facebook-php-sdk-v4-5.0-dev/src/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => 'xxxx',
'app_secret' => 'xxxxxxxx',
'default_graph_version' => 'v2.2',
]);
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($accessToken)) {
// Logged in!
$_SESSION['facebook_access_token'] = (string) $accessToken;
// Now you can redirect to another page and use the
// access token from $_SESSION['facebook_access_token']
$_SESSION['facebook_access_token'];
}
Insert this code after: $helper = $fb->getRedirectLoginHelper();
$_SESSION['FBRLH_state']=$_GET['state'];
and it will work or for more detail visit facebook login apps
You are likely not accessing your server using the domain registered to the app. Are you running your webserver on localhost? If so, edit your /etc/hosts file to include something like
127.0.0.1 local.<yourdomain>.com
and then go to local..com and that should take care of it