Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

263
Visualizações
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);
}
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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;
about 4 years ago · Santiago Trujillo Relatório

0

If you include the adset{end_time} field in the query for the ad, you can assume that ad is not actually running if the end_time was in the past. This is how we get a base list of ads to query on.

The next step we take (which probably won't help you, unfortunately, but may help others) is building a batch of simple requests (one per ad) to see if there are any insights data for that day. If the response is an empty 'data' array, we can remove that ID from the ad list.

After we've reduced the size of the ad list with those two steps we can then make requests to run all of our breakdown reports. This method almost cut our API requests in half.

I have yet to find a way to do a "give me all ads that are for sure running this day" query in one step.

Edit: I just found a better way to do this.... :

curl -G \
-d 'access_token=<ACCESS_TOKEN>' \
-d 'level=campaign' \
-d 'filtering=[{field:"ad.impressions",operator:"GREATER_THAN",value:0}]' \
'https://graph.facebook.com/v2.7/act_<ACCOUNT_ID>/insights'
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda