Estrutura da campanha de anúncios

O Facebook organiza os anúncios em uma estrutura de três níveis: campanha, conjunto de anúncios e anúncio. Na API, os desenvolvedores têm acesso a um quarto nível, chamado criativo.

Como funciona

Campanha

Estes objetos contêm seu objetivo de publicidade e um ou mais conjuntos de anúncios. Isso ajuda você a otimizar e a medir os resultados para cada objetivo de publicidade.

Conjuntos de anúncios

Os conjuntos de anúncios têm um ou mais anúncios. Você define o orçamento e o agendamento para cada conjunto de anúncios. Crie um conjunto de anúncios para cada público-alvo com seu lance; os anúncios no conjunto são direcionados para o mesmo público com o mesmo lance. Isso ajudará você a controlar o quanto gasta com cada público, a determinar quando o público verá seus anúncios e fornecer métricas para cada público.

Anúncios

Contém criativo do anúncio. Crie vários anúncios em cada conjunto para otimizar a veiculação de anúncios com base em diferentes imagens, links, vídeo, texto ou posicionamentos.

Criativos do anúncio

Contêm apenas os elementos visuais do anúncio, e não é possível alterá-los depois de serem criados. Cada conta de anúncios tem uma biblioteca de criativos para armazenar criativos para reutilização em anúncios.

Objetivo Programação Orçamento Lances Direcionamento Criativo

Campanha

Conjunto de anúncios

Anúncio

Mapeamento entre a nomenclatura voltada para o público do objeto e os pontos de extremidade da API:

Nome voltado ao público Ponto de extremidade da API

Campanha

/campanhas

Conjunto de anúncios

/adsets

Anúncio

/ads

Criativo

/adcreatives


Campanhas

Documentos de referência

A campanha é o nível mais alto da estrutura organizacional da conta de anúncios e deve representar um objetivo único para o anunciante, por exemplo, para estimular o engajamento de publicações da página. Definir o objetivo da campanha aplica a validação de quaisquer anúncios adicionados a essa campanha para garantir que eles também tenham o objetivo correto.

No Gerenciador de Anúncios, mostramos todas as campanhas ativas e suspensas em uma conta de anúncios.

Para ler as campanhas associadas a uma conta específica, faça uma solicitação para a conexão da conta de anúncios que está utilizando. Por padrão, apenas retornamos campanhas cujo status é ACTIVE ou PAUSED; então, você precisa especificar status adicionais, se necessário:

curl -X GET \ -d 'effective_status=[ "ACTIVE", "PAUSED" ]' \ -d 'fields="name,objective"' \ -d 'access_token=<ACCESS_TOKEN>' \ https://graph.facebook.com/v21.0/act_<AD_ACCOUNT_ID>/campaigns
'use strict'; const bizSdk = require('facebook-nodejs-business-sdk'); const AdAccount = bizSdk.AdAccount; const Campaign = bizSdk.Campaign; const access_token = '<ACCESS_TOKEN>'; const app_secret = '<APP_SECRET>'; const app_id = '<APP_ID>'; const id = '<AD_ACCOUNT_ID>'; const api = bizSdk.FacebookAdsApi.init(access_token); const showDebugingInfo = true; // Setting this to true shows more debugging info. if (showDebugingInfo) { api.setDebug(true); } const logApiCallResult = (apiCallName, data) => { console.log(apiCallName); if (showDebugingInfo) { console.log('Data:' + JSON.stringify(data)); } }; let fields, params; fields = [ 'name', 'objective', ]; params = { 'effective_status' : ['ACTIVE','PAUSED'], }; const campaignss = (new AdAccount(id)).getCampaigns( fields, params ); logApiCallResult('campaignss api call complete.', campaignss);
require __DIR__ . '/vendor/autoload.php'; use FacebookAds\Object\AdAccount; use FacebookAds\Object\Campaign; use FacebookAds\Api; use FacebookAds\Logger\CurlLogger; $access_token = '<ACCESS_TOKEN>'; $app_secret = '<APP_SECRET>'; $app_id = '<APP_ID>'; $id = '<AD_ACCOUNT_ID>'; $api = Api::init($app_id, $app_secret, $access_token); $api->setLogger(new CurlLogger()); $fields = array( 'name', 'objective', ); $params = array( 'effective_status' => array('ACTIVE','PAUSED'), ); echo json_encode((new AdAccount($id))->getCampaigns( $fields, $params )->getResponse()->getContent(), JSON_PRETTY_PRINT);
from facebook_business.adobjects.adaccount import AdAccount from facebook_business.adobjects.campaign import Campaign from facebook_business.api import FacebookAdsApi access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<AD_ACCOUNT_ID>' FacebookAdsApi.init(access_token=access_token) fields = [ 'name', 'objective', ] params = { 'effective_status': ['ACTIVE','PAUSED'], } print AdAccount(id).get_campaigns( fields=fields, params=params, )
import com.facebook.ads.sdk.*; import java.io.File; import java.util.Arrays; public class SAMPLE_CODE_EXAMPLE { public static void main (String args[]) throws APIException { String access_token = \"<ACCESS_TOKEN>\"; String app_secret = \"<APP_SECRET>\"; String app_id = \"<APP_ID>\"; String id = \"<AD_ACCOUNT_ID>\"; APIContext context = new APIContext(access_token).enableDebug(true); new AdAccount(id, context).getCampaigns() .setEffectiveStatus(Arrays.asList(Campaign.EnumEffectiveStatus.VALUE_ACTIVE,Campaign.EnumEffectiveStatus.VALUE_PAUSED)) .requestNameField() .requestObjectiveField() .execute(); } }
require 'facebook_ads' access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<AD_ACCOUNT_ID>' FacebookAds.configure do |config| config.access_token = access_token config.app_secret = app_secret end ad_account = FacebookAds::AdAccount.get(id) campaignss = ad_account.campaigns({ fields: { 'name''objective' }, effective_status: ['ACTIVE','PAUSED'], })

Também mostramos alguns insights de alto nível, incluindo impressões, cliques e o valor usado. É possível recuperá-los chamando o seguinte ponto de extremidade, opcionalmente especificando a hora de início e/ou fim:

use FacebookAds\Object\Campaign;

$campaign = new Campaign(<CAMPAIGN_ID>);
$insights = $campaign->getInsights(array(
  AdsInsightsFields::IMPRESSIONS,
  AdsInsightsFields::INLINE_LINK_CLICKS,
  AdsInsightsFields::SPEND,
), array(
  'end_time' => (new \DateTime('now'))->getTimestamp(),
));
from facebookads.adobjects.campaign import Campaign
from facebookads.adobjects.adsinsights import AdsInsights
import time

fields = [
    AdsInsights.Field.impressions,
    AdsInsights.Field.inline_link_clicks,
    AdsInsights.Field.spend,
]

params = {
    'end_time': int(time.time()),
}

campaign = Campaign(<CAMPAIGN_ID>)
insights = campaign.get_insights(fields=fields, params=params)
APINodeList<AdsInsights> adsInsightss = new Campaign(<CAMPAIGN_ID>, context).getInsights()
  .setParam("end_time", end_time)
  .requestField("impressions")
  .requestField("inline_link_clicks")
  .requestField("spend")
  .execute();
curl -G \
  -d 'end_time=1517287567' \
  -d 'fields=impressions,inline_link_clicks,spend' \
  -d 'access_token=<ACCESS_TOKEN>' \
  https://graph.facebook.com/v2.11/<CAMPAIGN_ID>/insights

Objetivos

Objetivos são ações que você quer que as pessoas façam quando virem seu anúncio. É necessário especificar o objetivo escolhido durante a criação da campanha.

A definição explícita do objetivo tem os seguintes benefícios:

  • Você obtém opções corretas de rastreamento, otimização e lances para seu anúncio.
  • Você pode ver painéis únicos de interface do usuário e análise para cada objetivo

A chamada de API mínima necessária para criar uma campanha é:

curl -X POST \ -F 'name="My First Campaign"' \ -F 'objective="OUTCOME_ENGAGEMENT"' \ -F 'status="PAUSED"' \ -F 'special_ad_categories=[]' \ -F 'access_token=<ACCESS_TOKEN>' \ https://graph.facebook.com/v21.0/act_<AD_ACCOUNT_ID>/campaigns
'use strict'; const bizSdk = require('facebook-nodejs-business-sdk'); const AdAccount = bizSdk.AdAccount; const Campaign = bizSdk.Campaign; const access_token = '<ACCESS_TOKEN>'; const app_secret = '<APP_SECRET>'; const app_id = '<APP_ID>'; const id = '<AD_ACCOUNT_ID>'; const api = bizSdk.FacebookAdsApi.init(access_token); const showDebugingInfo = true; // Setting this to true shows more debugging info. if (showDebugingInfo) { api.setDebug(true); } const logApiCallResult = (apiCallName, data) => { console.log(apiCallName); if (showDebugingInfo) { console.log('Data:' + JSON.stringify(data)); } }; let fields, params; fields = [ ]; params = { 'name' : 'My First Campaign', 'objective' : 'OUTCOME_ENGAGEMENT', 'status' : 'PAUSED', 'special_ad_categories' : [], }; const campaigns = (new AdAccount(id)).createCampaign( fields, params ); logApiCallResult('campaigns api call complete.', campaigns);
require __DIR__ . '/vendor/autoload.php'; use FacebookAds\Object\AdAccount; use FacebookAds\Object\Campaign; use FacebookAds\Api; use FacebookAds\Logger\CurlLogger; $access_token = '<ACCESS_TOKEN>'; $app_secret = '<APP_SECRET>'; $app_id = '<APP_ID>'; $id = '<AD_ACCOUNT_ID>'; $api = Api::init($app_id, $app_secret, $access_token); $api->setLogger(new CurlLogger()); $fields = array( ); $params = array( 'name' => 'My First Campaign', 'objective' => 'OUTCOME_ENGAGEMENT', 'status' => 'PAUSED', 'special_ad_categories' => array(), ); echo json_encode((new AdAccount($id))->createCampaign( $fields, $params )->exportAllData(), JSON_PRETTY_PRINT);
from facebook_business.adobjects.adaccount import AdAccount from facebook_business.adobjects.campaign import Campaign from facebook_business.api import FacebookAdsApi access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<AD_ACCOUNT_ID>' FacebookAdsApi.init(access_token=access_token) fields = [ ] params = { 'name': 'My First Campaign', 'objective': 'OUTCOME_ENGAGEMENT', 'status': 'PAUSED', 'special_ad_categories': [], } print AdAccount(id).create_campaign( fields=fields, params=params, )
import com.facebook.ads.sdk.*; import java.io.File; import java.util.Arrays; public class SAMPLE_CODE_EXAMPLE { public static void main (String args[]) throws APIException { String access_token = \"<ACCESS_TOKEN>\"; String app_secret = \"<APP_SECRET>\"; String app_id = \"<APP_ID>\"; String id = \"<AD_ACCOUNT_ID>\"; APIContext context = new APIContext(access_token).enableDebug(true); new AdAccount(id, context).createCampaign() .setName(\"My First Campaign\") .setObjective(Campaign.EnumObjective.VALUE_OUTCOME_ENGAGEMENT) .setStatus(Campaign.EnumStatus.VALUE_PAUSED) .setParam(\"special_ad_categories\", \"[]\") .execute(); } }
require 'facebook_ads' access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<AD_ACCOUNT_ID>' FacebookAds.configure do |config| config.access_token = access_token config.app_secret = app_secret end ad_account = FacebookAds::AdAccount.get(id) campaigns = ad_account.campaigns.create({ name: 'My First Campaign', objective: 'OUTCOME_ENGAGEMENT', status: 'PAUSED', special_ad_categories: [], })

Recursos:

Conjuntos de anúncios

Conjuntos de anúncios são grupos de anúncios e são usados para configurar o orçamento e o período para o qual os anúncios devem ser veiculados. Todos os anúncios contidos em um conjunto devem ter o mesmo direcionamento, orçamento, a mesma cobrança, meta de otimização e duração.

curl -X POST \ -F 'name="My First AdSet"' \ -F 'lifetime_budget=20000' \ -F 'start_time="2024-11-28T06:58:43-0800"' \ -F 'end_time="2024-12-05T06:58:43-0800"' \ -F 'campaign_id="<AD_CAMPAIGN_ID>"' \ -F 'bid_amount=500' \ -F 'billing_event="IMPRESSIONS"' \ -F 'optimization_goal="POST_ENGAGEMENT"' \ -F 'targeting={ "age_min": 20, "age_max": 24, "behaviors": [ { "id": 6002714895372, "name": "All travelers" } ], "genders": [ 1 ], "geo_locations": { "countries": [ "US" ], "regions": [ { "key": "4081" } ], "cities": [ { "key": "777934", "radius": 10, "distance_unit": "mile" } ] }, "interests": [ { "id": "<INTEREST_ID>", "name": "<INTEREST_NAME>" } ], "life_events": [ { "id": 6002714398172, "name": "Newlywed (1 year)" } ], "facebook_positions": [ "feed" ], "publisher_platforms": [ "facebook", "audience_network" ] }' \ -F 'status="PAUSED"' \ -F 'access_token=<ACCESS_TOKEN>' \ https://graph.facebook.com/v21.0/act_<AD_ACCOUNT_ID>/adsets
'use strict'; const bizSdk = require('facebook-nodejs-business-sdk'); const AdAccount = bizSdk.AdAccount; const AdSet = bizSdk.AdSet; const access_token = '<ACCESS_TOKEN>'; const app_secret = '<APP_SECRET>'; const app_id = '<APP_ID>'; const id = '<AD_ACCOUNT_ID>'; const api = bizSdk.FacebookAdsApi.init(access_token); const showDebugingInfo = true; // Setting this to true shows more debugging info. if (showDebugingInfo) { api.setDebug(true); } const logApiCallResult = (apiCallName, data) => { console.log(apiCallName); if (showDebugingInfo) { console.log('Data:' + JSON.stringify(data)); } }; let fields, params; fields = [ ]; params = { 'name' : 'My First AdSet', 'lifetime_budget' : '20000', 'start_time' : '2024-07-27T00:46:29-0700', 'end_time' : '2024-08-03T00:46:29-0700', 'campaign_id' : '<adCampaignLinkClicksID>', 'bid_amount' : '500', 'billing_event' : 'IMPRESSIONS', 'optimization_goal' : 'POST_ENGAGEMENT', 'targeting' : {'age_min':20,'age_max':24,'behaviors':[{'id':6002714895372,'name':'All travelers'}],'genders':[1],'geo_locations':{'countries':['US'],'regions':[{'key':'4081'}],'cities':[{'key':'777934','radius':10,'distance_unit':'mile'}]},'interests':[{'id':'<adsInterestID>','name':'<adsInterestName>'}],'life_events':[{'id':6002714398172,'name':'Newlywed (1 year)'}],'facebook_positions':['feed'],'publisher_platforms':['facebook','audience_network']}, 'status' : 'PAUSED', }; const adsets = (new AdAccount(id)).createAdSet( fields, params ); logApiCallResult('adsets api call complete.', adsets);
require __DIR__ . '/vendor/autoload.php'; use FacebookAds\Object\AdAccount; use FacebookAds\Object\AdSet; use FacebookAds\Api; use FacebookAds\Logger\CurlLogger; $access_token = '<ACCESS_TOKEN>'; $app_secret = '<APP_SECRET>'; $app_id = '<APP_ID>'; $id = '<AD_ACCOUNT_ID>'; $api = Api::init($app_id, $app_secret, $access_token); $api->setLogger(new CurlLogger()); $fields = array( ); $params = array( 'name' => 'My First AdSet', 'lifetime_budget' => '20000', 'start_time' => '2024-07-27T00:46:29-0700', 'end_time' => '2024-08-03T00:46:29-0700', 'campaign_id' => '<adCampaignLinkClicksID>', 'bid_amount' => '500', 'billing_event' => 'IMPRESSIONS', 'optimization_goal' => 'POST_ENGAGEMENT', 'targeting' => array('age_min' => 20,'age_max' => 24,'behaviors' => array(array('id' => 6002714895372,'name' => 'All travelers')),'genders' => array(1),'geo_locations' => array('countries' => array('US'),'regions' => array(array('key' => '4081')),'cities' => array(array('key' => '777934','radius' => 10,'distance_unit' => 'mile'))),'interests' => array(array('id' => '<adsInterestID>','name' => '<adsInterestName>')),'life_events' => array(array('id' => 6002714398172,'name' => 'Newlywed (1 year)')),'facebook_positions' => array('feed'),'publisher_platforms' => array('facebook','audience_network')), 'status' => 'PAUSED', ); echo json_encode((new AdAccount($id))->createAdSet( $fields, $params )->exportAllData(), JSON_PRETTY_PRINT);
from facebook_business.adobjects.adaccount import AdAccount from facebook_business.adobjects.adset import AdSet from facebook_business.api import FacebookAdsApi access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<AD_ACCOUNT_ID>' FacebookAdsApi.init(access_token=access_token) fields = [ ] params = { 'name': 'My First AdSet', 'lifetime_budget': '20000', 'start_time': '2024-07-27T00:46:29-0700', 'end_time': '2024-08-03T00:46:29-0700', 'campaign_id': '<adCampaignLinkClicksID>', 'bid_amount': '500', 'billing_event': 'IMPRESSIONS', 'optimization_goal': 'POST_ENGAGEMENT', 'targeting': {'age_min':20,'age_max':24,'behaviors':[{'id':6002714895372,'name':'All travelers'}],'genders':[1],'geo_locations':{'countries':['US'],'regions':[{'key':'4081'}],'cities':[{'key':'777934','radius':10,'distance_unit':'mile'}]},'interests':[{'id':'<adsInterestID>','name':'<adsInterestName>'}],'life_events':[{'id':6002714398172,'name':'Newlywed (1 year)'}],'facebook_positions':['feed'],'publisher_platforms':['facebook','audience_network']}, 'status': 'PAUSED', } print AdAccount(id).create_ad_set( fields=fields, params=params, )
import com.facebook.ads.sdk.*; import java.io.File; import java.util.Arrays; public class SAMPLE_CODE_EXAMPLE { public static void main (String args[]) throws APIException { String access_token = \"<ACCESS_TOKEN>\"; String app_secret = \"<APP_SECRET>\"; String app_id = \"<APP_ID>\"; String id = \"<AD_ACCOUNT_ID>\"; APIContext context = new APIContext(access_token).enableDebug(true); new AdAccount(id, context).createAdSet() .setName(\"My First AdSet\") .setLifetimeBudget(20000L) .setStartTime(\"2024-07-27T00:46:29-0700\") .setEndTime(\"2024-08-03T00:46:29-0700\") .setCampaignId(\"<adCampaignLinkClicksID>\") .setBidAmount(500L) .setBillingEvent(AdSet.EnumBillingEvent.VALUE_IMPRESSIONS) .setOptimizationGoal(AdSet.EnumOptimizationGoal.VALUE_POST_ENGAGEMENT) .setTargeting( new Targeting() .setFieldAgeMax(24L) .setFieldAgeMin(20L) .setFieldBehaviors(Arrays.asList( new IDName() .setFieldId(6002714895372L) .setFieldName(\"All travelers\") )) .setFieldFacebookPositions(Arrays.asList(\"feed\")) .setFieldGenders(Arrays.asList(1L)) .setFieldGeoLocations( new TargetingGeoLocation() .setFieldCities(Arrays.asList( new TargetingGeoLocationCity() .setFieldDistanceUnit(\"mile\") .setFieldKey(\"777934\") .setFieldRadius(10L) )) .setFieldCountries(Arrays.asList(\"US\")) .setFieldRegions(Arrays.asList( new TargetingGeoLocationRegion() .setFieldKey(\"4081\") )) ) .setFieldInterests(Arrays.asList( new IDName() .setFieldId(\"<adsInterestID>\") .setFieldName(\"<adsInterestName>\") )) .setFieldLifeEvents(Arrays.asList( new IDName() .setFieldId(6002714398172L) .setFieldName(\"Newlywed (1 year)\") )) .setFieldPublisherPlatforms(Arrays.asList(\"facebook\", \"audience_network\")) ) .setStatus(AdSet.EnumStatus.VALUE_PAUSED) .execute(); } }
require 'facebook_ads' access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<AD_ACCOUNT_ID>' FacebookAds.configure do |config| config.access_token = access_token config.app_secret = app_secret end ad_account = FacebookAds::AdAccount.get(id) adsets = ad_account.adsets.create({ name: 'My First AdSet', lifetime_budget: '20000', start_time: '2024-07-27T00:46:29-0700', end_time: '2024-08-03T00:46:29-0700', campaign_id: '<adCampaignLinkClicksID>', bid_amount: '500', billing_event: 'IMPRESSIONS', optimization_goal: 'POST_ENGAGEMENT', targeting: {'age_min':20,'age_max':24,'behaviors':[{'id':6002714895372,'name':'All travelers'}],'genders':[1],'geo_locations':{'countries':['US'],'regions':[{'key':'4081'}],'cities':[{'key':'777934','radius':10,'distance_unit':'mile'}]},'interests':[{'id':'<adsInterestID>','name':'<adsInterestName>'}],'life_events':[{'id':6002714398172,'name':'Newlywed (1 year)'}],'facebook_positions':['feed'],'publisher_platforms':['facebook','audience_network']}, status: 'PAUSED', })

É possível listar todos os conjuntos de anúncios dentro de uma campanha fazendo uma solicitação para o seguinte caminho, especificando os campos e status que deseja:

curl -X GET \ -d 'fields="name,start_time,end_time,daily_budget,lifetime_budget"' \ -d 'access_token=<ACCESS_TOKEN>' \ https://graph.facebook.com/v21.0/<AD_CAMPAIGN_ID>/adsets
'use strict'; const bizSdk = require('facebook-nodejs-business-sdk'); const Campaign = bizSdk.Campaign; const AdSet = bizSdk.AdSet; const access_token = '<ACCESS_TOKEN>'; const app_secret = '<APP_SECRET>'; const app_id = '<APP_ID>'; const id = '<AD_CAMPAIGN_ID>'; const api = bizSdk.FacebookAdsApi.init(access_token); const showDebugingInfo = true; // Setting this to true shows more debugging info. if (showDebugingInfo) { api.setDebug(true); } const logApiCallResult = (apiCallName, data) => { console.log(apiCallName); if (showDebugingInfo) { console.log('Data:' + JSON.stringify(data)); } }; let fields, params; fields = [ 'name', 'start_time', 'end_time', 'daily_budget', 'lifetime_budget', ]; params = { }; const adsetss = (new Campaign(id)).getAdSets( fields, params ); logApiCallResult('adsetss api call complete.', adsetss);
require __DIR__ . '/vendor/autoload.php'; use FacebookAds\Object\Campaign; use FacebookAds\Object\AdSet; use FacebookAds\Api; use FacebookAds\Logger\CurlLogger; $access_token = '<ACCESS_TOKEN>'; $app_secret = '<APP_SECRET>'; $app_id = '<APP_ID>'; $id = '<AD_CAMPAIGN_ID>'; $api = Api::init($app_id, $app_secret, $access_token); $api->setLogger(new CurlLogger()); $fields = array( 'name', 'start_time', 'end_time', 'daily_budget', 'lifetime_budget', ); $params = array( ); echo json_encode((new Campaign($id))->getAdSets( $fields, $params )->getResponse()->getContent(), JSON_PRETTY_PRINT);
from facebook_business.adobjects.campaign import Campaign from facebook_business.adobjects.adset import AdSet from facebook_business.api import FacebookAdsApi access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<AD_CAMPAIGN_ID>' FacebookAdsApi.init(access_token=access_token) fields = [ 'name', 'start_time', 'end_time', 'daily_budget', 'lifetime_budget', ] params = { } print Campaign(id).get_ad_sets( fields=fields, params=params, )
import com.facebook.ads.sdk.*; import java.io.File; import java.util.Arrays; public class SAMPLE_CODE_EXAMPLE { public static void main (String args[]) throws APIException { String access_token = \"<ACCESS_TOKEN>\"; String app_secret = \"<APP_SECRET>\"; String app_id = \"<APP_ID>\"; String id = \"<AD_CAMPAIGN_ID>\"; APIContext context = new APIContext(access_token).enableDebug(true); new Campaign(id, context).getAdSets() .requestNameField() .requestStartTimeField() .requestEndTimeField() .requestDailyBudgetField() .requestLifetimeBudgetField() .execute(); } }
require 'facebook_ads' access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<AD_CAMPAIGN_ID>' FacebookAds.configure do |config| config.access_token = access_token config.app_secret = app_secret end campaign = FacebookAds::Campaign.get(id) adsetss = campaign.adsets({ fields: { 'name''start_time''end_time''daily_budget''lifetime_budget' }, })

Anúncios

Um objeto de anúncio contém todas as informações necessárias para exibir um anúncio no Facebook, incluindo o criativo.

curl -X POST \ -F 'name="My Ad"' \ -F 'adset_id="<AD_SET_ID>"' \ -F 'creative={ "creative_id": "<CREATIVE_ID>" }' \ -F 'status="PAUSED"' \ -F 'access_token=<ACCESS_TOKEN>' \ https://graph.facebook.com/v21.0/act_<AD_ACCOUNT_ID>/ads
'use strict'; const bizSdk = require('facebook-nodejs-business-sdk'); const AdAccount = bizSdk.AdAccount; const Ad = bizSdk.Ad; const access_token = '<ACCESS_TOKEN>'; const app_secret = '<APP_SECRET>'; const app_id = '<APP_ID>'; const id = '<AD_ACCOUNT_ID>'; const api = bizSdk.FacebookAdsApi.init(access_token); const showDebugingInfo = true; // Setting this to true shows more debugging info. if (showDebugingInfo) { api.setDebug(true); } const logApiCallResult = (apiCallName, data) => { console.log(apiCallName); if (showDebugingInfo) { console.log('Data:' + JSON.stringify(data)); } }; let fields, params; fields = [ ]; params = { 'name' : 'My Ad', 'adset_id' : '<adSetID>', 'creative' : {'creative_id':'<adCreativeID>'}, 'status' : 'PAUSED', }; const ads = (new AdAccount(id)).createAd( fields, params ); logApiCallResult('ads api call complete.', ads);
require __DIR__ . '/vendor/autoload.php'; use FacebookAds\Object\AdAccount; use FacebookAds\Object\Ad; use FacebookAds\Api; use FacebookAds\Logger\CurlLogger; $access_token = '<ACCESS_TOKEN>'; $app_secret = '<APP_SECRET>'; $app_id = '<APP_ID>'; $id = '<AD_ACCOUNT_ID>'; $api = Api::init($app_id, $app_secret, $access_token); $api->setLogger(new CurlLogger()); $fields = array( ); $params = array( 'name' => 'My Ad', 'adset_id' => '<adSetID>', 'creative' => array('creative_id' => '<adCreativeID>'), 'status' => 'PAUSED', ); echo json_encode((new AdAccount($id))->createAd( $fields, $params )->exportAllData(), JSON_PRETTY_PRINT);
from facebook_business.adobjects.adaccount import AdAccount from facebook_business.adobjects.ad import Ad from facebook_business.api import FacebookAdsApi access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<AD_ACCOUNT_ID>' FacebookAdsApi.init(access_token=access_token) fields = [ ] params = { 'name': 'My Ad', 'adset_id': '<adSetID>', 'creative': {'creative_id':'<adCreativeID>'}, 'status': 'PAUSED', } print AdAccount(id).create_ad( fields=fields, params=params, )
import com.facebook.ads.sdk.*; import java.io.File; import java.util.Arrays; public class SAMPLE_CODE_EXAMPLE { public static void main (String args[]) throws APIException { String access_token = \"<ACCESS_TOKEN>\"; String app_secret = \"<APP_SECRET>\"; String app_id = \"<APP_ID>\"; String id = \"<AD_ACCOUNT_ID>\"; APIContext context = new APIContext(access_token).enableDebug(true); new AdAccount(id, context).createAd() .setName(\"My Ad\") .setAdsetId(<adSetID>L) .setCreative( new AdCreative() .setFieldId(\"<adCreativeID>\") ) .setStatus(Ad.EnumStatus.VALUE_PAUSED) .execute(); } }
require 'facebook_ads' access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<AD_ACCOUNT_ID>' FacebookAds.configure do |config| config.access_token = access_token config.app_secret = app_secret end ad_account = FacebookAds::AdAccount.get(id) ads = ad_account.ads.create({ name: 'My Ad', adset_id: '<adSetID>', creative: {'creative_id':'<adCreativeID>'}, status: 'PAUSED', })

Para visualizar uma prévia do seu anúncio, consulte nosso guia.

Por fim, se quiser listar todos os anúncios de um conjunto, é possível fazer uma solicitação para o seguinte caminho, especificando os campos que deseja recuperar:

use FacebookAds\Object\AdSet;
use FacebookAds\Object\Values\ArchivableCrudObjectEffectiveStatuses;
use FacebookAds\Object\Fields\AdFields;

$adset = new AdSet(<AD_SET_ID>);
$ads = $adset->getAds(array(
  AdFields::NAME,
  AdFields::CONFIGURED_STATUS,
  AdFields::EFFECTIVE_STATUS,
  AdFields::CREATIVE,
), array(
  AdFields::EFFECTIVE_STATUS => array(
    ArchivableCrudObjectEffectiveStatuses::ACTIVE,
    ArchivableCrudObjectEffectiveStatuses::PAUSED,
    ArchivableCrudObjectEffectiveStatuses::PENDING_REVIEW,
    ArchivableCrudObjectEffectiveStatuses::PREAPPROVED,
  ),
));
from facebookads.adobjects.adset import AdSet
from facebookads.adobjects.ad import Ad

fields = [
    Ad.Field.name,
    Ad.Field.configured_status,
    Ad.Field.effective_status,
    Ad.Field.creative,
]

params = {
    Ad.Field.effective_status: [
        'ACTIVE',
        'PAUSED',
        'PENDING_REVIEW',
        'PREAPPROVED',
    ],
}

ad_set = AdSet(<AD_SET_ID>)
ads = ad_set.get_ads(fields=fields, params=params)
APINodeList<Ad> ads = new AdSet(<AD_SET_ID>, context).getAds()
  .setEffectiveStatus("[\"ACTIVE\",\"PAUSED\",\"PENDING_REVIEW\",\"PREAPPROVED\"]")
  .requestNameField()
  .requestConfiguredStatusField()
  .requestEffectiveStatusField()
  .requestCreativeField()
  .execute();
curl -G \
  --data-urlencode 'effective_status=[ 
    "ACTIVE", 
    "PAUSED", 
    "PENDING_REVIEW", 
    "PREAPPROVED" 
  ]' \
  -d 'fields=name,configured_status,effective_status,creative' \
  -d 'access_token=<ACCESS_TOKEN>' \
  https://graph.facebook.com/v2.11/<AD_SET_ID>/ads

É possível que o número total de anúncios seja maior do que o número que deseja mostrar em uma única página. Nesse caso, será preciso especificar o campo limit como o número de itens que deseja recuperar e depois paginar por meio dos itens restantes.

A paginação é realizada usando os cursores retornados como parte da resposta:

"paging": {
  "previous" : "https://graph.facebook.com/...",
  "next": "https://graph.facebook.com/...", 
  "cursors": {
    "before": "NjAxNjc3NTU1ODMyNw==", 
    "after": "NjAxMTc0NTU2MjcyNw=="
  }

Se houver páginas adicionais para recuperar, a resposta incluirá os campos previous e next, e estas URLs poderão ser chamadas para recuperar essas páginas de dados. Leia mais sobre paginação baseada em cursor.