Estructura de las campañas publicitarias

Facebook organiza los anuncios en una estructura que consta de los tres niveles siguientes: campaña, conjunto de anuncios y anuncio. En la API, los desarrolladores tienen acceso a un cuarto nivel denominado “contenido”.

Funcionamiento

Campaña

Estos objetos contienen el objetivo publicitario y uno o varios conjuntos de anuncios. Esto te ayuda a optimizar y medir los resultados de cada objetivo publicitario.

Conjuntos de anuncios

Los conjuntos de anuncios tienen uno o varios anuncios. Tienes que definir el presupuesto y la programación para cada conjunto de anuncios. Crea un conjunto de anuncios para cada audiencia objetivo con la puja; los anuncios del conjunto se dirigen a la misma audiencia con la misma puja. Esto ayuda a controlar la cantidad que gastas en cada audiencia, determinar cuándo verá la audiencia los anuncios y proporciona métricas de cada audiencia.

Anuncios

Contiene el contenido del anuncio. Crea varios anuncios en cada conjunto de anuncios para optimizar la entrega de anuncios en función de diferentes imágenes, enlaces, vídeos, texto o ubicaciones.

Contenido del anuncio

Incluye solo los elementos visuales del anuncio y no puedes cambiarlos una vez creados. Cada cuenta publicitaria tiene una biblioteca de contenido para almacenar el contenido con el objetivo de reutilizarlo en otros anuncios.

Objetivo Programación Presupuesto Pujas Objetivo Contenido

Campaña

Conjunto de anuncios

Anuncio

Asignación entre la nomenclatura pública del objeto y los extremos de la API:

Nombre público Extremo de la API

Campaña

/campaigns

Conjunto de anuncios

/adsets

Anuncio

/ads

Contenido

/adcreatives


Campañas

Documentos de referencia

Una campaña es la estructura organizativa de nivel superior de una cuenta publicitaria y debe representar un único objetivo para un anunciante, por ejemplo, para impulsar la interacción con una publicación de la página. Al establecer el objetivo de la campaña, se aplica la validación de los anuncios añadidos a esa campaña para garantizar que también tengan el objetivo correcto.

En el Administrador de anuncios, mostramos todas las campañas activas y pausadas de una cuenta publicitaria.

Para leer las campañas asociadas a una cuenta específica, debes hacer una solicitud a la conexión de la cuenta publicitaria que usas. De forma predeterminada, solo devolvemos las campañas cuyo estado es ACTIVE o PAUSED, por lo que debes especificar otros estados si es necesario:

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'], })

También mostramos algunos insights generales, tales como las impresiones, los clics y el importe gastado. Para recuperarlos, llama al siguiente extremo y especifica de forma opcional la hora de inicio o finalización:

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

Los objetivos son acciones que quieres que los usuarios hagan cuando vean el anuncio. Tienes que especificar el objetivo elegido durante la creación de la campaña.

Establecer explícitamente el objetivo tiene los siguientes beneficios:

  • Obtienes opciones correctas de seguimiento, optimización y pujas para el anuncio.
  • Puedes ver IU únicas y paneles de análisis para cada objetivo.

La llamada mínima a la API necesaria para crear una campaña es:

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 anuncios

Los conjuntos de anuncios son grupos de anuncios que se usan para configurar el presupuesto y el periodo durante el que los anuncios deben estar publicados. Todos los anuncios incluidos en un conjunto de anuncios deben tener las mismas opciones de segmentación, presupuesto, facturación, objetivo de optimización y duración.

curl -X POST \ -F 'name="My First AdSet"' \ -F 'lifetime_budget=20000' \ -F 'start_time="2024-11-28T07:04:19-0800"' \ -F 'end_time="2024-12-05T07:04:19-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', })

Puedes enumerar todos los conjuntos de anuncios de una campaña con una solicitud a la siguiente ruta; debes especificar los campos y estados que quieres:

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' }, })

Anuncios

Un objeto de anuncio contiene toda la información necesaria para mostrar un anuncio en Facebook, incluido el contenido.

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 obtener una vista previa del anuncio, consulta nuestra guía.

Por último, si quieres enumerar todos los anuncios de un conjunto de anuncios, puedes hacer una solicitud a la siguiente ruta y especificar los campos que quieres 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

Puede que el número total de anuncios sea mayor que el número que quieres mostrar en una sola página. En este caso, debes especificar el campo limit como el número de elementos que quieres recuperar y, a continuación, paginar los elementos restantes.

La paginación se lleva a cabo con los cursores devueltos como parte de la respuesta:

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

Si hay páginas adicionales que recuperar, la respuesta incluye los campos previous y next, y se puede llamar a estas URL para recuperar estas páginas de datos. Obtén más información sobre la paginación basada en cursores.