我正在使用FB Ads API,按照文档中描述的步骤创建我的PHP文件,如下所示。它给了我
致命错误:未捕获的异常'FacebookAds \ Http \ Exception \ AuthorizationException',并显示消息“无效的OAuth访问令牌”。在第137行的/project/root/vendor/facebook/php-ads-sdk/src/FacebookAds/Http/Exception/RequestException.php
和
FacebookAds \ Http \ Exception \ AuthorizationException:无效的OAuth访问令牌。在第137行的/project/root/vendor/facebook/php-ads-sdk/src/FacebookAds/Http/Exception/RequestException.php
<?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';
}
答案 0 :(得分:0)
您还应该检查您拥有的访问令牌是否已过期,因为这也会导致引发身份验证异常。此访问令牌对象具有可用于测试此功能的函数isExpired
。
您可以使用Oauth2Client
并致电getLongLivedAccessToken
来扩展访问令牌。
$long_lived_token =
$fb->getOauth2Client()->getLongLivedAccessToken($access_token);
如果要查看令牌失效的原因,可以使用Developer Debug Tool: https://developers.facebook.com/tools/debug/