Ejemplo de código de oportunidades de presupuesto
En este ejemplo se muestra cómo obtener las oportunidades presupuestadas para cada campaña de la cuenta autenticada actual.
Sugerencia
Use el selector de lenguaje en el encabezado de documentación para elegir C#, Java, Php o Python.
Para obtener tokens de acceso y actualización para el usuario de Microsoft Advertising y realizar la primera llamada de servicio mediante la API de Bing Ads, consulte la Guía de inicio rápido . Querrá revisar la guía de introducción y los tutoriales de su lenguaje preferido, por ejemplo, C#, Java, Php y Python.
Los archivos auxiliares para ejemplos de C#, Java, Php y Python están disponibles en GitHub. Puede clonar cada repositorio o reasignar fragmentos de código según sea necesario.
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Threading.Tasks;
using Microsoft.BingAds.V13.AdInsight;
using Microsoft.BingAds.V13.CampaignManagement;
using Microsoft.BingAds;
namespace BingAdsExamplesLibrary.V13
{
/// <summary>
/// How to get the budget opportunities for each campaign in the current authenticated account.
/// </summary>
public class BudgetOpportunities : ExampleBase
{
public override string Description
{
get { return "Budget Opportunities | AdInsight V13"; }
}
public async override Task RunAsync(AuthorizationData authorizationData)
{
try
{
ApiEnvironment environment = ((OAuthDesktopMobileAuthCodeGrant)authorizationData.Authentication).Environment;
AdInsightExampleHelper AdInsightExampleHelper = new AdInsightExampleHelper(
OutputStatusMessageDefault: this.OutputStatusMessage);
AdInsightExampleHelper.AdInsightService = new ServiceClient<IAdInsightService>(
authorizationData: authorizationData,
environment: environment);
CampaignManagementExampleHelper CampaignManagementExampleHelper = new CampaignManagementExampleHelper(
OutputStatusMessageDefault: this.OutputStatusMessage);
CampaignManagementExampleHelper.CampaignManagementService = new ServiceClient<ICampaignManagementService>(
authorizationData: authorizationData,
environment: environment);
OutputStatusMessage("-----\nGetCampaignsByAccountId:");
var campaigns = (await CampaignManagementExampleHelper.GetCampaignsByAccountIdAsync(
accountId: authorizationData.AccountId,
campaignType: AllCampaignTypes,
returnAdditionalFields: CampaignAdditionalField.AdScheduleUseSearcherTimeZone)).Campaigns;
OutputStatusMessage("Campaigns:");
CampaignManagementExampleHelper.OutputArrayOfCampaign(campaigns);
IList<BudgetOpportunity> opportunities = null;
// Get the budget opportunities for each campaign in the current account.
foreach (var campaign in campaigns)
{
if (campaign.Id != null)
{
OutputStatusMessage("-----\nGetBudgetOpportunities:");
opportunities = (await AdInsightExampleHelper.GetBudgetOpportunitiesAsync(
campaignId: (long)campaign.Id)).Opportunities;
OutputStatusMessage("Opportunities:");
AdInsightExampleHelper.OutputArrayOfBudgetOpportunity(opportunities);
}
}
}
// Catch authentication exceptions
catch (OAuthTokenRequestException ex)
{
OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description));
}
// Catch AdInsight service exceptions
catch (FaultException<Microsoft.BingAds.V13.AdInsight.AdApiFaultDetail> ex)
{
OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
}
catch (FaultException<Microsoft.BingAds.V13.AdInsight.ApiFaultDetail> ex)
{
OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
}
// Catch Campaign Management service exceptions
catch (FaultException<Microsoft.BingAds.V13.CampaignManagement.AdApiFaultDetail> ex)
{
OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
}
catch (FaultException<Microsoft.BingAds.V13.CampaignManagement.ApiFaultDetail> ex)
{
OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
}
catch (Exception ex)
{
OutputStatusMessage(ex.Message);
}
}
}
}
package com.microsoft.bingads.examples.v13;
import com.microsoft.bingads.*;
import com.microsoft.bingads.v13.campaignmanagement.*;
import com.microsoft.bingads.v13.adinsight.*;
import java.util.ArrayList;
public class BudgetOpportunities extends ExampleBase {
static ServiceClient<IAdInsightService> AdInsightService;
static ServiceClient<ICampaignManagementService> CampaignService;
public static void main(java.lang.String[] args) {
try
{
authorizationData = getAuthorizationData();
AdInsightExampleHelper.AdInsightService = new ServiceClient<IAdInsightService>(
authorizationData,
API_ENVIRONMENT,
IAdInsightService.class);
CampaignManagementExampleHelper.CampaignManagementService = new ServiceClient<ICampaignManagementService>(
authorizationData,
API_ENVIRONMENT,
ICampaignManagementService.class);
// Get the budget opportunities for each campaign in the current account.
ArrayList<CampaignType> campaignTypes = new ArrayList<CampaignType>();
campaignTypes.add(CampaignType.AUDIENCE);
campaignTypes.add(CampaignType.SHOPPING);
campaignTypes.add(CampaignType.SEARCH);
outputStatusMessage("-----\nGetCampaignsByAccountId:");
GetCampaignsByAccountIdResponse getCampaignsByAccountIdResponse = CampaignManagementExampleHelper.getCampaignsByAccountId(
authorizationData.getAccountId(),
campaignTypes,
null
);
ArrayOfCampaign campaigns = getCampaignsByAccountIdResponse.getCampaigns();
outputStatusMessage("Campaigns:");
CampaignManagementExampleHelper.outputArrayOfCampaign(campaigns);
ArrayOfBudgetOpportunity opportunities = null;
for (Campaign campaign : campaigns.getCampaigns())
{
if (campaign.getId() != null)
{
outputStatusMessage("-----\nGetBudgetOpportunities:");
opportunities = AdInsightExampleHelper.getBudgetOpportunities(
(long)campaign.getId()).getOpportunities();
outputStatusMessage("Opportunities:");
AdInsightExampleHelper.outputArrayOfBudgetOpportunity(opportunities);
}
}
}
catch (Exception ex) {
String faultXml = ExampleExceptionHelper.getBingAdsExceptionFaultXml(ex, System.out);
outputStatusMessage(faultXml);
String message = ExampleExceptionHelper.handleBingAdsSDKException(ex, System.out);
outputStatusMessage(message);
}
}
}
<?php
namespace Microsoft\BingAds\Samples\V13;
// For more information about installing and using the Bing Ads PHP SDK,
// see https://go.microsoft.com/fwlink/?linkid=838593.
require_once __DIR__ . "/../vendor/autoload.php";
include __DIR__ . "/AuthHelper.php";
include __DIR__ . "/AdInsightExampleHelper.php";
include __DIR__ . "/CampaignManagementExampleHelper.php";
use SoapVar;
use SoapFault;
use Exception;
// Specify the Microsoft\BingAds\Auth classes that will be used.
use Microsoft\BingAds\Auth\ServiceClient;
use Microsoft\BingAds\Auth\ServiceClientType;
// Specify the Microsoft\BingAds\Samples classes that will be used.
use Microsoft\BingAds\Samples\V13\AuthHelper;
use Microsoft\BingAds\Samples\V13\AdInsightExampleHelper;
use Microsoft\BingAds\Samples\V13\CampaignManagementExampleHelper;
try
{
// Authenticate user credentials and set the account ID for the sample.
AuthHelper::Authenticate();
print("-----\r\nGetCampaignsByAccountId:\r\n");
$getCampaignsByAccountIdResponse = CampaignManagementExampleHelper::GetCampaignsByAccountId(
$GLOBALS['AuthorizationData']->AccountId,
AuthHelper::CampaignTypes,
AuthHelper::CampaignAdditionalFields
);
$campaigns = $getCampaignsByAccountIdResponse->Campaigns;
print("Campaigns:\r\n");
CampaignManagementExampleHelper::OutputArrayOfCampaign($campaigns);
// Get the budget opportunities for each campaign in the current account.
if(count((array)$campaigns) == 0 || !isset($campaigns->Campaign))
{
return;
}
foreach ($campaigns->Campaign as $campaign)
{
print("-----\r\nGetBudgetOpportunities:\r\n");
$opportunities = AdInsightExampleHelper::GetBudgetOpportunities(
$campaign->Id
)->Opportunities;
AdInsightExampleHelper::OutputArrayOfBudgetOpportunity($opportunities);
}
}
catch (SoapFault $e)
{
printf("-----\r\nFault Code: %s\r\nFault String: %s\r\nFault Detail: \r\n", $e->faultcode, $e->faultstring);
var_dump($e->detail);
print "-----\r\nLast SOAP request/response:\r\n";
print $GLOBALS['Proxy']->GetWsdl() . "\r\n";
print $GLOBALS['Proxy']->GetService()->__getLastRequest()."\r\n";
print $GLOBALS['Proxy']->GetService()->__getLastResponse()."\r\n";
}
catch (Exception $e)
{
// Ignore fault exceptions that we already caught.
if ($e->getPrevious())
{ ; }
else
{
print $e->getCode()." ".$e->getMessage()."\n\n";
print $e->getTraceAsString()."\n\n";
}
}
from auth_helper import *
from adinsight_example_helper import *
from campaignmanagement_example_helper import *
# You must provide credentials in auth_helper.py.
def main(authorization_data):
try:
output_status_message("-----\nGetCampaignsByAccountId:")
campaigns=campaign_service.GetCampaignsByAccountId(
AccountId=authorization_data.account_id,
CampaignType=ALL_CAMPAIGN_TYPES)
output_status_message("Campaigns:")
output_array_of_campaign(campaigns)
# Get the budget opportunities for each campaign in the current account.
for campaign in campaigns['Campaign']:
if campaign.Id is not None:
output_status_message("-----\nGetBudgetOpportunities:")
opportunities=adinsight_service.GetBudgetOpportunities(
CampaignId=campaign.Id)
output_status_message("Opportunities:")
output_array_of_budgetopportunity(opportunities)
except WebFault as ex:
output_webfault_errors(ex)
except Exception as ex:
output_status_message(ex)
# Main execution
if __name__ == '__main__':
print("Loading the web service client proxies...")
authorization_data=AuthorizationData(
account_id=None,
customer_id=None,
developer_token=DEVELOPER_TOKEN,
authentication=None,
)
adinsight_service=ServiceClient(
service='AdInsightService',
version=13,
authorization_data=authorization_data,
environment=ENVIRONMENT,
)
campaign_service=ServiceClient(
service='CampaignManagementService',
version=13,
authorization_data=authorization_data,
environment=ENVIRONMENT,
)
authenticate(authorization_data)
main(authorization_data)