0
我們正在嘗試使用Facebook廣告報告api更新第三方應用以及時瞭解我們在Facebook上的日常消費情況。我們希望通過cron作業自動更新這些值,但這似乎不起作用。我們必須去頁面刷新它,以便刷新api數據。是否有可能讓我們的腳本自動更新?這是我們的訪問令牌代碼。Facebook廣告API Cron工作
我認爲有可能獲得一個長壽命的令牌並將其保存到數據庫並使用它,但是我們無法檢索accessToken,因爲它在受保護的返回json中。
use FacebookAds\Api;
use FacebookAds\Object\AdSet;
use FacebookAds\Object\AdGroup;
use FacebookAds\Object\Fields\AdSetFields;
use FacebookAds\Object\Fields\AdGroupFields;
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Fields\AdAccountFields;
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookSDKException;
use Facebook\Entities\AccessToken;
// Initialize the SDK
FacebookSession::setDefaultApplication($app_id, $app_secret);
// Create the login helper and replace REDIRECT_URI with your URL
// Use the same domain you set for the apps 'App Domains'
// e.g. $helper = new FacebookRedirectLoginHelper('redirect');
$helper = new FacebookRedirectLoginHelper($redirect_uri);
// Check if existing session exists
if (isset($_SESSION) && isset($_SESSION['fb_token'])) {
// Create new session from saved access_token
$session = new FacebookSession($_SESSION['fb_token']);
// Validate the access_token to make sure it's still valid
try {
if (! $session->validate()) {
$session = null;
}
} catch (Exception $e) {
// Catch any exceptions
$session = null;
}
} else {
// No session exists
try {
$session = $helper->getSessionFromRedirect();
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
} catch(Exception $ex) {
// When validation fails or other local issues
echo $ex->message;
}
}
// Check if a session exists
if (isset($session)) {
// Save the session
$_SESSION['fb_token'] = $session->getToken();
$access_token = $_SESSION['fb_token'];
$long_session = $session->getLongLivedSession();
//print_r($long_session);
$longtoken = $long_session->getToken();
// Create session using saved token or the new one we generated at login
$session = new FacebookSession($long_session->getToken());
} else {
// No session
// Get login URL
$loginUrl = $helper->getLoginUrl($permissions);
//echo '<a href="' . $loginUrl . '">Log in</a>';
header('Location: '.$loginUrl.'');
}
// Initialize a new Session and instanciate an Api object
Api::init($app_id, $app_secret, $access_token);
// The Api object is now available trough singleton
$api = Api::instance();
// Get the GraphUser object for the cusrrent user:
try {
$me = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
// echo $me->getName();
} catch (FacebookRequestException $e) {
// The Graph API returned an error
} catch (\Exception $e) {
// Some other error occurred
}
我不認爲將Access令牌放入配置是一個好主意,因爲它會在一天內過期。 – 2015-03-23 11:00:17