Sebagai pembeli, Anda dapat melakukan hal berikut:
- Membuat dan mengirimkan materi iklan untuk ditinjau
- Melihat materi iklan yang ada
- Mem-patch materi iklan yang ada
Mengirimkan materi iklan untuk ditinjau
Gunakan buyers.creatives.create
untuk membuat dan mengirimkan materi iklan baru untuk ditinjau.
Anda hanya dapat memanggil buyers.creatives.create
satu kali per materi iklan. Untuk memperbarui
materi iklan yang ada, gunakan
buyers.creatives.patch
.
Anda dapat mengirimkan jenis materi iklan berikut untuk ditinjau:
Sebaiknya gunakan creativeId
unik untuk setiap
materi iklan Anda. Anda dapat menggunakan kembali creativeId
untuk dukungan lama jika materi iklan baru
memiliki format yang berbeda dengan materi iklan yang ada. Metode yang menargetkan materi iklan
tertentu, seperti buyers.creatives.get
, tidak berfungsi jika Anda menetapkan
creativeId
yang sama ke beberapa materi iklan. Jika Anda sudah memiliki materi iklan yang menggunakan
creativeId
yang sama, sebaiknya buat ulang materi iklan tersebut dengan ID unik.
Materi iklan HTML
Berikut ini menunjukkan cara membuat dan mengirimkan materi iklan sederhana dengan konten HTML untuk ditinjau dengan
buyers.creatives.create
.
REST
Permintaan
POST https://realtimebidding.googleapis.com/v1/buyers/<INSERT_ACCOUNT_ID_HERE>/creatives?alt=json Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE> Content-Type: application/json { "advertiserName": "Test", "creativeId": "HTML_Creative_d71e7cd9-8179-4683-ac5c-a203a9c660f2", "declaredAttributes": [ "CREATIVE_TYPE_HTML" ], "declaredClickThroughUrls": [ "http://test.com" ], "declaredRestrictedCategories": [], "declaredVendorIds": [], "html": { "snippet": "<iframe marginwidth=0 marginheight=0 height=600 frameborder=0 width=160 scrolling=no src=\"https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%&wprice=%%WINNING_PRICE_ESC%%\"></iframe>", "height": 250, "width": 300 } }
Respons
{ "name": "buyers/<ACCOUNT_ID>/creatives/HTML_Creative_d71e7cd9-8179-4683-ac5c-a203a9c660f2", "accountId": "<ACCOUNT_ID>", "creativeId": "HTML_Creative_d71e7cd9-8179-4683-ac5c-a203a9c660f2", "html": { "snippet": "<iframe marginwidth=0 marginheight=0 height=600 frameborder=0 width=160 scrolling=no src=\"https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%&wprice=%%WINNING_PRICE_ESC%%\"></iframe>", "width": 300, "height": 250 }, "creativeFormat": "HTML", "declaredClickThroughUrls": [ "http://test.com" ], "declaredAttributes": [ "CREATIVE_TYPE_HTML" ], "advertiserName": "Test", "version": 1, "apiUpdateTime": "2020-08-06T23:49:52.630384Z", "creativeServingDecision": { "lastStatusUpdate": "2020-08-06T23:49:52.710Z", "dealsPolicyCompliance": { "status": "PENDING_REVIEW" }, "networkPolicyCompliance": { "status": "PENDING_REVIEW" }, "platformPolicyCompliance": { "status": "PENDING_REVIEW" }, "chinaPolicyCompliance": { "status": "PENDING_REVIEW" }, "russiaPolicyCompliance": { "status": "PENDING_REVIEW" } } }
C#
/* Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied * See the License for the specific language governing permissions and * limitations under the License. */ using Google.Apis.RealTimeBidding.v1; using Google.Apis.RealTimeBidding.v1.Data; using Mono.Options; using System; using System.Collections.Generic; namespace Google.Apis.RealTimeBidding.Examples.v1.Buyers.Creatives { /// <summary> /// Creates a creative with HTML content for the given buyer account ID. /// </summary> public class CreateHtmlCreatives : ExampleBase { private RealTimeBiddingService rtbService; /// <summary> /// Constructor. /// </summary> public CreateHtmlCreatives() { rtbService = Utilities.GetRealTimeBiddingService(); } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get => "This code example creates a creative with HTML content for the given buyer " + "account ID."; } /// <summary> /// Parse specified arguments. /// </summary> protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) { string[] requiredOptions = new string[] {"account_id"}; bool showHelp = false; string accountId = null; string advertiserName = null; string creativeId = null; IList<string> declaredAttributes = new List<string>(); IList<string> declaredClickUrls = new List<string>(); IList<string> declaredRestrictedCategories = new List<string>(); IList<int?> declaredVendorIds = new List<int?>(); string htmlSnippet = null; int? htmlHeight = null; int? htmlWidth = null; var defaultHtmlSnippet = "<iframe marginwidth=0 marginheight=0 height=600 " + "frameborder=0 width=160 scrolling=no " + @"src=""https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%" + @"&wprice=%%WINNING_PRICE_ESC%%""></iframe>"; OptionSet options = new OptionSet { "Creates a creative with HTML content for the given buyer account ID.", { "h|help", "Show help message and exit.", h => showHelp = h != null }, { "a|account_id=", ("[Required] The resource ID of the buyers resource under which the " + "creatives were created. This will be used to construct the name used as " + "a path parameter for the creatives.get request."), a => accountId = a }, { "advertiser_name=", "The name of the company being advertised in the creative.", advertiser_name => advertiserName = advertiser_name }, { "c|creative_id=", ("The user-specified creative ID. The maximum length of the creative ID is " + "128 bytes."), c => creativeId = c }, { "declared_attributes=", ("The creative attributes being declared. Specify this argument for each " + "value you intend to include."), declared_attributes => declaredAttributes.Add(declared_attributes) }, { "declared_click_urls=", ("The click-through URLs being declared. Specify this argument for each " + "value you intend to include."), declared_click_through_urls => declaredClickUrls.Add( declared_click_through_urls) }, { "declared_restricted_categories=", ("The restricted categories being declared. Specify this argument for each " + "value you intend to include."), declared_restricted_categories => declaredRestrictedCategories.Add( declared_restricted_categories) }, { "declared_vendor_ids=", ("The vendor IDs being declared. Specify this argument for each value you " + "intend to include."), (int declared_vendor_ids) => declaredVendorIds.Add(declared_vendor_ids) }, { "html_snippet=", "The HTML snippet that displays the ad when inserted in the web page.", html_snippet => htmlSnippet = html_snippet }, { "html_height=", "The height of the HTML snippet in pixels.", (int html_height) => htmlHeight = html_height }, { "html_width=", "The width of the HTML snippet in pixels.", (int html_width) => htmlWidth = html_width }, }; List<string> extras = options.Parse(exampleArgs); var parsedArgs = new Dictionary<string, object>(); // Show help message. if(showHelp == true) { options.WriteOptionDescriptions(Console.Out); Environment.Exit(0); } // Set arguments. parsedArgs["account_id"] = accountId; parsedArgs["advertiser_name"] = advertiserName ?? "Test"; parsedArgs["creative_id"] = creativeId ?? String.Format( "HTML_Creative_{0}", System.Guid.NewGuid()); if (declaredAttributes.Count == 0) { declaredAttributes.Add("CREATIVE_TYPE_HTML"); } parsedArgs["declared_attributes"] = declaredAttributes; if (declaredClickUrls.Count == 0) { declaredClickUrls.Add("http://test.com"); } parsedArgs["declared_click_urls"] = declaredClickUrls; parsedArgs["declared_restricted_categories"] = declaredRestrictedCategories; parsedArgs["declared_vendor_ids"] = declaredVendorIds; parsedArgs["html_snippet"] = htmlSnippet ?? defaultHtmlSnippet; parsedArgs["html_height"] = htmlHeight ?? 250; parsedArgs["html_width"] = htmlWidth ?? 300; // Validate that options were set correctly. Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras); return parsedArgs; } /// <summary> /// Run the example. /// </summary> /// <param name="parsedArgs">Parsed arguments for the example.</param> protected override void Run(Dictionary<string, object> parsedArgs) { string accountId = (string) parsedArgs["account_id"]; string parent = $"buyers/{accountId}"; HtmlContent htmlContent = new HtmlContent(); htmlContent.Snippet = (string) parsedArgs["html_snippet"]; htmlContent.Height = (int) parsedArgs["html_height"]; htmlContent.Width = (int) parsedArgs["html_width"]; Creative newCreative = new Creative(); newCreative.AdvertiserName = (string) parsedArgs["advertiser_name"]; newCreative.CreativeId = (string) parsedArgs["creative_id"]; newCreative.DeclaredAttributes = (IList<string>) parsedArgs["declared_attributes"]; newCreative.DeclaredClickThroughUrls = (IList<string>) parsedArgs[ "declared_click_urls"]; newCreative.DeclaredRestrictedCategories = (IList<string>) parsedArgs[ "declared_restricted_categories"]; newCreative.DeclaredVendorIds = (IList<int?>) parsedArgs["declared_vendor_ids"]; newCreative.Html = htmlContent; BuyersResource.CreativesResource.CreateRequest request = rtbService.Buyers.Creatives.Create(newCreative, parent); Creative response = null; Console.WriteLine("Creating HTML creative for buyer: {0}", parent); try { response = request.Execute(); } catch (System.Exception exception) { throw new ApplicationException( $"Real-time Bidding API returned error response:\n{exception.Message}"); } Utilities.PrintCreative(response); } } }
Java
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.services.samples.authorizedbuyers.realtimebidding.v1.buyers.creatives; import com.google.api.services.realtimebidding.v1.RealTimeBidding; import com.google.api.services.realtimebidding.v1.model.Creative; import com.google.api.services.realtimebidding.v1.model.HtmlContent; import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Collections; import java.util.UUID; import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.ArgumentParserException; import net.sourceforge.argparse4j.inf.Namespace; /** Creates a creative with HTML content for the given buyer account ID. */ public class CreateHtmlCreatives { public static void execute(RealTimeBidding client, Namespace parsedArgs) throws IOException { Long accountId = parsedArgs.getLong("account_id"); String parentBuyerName = String.format("buyers/%s", accountId); HtmlContent htmlContent = new HtmlContent(); htmlContent.setSnippet(parsedArgs.getString("html_snippet")); htmlContent.setHeight(parsedArgs.getInt("html_height")); htmlContent.setWidth(parsedArgs.getInt("html_width")); Creative newCreative = new Creative(); newCreative.setAdvertiserName(parsedArgs.getString("advertiser_name")); newCreative.setCreativeId(parsedArgs.getString("creative_id")); newCreative.setDeclaredAttributes(parsedArgs.<String>getList("declared_attributes")); newCreative.setDeclaredClickThroughUrls(parsedArgs.<String>getList("declared_click_urls")); newCreative.setDeclaredRestrictedCategories( parsedArgs.<String>getList("declared_restricted_categories")); newCreative.setDeclaredVendorIds(parsedArgs.<Integer>getList("declared_vendor_ids")); newCreative.setHtml(htmlContent); Creative creative = client.buyers().creatives().create(parentBuyerName, newCreative).execute(); System.out.printf("Created creative for buyer Account ID '%s':\n", accountId); Utils.printCreative(creative); } public static void main(String[] args) { ArgumentParser parser = ArgumentParsers.newFor("CreateHtmlCreatives") .build() .defaultHelp(true) .description(("Creates an HTML creative for the given buyer account ID.")); parser .addArgument("-a", "--account_id") .help("The resource ID of the buyers resource under which the creative is to be created. ") .required(true) .type(Long.class); parser .addArgument("--advertiser_name") .help("The name of the company being advertised in the creative.") .setDefault("Test"); parser .addArgument("-c", "--creative_id") .help("The user-specified creative ID. The maximum length of the creative ID is 128 bytes.") .setDefault(String.format("HTML_Creative_%s", UUID.randomUUID())); parser .addArgument("--declared_attributes") .help( "The creative attributes being declared. Specify each attribute separated by a " + "space.") .nargs("*") .setDefault(Collections.singletonList("CREATIVE_TYPE_HTML")); parser .addArgument("--declared_click_urls") .help("The click-through URLs being declared. Specify each URL separated by a space.") .nargs("*") .setDefault(Collections.singletonList("http://test.com")); parser .addArgument("--declared_restricted_categories") .help( "The restricted categories being declared. Specify each category separated by a " + "space.") .nargs("*"); parser .addArgument("--declared_vendor_ids") .help("The vendor IDs being declared. Specify each ID separated by a space.") .type(Integer.class) .nargs("*"); parser .addArgument("--html_snippet") .help("The HTML snippet that displays the ad when inserted in the web page.") .setDefault( "<iframe marginwidth=0 marginheight=0 height=600 frameborder=0 width=160 " + "scrolling=no src=\"https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%" + "&wprice=%%WINNING_PRICE_ESC%%\"></iframe>"); parser .addArgument("--html_height") .help("The height of the HTML snippet in pixels.") .type(Integer.class) .setDefault(250); parser .addArgument("--html_width") .help("The width of the HTML snippet in pixels.") .type(Integer.class) .setDefault(300); Namespace parsedArgs = null; try { parsedArgs = parser.parseArgs(args); } catch (ArgumentParserException ex) { parser.handleError(ex); System.exit(1); } RealTimeBidding client = null; try { client = Utils.getRealTimeBiddingClient(); } catch (IOException ex) { System.out.printf("Unable to create RealTimeBidding API service:\n%s", ex); System.out.println("Did you specify a valid path to a service account key file?"); System.exit(1); } catch (GeneralSecurityException ex) { System.out.printf("Unable to establish secure HttpTransport:\n%s", ex); System.exit(1); } try { execute(client, parsedArgs); } catch (IOException ex) { System.out.printf("RealTimeBidding API returned error response:\n%s", ex); System.exit(1); } } }
PHP
<?php /** * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Buyers_Creatives; use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample; use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config; use Google_Service_RealTimeBidding_Creative; use Google_Service_RealTimeBidding_HtmlContent; /** * This example illustrates how to create HTML creatives for a given buyer account. */ class CreateHtmlCreatives extends BaseExample { public function __construct($client) { $this->service = Config::getGoogleServiceRealTimeBidding($client); } /** * @see BaseExample::getInputParameters() */ protected function getInputParameters() { return [ [ 'name' => 'account_id', 'display' => 'Account ID', 'description' => 'The resource ID of the buyers resource under which the creative is to be ' . 'created.', 'required' => true ], [ 'name' => 'advertiser_name', 'display' => 'Advertiser name', 'description' => 'The name of the company being advertised in the creative.', 'required' => false, 'default' => 'Test' ], [ 'name' => 'creative_id', 'display' => 'Creative ID', 'description' => 'The user-specified creative ID. The maximum length of the creative ID is ' . '128 bytes', 'required' => false, 'default' => 'HTML_Creative_' . uniqid() ], [ 'name' => 'declared_attributes', 'display' => 'Declared attributes', 'description' => 'The creative attributes being declared. Specify each attribute separated ' . 'by a comma.', 'required' => false, 'is_array' => true, 'default' => ['CREATIVE_TYPE_HTML'] ], [ 'name' => 'declared_click_urls', 'display' => 'Declared click URLs', 'description' => 'The click-through URLs being declared. Specify each URL separated by a ' . 'comma.', 'required' => false, 'is_array' => true, 'default' => ['http://test.com'] ], [ 'name' => 'declared_restricted_categories', 'display' => 'Declared restricted categories', 'description' => 'The restricted categories being declared. Specify each category separated ' . 'by a comma.', 'required' => false, 'is_array' => true ], [ 'name' => 'declared_vendor_ids', 'display' => 'Declared vendor IDs', 'description' => 'The vendor IDs being declared. Specify each ID separated by a comma.', 'required' => false, 'is_array' => true ], [ 'name' => 'html_snippet', 'display' => 'HTML snippet', 'description' => 'The HTML snippet that displays the ad when inserted in the web page.', 'required' => false, 'default' => '<iframe marginwidth=0 marginheight=0 height=600 frameborder=0 width=160 ' . 'scrolling=no src=\"https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%' . '&wprice=%%WINNING_PRICE_ESC%%\"></iframe>' ], [ 'name' => 'html_height', 'display' => 'Height', 'description' => 'The height of the HTML snippet in pixels.', 'required' => false, 'default' => 250 ], [ 'name' => 'html_width', 'display' => 'Width', 'description' => 'The width of the HTML snippet in pixels.', 'required' => false, 'default' => 300 ] ]; } /** * @see BaseExample::run() */ public function run() { $values = $this->formValues; $parentName = "buyers/$values[account_id]"; $html = new Google_Service_RealTimeBidding_HtmlContent(); $html->snippet = $values['html_snippet']; $html->height = $values['html_height']; $html->width = $values['html_width']; $newCreative = new Google_Service_RealTimeBidding_Creative(); $newCreative->advertiserName = $values['advertiser_name']; $newCreative->creativeId = $values['creative_id']; $newCreative->declaredAttributes = $values['declared_attributes']; $newCreative->declaredClickThroughUrls = $values['declared_click_urls']; $newCreative->declaredRestrictedCategories = $values['declared_restricted_categories']; $newCreative->declaredVendorIds = $values['declared_vendor_ids']; $newCreative->setHtml($html); print "<h2>Creating Creative for '$parentName':</h2>"; $result = $this->service->buyers_creatives->create($parentName, $newCreative); $this->printResult($result); } /** * @see BaseExample::getName() */ public function getName() { return 'Create Buyer HTML Creative'; } }
Python
#!/usr/bin/python # # Copyright 2020 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Creates a creative with HTML content for the given buyer account ID.""" import argparse import datetime import os import pprint import sys import uuid sys.path.insert(0, os.path.abspath('../../..')) from googleapiclient.errors import HttpError import util _BUYER_NAME_TEMPLATE = 'buyers/%s' DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE' def main(realtimebidding, args): account_id = args.account_id creative = { 'advertiserName': args.advertiser_name, 'creativeId': args.creative_id, 'declaredAttributes': args.declared_attributes, 'declaredClickThroughUrls': args.declared_click_urls, 'declaredRestrictedCategories': args.declared_restricted_categories, 'declaredVendorIds': [int(id) for id in args.declared_vendor_ids], 'html': { 'snippet': args.html_snippet, 'height': args.html_height, 'width': args.html_width } } print(f'Creating HTML creative for buyer account ID "{account_id}":') try: # Construct and execute the request. response = (realtimebidding.buyers().creatives().create( parent=_BUYER_NAME_TEMPLATE % account_id, body=creative).execute()) except HttpError as e: print(e) sys.exit(1) pprint.pprint(response) if __name__ == '__main__': try: service = util.GetService(version='v1') except IOError as ex: print(f'Unable to create realtimebidding service - {ex}') print('Did you specify the key file in util.py?') sys.exit(1) default_snippet_content = ( '<iframe marginwidth=0 marginheight=0 height=600 frameborder=0 ' 'width=160 scrolling=no src=\"https://test.com/ads?id=123456' '&curl=%%CLICK_URL_ESC%%&wprice=%%WINNING_PRICE_ESC%%\"></iframe>') parser = argparse.ArgumentParser( description=('Creates an HTML creative for the given buyer account ID.')) # Required fields. parser.add_argument( '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID, help=('The resource ID of the buyers resource under which the ' 'creative is to be created.')) # Optional fields. parser.add_argument( '--advertiser_name', default='Test', help='The name of the company being advertised in the creative.') parser.add_argument( '-c', '--creative_id', default='HTML_Creative_%s' % uuid.uuid4(), help=('The user-specified creative ID. The maximum length of the ' 'creative ID is 128 bytes.')) parser.add_argument( '--declared_attributes', nargs='*', default=['CREATIVE_TYPE_HTML'], help=('The creative attributes being declared. Specify each attribute ' 'separated by a space.')) parser.add_argument( '--declared_click_urls', nargs='*', default=['http://test.com'], help=('The click-through URLs being declared. Specify each URL ' 'separated by a space.')) parser.add_argument( '--declared_restricted_categories', nargs='*', default=[], help=('The restricted categories being declared. Specify each category ' 'separated by a space.')) parser.add_argument( '--declared_vendor_ids', nargs='*', default=[], help=('The vendor IDs being declared. Specify each ID separated by a ' 'space.')) parser.add_argument( '--html_snippet', default=default_snippet_content, help=('The HTML snippet that displays the ad when inserted in the ' 'web page.')) parser.add_argument( '--html_height', default=250, help='The height of the HTML snippet in pixels.') parser.add_argument( '--html_width', default=300, help='The width of the HTML snippet in pixels.') args = parser.parse_args() main(service, args)
Ruby
#!/usr/bin/env ruby # Encoding: utf-8 # # Copyright:: Copyright 2020 Google LLC # # License:: Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # # Creates a creative with HTML content for the given buyer account ID. require 'optparse' require 'securerandom' require_relative '../../../util' def create_html_creatives(realtimebidding, options) parent = "buyers/#{options[:account_id]}" body = Google::Apis::RealtimebiddingV1::Creative.new( advertiser_name: options[:advertiser_name], creative_id: options[:creative_id], declared_attributes: options[:declared_attributes], declared_click_through_urls: options[:declared_click_urls], declared_resricted_categories: options[:declared_restricted_categories], declared_vendor_ids: options[:declared_vendor_ids], html: Google::Apis::RealtimebiddingV1::HtmlContent.new( snippet: options[:html_snippet], height: options[:html_height], width: options[:html_width] ) ) puts "Creating HTML creative for buyer account '#{parent}'" creative = realtimebidding.create_buyer_creative(parent, creative_object=body) print_creative(creative) end if __FILE__ == $0 begin # Retrieve the service used to make API requests. service = get_service() rescue ArgumentError => e raise 'Unable to create service, with error message: #{e.message}' rescue Signet::AuthorizationError => e raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}' end default_snippet_content = <<~SNIPPET <iframe marginwidth=0 marginheight=0 height=600 frameborder=0 width=160 scrolling=no src="https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%&wprice=%%WINNING_PRICE_ESC%%"> </iframe> SNIPPET # Set options and default values for fields used in this example. options = [ Option.new( 'account_id', 'The resource ID of the buyers resource under which the creatives were created, This will be used to construct '\ 'the name used as a path parameter for the creatives.get request.', type: Integer, short_alias: 'a', required: true, default_value: nil ), Option.new( 'creative_id', 'The user-specified creative ID. The maximum length of the creative ID is 128 bytes.', short_alias: 'c', required: false, default_value: "HTML_Creative_#{SecureRandom.uuid}" ), Option.new( 'advertiser_name', 'The name of the company being advertised in the creative.', required: false, default_value: 'Test' ), Option.new( 'declared_attributes', 'The creative attributes being declared. Specify each attribute separated by a comma.', required: false, type: Array, default_value: ['CREATIVE_TYPE_HTML'] ), Option.new( 'declared_click_urls', 'The click-through URLs being declared. Specify each URL separated by a comma.', required: false, type: Array, default_value: ['http://test.com'] ), Option.new( 'declared_restricted_categories', 'The restricted categories being declared. Specify each category separated by a comma.', required: false, type: Array, default_value: [] ), Option.new( 'declared_vendor_ids', 'The vendor IDs being declared. Specify each ID separated by a space.', required: false, type: Array, default_value: [] ), Option.new( 'html_snippet', 'The HTML snippet that displays the ad when inserted in the web page.', required: false, default_value: default_snippet_content ), Option.new('html_height', 'The height of the HTML snippet in pixels.', required: false, default_value: 250), Option.new('html_width', 'The width of the HTML snippet in pixels.', required: false, default_value: 300), ] # Parse options. parser = Parser.new(options) opts = parser.parse(ARGV) begin create_html_creatives(service, opts) rescue Google::Apis::ServerError => e raise "The following server error occured:\n#{e.message}" rescue Google::Apis::ClientError => e raise "Invalid client request:\n#{e.message}" rescue Google::Apis::AuthorizationError => e raise "Authorization error occured:\n#{e.message}" end end
Materi iklan native
Berikut ini menunjukkan cara membuat dan mengirimkan materi iklan sederhana dengan konten native untuk ditinjau dengan
buyers.creatives.create
.
REST
Permintaan
POST https://realtimebidding.googleapis.com/v1/buyers/<INSERT_ACCOUNT_ID_HERE>/creatives?alt=json Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE> Content-Type: application/json { "advertiserName": "Test", "creativeId": "Native_Creative_b7116b38-e9d4-4f63-a02a-3d27660730be", "declaredAttributes": [ "NATIVE_ELIGIBILITY_ELIGIBLE" ], "declaredClickThroughUrls": [ "http://test.com" ], "declaredRestrictedCategories": [], "declaredVendorIds": [], "native": { "headline": "Luxury Mars Cruises", "body": "Visit the planet in a luxury spaceship.", "callToAction": "Book today", "advertiserName": "Galactic Luxury Cruises", "image": { "url": "https://native.test.com/image?id=123456", "height": 627, "width": 1200 }, "logo": { "url": "https://native.test.com/logo?id=123456", "height": 100, "width": 100 }, "clickLinkUrl": "https://www.google.com", "clickTrackingUrl": "https://native.test.com/click?id=123456" } }
Respons
{ "name": "buyers/<ACCOUNT_ID>/creatives/Native_Creative_b7116b38-e9d4-4f63-a02a-3d27660730be", "accountId": "<ACCOUNT_ID>", "creativeId": "Native_Creative_b7116b38-e9d4-4f63-a02a-3d27660730be", "native": { "headline": "Luxury Mars Cruises", "body": "Visit the planet in a luxury spaceship.", "callToAction": "Book today", "advertiserName": "Galactic Luxury Cruises", "image": { "url": "https://native.test.com/image?id=123456", "width": 1200, "height": 627 }, "logo": { "url": "https://native.test.com/logo?id=123456", "width": 100, "height": 100 }, "clickTrackingUrl": "https://native.test.com/click?id=123456", "clickLinkUrl": "https://www.google.com" }, "creativeFormat": "NATIVE", "declaredClickThroughUrls": [ "http://test.com" ], "declaredAttributes": [ "NATIVE_ELIGIBILITY_ELIGIBLE" ], "advertiserName": "Test", "version": 1, "apiUpdateTime": "2020-08-06T23:55:19.967732Z", "creativeServingDecision": { "lastStatusUpdate": "2020-08-06T23:55:20.076Z", "dealsPolicyCompliance": { "status": "PENDING_REVIEW" }, "networkPolicyCompliance": { "status": "PENDING_REVIEW" }, "platformPolicyCompliance": { "status": "PENDING_REVIEW" }, "chinaPolicyCompliance": { "status": "PENDING_REVIEW" }, "russiaPolicyCompliance": { "status": "PENDING_REVIEW" } } }
C#
/* Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied * See the License for the specific language governing permissions and * limitations under the License. */ using Google.Apis.RealTimeBidding.v1; using Google.Apis.RealTimeBidding.v1.Data; using Mono.Options; using System; using System.Collections.Generic; namespace Google.Apis.RealTimeBidding.Examples.v1.Buyers.Creatives { /// <summary> /// Creates a creative with native content for the given buyer account ID. /// </summary> public class CreateNativeCreatives : ExampleBase { private RealTimeBiddingService rtbService; /// <summary> /// Constructor. /// </summary> public CreateNativeCreatives() { rtbService = Utilities.GetRealTimeBiddingService(); } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get => "This code example creates a creative with native content for the given " + "buyer account ID."; } /// <summary> /// Parse specified arguments. /// </summary> protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) { string[] requiredOptions = new string[] {"account_id"}; bool showHelp = false; string accountId = null; string advertiserName = null; string creativeId = null; IList<string> declaredAttributes = new List<string>(); IList<string> declaredClickUrls = new List<string>(); IList<string> declaredRestrictedCategories = new List<string>(); IList<int?> declaredVendorIds = new List<int?>(); string nativeHeadline = null; string nativeBody = null; string nativeCallToAction = null; string nativeAdvertiserName = null; string nativeImageUrl = null; int? nativeImageHeight = null; int? nativeImageWidth = null; string nativeLogoUrl = null; int? nativeLogoHeight = null; int? nativeLogoWidth = null; string nativeClickLinkUrl = null; string nativeClickTrackingUrl = null; OptionSet options = new OptionSet { "Creates a creative with native content for the given buyer account ID.", { "h|help", "Show help message and exit.", h => showHelp = h != null }, { "a|account_id=", ("[Required] The resource ID of the buyers resource under which the " + "creatives were created. This will be used to construct the name used as " + "a path parameter for the creatives.get request."), a => accountId = a }, { "advertiser_name=", "The name of the company being advertised in the creative.", advertiser_name => advertiserName = advertiser_name }, { "c|creative_id=", ("The user-specified creative ID. The maximum length of the creative ID is " + "128 bytes."), c => creativeId = c }, { "declared_attributes=", ("The creative attributes being declared. Specify this argument for each " + "value you intend to include."), declared_attributes => declaredAttributes.Add(declared_attributes) }, { "declared_click_urls=", ("The click-through URLs being declared. Specify this argument for each " + "value you intend to include."), declared_click_through_urls => declaredClickUrls.Add( declared_click_through_urls) }, { "declared_restricted_categories=", ("The restricted categories being declared. Specify this argument for each " + "value you intend to include."), declared_restricted_categories => declaredRestrictedCategories.Add( declared_restricted_categories) }, { "declared_vendor_ids=", ("The vendor IDs being declared. Specify this argument for each value you " + "intend to include."), (int declared_vendor_ids) => declaredVendorIds.Add(declared_vendor_ids) }, { "native_headline=", "A short title for the ad.", native_headline => nativeHeadline = native_headline }, { "native_body=", "A long description of the ad.", native_body => nativeBody = native_body }, { "native_call_to_action=", "A label for the button that the user is supposed to click.", native_call_to_action => nativeCallToAction = native_call_to_action }, { "native_advertiser_name=", "The name of the advertiser or sponsor, to be displayed in the ad creative.", native_advertiser_name => nativeAdvertiserName = native_advertiser_name }, { "native_image_url=", "The URL of the large image to be included in the native ad.", native_image_url => nativeImageUrl = native_image_url }, { "native_image_height=", "The height in pixels of the native ad's large image.", (int native_image_height) => nativeImageHeight = native_image_height }, { "native_image_width=", "The width in pixels of the native ad's large image.", (int native_image_width) => nativeImageWidth = native_image_width }, { "native_logo_url=", "The URL of a smaller image to be included in the native ad.", native_logo_url => nativeLogoUrl = native_logo_url }, { "native_logo_height=", "The height in pixels of the native ad's smaller image.", (int native_logo_height) => nativeLogoHeight = native_logo_height }, { "native_logo_width=", "The height in pixels of the native ad's smaller image.", (int native_logo_width) => nativeLogoWidth = native_logo_width }, { "native_click_link_url=", "The URL that the browser/SDK will load when the user clicks the ad.", native_click_link_url => nativeClickLinkUrl = native_click_link_url }, { "native_click_tracking_url=", "The URL to use for click tracking.", native_click_tracking_url => nativeClickTrackingUrl = native_click_tracking_url }, }; List<string> extras = options.Parse(exampleArgs); var parsedArgs = new Dictionary<string, object>(); // Show help message. if(showHelp == true) { options.WriteOptionDescriptions(Console.Out); Environment.Exit(0); } // Set arguments. parsedArgs["account_id"] = accountId; parsedArgs["advertiser_name"] = advertiserName ?? "Test"; parsedArgs["creative_id"] = creativeId ?? String.Format( "Native_Creative_{0}", System.Guid.NewGuid()); if (declaredAttributes.Count == 0) { declaredAttributes.Add("NATIVE_ELIGIBILITY_ELIGIBLE"); } parsedArgs["declared_attributes"] = declaredAttributes; if (declaredClickUrls.Count == 0) { declaredClickUrls.Add("http://test.com"); } parsedArgs["declared_click_urls"] = declaredClickUrls; parsedArgs["declared_restricted_categories"] = declaredRestrictedCategories; parsedArgs["declared_vendor_ids"] = declaredVendorIds; parsedArgs["native_headline"] = nativeHeadline ?? "Luxury Mars Cruises"; parsedArgs["native_body"] = nativeBody ?? "Visit the planet in a luxury spaceship."; parsedArgs["native_call_to_action"] = nativeHeadline ?? "Book today"; parsedArgs["native_advertiser_name"] = nativeAdvertiserName ?? "Galactic Luxury Cruises"; parsedArgs["native_image_url"] = nativeImageUrl ?? "https://native.test.com/image?id=123456"; parsedArgs["native_image_height"] = nativeImageHeight ?? 627; parsedArgs["native_image_width"] = nativeImageWidth ?? 1200; parsedArgs["native_image_url"] = "https://native.test.com/image?id=123456"; parsedArgs["native_image_height"] = 627; parsedArgs["native_image_width"] = 1200; parsedArgs["native_logo_url"] = nativeLogoUrl ?? "https://native.test.com/logo?id=123456"; parsedArgs["native_logo_height"] = nativeLogoHeight ?? 100; parsedArgs["native_logo_width"] = nativeLogoWidth ?? 100; parsedArgs["native_click_link_url"] = nativeClickLinkUrl ?? "https://www.google.com"; parsedArgs["native_click_tracking_url"] = nativeClickTrackingUrl ?? "https://native.test.com/click?id=123456"; // Validate that options were set correctly. Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras); return parsedArgs; } /// <summary> /// Run the example. /// </summary> /// <param name="parsedArgs">Parsed arguments for the example.</param> protected override void Run(Dictionary<string, object> parsedArgs) { string accountId = (string) parsedArgs["account_id"]; string parent = $"buyers/{accountId}"; Image nativeImage = new Image(); nativeImage.Url = (string) parsedArgs["native_image_url"]; nativeImage.Height = (int?) parsedArgs["native_image_height"]; nativeImage.Width = (int?) parsedArgs["native_image_width"]; Image nativeLogo = new Image(); nativeLogo.Url = (string) parsedArgs["native_logo_url"]; nativeLogo.Height = (int?) parsedArgs["native_logo_height"]; nativeLogo.Width = (int?) parsedArgs["native_logo_width"]; NativeContent nativeContent = new NativeContent(); nativeContent.Headline = (string) parsedArgs["native_headline"]; nativeContent.Body = (string) parsedArgs["native_body"]; nativeContent.CallToAction = (string) parsedArgs["native_call_to_action"]; nativeContent.AdvertiserName = (string) parsedArgs["native_advertiser_name"]; nativeContent.Image = nativeImage; nativeContent.Logo = nativeLogo; nativeContent.ClickLinkUrl = (string) parsedArgs["native_click_link_url"]; nativeContent.ClickTrackingUrl = (string) parsedArgs["native_click_tracking_url"]; Creative newCreative = new Creative(); newCreative.AdvertiserName = (string) parsedArgs["advertiser_name"]; newCreative.CreativeId = (string) parsedArgs["creative_id"]; newCreative.DeclaredAttributes = (IList<string>) parsedArgs["declared_attributes"]; newCreative.DeclaredClickThroughUrls = (IList<string>) parsedArgs[ "declared_click_urls"]; newCreative.DeclaredRestrictedCategories = (IList<string>) parsedArgs[ "declared_restricted_categories"]; newCreative.DeclaredVendorIds = (IList<int?>) parsedArgs["declared_vendor_ids"]; newCreative.Native = nativeContent; BuyersResource.CreativesResource.CreateRequest request = rtbService.Buyers.Creatives.Create(newCreative, parent); Creative response = null; Console.WriteLine("Creating native creative for buyer: {0}", parent); try { response = request.Execute(); } catch (System.Exception exception) { throw new ApplicationException( $"Real-time Bidding API returned error response:\n{exception.Message}"); } Utilities.PrintCreative(response); } } }
Java
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.services.samples.authorizedbuyers.realtimebidding.v1.buyers.creatives; import com.google.api.services.realtimebidding.v1.RealTimeBidding; import com.google.api.services.realtimebidding.v1.model.Creative; import com.google.api.services.realtimebidding.v1.model.Image; import com.google.api.services.realtimebidding.v1.model.NativeContent; import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Collections; import java.util.UUID; import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.ArgumentParserException; import net.sourceforge.argparse4j.inf.Namespace; /** Creates a creative with native content for the given buyer account ID. */ public class CreateNativeCreatives { public static void execute(RealTimeBidding client, Namespace parsedArgs) throws IOException { Long accountId = parsedArgs.getLong("account_id"); String parentBuyerName = String.format("buyers/%s", accountId); Image image = new Image(); image.setUrl(parsedArgs.getString("native_image_url")); image.setHeight(parsedArgs.getInt("native_image_height")); image.setWidth(parsedArgs.getInt("native_image_width")); Image logo = new Image(); logo.setUrl(parsedArgs.getString("native_logo_url")); logo.setHeight(parsedArgs.getInt("native_logo_height")); logo.setWidth(parsedArgs.getInt("native_logo_width")); NativeContent nativeContent = new NativeContent(); nativeContent.setHeadline(parsedArgs.getString("native_headline")); nativeContent.setBody(parsedArgs.getString("native_body")); nativeContent.setCallToAction(parsedArgs.getString("native_call_to_action")); nativeContent.setAdvertiserName(parsedArgs.getString("native_advertiser_name")); nativeContent.setImage(image); nativeContent.setLogo(logo); nativeContent.setClickLinkUrl(parsedArgs.getString("native_click_link_url")); nativeContent.setClickTrackingUrl(parsedArgs.getString("native_click_tracking_url")); Creative newCreative = new Creative(); newCreative.setAdvertiserName(parsedArgs.getString("advertiser_name")); newCreative.setCreativeId(parsedArgs.getString("creative_id")); newCreative.setDeclaredAttributes(parsedArgs.<String>getList("declared_attributes")); newCreative.setDeclaredClickThroughUrls(parsedArgs.<String>getList("declared_click_urls")); newCreative.setDeclaredRestrictedCategories( parsedArgs.<String>getList("declared_restricted_categories")); newCreative.setDeclaredVendorIds(parsedArgs.<Integer>getList("declared_vendor_ids")); newCreative.setNative(nativeContent); Creative creative = client.buyers().creatives().create(parentBuyerName, newCreative).execute(); System.out.printf("Created creative for buyer Account ID '%s':\n", accountId); Utils.printCreative(creative); } public static void main(String[] args) { ArgumentParser parser = ArgumentParsers.newFor("CreateNativeCreatives") .build() .defaultHelp(true) .description(("Creates an native creative for the given buyer account ID.")); parser .addArgument("-a", "--account_id") .help("The resource ID of the buyers resource under which the creative is to be created. ") .required(true) .type(Long.class); parser .addArgument("--advertiser_name") .help("The name of the company being advertised in the creative.") .setDefault("Test"); parser .addArgument("-c", "--creative_id") .help("The user-specified creative ID. The maximum length of the creative ID is 128 bytes.") .setDefault(String.format("Native_Creative_%s", UUID.randomUUID())); parser .addArgument("--declared_attributes") .help( "The creative attributes being declared. Specify each attribute separated by a " + "space.") .nargs("*") .setDefault(Collections.singletonList("NATIVE_ELIGIBILITY_ELIGIBLE")); parser .addArgument("--declared_click_urls") .help("The click-through URLs being declared. Specify each URL separated by a space.") .nargs("*") .setDefault(Collections.singletonList("http://test.com")); parser .addArgument("--declared_restricted_categories") .help( "The restricted categories being declared. Specify each category separated by a " + "space.") .nargs("*"); parser .addArgument("--declared_vendor_ids") .help("The vendor IDs being declared. Specify each ID separated by a space.") .type(Integer.class) .nargs("*"); parser .addArgument("--native_headline") .help("A short title for the ad.") .setDefault("Luxury Mars Cruises"); parser .addArgument("--native_body") .help("A long description of the ad.") .setDefault("Visit the planet in a luxury spaceship."); parser .addArgument("--native_call_to_action") .help("A label for the button that the user is supposed to click.") .setDefault("Book today"); parser .addArgument("--native_advertiser_name") .help("The name of the advertiser or sponsor, to be displayed in the ad creative.") .setDefault("Galactic Luxury Cruises"); parser .addArgument("--native_image_url") .help("The URL of the large image to be included in the native ad.") .setDefault("https://native.test.com/image?id=123456"); parser .addArgument("--native_image_height") .help("The height in pixels of the native ad's large image.") .type(Integer.class) .setDefault(627); parser .addArgument("--native_image_width") .help("The width in pixels of the native ad's large image.") .type(Integer.class) .setDefault(1200); parser .addArgument("--native_logo_url") .help("The URL of a smaller image to be included in the native ad.") .setDefault("https://native.test.com/logo?id=123456"); parser .addArgument("--native_logo_height") .help("The height in pixels of the native ad's smaller image.") .type(Integer.class) .setDefault(100); parser .addArgument("--native_logo_width") .help("The width in pixels of the native ad's smaller image.") .type(Integer.class) .setDefault(100); parser .addArgument("--native_click_link_url") .help("The URL that the browser/SDK will load when the user clicks the ad.") .setDefault("https://www.google.com"); parser .addArgument("--native_click_tracking_url") .help("The URL to use for click tracking.") .setDefault("https://native.test.com/click?id=123456"); Namespace parsedArgs = null; try { parsedArgs = parser.parseArgs(args); } catch (ArgumentParserException ex) { parser.handleError(ex); System.exit(1); } RealTimeBidding client = null; try { client = Utils.getRealTimeBiddingClient(); } catch (IOException ex) { System.out.printf("Unable to create RealTimeBidding API service:\n%s", ex); System.out.println("Did you specify a valid path to a service account key file?"); System.exit(1); } catch (GeneralSecurityException ex) { System.out.printf("Unable to establish secure HttpTransport:\n%s", ex); System.exit(1); } try { execute(client, parsedArgs); } catch (IOException ex) { System.out.printf("RealTimeBidding API returned error response:\n%s", ex); System.exit(1); } } }
PHP
<?php /** * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Buyers_Creatives; use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample; use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config; use Google_Service_RealTimeBidding_Creative; use Google_Service_RealTimeBidding_Image; use Google_Service_RealTimeBidding_NativeContent; /** * This example illustrates how to create native creatives for a given buyer account. */ class CreateNativeCreatives extends BaseExample { public function __construct($client) { $this->service = Config::getGoogleServiceRealTimeBidding($client); } /** * @see BaseExample::getInputParameters() */ protected function getInputParameters() { return [ [ 'name' => 'account_id', 'display' => 'Account ID', 'description' => 'The resource ID of the buyers resource under which the creative is to be ' . 'created.', 'required' => true ], [ 'name' => 'advertiser_name', 'display' => 'Advertiser name', 'description' => 'The name of the company being advertised in the creative.', 'required' => false, 'default' => 'Test' ], [ 'name' => 'creative_id', 'display' => 'Creative ID', 'description' => 'The user-specified creative ID. The maximum length of the creative ID is ' . '128 bytes', 'required' => false, 'default' => 'Native_Creative_' . uniqid() ], [ 'name' => 'declared_attributes', 'display' => 'Declared attributes', 'description' => 'The creative attributes being declared. Specify each attribute separated ' . 'by a comma.', 'required' => false, 'is_array' => true, 'default' => ['NATIVE_ELIGIBILITY_ELIGIBLE'] ], [ 'name' => 'declared_click_urls', 'display' => 'Declared click URLs', 'description' => 'The click-through URLs being declared. Specify each URL separated by a ' . 'comma.', 'required' => false, 'is_array' => true, 'default' => ['http://test.com'] ], [ 'name' => 'declared_restricted_categories', 'display' => 'Declared restricted categories', 'description' => 'The restricted categories being declared. Specify each category separated ' . 'by a comma.', 'required' => false, 'is_array' => true ], [ 'name' => 'declared_vendor_ids', 'display' => 'Declared vendor IDs', 'description' => 'The vendor IDs being declared. Specify each ID separated by a comma.', 'required' => false, 'is_array' => true ], [ 'name' => 'native_headline', 'display' => 'Native ad headline', 'description' => 'A short title for the ad.', 'required' => false, 'default' => 'Luxury Mars Cruises' ], [ 'name' => 'native_body', 'display' => 'Native ad body', 'description' => 'A long description of the ad.', 'required' => false, 'default' => 'Visit the planet in a luxury spaceship.' ], [ 'name' => 'native_call_to_action', 'display' => 'Native ad call to action', 'description' => 'A label for the button that the user is supposed to click.', 'required' => false, 'default' => 'Book today' ], [ 'name' => 'native_advertiser_name', 'display' => 'Native ad advertiser name', 'description' => 'The name of the advertiser or sponsor, to be displayed in the ad creative.', 'required' => false, 'default' => 'Galactic Luxury Cruises' ], [ 'name' => 'native_image_url', 'display' => 'Native ad image url', 'description' => 'The URL of the large image to be included in the native ad.', 'required' => false, 'default' => 'https://native.test.com/image?id=123456' ], [ 'name' => 'native_image_height', 'display' => 'Native ad image height', 'description' => 'The height in pixels of the native ad\'s large image.', 'required' => false, 'default' => 627 ], [ 'name' => 'native_image_width', 'display' => 'Native ad image width', 'description' => 'The width in pixels of the native ad\'s large image.', 'required' => false, 'default' => 1200 ], [ 'name' => 'native_logo_url', 'display' => 'Native ad logo url', 'description' => 'The URL of a smaller image to be included in the native ad.', 'required' => false, 'default' => 'https://native.test.com/logo?id=123456' ], [ 'name' => 'native_logo_height', 'display' => 'Native ad logo height', 'description' => 'The height in pixels of the native ad\'s smaller image.', 'required' => false, 'default' => 100 ], [ 'name' => 'native_logo_width', 'display' => 'Native ad logo width', 'description' => 'The width in pixels of the native ad\'s smaller image.', 'required' => false, 'default' => 100 ], [ 'name' => 'native_click_link_url', 'display' => 'Native ad click link URL', 'description' => 'The URL that the browser/SDK will load when the user clicks ' . 'the ad.', 'required' => false, 'default' => 'https://www.google.com' ], [ 'name' => 'native_click_tracking_url', 'display' => 'Native ad click tracking URL', 'description' => 'The URL to use for click tracking.', 'required' => false, 'default' => 'https://native.test.com/click?id=123456' ] ]; } /** * @see BaseExample::run() */ public function run() { $values = $this->formValues; $parentName = "buyers/$values[account_id]"; $image = new Google_Service_RealTimeBidding_Image(); $image->url = $values['native_image_url']; $image->height = $values['native_image_height']; $image->width = $values['native_image_width']; $logo = new Google_Service_RealTimeBidding_Image(); $logo->url = $values['native_logo_url']; $logo->height = $values['native_logo_height']; $logo->width = $values['native_logo_width']; $native = new Google_Service_RealTimeBidding_NativeContent(); $native->headline = $values['native_headline']; $native->body = $values['native_body']; $native->callToAction = $values['native_call_to_action']; $native->advertiserName = $values['native_advertiser_name']; $native->setImage($image); $native->setLogo($logo); $newCreative = new Google_Service_RealTimeBidding_Creative(); $newCreative->advertiserName = $values['advertiser_name']; $newCreative->creativeId = $values['creative_id']; $newCreative->declaredAttributes = $values['declared_attributes']; $newCreative->declaredClickThroughUrls = $values['declared_click_urls']; $newCreative->declaredRestrictedCategories = $values['declared_restricted_categories']; $newCreative->declaredVendorIds = $values['declared_vendor_ids']; $newCreative->setNative($native); print "<h2>Creating Creative for '$parentName':</h2>"; $result = $this->service->buyers_creatives->create($parentName, $newCreative); $this->printResult($result); } /** * @see BaseExample::getName() */ public function getName() { return 'Create Buyer Native Creative'; } }
Python
#!/usr/bin/python # # Copyright 2020 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Creates a creative with native content for the given buyer account ID.""" import argparse import datetime import os import pprint import sys import uuid sys.path.insert(0, os.path.abspath('../../..')) from googleapiclient.errors import HttpError import util _BUYER_NAME_TEMPLATE = 'buyers/%s' DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE' def main(realtimebidding, args): account_id = args.account_id creative = { 'advertiserName': args.advertiser_name, 'creativeId': args.creative_id, 'declaredAttributes': args.declared_attributes, 'declaredClickThroughUrls': args.declared_click_urls, 'declaredRestrictedCategories': args.declared_restricted_categories, 'declaredVendorIds': [int(id) for id in args.declared_vendor_ids], 'native': { 'headline': args.native_headline, 'body': args.native_body, 'callToAction': args.native_call_to_action, 'advertiserName': args.native_advertiser_name, 'image': { 'url': args.native_image_url, 'height': args.native_image_height, 'width': args.native_image_width }, 'logo': { 'url': args.native_logo_url, 'height': args.native_logo_height, 'width': args.native_logo_width }, 'clickLinkUrl': args.native_click_link_url, 'clickTrackingUrl': args.native_click_tracking_url } } print(f'Creating native creative for buyer account ID "{account_id}":') try: # Construct and execute the request. response = (realtimebidding.buyers().creatives().create( parent=_BUYER_NAME_TEMPLATE % account_id, body=creative).execute()) except HttpError as e: print(e) sys.exit(1) pprint.pprint(response) if __name__ == '__main__': try: service = util.GetService(version='v1') except IOError as ex: print(f'Unable to create realtimebidding service - {ex}') print('Did you specify the key file in util.py?') sys.exit(1) parser = argparse.ArgumentParser( description=('Creates a native creative for the given buyer account ID.') ) # Required fields. parser.add_argument( '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID, help=('The resource ID of the buyers resource under which the ' 'creative is to be created.')) # Optional fields. parser.add_argument( '--advertiser_name', default='Test', help='The name of the company being advertised in the creative.') parser.add_argument( '-c', '--creative_id', default='Native_Creative_%s' % uuid.uuid4(), help=('The user-specified creative ID. The maximum length of the ' 'creative ID is 128 bytes.')) parser.add_argument( '--declared_attributes', nargs='*', default=['NATIVE_ELIGIBILITY_ELIGIBLE'], help=('The creative attributes being declared. Specify each attribute ' 'separated by a space.')) parser.add_argument( '--declared_click_urls', nargs='*', default=['http://test.com'], help=('The click-through URLs being declared. Specify each URL ' 'separated by a space.')) parser.add_argument( '--declared_restricted_categories', nargs='*', default=[], help=('The restricted categories being declared. Specify each category ' 'separated by a space.')) parser.add_argument( '--declared_vendor_ids', nargs='*', default=[], help=('The vendor IDs being declared. Specify each ID separated by a ' 'space.')) parser.add_argument( '--native_headline', default='Luxury Mars Cruises', help=('A short title for the ad.')) parser.add_argument( '--native_body', default='Visit the planet in a luxury spaceship.', help='A long description of the ad.'), parser.add_argument( '--native_call_to_action', default='Book today', help='A label for the button that the user is supposed to click.') parser.add_argument( '--native_advertiser_name', default='Galactic Luxury Cruises', help=('The name of the advertiser or sponsor, to be displayed in the ad ' 'creative.')), parser.add_argument( '--native_image_url', default='https://native.test.com/image?id=123456', help='The URL of the large image to be included in the native ad.'), parser.add_argument( '--native_image_height', default=627, help='The height in pixels of the native ad\'s large image.'), parser.add_argument( '--native_image_width', default=1200, help='The width in pixels of the native ad\'s large image.'), parser.add_argument( '--native_logo_url', default='https://native.test.com/logo?id=123456', help='The URL of a smaller image to be included in the native ad.'), parser.add_argument( '--native_logo_height', default=100, help='The height in pixels of the native ad\'s smaller image.'), parser.add_argument( '--native_logo_width', default=100, help='The width in pixels of the native ad\'s smaller image.'), parser.add_argument( '--native_click_link_url', default='https://www.google.com', help=('The URL that the browser/SDK will load when the user clicks the ' 'ad.')), parser.add_argument( '--native_click_tracking_url', default='https://native.test.com/click?id=123456', help='The URL to use for click tracking.'), args = parser.parse_args() main(service, args)
Ruby
#!/usr/bin/env ruby # Encoding: utf-8 # # Copyright:: Copyright 2020 Google LLC # # License:: Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # # Creates a creative with native content for the given buyer account ID. require 'optparse' require 'securerandom' require_relative '../../../util' def create_native_creatives(realtimebidding, options) parent = "buyers/#{options[:account_id]}" body = Google::Apis::RealtimebiddingV1::Creative.new( advertiser_name: options[:advertiser_name], creative_id: options[:creative_id], declared_attributes: options[:declared_attributes], declared_click_through_urls: options[:declared_click_urls], declared_resricted_categories: options[:declared_restricted_categories], declared_vendor_ids: options[:declared_vendor_ids], native: Google::Apis::RealtimebiddingV1::NativeContent.new( headline: options[:native_headline], body: options[:native_body], call_to_action: options[:native_call_to_action], advertiser_name: options[:native_advertiser_name], image: Google::Apis::RealtimebiddingV1::Image.new( url: options[:native_image_url], height: options[:native_image_height], width: options[:native_image_width] ), logo: Google::Apis::RealtimebiddingV1::Image.new( url: options[:native_logo_url], height: options[:native_logo_height], width: options[:native_logo_width] ), click_link_url: options[:native_click_link_url], click_tracking_url: options[:native_click_tracking_url] ) ) puts "Creating native creative for buyer account '#{parent}'" creative = realtimebidding.create_buyer_creative(parent, creative_object=body) print_creative(creative) end if __FILE__ == $0 begin # Retrieve the service used to make API requests. service = get_service() rescue ArgumentError => e raise 'Unable to create service, with error message: #{e.message}' rescue Signet::AuthorizationError => e raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}' end # Set options and default values for fields used in this example. options = [ Option.new( 'account_id', 'The resource ID of the buyers resource under which the creatives were created, This will be used to construct '\ 'the name used as a path parameter for the creatives.get request.', type: Integer, short_alias: 'a', required: true, default_value: nil ), Option.new( 'creative_id', 'The user-specified creative ID. The maximum length of the creative ID is 128 bytes.', short_alias: 'c', required: false, default_value: "Native_Creative_#{SecureRandom.uuid}" ), Option.new( 'advertiser_name', 'The name of the company being advertised in the creative.', required: false, default_value: 'Test' ), Option.new( 'declared_attributes', 'The creative attributes being declared. Specify each attribute separated by a comma.', required: false, type: Array, default_value: ['NATIVE_ELIGIBILITY_ELIGIBLE'] ), Option.new( 'declared_click_urls', 'The click-through URLs being declared. Specify each URL separated by a comma.', required: false, type: Array, default_value: ['http://test.com'] ), Option.new( 'declared_restricted_categories', 'The restricted categories being declared. Specify each category separated by a comma.', required: false, type: Array, default_value: [] ), Option.new( 'declared_vendor_ids', 'The vendor IDs being declared. Specify each ID separated by a space.', required: false, type: Array, default_value: [] ), Option.new('native_headline', 'A short title for the ad.', required: false, default_value: 'Luxury Mars Cruises'), Option.new( 'native_body', 'A long description of the ad.', required: false, default_value: 'Visit the planet in a luxury spaceship.' ), Option.new( 'native_call_to_action', 'A label for the button that the user is supposed to click.', required: false, default_value: 'Book today' ), Option.new( 'native_advertiser_name', 'The name of the advertiser or sponsor, to be displayed in the ad creative', required: false, default_value: 'Galactic Luxury Cruises' ), Option.new( 'native_image_url', 'The URL of the large image to be included in the native ad.', required: false, default_value: 'https://native.test.com/image?id=123456' ), Option.new( 'native_image_height', 'The height in pixels of the native ad\'s large image.', required: false, default_value: 627 ), Option.new( 'native_image_width', 'The width in pixels of the native ad\'s large image.', required: false, default_value: 1200 ), Option.new( 'native_logo_url', 'The URL of a smaller image to be included in the native ad.', required: false, default_value: 'https://native.test.com/logo?id=123456' ), Option.new( 'native_logo_height', 'The height in pixels of the native ad\'s smaller image.', required: false, default_value: 100 ), Option.new( 'native_logo_width', 'The width in pixels of the native ad\'s smaller image.', required: false, default_value: 100 ), Option.new( 'native_click_link_url', 'The URL that the browser/SDK will load when the user clicks the ad.', required: false, default_value: 'https://www.google.com' ), Option.new( 'native_click_tracking_url', 'The URL to use for click tracking.', required: false, default_value: 'https://native.test.com/click?id=123456' ), ] # Parse options. parser = Parser.new(options) opts = parser.parse(ARGV) begin create_native_creatives(service, opts) rescue Google::Apis::ServerError => e raise "The following server error occured:\n#{e.message}" rescue Google::Apis::ClientError => e raise "Invalid client request:\n#{e.message}" rescue Google::Apis::AuthorizationError => e raise "Authorization error occured:\n#{e.message}" end end
Materi iklan video
Berikut ini cara membuat dan mengirimkan materi iklan sederhana dengan konten video untuk ditinjau dengan buyers.creatives.create
.
REST
Permintaan
POST https://realtimebidding.googleapis.com/v1/buyers/<INSERT_ACCOUNT_ID_HERE>/creatives?alt=json Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE> Content-Type: application/json { "advertiserName": "Test", "creativeId": "HTML_Creative_87b8902b-51ad-421a-849a-a064e1b4c6e3", "declaredAttributes": [ "CREATIVE_TYPE_VAST_VIDEO" ], "declaredClickThroughUrls": [ "http://test.com" ], "declaredRestrictedCategories": [], "declaredVendorIds": [], "video": { "videoUrl": "https://video.test.com/ads?id=123456&wprice=%%WINNING_PRICE%%" } }
Respons
{ "name": "buyers/<ACCOUNT_ID>/creatives/HTML_Creative_87b8902b-51ad-421a-849a-a064e1b4c6e3", "accountId": "<ACCOUNT_ID>", "creativeId": "HTML_Creative_87b8902b-51ad-421a-849a-a064e1b4c6e3", "video": { "videoUrl": "https://video.test.com/ads?id=123456&wprice=%%WINNING_PRICE%%" }, "creativeFormat": "VIDEO", "declaredClickThroughUrls": [ "http://test.com" ], "declaredAttributes": [ "CREATIVE_TYPE_VAST_VIDEO" ], "advertiserName": "Test", "version": 1, "apiUpdateTime": "2020-08-06T23:59:58.554262Z", "creativeServingDecision": { "lastStatusUpdate": "2020-08-06T23:59:58.555Z", "dealsPolicyCompliance": { "status": "PENDING_REVIEW" }, "networkPolicyCompliance": { "status": "PENDING_REVIEW" }, "platformPolicyCompliance": { "status": "PENDING_REVIEW" }, "chinaPolicyCompliance": { "status": "PENDING_REVIEW" }, "russiaPolicyCompliance": { "status": "PENDING_REVIEW" } } }
C#
/* Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied * See the License for the specific language governing permissions and * limitations under the License. */ using Google.Apis.RealTimeBidding.v1; using Google.Apis.RealTimeBidding.v1.Data; using Mono.Options; using System; using System.Collections.Generic; namespace Google.Apis.RealTimeBidding.Examples.v1.Buyers.Creatives { /// <summary> /// Creates a creative with video content for the given buyer account ID. /// </summary> public class CreateVideoCreatives : ExampleBase { private RealTimeBiddingService rtbService; /// <summary> /// Constructor. /// </summary> public CreateVideoCreatives() { rtbService = Utilities.GetRealTimeBiddingService(); } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get => "This code example creates a creative with video content for the given buyer " + "account ID."; } /// <summary> /// Parse specified arguments. /// </summary> protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) { string[] requiredOptions = new string[] {"account_id"}; bool showHelp = false; string accountId = null; string advertiserName = null; string creativeId = null; IList<string> declaredAttributes = new List<string>(); IList<string> declaredClickUrls = new List<string>(); IList<string> declaredRestrictedCategories = new List<string>(); IList<int?> declaredVendorIds = new List<int?>(); string videoUrl = null; var defaultVideoUrl = "https://video.test.com/ads?id=123456&wprice=%%WINNING_PRICE%%"; OptionSet options = new OptionSet { "Creates a creative with video content for the given buyer account ID.", { "h|help", "Show help message and exit.", h => showHelp = h != null }, { "a|account_id=", ("[Required] The resource ID of the buyers resource under which the " + "creatives were created. This will be used to construct the name used as " + "a path parameter for the creatives.get request."), a => accountId = a }, { "advertiser_name=", "The name of the company being advertised in the creative.", advertiser_name => advertiserName = advertiser_name }, { "c|creative_id=", ("The user-specified creative ID. The maximum length of the creative ID is " + "128 bytes."), c => creativeId = c }, { "declared_attributes=", ("The creative attributes being declared. Specify this argument for each " + "value you intend to include."), declared_attributes => declaredAttributes.Add(declared_attributes) }, { "declared_click_urls=", ("The click-through URLs being declared. Specify this argument for each " + "value you intend to include."), declared_click_through_urls => declaredClickUrls.Add( declared_click_through_urls) }, { "declared_restricted_categories=", ("The restricted categories being declared. Specify this argument for each " + "value you intend to include."), declared_restricted_categories => declaredRestrictedCategories.Add( declared_restricted_categories) }, { "declared_vendor_ids=", ("The vendor IDs being declared. Specify this argument for each value you " + "intend to include."), (int declared_vendor_ids) => declaredVendorIds.Add(declared_vendor_ids) }, { "video_url=", "The URL used to fetch a video ad.", video_url => videoUrl = video_url } }; List<string> extras = options.Parse(exampleArgs); var parsedArgs = new Dictionary<string, object>(); // Show help message. if(showHelp == true) { options.WriteOptionDescriptions(Console.Out); Environment.Exit(0); } // Set arguments. parsedArgs["account_id"] = accountId; parsedArgs["advertiser_name"] = advertiserName ?? "Test"; parsedArgs["creative_id"] = creativeId ?? String.Format( "Video_Creative_{0}", System.Guid.NewGuid()); if (declaredAttributes.Count == 0) { declaredAttributes.Add("CREATIVE_TYPE_VAST_VIDEO"); } parsedArgs["declared_attributes"] = declaredAttributes; if (declaredClickUrls.Count == 0) { declaredClickUrls.Add("http://test.com"); } parsedArgs["declared_click_urls"] = declaredClickUrls; parsedArgs["declared_restricted_categories"] = declaredRestrictedCategories; parsedArgs["declared_vendor_ids"] = declaredVendorIds; parsedArgs["video_url"] = videoUrl ?? defaultVideoUrl; // Validate that options were set correctly. Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras); return parsedArgs; } /// <summary> /// Run the example. /// </summary> /// <param name="parsedArgs">Parsed arguments for the example.</param> protected override void Run(Dictionary<string, object> parsedArgs) { string accountId = (string) parsedArgs["account_id"]; string parent = $"buyers/{accountId}"; VideoContent videoContent = new VideoContent(); videoContent.VideoUrl = (string) parsedArgs["video_url"]; Creative newCreative = new Creative(); newCreative.AdvertiserName = (string) parsedArgs["advertiser_name"]; newCreative.CreativeId = (string) parsedArgs["creative_id"]; newCreative.DeclaredAttributes = (IList<string>) parsedArgs["declared_attributes"]; newCreative.DeclaredClickThroughUrls = (IList<string>) parsedArgs[ "declared_click_urls"]; newCreative.DeclaredRestrictedCategories = (IList<string>) parsedArgs[ "declared_restricted_categories"]; newCreative.DeclaredVendorIds = (IList<int?>) parsedArgs["declared_vendor_ids"]; newCreative.Video = videoContent; BuyersResource.CreativesResource.CreateRequest request = rtbService.Buyers.Creatives.Create(newCreative, parent); Creative response = null; Console.WriteLine("Creating video creative for buyer: {0}", parent); try { response = request.Execute(); } catch (System.Exception exception) { throw new ApplicationException( $"Real-time Bidding API returned error response:\n{exception.Message}"); } Utilities.PrintCreative(response); } } }
Java
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.services.samples.authorizedbuyers.realtimebidding.v1.buyers.creatives; import com.google.api.services.realtimebidding.v1.RealTimeBidding; import com.google.api.services.realtimebidding.v1.model.Creative; import com.google.api.services.realtimebidding.v1.model.VideoContent; import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Collections; import java.util.UUID; import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.ArgumentParserException; import net.sourceforge.argparse4j.inf.Namespace; /** Creates a creative with video content for the given buyer account ID. */ public class CreateVideoCreatives { public static void execute(RealTimeBidding client, Namespace parsedArgs) throws IOException { Long accountId = parsedArgs.getLong("account_id"); String parentBuyerName = String.format("buyers/%s", accountId); VideoContent videoContent = new VideoContent(); videoContent.setVideoUrl(parsedArgs.getString("video_url")); Creative newCreative = new Creative(); newCreative.setAdvertiserName(parsedArgs.getString("advertiser_name")); newCreative.setCreativeId(parsedArgs.getString("creative_id")); newCreative.setDeclaredAttributes(parsedArgs.<String>getList("declared_attributes")); newCreative.setDeclaredClickThroughUrls(parsedArgs.<String>getList("declared_click_urls")); newCreative.setDeclaredRestrictedCategories( parsedArgs.<String>getList("declared_restricted_categories")); newCreative.setDeclaredVendorIds(parsedArgs.<Integer>getList("declared_vendor_ids")); newCreative.setVideo(videoContent); Creative creative = client.buyers().creatives().create(parentBuyerName, newCreative).execute(); System.out.printf("Created creative for buyer Account ID '%s':\n", accountId); Utils.printCreative(creative); } public static void main(String[] args) { ArgumentParser parser = ArgumentParsers.newFor("CreateVideoCreatives") .build() .defaultHelp(true) .description(("Creates a video creative for the given buyer account ID.")); parser .addArgument("-a", "--account_id") .help("The resource ID of the buyers resource under which the creative is to be created. ") .required(true) .type(Long.class); parser .addArgument("--advertiser_name") .help("The name of the company being advertised in the creative.") .setDefault("Test"); parser .addArgument("-c", "--creative_id") .help("The user-specified creative ID. The maximum length of the creative ID is 128 bytes.") .setDefault(String.format("Video_Creative_%s", UUID.randomUUID())); parser .addArgument("--declared_attributes") .help( "The creative attributes being declared. Specify each attribute separated by a " + "space.") .nargs("*") .setDefault(Collections.singletonList("CREATIVE_TYPE_VAST_VIDEO")); parser .addArgument("--declared_click_urls") .help("The click-through URLs being declared. Specify each URL separated by a space.") .nargs("*") .setDefault(Collections.singletonList("http://test.com")); parser .addArgument("--declared_restricted_categories") .help( "The restricted categories being declared. Specify each category separated by a " + "space.") .nargs("*"); parser .addArgument("--declared_vendor_ids") .help("The vendor IDs being declared. Specify each ID separated by a space.") .type(Integer.class) .nargs("*"); parser .addArgument("--video_url") .help("The URL to fetch a video ad.") .setDefault("https://video.test.com/ads?id=123456&wprice=%%WINNING_PRICE%%"); Namespace parsedArgs = null; try { parsedArgs = parser.parseArgs(args); } catch (ArgumentParserException ex) { parser.handleError(ex); System.exit(1); } RealTimeBidding client = null; try { client = Utils.getRealTimeBiddingClient(); } catch (IOException ex) { System.out.printf("Unable to create RealTimeBidding API service:\n%s", ex); System.out.println("Did you specify a valid path to a service account key file?"); System.exit(1); } catch (GeneralSecurityException ex) { System.out.printf("Unable to establish secure HttpTransport:\n%s", ex); System.exit(1); } try { execute(client, parsedArgs); } catch (IOException ex) { System.out.printf("RealTimeBidding API returned error response:\n%s", ex); System.exit(1); } } }
PHP
<?php /** * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Buyers_Creatives; use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample; use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config; use Google_Service_RealTimeBidding_Creative; use Google_Service_RealTimeBidding_VideoContent; /** * This example illustrates how to create video creatives for a given buyer account. */ class CreateVideoCreatives extends BaseExample { public function __construct($client) { $this->service = Config::getGoogleServiceRealTimeBidding($client); } /** * @see BaseExample::getInputParameters() */ protected function getInputParameters() { return [ [ 'name' => 'account_id', 'display' => 'Account ID', 'description' => 'The resource ID of the buyers resource under which the creative is to be ' . 'created.', 'required' => true ], [ 'name' => 'advertiser_name', 'display' => 'Advertiser name', 'description' => 'The name of the company being advertised in the creative.', 'required' => false, 'default' => 'Test' ], [ 'name' => 'creative_id', 'display' => 'Creative ID', 'description' => 'The user-specified creative ID. The maximum length of the creative ID is ' . '128 bytes', 'required' => false, 'default' => 'Video_Creative_' . uniqid() ], [ 'name' => 'declared_attributes', 'display' => 'Declared attributes', 'description' => 'The creative attributes being declared. Specify each attribute separated ' . 'by a comma.', 'required' => false, 'is_array' => true, 'default' => ['CREATIVE_TYPE_VAST_VIDEO'] ], [ 'name' => 'declared_click_urls', 'display' => 'Declared click URLs', 'description' => 'The click-through URLs being declared. Specify each URL separated by a comma.', 'required' => false, 'is_array' => true, 'default' => ['http://test.com'] ], [ 'name' => 'declared_restricted_categories', 'display' => 'Declared restricted categories', 'description' => 'The restricted categories being declared. Specify each category separated ' . 'by a comma.', 'required' => false, 'is_array' => true ], [ 'name' => 'declared_vendor_ids', 'display' => 'Declared vendor IDs', 'description' => 'The vendor IDs being declared. Specify each ID separated by a comma.', 'required' => false, 'is_array' => true ], [ 'name' => 'video_url', 'display' => 'Video URL', 'description' => 'The URL to fetch a video ad.', 'required' => false, 'default' => 'https://video.test.com/ads?id=123456&wprice=%%WINNING_PRICE%%' ] ]; } /** * @see BaseExample::run() */ public function run() { $values = $this->formValues; $parentName = "buyers/$values[account_id]"; $video = new Google_Service_RealTimeBidding_VideoContent(); $video->videoUrl = $values['video_url']; $newCreative = new Google_Service_RealTimeBidding_Creative(); $newCreative->advertiserName = $values['advertiser_name']; $newCreative->creativeId = $values['creative_id']; $newCreative->declaredAttributes = $values['declared_attributes']; $newCreative->declaredClickThroughUrls = $values['declared_click_urls']; $newCreative->declaredRestrictedCategories = $values['declared_restricted_categories']; $newCreative->declaredVendorIds = $values['declared_vendor_ids']; $newCreative->setVideo($video); print "<h2>Creating Creative for '$parentName':</h2>"; $result = $this->service->buyers_creatives->create($parentName, $newCreative); $this->printResult($result); } /** * @see BaseExample::getName() */ public function getName() { return 'Create Buyer Video Creative'; } }
Python
#!/usr/bin/python # # Copyright 2020 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Creates a creative with video content for the given buyer account ID.""" import argparse import datetime import os import pprint import sys import uuid sys.path.insert(0, os.path.abspath('../../..')) from googleapiclient.errors import HttpError import util _BUYER_NAME_TEMPLATE = 'buyers/%s' DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE' def main(realtimebidding, args): account_id = args.account_id creative = { 'advertiserName': args.advertiser_name, 'creativeId': args.creative_id, 'declaredAttributes': args.declared_attributes, 'declaredClickThroughUrls': args.declared_click_urls, 'declaredRestrictedCategories': args.declared_restricted_categories, 'declaredVendorIds': [int(id) for id in args.declared_vendor_ids], 'video': { 'videoUrl': args.video_url } } print(f'Creating video creative for buyer account ID "{account_id}":') try: # Construct and execute the request. response = (realtimebidding.buyers().creatives().create( parent=_BUYER_NAME_TEMPLATE % account_id, body=creative).execute()) except HttpError as e: print(e) sys.exit(1) pprint.pprint(response) if __name__ == '__main__': try: service = util.GetService(version='v1') except IOError as ex: print(f'Unable to create realtimebidding service - {ex}') print('Did you specify the key file in util.py?') sys.exit(1) parser = argparse.ArgumentParser( description=('Creates a video creative for the given buyer account ID.') ) # Required fields. parser.add_argument( '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID, help=('The resource ID of the buyers resource under which the ' 'creative is to be created.')) # Optional fields. parser.add_argument( '--advertiser_name', default='Test', help='The name of the company being advertised in the creative.') parser.add_argument( '-c', '--creative_id', default='HTML_Creative_%s' % uuid.uuid4(), help=('The user-specified creative ID. The maximum length of the ' 'creative ID is 128 bytes.')) parser.add_argument( '--declared_attributes', nargs='*', default=['CREATIVE_TYPE_VAST_VIDEO'], help=('The creative attributes being declared. Specify each attribute ' 'separated by a space.')) parser.add_argument( '--declared_click_urls', nargs='*', default=['http://test.com'], help=('The click-through URLs being declared. Specify each URL ' 'separated by a space.')) parser.add_argument( '--declared_restricted_categories', nargs='*', default=[], help=('The restricted categories being declared. Specify each category ' 'separated by a space.')) parser.add_argument( '--declared_vendor_ids', nargs='*', default=[], help=('The vendor IDs being declared. Specify each ID separated by a ' 'space.')) parser.add_argument( '--video_url', help='The URL to fetch a video ad.', default='https://video.test.com/ads?id=123456&wprice=%%WINNING_PRICE%%') args = parser.parse_args() main(service, args)
Ruby
#!/usr/bin/env ruby # Encoding: utf-8 # # Copyright:: Copyright 2020 Google LLC # # License:: Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # # Creates a creative with video content for the given buyer account ID. require 'optparse' require 'securerandom' require_relative '../../../util' def create_video_creatives(realtimebidding, options) parent = "buyers/#{options[:account_id]}" body = Google::Apis::RealtimebiddingV1::Creative.new( advertiser_name: options[:advertiser_name], creative_id: options[:creative_id], declared_attributes: options[:declared_attributes], declared_click_through_urls: options[:declared_click_urls], declared_resricted_categories: options[:declared_restricted_categories], declared_vendor_ids: options[:declared_vendor_ids], video: Google::Apis::RealtimebiddingV1::VideoContent.new( video_url: options[:video_url] ) ) puts "Creating video creative for buyer account '#{parent}'" creative = realtimebidding.create_buyer_creative(parent, creative_object=body) print_creative(creative) end if __FILE__ == $0 begin # Retrieve the service used to make API requests. service = get_service() rescue ArgumentError => e raise 'Unable to create service, with error message: #{e.message}' rescue Signet::AuthorizationError => e raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}' end # Set options and default values for fields used in this example. options = [ Option.new( 'account_id', 'The resource ID of the buyers resource under which the creatives were created, This will be used to construct '\ 'the name used as a path parameter for the creatives.get request.', type: Integer, short_alias: 'a', required: true, default_value: nil ), Option.new( 'creative_id', 'The user-specified creative ID. The maximum length of the creative ID is 128 bytes.', short_alias: 'c', required: false, default_value: "Video_Creative_#{SecureRandom.uuid}" ), Option.new( 'advertiser_name', 'The name of the company being advertised in the creative.', required: false, default_value: 'Test' ), Option.new( 'declared_attributes', 'The creative attributes being declared. Specify each attribute separated by a comma.', required: false, type: Array, default_value: ['CREATIVE_TYPE_VAST_VIDEO'] ), Option.new( 'declared_click_urls', 'The click-through URLs being declared. Specify each URL separated by a comma.', required: false, type: Array, default_value: ['http://test.com'] ), Option.new( 'declared_restricted_categories', 'The restricted categories being declared. Specify each category separated by a comma.', required: false, type: Array, default_value: [] ), Option.new( 'declared_vendor_ids', 'The vendor IDs being declared. Specify each ID separated by a space.', required: false, type: Array, default_value: [] ), Option.new( 'video_url', 'The URL to fetch a video ad.', required: false, default_value: 'https://video.test.com/ads?id=123456&wprice=%%WINNING_PRICE%%' ), ] # Parse options. parser = Parser.new(options) opts = parser.parse(ARGV) begin create_video_creatives(service, opts) rescue Google::Apis::ServerError => e raise "The following server error occured:\n#{e.message}" rescue Google::Apis::ClientError => e raise "Invalid client request:\n#{e.message}" rescue Google::Apis::AuthorizationError => e raise "Authorization error occured:\n#{e.message}" end end
Materi iklan SDK Pembeli
Untuk mengajukan bid dengan iklan yang dirender SDK pembeli, kirimkan materi iklan untuk ditinjau sebagai materi iklan HTML atau video. Materi iklan yang Anda kirim harus secara akurat merepresentasikan data rendering untuk SDK pembeli.
Setelah materi iklan disetujui, gunakan kolom id
, rendering_data
, dan declared_ad
dari sdk_rendered_ad
dalam respons bid Anda untuk menempatkan bid dengan
materi iklan. Anda juga dapat menggunakan materi iklan sebagai jenis yang Anda kirimkan untuk ditinjau
(HTML atau video).
Mengambil materi iklan yang ada
Berikut cara melihat materi iklan yang ada:
buyers.creatives.get
: Menampilkan satu materi iklan.buyers.creatives.list
: Mencantumkan beberapa materi iklan.
Mendapatkan materi iklan individual
Berikut ini cara mengambil materi iklan individual untuk
pembeli tertentu dengan
buyers.creatives.get
.
Kecuali jika parameter view
ditentukan sebagai FULL
, respons akan mengecualikan
sebagian besar kolom selain creativeServingDecision
.
REST
Permintaan
GET https://realtimebidding.googleapis.com/v1/buyers/<INSERT_ACCOUNT_ID_HERE>/creatives/HTML_Creative_09bb2ded-df72-42e6-a98f-28792b94ae4e?alt=json Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE> Content-Type: application/json
Respons
{ "accountId": "<ACCOUNT_ID>", "creativeId": "HTML_Creative_09bb2ded-df72-42e6-a98f-28792b94ae4e", "creativeFormat": "HTML", "creativeServingDecision": { "detectedProductCategories": [ 10016, 10019, 10141, 10168, 10754, 10885, 12206 ], "detectedLanguages": [ "en" ], "detectedAttributes": [ "CREATIVE_TYPE_HTML" ], "lastStatusUpdate": "2020-07-30T04:47:31.616018Z", "dealsPolicyCompliance": { "status": "APPROVED" }, "networkPolicyCompliance": { "status": "APPROVED" }, "platformPolicyCompliance": { "status": "APPROVED" }, "chinaPolicyCompliance": { "status": "APPROVED" }, "russiaPolicyCompliance": { "status": "APPROVED" } } }
C#
/* Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied * See the License for the specific language governing permissions and * limitations under the License. */ using Google.Apis.RealTimeBidding.v1; using Google.Apis.RealTimeBidding.v1.Data; using Mono.Options; using System; using System.Collections.Generic; namespace Google.Apis.RealTimeBidding.Examples.v1.Buyers.Creatives { /// <summary> /// Gets a single creative for the given buyer account ID and creative ID. /// </summary> public class GetCreatives : ExampleBase { private RealTimeBiddingService rtbService; /// <summary> /// Constructor. /// </summary> public GetCreatives() { rtbService = Utilities.GetRealTimeBiddingService(); } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get => "This code example gets a specific creative for a buyer account."; } /// <summary> /// Parse specified arguments. /// </summary> protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) { string[] requiredOptions = new string[] {"account_id", "creative_id"}; bool showHelp = false; string accountId = null; string creativeId = null; string view = null; OptionSet options = new OptionSet { "Get a creative for a given buyer account ID and creative ID.", { "h|help", "Show help message and exit.", h => showHelp = h != null }, { "a|account_id=", ("[Required] The resource ID of the buyers resource under which the " + "creatives were created. This will be used to construct the name used as " + "a path parameter for the creatives.get request."), a => accountId = a }, { "c|creative_id=", ("[Required] The resource ID of the buyers.creatives resource for which the " + "creative was created. This will be used to construct the name used as a " + "path parameter for the creatives.get request."), c => creativeId = c }, { "v|view=", ("Controls the amount of information included in the response. By default, " + "the creatives.get method only includes creativeServingDecision. This " + "sample configures the view to return the full contents of the creative " + @"by setting this to ""FULL""."), v => view = v }, }; List<string> extras = options.Parse(exampleArgs); var parsedArgs = new Dictionary<string, object>(); // Show help message. if(showHelp == true) { options.WriteOptionDescriptions(Console.Out); Environment.Exit(0); } // Set optional arguments. parsedArgs["account_id"] = accountId; parsedArgs["creative_id"] = creativeId; parsedArgs["view"] = view ?? "FULL"; // Validate that options were set correctly. Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras); return parsedArgs; } /// <summary> /// Run the example. /// </summary> /// <param name="parsedArgs">Parsed arguments for the example.</param> protected override void Run(Dictionary<string, object> parsedArgs) { string accountId = (string) parsedArgs["account_id"]; string creativeId = (string) parsedArgs["creative_id"]; string name = $"buyers/{accountId}/creatives/{creativeId}"; BuyersResource.CreativesResource.GetRequest request = rtbService.Buyers.Creatives.Get(name); request.View = (BuyersResource.CreativesResource.GetRequest.ViewEnum) Enum.Parse( typeof(BuyersResource.CreativesResource.ListRequest.ViewEnum), (string) parsedArgs["view"], false); Creative response = null; Console.WriteLine("Getting creative with name: {0}", name); try { response = request.Execute(); } catch (System.Exception exception) { throw new ApplicationException( $"Real-time Bidding API returned error response:\n{exception.Message}"); } Utilities.PrintCreative(response); } } }
Java
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.services.samples.authorizedbuyers.realtimebidding.v1.buyers.creatives; import com.google.api.services.realtimebidding.v1.RealTimeBidding; import com.google.api.services.realtimebidding.v1.model.Creative; import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils; import java.io.IOException; import java.security.GeneralSecurityException; import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.ArgumentParserException; import net.sourceforge.argparse4j.inf.Namespace; /** * This sample illustrates how to get a single creative for the given buyer account ID and creative * ID. */ public class GetCreatives { public static void execute(RealTimeBidding client, Namespace parsedArgs) throws IOException { Long accountId = parsedArgs.getLong("account_id"); String creativeId = parsedArgs.getString("creative_id"); String name = String.format("buyers/%s/creatives/%s", accountId, creativeId); Creative creative = client.buyers().creatives().get(name).setView(parsedArgs.getString("view")).execute(); System.out.printf( "Found Creative with ID '%s' for buyer account ID '%d':\n", creativeId, accountId); Utils.printCreative(creative); } public static void main(String[] args) { ArgumentParser parser = ArgumentParsers.newFor("GetCreatives") .build() .defaultHelp(true) .description(("Get a creative for the given buyer account ID and creative ID.")); parser .addArgument("-a", "--account_id") .help( "The resource ID of the buyers resource under which the creatives were created. " + "This will be used to construct the parent used as a path parameter for the " + "creatives.list request.") .required(true) .type(Long.class); parser .addArgument("-c", "--creative_id") .help( "The resource ID of the buyers.creatives resource for which the creative was created." + " This will be used to construct the name used as a path parameter for the" + " creatives.get request.") .required(true); parser .addArgument("-v", "--view") .help( "Controls the amount of information included in the response. By default, the" + " creatives.list method only includes creativeServingDecision. This sample" + " configures the view to return the full contents of the creatives by setting" + " this to 'FULL'.") .choices("FULL", "SERVING_DECISION_ONLY") .setDefault("FULL"); Namespace parsedArgs = null; try { parsedArgs = parser.parseArgs(args); } catch (ArgumentParserException ex) { parser.handleError(ex); System.exit(1); } RealTimeBidding client = null; try { client = Utils.getRealTimeBiddingClient(); } catch (IOException ex) { System.out.printf("Unable to create RealTimeBidding API service:\n%s", ex); System.out.println("Did you specify a valid path to a service account key file?"); System.exit(1); } catch (GeneralSecurityException ex) { System.out.printf("Unable to establish secure HttpTransport:\n%s", ex); System.exit(1); } try { execute(client, parsedArgs); } catch (IOException ex) { System.out.printf("RealTimeBidding API returned error response:\n%s", ex); System.exit(1); } } }
PHP
<?php /** * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Buyers_Creatives; use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample; use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config; /** * This example illustrates how to get a single creative for the given account and creative IDs. */ class GetCreatives extends BaseExample { public function __construct($client) { $this->service = Config::getGoogleServiceRealTimeBidding($client); } /** * @see BaseExample::getInputParameters() */ protected function getInputParameters() { return [ [ 'name' => 'account_id', 'display' => 'Account ID', 'required' => true, 'description' => 'The resource ID of the buyers resource under which the creative was ' . 'created. This will be used to construct the name used as a path parameter ' . 'for the creatives.get request.' ], [ 'name' => 'creative_id', 'display' => 'Creative ID', 'required' => true, 'description' => 'The resource ID of the buyers.creatives resource under which the creative ' . 'was created. This will be used to construct the name used as a path ' . 'parameter for the creatives.get request.' ] ]; } /** * @see BaseExample::run() */ public function run() { $values = $this->formValues; $name = "buyers/$values[account_id]/creatives/$values[creative_id]"; try { $creative = $this->service->buyers_creatives->get($name); print '<h2>Found creative.</h2>'; $this->printResult($creative); } catch (Google_Service_Exception $ex) { if ($ex->getCode() === 404 || $ex->getCode() === 403) { print '<h1>Creative not found or can\'t access creative</h1>'; } else { throw $ex; } } } /** * @see BaseExample::getName() */ public function getName() { return 'Get Creative'; } }
Python
#!/usr/bin/python # # Copyright 2020 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Gets a single creative for the given account and creative IDs.""" import argparse import os import pprint import sys sys.path.insert(0, os.path.abspath('../../..')) from googleapiclient.errors import HttpError import util _CREATIVES_NAME_TEMPLATE = 'buyers/%s/creatives/%s' DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE' DEFAULT_CREATIVE_RESOURCE_ID = 'ENTER_CREATIVE_RESOURCE_ID_HERE' def main(realtimebidding, account_id, creative_id): print(f'Get Creative with ID "{creative_id}" for account "{account_id}":') try: # Construct and execute the request. response = realtimebidding.buyers().creatives().get( name=_CREATIVES_NAME_TEMPLATE % (account_id, creative_id)).execute() except HttpError as e: print(e) sys.exit(1) pprint.pprint(response) if __name__ == '__main__': try: service = util.GetService(version='v1') except IOError as ex: print(f'Unable to create realtimebidding service - {ex}') print('Did you specify the key file in util.py?') sys.exit(1) parser = argparse.ArgumentParser( description=('Get a creative for the given buyer account ID and ' 'creative ID.')) # Required fields. parser.add_argument( '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID, help=('The resource ID of the buyers resource under which the ' 'creative was created. This will be used to construct the ' 'name used as a path parameter for the creatives.get request.')) parser.add_argument( '-c', '--creative_id', default=DEFAULT_CREATIVE_RESOURCE_ID, help=('The resource ID of the buyers.creatives resource for which the ' 'creative was created. This will be used to construct the name ' 'used as a path parameter for the creatives.get request.')) args = parser.parse_args() main(service, args.account_id, args.creative_id)
Ruby
#!/usr/bin/env ruby # Encoding: utf-8 # # Copyright:: Copyright 2020 Google LLC # # License:: Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # # Gets a single creative for the given account and creative IDs. require 'optparse' require_relative '../../../util' def get_creatives(realtimebidding, options) name = "buyers/#{options[:account_id]}/creatives/#{options[:creative_id]}" puts "Get creative with name '#{name}'" creative = realtimebidding.get_buyer_creative(name, view: options[:view]) print_creative(creative) end if __FILE__ == $0 begin # Retrieve the service used to make API requests. service = get_service() rescue ArgumentError => e raise 'Unable to create service, with error message: #{e.message}' rescue Signet::AuthorizationError => e raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}' end # Set options and default values for fields used in this example. options = [ Option.new( 'account_id', 'The resource ID of the buyers resource under which the creatives were created, This will be used to construct '\ 'the name used as a path parameter for the creatives.get request.', type: Integer, short_alias: 'a', required: true, default_value: nil ), Option.new( 'creative_id', 'The resource ID of the buyers.creatives resource for which the creative was created. This will be used to '\ 'construct the name used as a path parameter for the creatives.get request.', short_alias: 'c', required: true, default_value: nil ), Option.new( 'view', 'Controls the amount of information included in the response. By default, the creatives.get method only '\ 'includes creativeServingDecision. This sample configures the view to return the full contents of the creative'\ 'by setting this to FULL.', short_alias: 'v', required: false, default_value: 'FULL' ), ] # Parse options. parser = Parser.new(options) opts = parser.parse(ARGV) begin get_creatives(service, opts) rescue Google::Apis::ServerError => e raise "The following server error occured:\n#{e.message}" rescue Google::Apis::ClientError => e raise "Invalid client request:\n#{e.message}" rescue Google::Apis::AuthorizationError => e raise "Authorization error occured:\n#{e.message}" end end
Mencantumkan beberapa materi iklan
Berikut ini penjelasan cara mengambil daftar materi iklan untuk pembeli
tertentu dengan buyers.creatives.list
.
Kecuali jika parameter view
ditentukan sebagai FULL
, respons akan mengecualikan sebagian besar
kolom selain creativeServingDecision
.
Metode ini mendukung pemfilteran daftar.
Jika Anda tidak menggunakan pemfilteran, buyers.creatives.list
akan menampilkan semua materi iklan
yang terkait dengan akun pembeli.
Panggilan ini mungkin memerlukan waktu beberapa jam untuk diselesaikan jika materi iklan berjumlah besar. Anda mungkin perlu mengonfigurasi waktu tunggu yang lebih lama untuk panggilan ini, hingga lima menit.
Metode ini menampilkan snapshot materi iklan pada saat Anda membuat
permintaan. Untuk permintaan besar yang di-paging, snapshot diambil pada saat
permintaan untuk halaman pertama. Karena waktu yang diperlukan untuk memproses permintaan besar
yang di-paging, kolom creativeServingDecision
dan lastStatusUpdate
dapat berubah untuk materi iklan di halaman berurutan pada saat Anda mendapatkan respons.
Pembaruan yang terjadi setelah snapshot tidak akan dicatat dalam respons. Artinya, respons mungkin tidak berisi informasi terbaru untuk permintaan besar yang diberi nomor halaman.
REST
Permintaan
GET https://realtimebidding.googleapis.com/v1/buyers/<INSERT_ACCOUNT_ID_HERE>/creatives?filter=creativeServingDecision.networkPolicyCompliance.status%3DAPPROVED+AND+creativeFormat%3DHTML&view=FULL&pageSize=3&alt=json Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE> Content-Type: application/json
Respons
{ "creatives": [ { "name": "buyers/<ACCOUNT_ID>/creatives/HTML_Creative_%2389d53648-1e9d-428e-bd60-06f8f81d8a0d", "accountId": "<ACCOUNT_ID>", "creativeId": "HTML_Creative_#89d53648-1e9d-428e-bd60-06f8f81d8a0d", "html": { "snippet": "<iframe marginwidth=0 marginheight=0 height=600 frameborder=0 width=160 scrolling=no src=\\\"https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%&wprice=%%WINNING_PRICE_ESC%%\\\"></iframe>", "width": 300, "height": 250 }, "creativeFormat": "HTML", "declaredClickThroughUrls": [ "http://test.com" ], "declaredAttributes": [ "CREATIVE_TYPE_HTML" ], "advertiserName": "Test", "apiUpdateTime": "2020-07-17T23:34:48.072475Z", "activityMetrics": { "yesterday": { "spend": { "currencyCode": "USD" }, "forgoneSpend": { "currencyCode": "USD" } }, "last7Days": { "spend": { "currencyCode": "USD" }, "forgoneSpend": { "currencyCode": "USD" } } }, "previewUrl": "https://storage.googleapis.com/g-authorized-buyers-creative-previews/lVljTKfc2vIA0JiMoEawKsslu5cWrXgD_tuFwRADsyinpD5J2XYMX7eNAwQ", "creativeServingDecision": { "detectedProductCategories": [ 10016, 10019, 10141, 10168, 10754, 10885, 12206 ], "detectedLanguages": [ "en" ], "detectedAttributes": [ "CREATIVE_TYPE_HTML" ], "lastStatusUpdate": "2020-07-18T08:24:46.847935Z", "dealsPolicyCompliance": { "status": "APPROVED" }, "networkPolicyCompliance": { "status": "APPROVED" }, "platformPolicyCompliance": { "status": "APPROVED" }, "chinaPolicyCompliance": { "status": "DISAPPROVED" }, "russiaPolicyCompliance": { "status": "DISAPPROVED" } } }, { "name": "buyers/<ACCOUNT_ID>/creatives/HTML_Creative_%23ac0770fa-5294-4571-856e-9ec6f613e590", "accountId": "<ACCOUNT_ID>", "creativeId": "HTML_Creative_#ac0770fa-5294-4571-856e-9ec6f613e590", "html": { "snippet": "<iframe marginwidth=0 marginheight=0 height=600 frameborder=0 width=160 scrolling=no src=\"https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%&wprice=%%WINNING_PRICE_ESC%%\"></iframe>", "width": 300, "height": 250 }, "creativeFormat": "HTML", "declaredClickThroughUrls": [ "test.com" ], "declaredAttributes": [ "CREATIVE_TYPE_HTML" ], "advertiserName": "Test", "apiUpdateTime": "2020-07-15T21:24:10.269378Z", "activityMetrics": { "yesterday": { "spend": { "currencyCode": "USD" }, "forgoneSpend": { "currencyCode": "USD" } }, "last7Days": { "spend": { "currencyCode": "USD" }, "forgoneSpend": { "currencyCode": "USD" } } }, "previewUrl": "https://storage.googleapis.com/g-authorized-buyers-creative-previews/hedyN-6bCXEA0JiMoD8I704lPjLIl_-GXo7AOqBnWQJaOnuH6w6hUWzre2A", "creativeServingDecision": { "detectedProductCategories": [ 10016, 10019, 10141, 10168, 10754, 10885, 12206 ], "detectedLanguages": [ "en" ], "detectedAttributes": [ "CREATIVE_TYPE_HTML" ], "lastStatusUpdate": "2020-07-15T22:02:39.925606Z", "dealsPolicyCompliance": { "status": "APPROVED" }, "networkPolicyCompliance": { "status": "APPROVED" }, "platformPolicyCompliance": { "status": "APPROVED" }, "chinaPolicyCompliance": { "status": "APPROVED" }, "russiaPolicyCompliance": { "status": "APPROVED" } } }, { "name": "buyers/<ACCOUNT_ID>/creatives/HTML_Creative_%2383fb53fa-e8be-42f8-88cd-30453f04ab9b", "accountId": "<ACCOUNT_ID>", "creativeId": "HTML_Creative_#83fb53fa-e8be-42f8-88cd-30453f04ab9b", "html": { "snippet": "<iframe marginwidth=0 marginheight=0 height=600 frameborder=0 width=160 scrolling=no\n src=\"https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%&wprice=%%WINNING_PRICE_ESC%%\">\n</iframe>\n", "width": 300, "height": 250 }, "creativeFormat": "HTML", "declaredClickThroughUrls": [ "http://test.com" ], "declaredAttributes": [ "CREATIVE_TYPE_HTML" ], "advertiserName": "Test", "version": 1, "apiUpdateTime": "2020-07-23T20:41:48.420172Z", "activityMetrics": { "yesterday": { "spend": { "currencyCode": "USD" }, "forgoneSpend": { "currencyCode": "USD" } }, "last7Days": { "spend": { "currencyCode": "USD" }, "forgoneSpend": { "currencyCode": "USD" } } }, "previewUrl": "https://storage.googleapis.com/g-authorized-buyers-creative-previews/vm8sg3ISJRsA0JiMoAT89KJdex1E9Bq9dPyRUSL9g9pu4P73NbwJOUM_G2U", "creativeServingDecision": { "detectedProductCategories": [ 10016, 10019, 10141, 10168, 10754, 10885, 12206 ], "detectedLanguages": [ "en" ], "detectedAttributes": [ "CREATIVE_TYPE_HTML" ], "lastStatusUpdate": "2020-07-23T21:29:31.105040Z", "dealsPolicyCompliance": { "status": "APPROVED" }, "networkPolicyCompliance": { "status": "APPROVED" }, "platformPolicyCompliance": { "status": "APPROVED" }, "chinaPolicyCompliance": { "status": "APPROVED" }, "russiaPolicyCompliance": { "status": "APPROVED" } } } ], "nextPageToken": "CngKTPcAAAAA_____4AA__8AAP__AAD__wAA__8AAP__AAD__wAA__8AAP8B__5zbi01MzcyODQxMC03NTc4NzQ1OTI4MDI0NTAwODAxAAEQAyEEJCN6EliW_DkAAAAA_____0gDUABaCwnlcIbkBz11fxADYKWxoxIaWGNyZWF0aXZlU2VydmluZ0RlY2lzaW9uLm9wZW5BdWN0aW9uU2VydmluZ1N0YXR1cy5zdGF0dXM9QVBQUk9WRUQgQU5EIGNyZWF0aXZlRm9ybWF0PUhUTUwg166a-uyH6wI=", "totalSize": 25 }
C#
/* Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied * See the License for the specific language governing permissions and * limitations under the License. */ using Google.Apis.RealTimeBidding.v1; using Google.Apis.RealTimeBidding.v1.Data; using Mono.Options; using System; using System.Collections.Generic; namespace Google.Apis.RealTimeBidding.Examples.v1.Buyers.Creatives { /// <summary> /// Lists creatives for a given buyer account ID. /// </summary> public class ListCreatives : ExampleBase { private RealTimeBiddingService rtbService; /// <summary> /// Constructor. /// </summary> public ListCreatives() { rtbService = Utilities.GetRealTimeBiddingService(); } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get => "This code example lists all creatives for a given buyer account."; } /// <summary> /// Parse specified arguments. /// </summary> protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) { string[] requiredOptions = new string[] {"account_id"}; bool showHelp = false; string defaultFilter = "creativeServingDecision.networkPolicyCompliance.status=" + "APPROVED AND creativeFormat=HTML"; string accountId = null; string filter = null; int? pageSize = null; string view = null; OptionSet options = new OptionSet { "List creatives for the given buyer account.", { "h|help", "Show help message and exit.", h => showHelp = h != null }, { "a|account_id=", ("[Required] The resource ID of the buyers resource under which the " + "creatives were created. This will be used to construct the parent used as " + "a path parameter for the creatives.list request."), a => accountId = a }, { "p|page_size=", ("The number of rows to return per page. The server may return fewer rows " + "than specified."), (int p) => pageSize = p }, { "f|filter=", ("Query string to filter creatives. If no filter is specified, all active " + "creatives will be returned. To demonstrate usage, the default behavior of" + "this sample is to filter such that only approved HTML snippet creatives " + "are returned."), f => filter = f }, { "v|view=", ("Controls the amount of information included in the response. By default, " + "the creatives.list method only includes creativeServingDecision. This " + "sample configures the view to return the full contents of the creatives " + @"by setting this to ""FULL""."), v => view = v }, }; List<string> extras = options.Parse(exampleArgs); var parsedArgs = new Dictionary<string, object>(); // Show help message. if(showHelp == true) { options.WriteOptionDescriptions(Console.Out); Environment.Exit(0); } // Set arguments. parsedArgs["account_id"] = accountId; parsedArgs["pageSize"] = pageSize ?? Utilities.MAX_PAGE_SIZE; parsedArgs["filter"] = filter ?? defaultFilter; parsedArgs["view"] = view ?? "FULL"; // Validate that options were set correctly. Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras); return parsedArgs; } /// <summary> /// Run the example. /// </summary> /// <param name="parsedArgs">Parsed arguments for the example.</param> protected override void Run(Dictionary<string, object> parsedArgs) { string accountId = (string) parsedArgs["account_id"]; string parent = $"buyers/{accountId}"; string pageToken = null; Console.WriteLine(@"Listing creatives for buyer account ""{0}""", parent); do { BuyersResource.CreativesResource.ListRequest request = rtbService.Buyers.Creatives.List(parent); request.Filter = (string) parsedArgs["filter"]; request.PageSize = (int) parsedArgs["pageSize"]; request.PageToken = pageToken; request.View = (BuyersResource.CreativesResource.ListRequest.ViewEnum) Enum.Parse( typeof(BuyersResource.CreativesResource.ListRequest.ViewEnum), (string) parsedArgs["view"], false); ListCreativesResponse page = null; try { page = request.Execute(); } catch (System.Exception exception) { throw new ApplicationException( $"Real-time Bidding API returned error response:\n{exception.Message}"); } var creatives = page.Creatives; pageToken = page.NextPageToken; if(creatives == null) { Console.WriteLine("No creatives found for buyer account."); } else { foreach (Creative creative in creatives) { Utilities.PrintCreative(creative); } } } while(pageToken != null); } } }
Java
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.services.samples.authorizedbuyers.realtimebidding.v1.buyers.creatives; import com.google.api.services.realtimebidding.v1.RealTimeBidding; import com.google.api.services.realtimebidding.v1.model.Creative; import com.google.api.services.realtimebidding.v1.model.ListCreativesResponse; import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.List; import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.ArgumentParserException; import net.sourceforge.argparse4j.inf.Namespace; /** This sample illustrates how to list Creatives for a given buyer account ID. */ public class ListCreatives { public static void execute(RealTimeBidding client, Namespace parsedArgs) throws IOException { Long accountId = parsedArgs.getLong("account_id"); Integer pageSize = parsedArgs.getInt("page_size"); String parentBuyerName = String.format("buyers/%s", accountId); String pageToken = null; System.out.printf("Found Creatives for buyer Account ID '%d':\n", accountId); do { List<Creative> creatives = null; ListCreativesResponse response = client .buyers() .creatives() .list(parentBuyerName) .setFilter(parsedArgs.getString("filter")) .setView(parsedArgs.getString("view")) .setPageSize(pageSize) .setPageToken(pageToken) .execute(); creatives = response.getCreatives(); pageToken = response.getNextPageToken(); if (creatives == null) { System.out.println("No creatives found."); } else { for (Creative creative : creatives) { Utils.printCreative(creative); } } } while (pageToken != null); } public static void main(String[] args) { ArgumentParser parser = ArgumentParsers.newFor("ListCreatives") .build() .defaultHelp(true) .description(("Lists creatives associated with the given buyer account.")); parser .addArgument("-a", "--account_id") .help( "The resource ID of the buyers resource under which the creatives were created. " + "This will be used to construct the parent used as a path parameter for the " + "creatives.list request.") .required(true) .type(Long.class); parser .addArgument("-p", "--page_size") .help( "The resource ID of the buyers resource under which the user lists were created. " + "This will be used to construct the parent used as a path parameter for the " + "userLists.list request.") .setDefault(Utils.getMaximumPageSize()) .type(Integer.class); parser .addArgument("-f", "--filter") .help( "Query string to filter creatives. If no filter is specified, all active creatives will" + " be returned. To demonstrate usage, the default behavior of this sample is to" + " filter such that only approved HTML snippet creatives are returned.") .setDefault( "creativeServingDecision.networkPolicyCompliance.status=APPROVED " + "AND creativeFormat=HTML"); parser .addArgument("-v", "--view") .help( "Controls the amount of information included in the response. By default, the" + " creatives.list method only includes creativeServingDecision. This sample" + " configures the view to return the full contents of the creatives by setting" + " this to 'FULL'.") .choices("FULL", "SERVING_DECISION_ONLY") .setDefault("FULL"); Namespace parsedArgs = null; try { parsedArgs = parser.parseArgs(args); } catch (ArgumentParserException ex) { parser.handleError(ex); System.exit(1); } RealTimeBidding client = null; try { client = Utils.getRealTimeBiddingClient(); } catch (IOException ex) { System.out.printf("Unable to create RealTimeBidding API service:\n%s", ex); System.out.println("Did you specify a valid path to a service account key file?"); System.exit(1); } catch (GeneralSecurityException ex) { System.out.printf("Unable to establish secure HttpTransport:\n%s", ex); System.exit(1); } try { execute(client, parsedArgs); } catch (IOException ex) { System.out.printf("RealTimeBidding API returned error response:\n%s", ex); System.exit(1); } } }
PHP
<?php /** * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Buyers_Creatives; use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample; use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config; /** * This example illustrates how to list creatives for the given buyer's account ID. */ class ListCreatives extends BaseExample { public function __construct($client) { $this->service = Config::getGoogleServiceRealTimeBidding($client); } /** * @see BaseExample::getInputParameters() */ protected function getInputParameters() { return [ [ 'name' => 'account_id', 'display' => 'Buyer account ID', 'required' => true, 'description' => 'The resource ID of the buyers resource under which the creatives were ' . 'created. This will be used to construct the parent used as a path ' . 'parameter for the creatives.list request.' ], [ 'name' => 'filter', 'display' => 'Filter', 'required' => false, 'description' => 'Query string to filter creatives. If no filter is specified, all active ' . 'creatives will be returned. To demonstrate usage, the default behavior of ' . 'this sample is to filter such that only approved HTML snippet creatives ' . 'are returned.', 'default' => 'creativeServingDecision.networkPolicyCompliance.status=APPROVED ' . 'AND creativeFormat=HTML' ], [ 'name' => 'view', 'display' => 'View', 'required' => false, 'description' => 'Controls the amount of information included in the response. By default, ' . 'the creatives.list method only includes creativeServingDecision. This ' . 'sample configures the view to return the full contents of the creatives by ' . 'setting this to "FULL".', 'default' => 'FULL' ] ]; } /** * @see BaseExample::run() */ public function run() { $values = $this->formValues; $parentName = "buyers/$values[account_id]"; $queryParams = [ 'filter' => $values['filter'], 'pageSize' => 10, 'view' => $values['view'] ]; $result = $this->service->buyers_creatives->listBuyersCreatives($parentName, $queryParams); print "<h2>Creatives found for '$parentName':</h2>"; if (empty($result['creatives'])) { print '<p>No Creatives found</p>'; } else { foreach ($result['creatives'] as $creative) { $this->printResult($creative); } } } /** * @see BaseExample::getName() */ public function getName() { return 'List Buyer Creatives'; } }
Python
#!/usr/bin/python # # Copyright 2020 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Lists creatives for the given buyer account ID.""" import argparse import os import pprint import sys sys.path.insert(0, os.path.abspath('../../..')) from googleapiclient.errors import HttpError import util _BUYER_NAME_TEMPLATE = 'buyers/%s' DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE' def main(realtimebidding, args): account_id = args.account_id list_filter = args.filter view = args.view page_size = args.page_size page_token = None more_pages = True print(f'Listing creatives for buyer account: "{account_id}".') while more_pages: try: # Construct and execute the request. response = realtimebidding.buyers().creatives().list( parent=_BUYER_NAME_TEMPLATE % account_id, pageToken=page_token, filter=list_filter, view=view, pageSize=page_size).execute() except HttpError as e: print(e) sys.exit(1) pprint.pprint(response) page_token = response.get('nextPageToken') more_pages = bool(page_token) if __name__ == '__main__': try: service = util.GetService(version='v1') except IOError as ex: print(f'Unable to create realtimebidding service - {ex}') print('Did you specify the key file in util.py?') sys.exit(1) default_list_filter = ( 'creativeServingDecision.networkPolicyCompliance.status=APPROVED ' 'AND creativeFormat=HTML') parser = argparse.ArgumentParser( description=('Lists creatives for the given buyer account.')) # Required fields. parser.add_argument( '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID, help=('The resource ID of the buyers resource under which the ' 'creatives were created. This will be used to construct the ' 'parent used as a path parameter for the creatives.list request.')) parser.add_argument( '-p', '--page_size', default=util.MAX_PAGE_SIZE, help=('The number of rows to return per page. The server may return ' 'fewer rows than specified.')) # Optional fields. parser.add_argument( '-f', '--filter', default=default_list_filter, help=('Query string to filter creatives. If no filter is specified, all ' 'active creatives will be returned. To demonstrate usage, the ' 'default behavior of this sample is to filter such that only ' 'approved HTML snippet creatives are returned.')) parser.add_argument( '-v', '--view', default='FULL', help=('Controls the amount of information included in the response. By ' 'default, the creatives.list method only includes ' 'creativeServingDecision. This sample configures the view to ' 'return the full contents of the creatives by setting this to ' '"FULL".')) args = parser.parse_args() main(service, args)
Ruby
#!/usr/bin/env ruby # Encoding: utf-8 # # Copyright:: Copyright 2020 Google LLC # # License:: Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # # Retrieves creatives for a given buyer account ID. require 'optparse' require_relative '../../../util' def list_creatives(realtimebidding, options) parent = "buyers/#{options[:account_id]}" filter = options[:filter] view = options[:view] page_size = options[:page_size] page_token = nil puts "Listing creatives for buyer account '#{parent}'" begin response = realtimebidding.list_buyer_creatives( parent, filter: filter, view: view, page_size: page_size, page_token: page_token ) page_token = response.next_page_token unless response.creatives.nil? response.creatives.each do |creative| print_creative(creative) end else puts 'No creatives found for buyer account' end end until page_token == nil end if __FILE__ == $0 begin # Retrieve the service used to make API requests. service = get_service() rescue ArgumentError => e raise 'Unable to create service, with error message: #{e.message}' rescue Signet::AuthorizationError => e raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}' end default_list_filter = 'creativeServingDecision.networkPolicyCompliance.status=APPROVED AND creativeFormat=HTML' # Set options and default values for fields used in this example. options = [ Option.new( 'account_id', 'The resource ID of the buyers resource under which the creatives were created, This will be used to construct'\ 'the parent used as a path parameter for the creatives.list request.', type: Integer, short_alias: 'a', required: true, default_value: nil ), Option.new( 'filter', 'Query string to filter creatives. If no filter is specified, all active creatives will be returned. To '\ 'demonstrate usage, the default behavior of this sample is to filter such that only approved HTML snippet '\ 'creatives are returned.', short_alias: 'f', required: false, default_value: default_list_filter ), Option.new( 'view', 'Controls the amount of information included in the response. By default, the creatives.list method only '\ 'includes creativeServingDecision. This sample configures the view to return the full contents of creatives by '\ 'setting this to FULL.', short_alias: 'v', required: false, default_value: 'FULL' ), Option.new( 'page_size', 'The number of rows to return per page. The server may return fewer rows than specified.', type: Array, short_alias: 'u', required: false, default_value: MAX_PAGE_SIZE ), ] # Parse options. parser = Parser.new(options) opts = parser.parse(ARGV) begin list_creatives(service, opts) rescue Google::Apis::ServerError => e raise "The following server error occured:\n#{e.message}" rescue Google::Apis::ClientError => e raise "Invalid client request:\n#{e.message}" rescue Google::Apis::AuthorizationError => e raise "Authorization error occured:\n#{e.message}" end end
Melakukan patch pada materi iklan yang ada
Berikut ini cara melakukan patch pada materi iklan yang ada untuk pembeli
tertentu dengan buyers.creatives.patch
.
Materi iklan hanya dapat di-patch jika telah menyelesaikan peninjauan, dan version
-nya akan ditambah setelah patch berhasil.
Kecuali jika Anda ingin mengganti semua kolom materi iklan yang dapat ditulis, Anda harus menentukan kolom yang di-patch dengan parameter updateMask
. Jika tidak,
atribut apa pun yang dapat ditulis dalam isi permintaan, termasuk nilai kosong atau null,
akan menimpa nilai yang ada.
REST
Permintaan
PATCH https://realtimebidding.googleapis.com/v1/buyers/<INSERT_ACCOUNT_ID_HERE>/creatives/HTML_Creative_09bb2ded-df72-42e6-a98f-28792b94ae4e?updateMask=advertiserName%2CdeclaredClickThroughUrls&alt=json Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE> Content-Type: application/json { "advertiserName": "Test-Advertiser-ed901b94-8e6f-40ee-adc2-666fe2224e01", "declaredClickThroughUrls": [ "https://test.clickurl.com/93d4666e-b5de-406b-9729-fa75b53e655c", "https://test.clickurl.com/db4939f0-79ba-4bfb-a21e-6e198a052de5", "https://test.clickurl.com/33e02bcb-ada2-4240-933e-afb356fbe8af" ] }
Respons
{ "name": "buyers/<ACCOUNT_ID>/creatives/HTML_Creative_09bb2ded-df72-42e6-a98f-28792b94ae4e", "accountId": "<ACCOUNT_ID>", "creativeId": "HTML_Creative_09bb2ded-df72-42e6-a98f-28792b94ae4e", "html": { "snippet": "<iframe marginwidth=0 marginheight=0 height=600 frameborder=0 width=160 scrolling=no src=\"https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%&wprice=%%WINNING_PRICE_ESC%%\"></iframe>", "width": 300, "height": 250 }, "creativeFormat": "HTML", "declaredClickThroughUrls": [ "https://test.clickurl.com/93d4666e-b5de-406b-9729-fa75b53e655c", "https://test.clickurl.com/db4939f0-79ba-4bfb-a21e-6e198a052de5", "https://test.clickurl.com/33e02bcb-ada2-4240-933e-afb356fbe8af" ], "declaredAttributes": [ "CREATIVE_TYPE_HTML" ], "advertiserName": "Test-Advertiser-ed901b94-8e6f-40ee-adc2-666fe2224e01", "version": 2, "apiUpdateTime": "2020-08-07T00:47:42.431231Z", "creativeServingDecision": { "lastStatusUpdate": "2020-08-07T00:47:42.432Z", "dealsPolicyCompliance": { "status": "PENDING_REVIEW" }, "networkPolicyCompliance": { "status": "PENDING_REVIEW" }, "platformPolicyCompliance": { "status": "PENDING_REVIEW" }, "chinaPolicyCompliance": { "status": "PENDING_REVIEW" }, "russiaPolicyCompliance": { "status": "PENDING_REVIEW" } } }
C#
/* Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied * See the License for the specific language governing permissions and * limitations under the License. */ using Google.Apis.RealTimeBidding.v1; using Google.Apis.RealTimeBidding.v1.Data; using Mono.Options; using System; using System.Collections.Generic; namespace Google.Apis.RealTimeBidding.Examples.v1.Buyers.Creatives { /// <summary> /// Patches a creative with the specified name. /// </summary> public class PatchCreatives : ExampleBase { private RealTimeBiddingService rtbService; /// <summary> /// Constructor. /// </summary> public PatchCreatives() { rtbService = Utilities.GetRealTimeBiddingService(); } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get => "This code example patches a creative having the specified name."; } /// <summary> /// Parse specified arguments. /// </summary> protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) { string[] requiredOptions = new string[] {"account_id", "creative_id"}; bool showHelp = false; string accountId = null; string creativeId = null; OptionSet options = new OptionSet { "Patches the specified creative.", { "h|help", "Show help message and exit.", h => showHelp = h != null }, { "a|account_id=", ("[Required] The resource ID of the buyers resource under which the " + "creatives were created. This will be used to construct the name used as " + "a path parameter for the creatives.get request."), a => accountId = a }, { "c|creative_id=", ("[Required] The resource ID of the buyers.creatives resource for which the " + "creative was created. This will be used to construct the name used as a " + "path parameter for the creatives.patch request."), c => creativeId = c } }; List<string> extras = options.Parse(exampleArgs); var parsedArgs = new Dictionary<string, object>(); // Show help message. if(showHelp == true) { options.WriteOptionDescriptions(Console.Out); Environment.Exit(0); } // Set arguments. parsedArgs["account_id"] = accountId; parsedArgs["creative_id"] = creativeId; // Validate that options were set correctly. Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras); return parsedArgs; } /// <summary> /// Run the example. /// </summary> /// <param name="parsedArgs">Parsed arguments for the example.</param> protected override void Run(Dictionary<string, object> parsedArgs) { var accountId = (string) parsedArgs["account_id"]; var creativeId = (string) parsedArgs["creative_id"]; var name = $"buyers/{accountId}/creatives/{creativeId}"; IList<String> declaredClickThroughUrls = new List<string>(new string[] { $"https://test.clickurl.com/{System.Guid.NewGuid()}", $"https://test.clickurl.com/{System.Guid.NewGuid()}", $"https://test.clickurl.com/{System.Guid.NewGuid()}" }); Creative update = new Creative(); update.AdvertiserName = $"Test-Advertiser-{System.Guid.NewGuid()}"; update.DeclaredClickThroughUrls = declaredClickThroughUrls; BuyersResource.CreativesResource.PatchRequest request = rtbService.Buyers.Creatives.Patch(update, name); // Configure the update mask such that only the advertiserName and // declaredClickThroughUrls fields are updated. If not set, the patch method would // overwrite all other writable fields with a null value. request.UpdateMask = "advertiserName,declaredClickThroughUrls"; Creative response = null; Console.WriteLine("Patching creative with name: {0}", name); try { response = request.Execute(); } catch (System.Exception exception) { throw new ApplicationException( $"Real-time Bidding API returned error response:\n{exception.Message}"); } Utilities.PrintCreative(response); } } }
Java
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.services.samples.authorizedbuyers.realtimebidding.v1.buyers.creatives; import com.google.api.services.realtimebidding.v1.RealTimeBidding; import com.google.api.services.realtimebidding.v1.model.Creative; import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Arrays; import java.util.List; import java.util.UUID; import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.ArgumentParserException; import net.sourceforge.argparse4j.inf.Namespace; /** Patches a creative with the specified name. */ public class PatchCreatives { public static void execute(RealTimeBidding client, Namespace parsedArgs) throws IOException { Long accountId = parsedArgs.getLong("account_id"); String creativeId = parsedArgs.getString("creative_id"); String name = String.format("buyers/%s/creatives/%s", accountId, creativeId); List<String> declaredClickThroughUrls = Arrays.asList( String.format("https://test.clickurl.com/%s", UUID.randomUUID()), String.format("https://test.clickurl.com/%s", UUID.randomUUID()), String.format("https://test.clickurl.com/%s", UUID.randomUUID())); Creative update = new Creative(); update.setAdvertiserName(String.format("Test-Advertiser-%s", UUID.randomUUID())); update.setDeclaredClickThroughUrls(declaredClickThroughUrls); String uMask = "advertiserName,declaredClickThroughUrls"; Creative creative = client.buyers().creatives().patch(name, update).setUpdateMask(uMask).execute(); System.out.printf("Patched creative for buyer Account ID '%s':\n", accountId); Utils.printCreative(creative); } public static void main(String[] args) { ArgumentParser parser = ArgumentParsers.newFor("PatchCreatives") .build() .defaultHelp(true) .description( ("Patches the specified creative's advertiserName and " + "declaredClickThroughUrls.")); parser .addArgument("-a", "--account_id") .help("The resource ID of the buyers resource under which the creative is to be created.") .required(true) .type(Long.class); parser .addArgument("-c", "--creative_id") .help( "The resource ID of the buyers.creatives resource for which the creative was created." + " This will be used to construct the name used as a path parameter for the" + " creatives.patch request.") .required(true); Namespace parsedArgs = null; try { parsedArgs = parser.parseArgs(args); } catch (ArgumentParserException ex) { parser.handleError(ex); System.exit(1); } RealTimeBidding client = null; try { client = Utils.getRealTimeBiddingClient(); } catch (IOException ex) { System.out.printf("Unable to create RealTimeBidding API service:\n%s", ex); System.out.println("Did you specify a valid path to a service account key file?"); System.exit(1); } catch (GeneralSecurityException ex) { System.out.printf("Unable to establish secure HttpTransport:\n%s", ex); System.exit(1); } try { execute(client, parsedArgs); } catch (IOException ex) { System.out.printf("RealTimeBidding API returned error response:\n%s", ex); System.exit(1); } } }
PHP
<?php /** * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Buyers_Creatives; use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample; use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config; use Google_Service_RealTimeBidding_Creative; /** * This example illustrates how to patch a creative with the specified account and creative IDs. */ class PatchCreatives extends BaseExample { public function __construct($client) { $this->service = Config::getGoogleServiceRealTimeBidding($client); } /** * @see BaseExample::getInputParameters() */ protected function getInputParameters() { return [ [ 'name' => 'account_id', 'display' => 'Account ID', 'description' => 'The resource ID of the buyers resource under which the creative was ' . 'created. This will be used to construct the name used as a path parameter ' . 'for the creatives.patch request.', 'required' => true ], [ 'name' => 'creative_id', 'display' => 'Creative ID', 'description' => 'The resource ID of the buyers.creatives resource for which the creative ' . 'was created. This will be used to construct the name used as a path ' . 'parameter for the creatives.patch request.', 'required' => true ] ]; } /** * @see BaseExample::run() */ public function run() { $values = $this->formValues; $name = "buyers/$values[account_id]/creatives/$values[creative_id]"; $patchedCreative = new Google_Service_RealTimeBidding_Creative(); $patchedCreative->advertiserName = 'Test-Advertiser-' . uniqid(); $patchedCreative->declaredClickThroughUrls = [ 'https://test.clickurl.com/' . uniqid(), 'https://test.clickurl.com/' . uniqid(), 'https://test.clickurl.com/' . uniqid() ]; $queryParams = [ 'updateMask' => 'advertiserName,declaredClickThroughUrls' ]; print "<h2>Patching Creative '$name':</h2>"; $result = $this->service->buyers_creatives->patch($name, $patchedCreative, $queryParams); $this->printResult($result); } /** * @see BaseExample::getName() */ public function getName() { return 'Patch Buyer Creative'; } }
Python
#!/usr/bin/python # # Copyright 2020 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This example patches a creative with the specified name.""" import argparse import datetime import os import pprint import sys import uuid sys.path.insert(0, os.path.abspath('../../..')) from googleapiclient.errors import HttpError import util _CREATIVES_NAME_TEMPLATE = 'buyers/%s/creatives/%s' DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE' DEFAULT_CREATIVE_RESOURCE_ID = 'ENTER_USERLIST_RESOURCE_ID_HERE' def main(realtimebidding, args): account_id = args.account_id creative_id = args.creative_id creative = { 'advertiserName': f'Test-Advertiser-{uuid.uuid4()}', 'declaredClickThroughUrls': [f'https://test.clickurl.com/{uuid.uuid4()}' for _ in range(3)] } update_mask = ','.join(creative.keys()) print(f'Patching creative with ID {creative_id} for buyer account ID ' f'{account_id}:') try: # Construct and execute the request. response = (realtimebidding.buyers().creatives().patch( name=_CREATIVES_NAME_TEMPLATE % (account_id, creative_id), body=creative, updateMask=update_mask).execute()) except HttpError as e: print(e) sys.exit(1) pprint.pprint(response) if __name__ == '__main__': try: service = util.GetService(version='v1') except IOError as ex: print(f'Unable to create realtimebidding service - {ex}') print('Did you specify the key file in util.py?') sys.exit(1) parser = argparse.ArgumentParser( description=('Patches the specified creative.') ) # Required fields. parser.add_argument( '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID, help=('The resource ID of the buyers resource under which the ' 'creative was created. This will be used to construct the ' 'name used as a path parameter for the creatives.patch request.')) parser.add_argument( '-c', '--creative_id', default=DEFAULT_CREATIVE_RESOURCE_ID, help='The resource ID of the buyers.creatives resource for which the ' 'creative was created. This will be used to construct the ' 'name used as a path parameter for the creatives.patch request.') args = parser.parse_args() main(service, args)
Ruby
#!/usr/bin/env ruby # Encoding: utf-8 # # Copyright:: Copyright 2020 Google LLC # # License:: Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # # This example patches a creative with the specified name. require 'optparse' require 'securerandom' require_relative '../../../util' def patch_creatives(realtimebidding, options) name = "buyers/#{options[:account_id]}/creatives/#{options[:creative_id]}" declared_click_through_urls = [ "https://test.clickurl.com/#{SecureRandom.uuid}", "https://test.clickurl.com/#{SecureRandom.uuid}", "https://test.clickurl.com/#{SecureRandom.uuid}" ] body = Google::Apis::RealtimebiddingV1::Creative.new( advertiser_name: options[:advertiser_name], declared_click_through_urls: declared_click_through_urls, ) update_mask = 'advertiserName,declaredClickThroughUrls' puts "Patching creative with name '#{name}'" creative = realtimebidding.patch_buyer_creative( name, creative_object=body, update_mask: update_mask) print_creative(creative) end if __FILE__ == $0 begin # Retrieve the service used to make API requests. service = get_service() rescue ArgumentError => e raise 'Unable to create service, with error message: #{e.message}' rescue Signet::AuthorizationError => e raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}' end # Set options and default values for fields used in this example. options = [ Option.new( 'account_id', 'The resource ID of the buyers resource under which the creative was created, This will be used to construct '\ 'the name used as a path parameter for the creatives.patch request.', type: Integer, short_alias: 'a', required: true, default_value: nil ), Option.new( 'creative_id', 'The resource ID of the buyers.creatives resource for which the creative was created. This will be used to '\ 'construct the name used as a path parameter for the creatives.patch request.', short_alias: 'c', required: true, default_value: nil ), Option.new( 'advertiser_name', 'The name of the company being advertised in the creative.', required: false, default_value: "Advertiser ##{SecureRandom.uuid}" ), ] # Parse options. parser = Parser.new(options) opts = parser.parse(ARGV) begin patch_creatives(service, opts) rescue Google::Apis::ServerError => e raise "The following server error occured:\n#{e.message}" rescue Google::Apis::ClientError => e raise "Invalid client request:\n#{e.message}" rescue Google::Apis::AuthorizationError => e raise "Authorization error occured:\n#{e.message}" end end