Search code examples
facebookfacebook-graph-apifacebook-php-sdkfacebook-ads-apifacebook-marketing-api

How can I get the amount spent / Faceook Marketing API


I'm working on Facebook Marketing API (v6.0) and trying to get the amount spent of each adset I have, actually I've started with Graph API explorer but I found nothing called spend and amount spent as a field, so after a while I got this trick which actually return false data , so the equation is like the following: daily_budget - budget_remaining = amount_spent , so let's assume that we have 900 - 800 = it returns 100 in my application while in business manager I got 50, here is my endpoint api

public function facebookData()
{
    $fb = new \Facebook\Facebook([
        'app_id' => 'xxxxx',
        'app_secret' => 'xxxxxxx',
        'default_graph_version' => 'v6.0',
        //'default_access_token' => '{access-token}', // optional
      ]);        
    try {
        // Returns a `FacebookFacebookResponse` object
        $response = $fb->get(
          '/act_xxxxxx/?fields=business,adsets.limit(1000){name,budget_remaining,daily_budget}',
          'my_accesstoken'
        );
      } catch(FacebookExceptionsFacebookResponseException $e) {
        echo 'Graph return=<i></i>ed an error: ' . $e->getMessage();
        exit;
      } catch(FacebookExceptionsFacebookSDKException $e) {
        echo 'Facebook SDK returned an error: ' . $e->getMessage();
        exit;
      }

      $data = $response->getGraphObject()->getProperty('adsets');        
      try
      {         
      foreach ($data as $ad) {
         \App\FacebookAd::UpdateOrCreate([
          'ad_id' => $ad['id'],
        ],[
          'name' => $ad['name'],
          'budget_remaining' => substr($ad['budget_remaining'],0,-2),
          'daily_budget' => substr($ad['daily_budget'],0,-2),
          'total' => substr($ad['daily_budget'],0,-2) - substr($ad['budget_remaining'],0,-2), // remove last two zeros
          'account_id' => "unset",
        ]);
      }
    }
    catch(\Exception $e)
    {
      Log::error($e->getMessage());
    }
}

Solution

  • Try to use insights. https://developers.facebook.com/docs/marketing-api/reference/ads-insights/

    In your link, add next "insights{spend}". So it will give: '/act_xxxxxx/?fields=business,adsets.limit(1000){name,insights{spend}}'