Criar um anúncio responsivo de display

Os anúncios responsivos de display são o tipo recomendado nas campanhas inteligentes de display. Para criar um anúncio responsivo de display, é preciso criar um novo objeto ResponsiveDisplayAdInfo e defini-lo como um objeto AdGroupAd.

ResponsiveDisplayAdInfo permite reutilizar recursos criados anteriormente na sua conta para definir muitos campos, como:

  • marketing_images
  • square_marketing_images
  • headlines
  • long_headline
  • descriptions
  • youtube_videos

Consulte ResponsiveDisplayAdInfo para as especificações sobre imagens e textos que podem ser usados para criar um recurso para cada campo. Para ver mais detalhes sobre recursos, consulte o guia do desenvolvedor Recursos.

Exemplo de código

Criar o anúncio responsivo de display

O snippet a seguir cria um anúncio responsivo de display, além de instanciar um recurso de imagem e atribuir o anúncio a um novo anúncio do grupo.

Java

private static void createResponsiveDisplayAd(
    GoogleAdsClient googleAdsClient,
    long customerId,
    String adGroupResourceName,
    String marketingImageAssetResourceName,
    String squareMarketingImageAssetResourceName)
    throws IOException {
  // Creates a new image asset for marketing image and square marketing image if there are no
  // asset resource names specified.
  if (marketingImageAssetResourceName == null) {
    marketingImageAssetResourceName =
        createImageAsset(googleAdsClient, customerId, MARKETING_IMAGE_URL, "Marketing Image");
  }
  if (squareMarketingImageAssetResourceName == null) {
    squareMarketingImageAssetResourceName =
        createImageAsset(
            googleAdsClient, customerId, SQUARE_MARKETING_IMAGE_URL, "Square Marketing Image");
  }

  // Creates a responsive display ad info.
  ResponsiveDisplayAdInfo responsiveDisplayAdInfo =
      ResponsiveDisplayAdInfo.newBuilder()
          // Sets some basic required information for the responsive display ad.
          .addHeadlines(AdTextAsset.newBuilder().setText("Travel"))
          .setLongHeadline(AdTextAsset.newBuilder().setText("Travel the World"))
          .addDescriptions(AdTextAsset.newBuilder().setText("Take to the air!"))
          .setBusinessName("Google")
          // Sets the marketing image and square marketing image to the previously created image
          // assets.
          .addMarketingImages(AdImageAsset.newBuilder().setAsset(marketingImageAssetResourceName))
          .addSquareMarketingImages(
              AdImageAsset.newBuilder().setAsset(squareMarketingImageAssetResourceName))
          // Optional: Sets call to action text, price prefix, and promotion text.
          .setCallToActionText("Shop Now")
          .setPricePrefix("as low as")
          .setPromoText("Free shipping!")
          .build();

  // Creates an ad group ad with the created responsive display ad info.
  AdGroupAd adGroupAd =
      AdGroupAd.newBuilder()
          .setAdGroup(adGroupResourceName)
          .setStatus(AdGroupAdStatus.PAUSED)
          .setAd(
              Ad.newBuilder()
                  .addFinalUrls("https://www.example.com")
                  .setResponsiveDisplayAd(responsiveDisplayAdInfo))
          .build();

  // Creates the operation.
  AdGroupAdOperation operation = AdGroupAdOperation.newBuilder().setCreate(adGroupAd).build();

  // Creates the ad group ad service client.
  try (AdGroupAdServiceClient adGroupAdServiceClient =
      googleAdsClient.getLatestVersion().createAdGroupAdServiceClient()) {
    // Adds the responsive display ad.
    MutateAdGroupAdsResponse response =
        adGroupAdServiceClient.mutateAdGroupAds(
            Long.toString(customerId), ImmutableList.of(operation));
    // Displays the response.
    System.out.printf(
        "Added ad group ad with resource name '%s'.%n", response.getResults(0).getResourceName());
  }
}
      

C#

private static string CreateResponsiveDisplayAd(GoogleAdsClient client, long customerId,
    string adGroupResourceName, string marketingImageAssetResourceName,
    string squareMarketingImageAssetResourceName)
{
    // Get the AdGroupAdServiceClient.
    AdGroupAdServiceClient adGroupAdService =
        client.GetService(Services.V11.AdGroupAdService);

    // Creates a responsive display ad info.
    ResponsiveDisplayAdInfo responsiveDisplayAdInfo = new ResponsiveDisplayAdInfo()
    {
        // Sets some basic required information for the responsive display ad.
        Headlines = { new AdTextAsset() { Text = "Travel" } },
        LongHeadline = new AdTextAsset() { Text = "Travel the World" },
        Descriptions = { new AdTextAsset() { Text = "Take to the air!" } },
        BusinessName = "Google",

        // Sets the marketing image and square marketing image to the previously created
        // image assets.
        MarketingImages =
        {
            new AdImageAsset() { Asset = marketingImageAssetResourceName }
        },
        SquareMarketingImages =
        {
            new AdImageAsset() { Asset = squareMarketingImageAssetResourceName }
        },

        // Optional: Sets call to action text, price prefix and promotion text.
        CallToActionText = "Shop Now",
        PricePrefix = "as low as",
        PromoText = "Free shipping!"
    };

    // Creates an ad group ad with the created responsive display ad info.
    AdGroupAd adGroupAd = new AdGroupAd()
    {
        AdGroup = adGroupResourceName,
        Status = AdGroupAdStatus.Paused,
        Ad = new Ad()
        {
            FinalUrls = { "https://www.example.com" },
            ResponsiveDisplayAd = responsiveDisplayAdInfo
        }
    };

    // Creates an ad group ad operation.
    AdGroupAdOperation operation = new AdGroupAdOperation()
    {
        Create = adGroupAd
    };

    // Issues a mutate request to add the ad.
    MutateAdGroupAdsResponse response =
        adGroupAdService.MutateAdGroupAds(customerId.ToString(), new[] { operation });

    string adGroupAdResourceName = response.Results.First().ResourceName;

    // Print out some information about the added ad group ad.
    Console.WriteLine($"Added ad group ad with resource name = '{adGroupAdResourceName}'.");

    return adGroupAdResourceName;
}
      

PHP

private static function createResponsiveDisplayAd(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    string $adGroupResourceName,
    ?int $marketingImageAssetId,
    ?int $squareMarketingImageAssetId
) {
    // Creates a new image asset for marketing image and square marketing image if there are no
    // assets' IDs specified.
    $marketingImageAssetResourceName = $marketingImageAssetId
        ? ResourceNames::forAsset($customerId, $marketingImageAssetId)
        : self::createImageAsset(
            $googleAdsClient,
            $customerId,
            self::MARKETING_IMAGE_URL,
            'Marketing Image'
        );
    $squareMarketingImageAssetResourceName = $squareMarketingImageAssetId
        ? ResourceNames::forAsset($customerId, $squareMarketingImageAssetId)
        : self::createImageAsset(
            $googleAdsClient,
            $customerId,
            self::SQUARE_MARKETING_IMAGE_URL,
            'Square Marketing Image'
        );

    // Creates a responsive display ad info.
    $responsiveDisplayAdInfo = new ResponsiveDisplayAdInfo([
        // Sets some basic required information for the responsive display ad.
        'headlines' => [new AdTextAsset(['text' => 'Travel'])],
        'long_headline' => new AdTextAsset(['text' => 'Travel the World']),
        'descriptions' => [new AdTextAsset(['text' => 'Take to the air!'])],
        'business_name' => 'Google',
        // Sets the marketing image and square marketing image to the previously created
        // image assets.
        'marketing_images' => [
            new AdImageAsset(['asset' => $marketingImageAssetResourceName])
        ],
        'square_marketing_images' => [
            new AdImageAsset(['asset' => $squareMarketingImageAssetResourceName])
        ],
        // Optional: Sets call to action text, price prefix and promotion text.
        'call_to_action_text' => 'Shop Now',
        'price_prefix' => 'as low as',
        'promo_text' => 'Free shipping!',
    ]);

    // Creates an ad group ad with the created responsive display ad info.
    $adGroupAd = new AdGroupAd([
        'ad_group' => $adGroupResourceName,
        'status' => AdGroupAdStatus::PAUSED,
        'ad' => new Ad([
            'final_urls' => ['https://www.example.com'],
            'responsive_display_ad' => $responsiveDisplayAdInfo
        ])
    ]);

    // Creates an ad group ad operation.
    $adGroupAdOperation = new AdGroupAdOperation();
    $adGroupAdOperation->setCreate($adGroupAd);

    // Issues a mutate request to add the ad group ad.
    $adGroupAdServiceClient = $googleAdsClient->getAdGroupAdServiceClient();
    /** @var MutateAdGroupAdsResponse $adGroupAdResponse */
    $adGroupAdResponse = $adGroupAdServiceClient->mutateAdGroupAds(
        $customerId,
        [$adGroupAdOperation]
    );

    // Prints out some information about the newly created ad.
    $adGroupAdResourceName = $adGroupAdResponse->getResults()[0]->getResourceName();
    printf("Added ad group ad named '%s'.%s", $adGroupAdResourceName, PHP_EOL);
}
      

Python

def create_responsive_display_ad(
    client,
    customer_id,
    ad_group_resource_name,
    marketing_image_asset_id,
    square_marketing_image_asset_id,
):
    ad_group_ad_service = client.get_service("AdGroupAdService")
    ad_group_ad_operation = client.get_type("AdGroupAdOperation")
    ad_group_ad = ad_group_ad_operation.create
    ad_group_ad.ad_group = ad_group_resource_name
    ad_group_ad.status = client.enums.AdGroupAdStatusEnum.PAUSED
    ad = ad_group_ad.ad
    ad.final_urls.append("https://www.example.com")
    responsive_display_ad = ad.responsive_display_ad

    # Add a headline
    headline = client.get_type("AdTextAsset")
    headline.text = "Travel"
    responsive_display_ad.headlines.append(headline)

    # Add the long headline
    responsive_display_ad.long_headline.text = "Travel the World"

    # Add a description
    description = client.get_type("AdTextAsset")
    description.text = "Take to the air!"
    responsive_display_ad.descriptions.append(description)

    # Add the business name
    responsive_display_ad.business_name = "Google"

    asset_service = client.get_service("AssetService")
    # Add a marketing image
    marketing_image = client.get_type("AdImageAsset")
    marketing_image.asset = asset_service.asset_path(
        customer_id, marketing_image_asset_id
    )
    responsive_display_ad.marketing_images.append(marketing_image)

    # Add a square marketing image
    square_marketing_image = client.get_type("AdImageAsset")
    square_marketing_image.asset = asset_service.asset_path(
        customer_id, square_marketing_image_asset_id
    )
    responsive_display_ad.square_marketing_images.append(square_marketing_image)

    # Add the call to action
    responsive_display_ad.call_to_action_text = "Shop Now"

    # Add the price prefix
    responsive_display_ad.price_prefix = "as low as"

    # Add the promo text
    responsive_display_ad.promo_text = "Free shipping!"

    try:
        ad_group_ad_response = ad_group_ad_service.mutate_ad_group_ads(
            customer_id=customer_id, operations=[ad_group_ad_operation]
        )
    except GoogleAdsException as ex:
        handle_googleads_exception(ex)

    return ad_group_ad_response.results[0].resource_name
      

Ruby

def create_responsive_display_ad(
  client,
  customer_id,
  ad_group,
  marketing_image_asset_resource_name,
  square_marketing_image_asset_resource_name
)
  marketing_image_url = 'https://gaagl.page.link/Eit5'
  square_marketing_image_url = 'https://gaagl.page.link/bjYi'

  # Creates a new image asset for marketing image and square marketing image
  # if there are no assets' resource names specified.
  marketing_image_asset_resource_name ||= create_image_asset(
    client,
    customer_id,
    marketing_image_url,
    'Marketing Image',
  )
  square_marketing_image_asset_resource_name ||= create_image_asset(
    client,
    customer_id,
    square_marketing_image_url,
    'Square Marketing Image',
  )

  # Creates an ad group ad operation.
  operation = client.operation.create_resource.ad_group_ad do |aga|
    aga.ad_group = ad_group
    aga.status = :PAUSED
    aga.ad = client.resource.ad do |a|
      a.final_urls << "https://www.example.com"
      a.responsive_display_ad = client.resource.responsive_display_ad_info do |rda|
        # Sets some basic required information for the responsive display ad.
        rda.headlines << client.resource.ad_text_asset do |ata|
          ata.text = 'Travel'
        end
        rda.long_headline = client.resource.ad_text_asset do |ata|
          ata.text = 'Travel the World'
        end
        rda.descriptions << client.resource.ad_text_asset do |ata|
          ata.text = 'Take to the air!'
        end
        rda.business_name = 'Google'
        # Sets the marketing image and square marketing image to the previously
        # created image assets.
        rda.marketing_images << client.resource.ad_image_asset do |aia|
          aia.asset = marketing_image_asset_resource_name
        end
        rda.square_marketing_images << client.resource.ad_image_asset do |aia|
          aia.asset = square_marketing_image_asset_resource_name
        end
        # Optional: Sets call to action text, price prefix and promotion text.
        rda.call_to_action_text = 'Shop Now'
        rda.price_prefix = 'as low as'
        rda.promo_text = 'Free shipping!'
      end
    end
  end

  # Issues a mutate request to add the ad group ad.
  response = client.service.ad_group_ad.mutate_ad_group_ads(
    customer_id: customer_id,
    operations: [operation],
  )

  # Prints out some information about the newly created ad.
  resource_name = response.results.first.resource_name
  puts "Added ad group ad named #{resource_name}"

  resource_name
end
      

Perl

sub create_responsive_display_ad {
  my ($api_client, $customer_id, $ad_group_resource_name,
    $marketing_image_asset_id, $square_marketing_image_asset_id)
    = @_;

  # Create a new image asset for marketing image and square marketing image if
  # there are no assets' IDs specified.
  my $marketing_image_asset_resource_name =
    defined $marketing_image_asset_id
    ? Google::Ads::GoogleAds::V11::Utils::ResourceNames::asset($customer_id,
    $marketing_image_asset_id)
    : create_image_asset($api_client, $customer_id, MARKETING_IMAGE_URL,
    "Marketing Image");

  my $square_marketing_image_asset_resource_name =
    defined $square_marketing_image_asset_id
    ? Google::Ads::GoogleAds::V11::Utils::ResourceNames::asset($customer_id,
    $square_marketing_image_asset_id)
    : create_image_asset($api_client, $customer_id, SQUARE_MARKETING_IMAGE_URL,
    "Square Marketing Image");

  # Create a responsive display ad info.
  my $responsive_display_ad_info =
    Google::Ads::GoogleAds::V11::Common::ResponsiveDisplayAdInfo->new({
      # Set some basic required information for the responsive display ad.
      headlines => [
        Google::Ads::GoogleAds::V11::Common::AdTextAsset->new({
            text => "Travel"
          })
      ],
      longHeadline => Google::Ads::GoogleAds::V11::Common::AdTextAsset->new({
          text => "Travel the World"
        }
      ),
      descriptions => [
        Google::Ads::GoogleAds::V11::Common::AdTextAsset->new({
            text => "Take to the air!"
          })
      ],
      businessName => "Google",
      # Set the marketing image and square marketing image to the previously
      # created image assets.
      marketingImages => [
        Google::Ads::GoogleAds::V11::Common::AdImageAsset->new({
            asset => $marketing_image_asset_resource_name
          })
      ],
      squareMarketingImages => [
        Google::Ads::GoogleAds::V11::Common::AdImageAsset->new({
            asset => $square_marketing_image_asset_resource_name
          })
      ],
      # Optional: Set call to action text, price prefix and promotion text.
      callToActionText => "Shop Now",
      pricePrefix      => "as low as",
      promoText        => "Free shipping!"
    });

  # Create an ad group ad with the created responsive display ad info.
  my $ad_group_ad = Google::Ads::GoogleAds::V11::Resources::AdGroupAd->new({
      adGroup => $ad_group_resource_name,
      status => Google::Ads::GoogleAds::V11::Enums::AdGroupAdStatusEnum::PAUSED,
      ad     => Google::Ads::GoogleAds::V11::Resources::Ad->new({
          finalUrls           => ["https://www.example.com"],
          responsiveDisplayAd => $responsive_display_ad_info
        })});

  # Create an ad group ad operation.
  my $ad_group_ad_operation =
    Google::Ads::GoogleAds::V11::Services::AdGroupAdService::AdGroupAdOperation
    ->new({
      create => $ad_group_ad
    });

  # Issue a mutate request to add the ad group ad.
  my $ad_group_ads_response = $api_client->AdGroupAdService()->mutate({
      customerId => $customer_id,
      operations => [$ad_group_ad_operation]});

  # Print out some information about the newly created ad.
  my $ad_group_ad_resource_name =
    $ad_group_ads_response->{results}[0]{resourceName};
  printf "Added ad group ad named '%s'.\n", $ad_group_ad_resource_name;
}
      

Criar o recurso de imagem do anúncio

Veja a função que cria a imagem asset:

Java

private static String createImageAsset(
    GoogleAdsClient googleAdsClient, long customerId, String imageUrl, String imageName)
    throws IOException {
  // Creates a media file.
  byte[] assetBytes = ByteStreams.toByteArray(new URL(imageUrl).openStream());
  Asset asset =
      Asset.newBuilder()
          .setName(imageName)
          .setType(AssetType.IMAGE)
          .setImageAsset(ImageAsset.newBuilder().setData(ByteString.copyFrom(assetBytes)).build())
          .build();

  // Creates an asset operation.
  AssetOperation operation = AssetOperation.newBuilder().setCreate(asset).build();

  // Creates the asset service client.
  try (AssetServiceClient assetServiceClient =
      googleAdsClient.getLatestVersion().createAssetServiceClient()) {
    // Adds the image asset.
    MutateAssetsResponse response =
        assetServiceClient.mutateAssets(Long.toString(customerId), ImmutableList.of(operation));
    String imageResourceName = response.getResults(0).getResourceName();
    System.out.printf("Created image asset with resource name '%s'.%n", imageResourceName);
    return imageResourceName;
  }
}
      

C#

private static string UploadImageAsset(GoogleAdsClient client, long customerId,
    string imageUrl, long width, long height, string imageName)
{
    // Get the AssetServiceClient.
    AssetServiceClient assetService =
        client.GetService(Services.V11.AssetService);

    // Creates an image content.
    byte[] imageContent = MediaUtilities.GetAssetDataFromUrl(imageUrl, client.Config);

    // Creates an image asset.
    ImageAsset imageAsset = new ImageAsset()
    {
        Data = ByteString.CopyFrom(imageContent),
        FileSize = imageContent.Length,
        MimeType = MimeType.ImageJpeg,
        FullSize = new ImageDimension()
        {
            HeightPixels = height,
            WidthPixels = width,
            Url = imageUrl
        }
    };

    // Creates an asset.
    Asset asset = new Asset()
    {
        // Optional: Provide a unique friendly name to identify your asset.
        // If you specify the name field, then both the asset name and the image being
        // uploaded should be unique, and should not match another ACTIVE asset in this
        // customer account.
        // Name = 'Jupiter Trip #' + ExampleUtilities.GetRandomString(),
        Type = AssetType.Image,
        ImageAsset = imageAsset,
        Name = imageName
    };

    // Creates an asset operation.
    AssetOperation operation = new AssetOperation()
    {
        Create = asset
    };

    // Issues a mutate request to add the asset.
    MutateAssetsResponse response =
        assetService.MutateAssets(customerId.ToString(), new[] { operation });

    string assetResourceName = response.Results.First().ResourceName;

    // Print out some information about the added asset.
    Console.WriteLine($"Added asset with resource name = '{assetResourceName}'.");

    return assetResourceName;
}
      

PHP

private static function createImageAsset(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    string $imageUrl,
    string $imageName
) {
    // Creates a media file.
    $asset = new Asset([
        'name' => $imageName,
        'type' => AssetType::IMAGE,
        'image_asset' => new ImageAsset(['data' => file_get_contents($imageUrl)])
    ]);

    // Creates an asset operation.
    $assetOperation = new AssetOperation();
    $assetOperation->setCreate($asset);

    // Issues a mutate request to add the asset.
    $assetServiceClient = $googleAdsClient->getAssetServiceClient();
    $response = $assetServiceClient->mutateAssets($customerId, [$assetOperation]);

    // Prints out information about the newly added asset.
    $assetResourceName = $response->getResults()[0]->getResourceName();
    printf(
        "A new image asset has been added with resource name: '%s'.%s",
        $assetResourceName,
        PHP_EOL
    );

    return $assetResourceName;
}
      

Python

def upload_image_asset(
    client, customer_id, image_url, image_width, image_height, image_name
):
    # Download image from URL
    image_content = requests.get(image_url).content

    asset_operation = client.get_type("AssetOperation")
    asset = asset_operation.create
    # Optional: Provide a unique friendly name to identify your asset. If you
    # specify the name field, then both the asset name and the image being
    # uploaded should be unique, and should not match another ACTIVE asset in
    # this customer account.
    # asset.name = f'Jupiter Trip #{uuid4()}'
    asset_type_enum = client.enums.AssetTypeEnum
    asset.type_ = asset_type_enum.IMAGE
    asset.name = image_name
    image_asset = asset.image_asset
    image_asset.data = image_content
    image_asset.file_size = len(image_content)
    image_asset.mime_type = client.enums.MimeTypeEnum.IMAGE_JPEG
    image_asset.full_size.width_pixels = image_width
    image_asset.full_size.height_pixels = image_height
    image_asset.full_size.url = image_url

    asset_service = client.get_service("AssetService")
    content_type_enum = client.enums.ResponseContentTypeEnum

    request = client.get_type("MutateAssetsRequest")
    request.customer_id = customer_id
    request.operations = [asset_operation]
    # Setting this parameter tells the API to return the Asset object in the
    # response, allowing us to easily retrieve its ID.
    request.response_content_type = content_type_enum.MUTABLE_RESOURCE

    try:
        mutate_asset_response = asset_service.mutate_assets(request=request)
        return mutate_asset_response.results[0].asset.id
    except GoogleAdsException as ex:
        handle_googleads_exception(ex)
      

Ruby

def create_image_asset(client, customer_id, image_url, image_name)
  # Creates an asset operation.
  operation = client.operation.create_resource.asset do |a|
    a.name = image_name
    a.type = :IMAGE
    a.image_asset = client.resource.image_asset do |image|
      image.data = open(image_url) { |f| f.read }
    end
  end

  # Issues a mutate request to add the asset.
  response = client.service.asset.mutate_assets(
    customer_id: customer_id,
    operations: [operation],
  )

  # Prints out information about the newly added asset.
  resource_name = response.results.first.resource_name
  puts "A new image asset has been added with resource name: #{resource_name}"

  resource_name
end
      

Perl

sub create_image_asset {
  my ($api_client, $customer_id, $image_url, $image_name) = @_;

  # Create an asset.
  my $asset = Google::Ads::GoogleAds::V11::Resources::Asset->new({
      name       => $image_name,
      type       => IMAGE,
      imageAsset => Google::Ads::GoogleAds::V11::Common::ImageAsset->new({
          data => get_base64_data_from_url($image_url)})});

  # Create an asset operation.
  my $asset_operation =
    Google::Ads::GoogleAds::V11::Services::AssetService::AssetOperation->new({
      create => $asset
    });

  # Issue a mutate request to add the asset.
  my $assets_response = $api_client->AssetService()->mutate({
      customerId => $customer_id,
      operations => [$asset_operation]});

  # Print out information about the newly added asset.
  my $asset_resource_name = $assets_response->{results}[0]{resourceName};
  printf "A new image asset has been added with resource name: '%s'.\n",
    $asset_resource_name;

  return $asset_resource_name;
}