Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve all my active Facebook ads?

I'm creating a dashboard for myself that helps me keep track of the Facebook ads I'm running.

What I've not been able to figure out is:

How can I retrieve an array of ad IDs for all ads that are active or could soon be active after no further action on my part?

In other words, I want all ads that I've set to Active and that exist within Adsets and Campaigns that are active (and therefore these ads are live right now)... plus all the ads that from my perspective are Active but that Facebook has set to another status such as Pending Review (and will soon set back to Active).

I have some code below, but the problem is that it also accidentally includes Pending ads that--once reviewed and approved by Facebook--will be inactive rather than active (because I've set them that way). And I do NOT want this type of ad to be included in my report.

My report should only show me ones where I'm actively spending money or have the potential to spend money as soon as FB approves them.

I think I understand the difference between configured_status and effective_status in AbstractArchivableCrudObjectFields, but I don't know that it's enough to help me because I have lots of ads set to Active that are within Adsets that are Inactive, and I don't want to see those listed in my report.

Any recommendations?

public function getActiveAdIds() {
    $key = 'activeAdIds';
    $adIdsJson = Cache::get($key);
    if ($adIdsJson) {
        $adIds = json_decode($adIdsJson);
    } else {
        $adsResponse = $this->getAdsByStatus([ArchivableCrudObjectEffectiveStatuses::ACTIVE, ArchivableCrudObjectEffectiveStatuses::PENDING_REVIEW]);
        $ads = $adsResponse->data;
        $adIds = [];
        foreach ($ads as $ad) {
            $adIds[] = $ad->id;
        }
        $adIdsJson = json_encode($adIds);
        Cache::put($key, $adIdsJson, 1);
    }
    return $adIds;
}

public function getAdsByStatus($statuses) {
    $params = [\FacebookAds\Object\Fields\AbstractArchivableCrudObjectFields::EFFECTIVE_STATUS => $statuses];
    $adAccount = new AdAccount(self::ACT_PREPEND . $this->fbConfig['account_id']);
    $cursor = $adAccount->getAds([], $params);
    $response = $cursor->getResponse();
    $jsonString = $response->getBody();
    return json_decode($jsonString);
}
like image 941
Ryan Avatar asked Apr 05 '17 17:04

Ryan


1 Answers

I get stats based on assets for my active campaigns. I have 119 ad accounts. This is php code which I used it for this purpose (any suggestion to improve it will be appreciated):

    $fields = array(AdsInsightsFields::ACCOUNT_NAME,AdsInsightsFields::CAMPAIGN_ID,
                    AdsInsightsFields::CAMPAIGN_NAME, AdsInsightsFields::ADSET_ID,
                    AdsInsightsFields::ADSET_NAME,AdsInsightsFields::DATE_START,
                    AdsInsightsFields::DATE_STOP,AdsInsightsFields::REACH,
                    AdsInsightsFields::SPEND, AdsInsightsFields::IMPRESSIONS,
                    AdsInsightsFields::CLICKS, AdsInsightsFields::WEBSITE_CLICKS,
                    AdsInsightsFields::CALL_TO_ACTION_CLICKS,AdsInsightsFields::ACTIONS,
                    AdsInsightsFields::TOTAL_ACTIONS,AdsInsightsFields::CPC,
                    AdsInsightsFields::CPM,AdsInsightsFields::CPP,
                    AdsInsightsFields::CTR,AdsInsightsFields::OBJECTIVE,);
    $params_c['date_preset'] = AdDatePresetValues::YESTERDAY;
    $params_c['time_increment'] = 1;
    $params_c['action_attribution_windows'] = array('1d_view', '28d_click');
    $params_c['effective_status'] = AdStatusValues::ACTIVE;
    $params_c['level'] = AdsInsightsLevelValues::ADSET;
    $params_c['filtering'] = [array("field"=>"campaign.delivery_info", 
                                   "operator"=>"IN",
                                    "value"=>array("active"))];
    $params_c['fields']= $fields;     
    try{
         // Initialize a new Session and instanciate an Api object
        Api::init(self::api_key, self::secret_token, self::extended_token)->getHttpClient()->setCaBundlePath( $this->path_cert);

        // The Api object is now available trough singleton
        $api = Api::instance();
        $user = new \FacebookAds\Object\Business($business_id);
        $user->read(array(BusinessFields::ID));

        //get all ad_account from Business
        $accounts = $user->getAssignedAdAccounts(
                      array(
                    AdAccountFields::ID,
                 ),
                  array('limit'=>1000,)
                );                                    

    } catch (FacebookAds\Exception\Exception $ex) {
        return $ex->getMessage();
    }   

    if(isset($accounts) && ($accounts->count() > 0)):           
        do{

            $ad_account = $accounts->current();            
            $adset_insights = $ad_account->getInsights($fields,$params_c); 

            do {
                $adset_insights->fetchAfter();
            } while ($adset_insights->getNext());

            $adsets = $adset_insights->getArrayCopy(true); 
    }
    while ($accounts->current());    
    endif;
like image 134
Angie Avatar answered Oct 05 '22 23:10

Angie