tytyguy
tytyguy

Reputation: 350

Facebook Ads API Cron Job

We are trying to use the facebook ad reporting api to update a 3rd party app to keep up-to-date on our daily spending on facebook. We would like for these values to update automatically via a cron job but this doesn't appear to work. We have to go to the page and refresh it, for it to refresh the api data. Is it possible to get our script to update automatically? Here is our access token code.

I thought it was possible to get a long lived token and save it to the database and use that but we are unable to retrieve the accessToken because its :protected in the return 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
 }

Upvotes: 0

Views: 642

Answers (1)

bjeavons
bjeavons

Reputation: 1133

I read two questions in your post, the first is that you would like to have a background process (invoked by cron) that reads your daily spending and second that you don't have a long-lived user access token so your script isn't working correctly.

If I understand your goals correctly, it seems that these two issues are a bit conflated which I recommend separating. Follow the Facebook access token documentation for getting a long-lived token and use it directly in your script. Skip PHP session management and just put the long-lived token in a database, simple config file, or directly into the script.

And then if you're not already, have this script invoked by cron or another scheduled background processing system. It can pull your daily spending data and provide it to the 3rd party app.

Upvotes: 2

Related Questions