您可以使用 Google Ad Manager API 建構應用程式,用於管理廣告空間、建立訂單、提取報表等。
Ad Manager API 使用 SOAP。為協助您快速上手,我們提供了 Java、.NET、Python、PHP 和 Ruby 的用戶端程式庫。
如要提出第一個 API 要求,請按照下列步驟操作:
存取 Ad Manager 聯播網
如果您沒有 Ad Manager 帳戶,請註冊一個。如果您想在獨立環境中測試 API,也可以建立測試網路。請注意,您不需要 AdSense 帳戶進行測試。
記下聯播網代碼。您登入網路時,可以在網址中找到這個網址例如,在 https://admanager.google.com/1234#home
網址中,1234
是您的網路代碼。
建立驗證憑證
您必須使用 OAuth 2.0 驗證所有 Ad Manager API 請求。下方步驟說明存取自有 Ad Manager 資料的用途。如需詳細資訊及其他選項,請參閱驗證。
在專案選單中選擇「建立專案」,輸入專案名稱,並視需求編輯所提供的專案 ID。按一下「Create」(建立)。
在「憑證」頁面上選取「建立憑證」,然後選取「服務帳戶金鑰」。
按一下「建立」,下載內含私密金鑰的檔案。
設定 Ad Manager 聯播網
登入 Google Ad Manager。
在側欄中,依序按一下「管理」>「通用設定」。
在「一般設定」>「API 存取權」下方,按一下滑桿至「已啟用」。
按一下頁面底部的「儲存」按鈕。
設定客戶
下載其中一個 Ad Manager 用戶端程式庫。程式庫提供包裝函式函式和功能,可讓您更輕鬆快速地開發應用程式。
下列分頁提供用戶端程式庫,協助您以每種語言編寫程式碼的快速入門導覽課程。
Java
以下為 Java 用戶端程式庫使用的基本範例。如需詳細的使用資訊,請參閱用戶端程式庫發行版中的 README 檔案。
- 設定憑證
在殼層中執行下列指令:
curl https://raw.githubusercontent.com/googleads/googleads-java-lib/main/examples/admanager_axis/src/main/resources/ads.properties -o ~/ads.properties
開啟~/ads.properties
檔案並填入下列欄位:[...] api.admanager.applicationName=INSERT_APPLICATION_NAME_HERE api.admanager.jsonKeyFilePath=INSERT_PATH_TO_JSON_KEY_FILE_HERE api.admanager.networkCode=INSERT_NETWORK_CODE_HERE [...]
-
指定依附元件
編輯
pom.xml
檔案,並將以下內容新增至dependencies
標記。您可以在 GitHub 找到最新版本編號。<dependency> <groupId>com.google.api-ads</groupId> <artifactId>ads-lib</artifactId> <version>RELEASE</version> </dependency> <dependency> <groupId>com.google.api-ads</groupId> <artifactId>dfp-axis</artifactId> <version>RELEASE</version> </dependency>
-
撰寫程式碼並提出要求!
import com.google.api.ads.common.lib.auth.OfflineCredentials; import com.google.api.ads.common.lib.auth.OfflineCredentials.Api; import com.google.api.ads.admanager.axis.factory.AdManagerServices; import com.google.api.ads.admanager.axis.v202405.Network; import com.google.api.ads.admanager.axis.v202405.NetworkServiceInterface; import com.google.api.ads.admanager.lib.client.AdManagerSession; import com.google.api.client.auth.oauth2.Credential; public class App { public static void main(String[] args) throws Exception { Credential oAuth2Credential = new OfflineCredentials.Builder() .forApi(Api.AD_MANAGER) .fromFile() .build() .generateCredential(); // Construct an AdManagerSession. AdManagerSession session = new AdManagerSession.Builder() .fromFile() .withOAuth2Credential(oAuth2Credential) .build(); // Construct a Google Ad Manager service factory, which can only be used once per // thread, but should be reused as much as possible. AdManagerServices adManagerServices = new AdManagerServices(); // Retrieve the appropriate service NetworkServiceInterface networkService = adManagerServices.get(session, NetworkServiceInterface.class); // Make a request Network network = networkService.getCurrentNetwork(); System.out.printf("Current network has network code '%s' and display" + " name '%s'.%n", network.getNetworkCode(), network.getDisplayName()); } }
Python
以下提供基本範例,說明如何使用 Python 用戶端程式庫。 Python 用戶端程式庫支援 Python 3.6 以上版本。如需詳細的使用資訊,請參閱用戶端程式庫發行的 README 檔案。
- 安裝程式庫並設定憑證。
在殼層中執行下列指令:
pip install googleads
curl https://raw.githubusercontent.com/googleads/googleads-python-lib/main/googleads.yaml \ -o ~/googleads.yaml
- 設定
~/googleads.yaml
檔案。填妥以下欄位:
ad_manager: application_name: INSERT_APPLICATION_NAME_HERE network_code: INSERT_NETWORK_CODE_HERE path_to_private_key_file: INSERT_PATH_TO_FILE_HERE
-
執行一些程式碼並提出要求。
# Import the library. from googleads import ad_manager # Initialize a client object, by default uses the credentials in ~/googleads.yaml. client = ad_manager.AdManagerClient.LoadFromStorage() # Initialize a service. network_service = client.GetService('NetworkService', version='v202405') # Make a request. current_network = network_service.getCurrentNetwork() print("Current network has network code '%s' and display name '%s'." % (current_network['networkCode'], current_network['displayName']))
PHP
以下為使用 PHP 用戶端程式庫的基本範例,
-
安裝程式庫並設定憑證。
在殼層中執行下列指令,安裝用戶端程式庫並將 adsapi_php.ini 檔案下載至主目錄:
composer require googleads/googleads-php-lib
curl https://raw.githubusercontent.com/googleads/googleads-php-lib/main/examples/AdManager/adsapi_php.ini -o ~/adsapi_php.ini
-
設定
~/adsapi_php.ini
檔案。填妥以下欄位:
[AD_MANAGER] networkCode = "INSERT_NETWORK_CODE_HERE" applicationName = "INSERT_APPLICATION_NAME_HERE" [OAUTH2] jsonKeyFilePath = "INSERT_ABSOLUTE_PATH_TO_OAUTH2_JSON_KEY_FILE_HERE" scopes = "https://www.googleapis.com/auth/dfp"
-
執行一些程式碼並提出要求!
<?php require 'vendor/autoload.php'; use Google\AdsApi\AdManager\AdManagerSession; use Google\AdsApi\AdManager\AdManagerSessionBuilder; use Google\AdsApi\AdManager\v202405\ApiException; use Google\AdsApi\AdManager\v202405\ServiceFactory; use Google\AdsApi\Common\OAuth2TokenBuilder; // Generate a refreshable OAuth2 credential for authentication. $oAuth2Credential = (new OAuth2TokenBuilder()) ->fromFile() ->build(); // Construct an API session configured from a properties file and the OAuth2 // credentials above. $session = (new AdManagerSessionBuilder()) ->fromFile() ->withOAuth2Credential($oAuth2Credential) ->build(); // Get a service. $serviceFactory = new ServiceFactory(); $networkService = $serviceFactory->createNetworkService($session); // Make a request $network = $networkService->getCurrentNetwork(); printf( "Network with code %d and display name '%s' was found.\n", $network->getNetworkCode(), $network->getDisplayName() );
.NET
以下基本範例說明如何使用 .NET 用戶端程式庫
- 建立新專案
開啟 Visual Studio 並建立新專案 (主控台應用程式)。
- 在專案中加入必要的程式庫參照
為 Google.Dfp 新增 nuget 依附元件。
- 設定 App.config
將 src\App.config 複製到專案目錄,並加進專案。如果您的應用程式有自己的 App.config,您可以將下列節點複製到 App.config:
- 設定/AdManagerApi
- configuration/configSections/section[name="AdManagerApi"]
- configuration/system.net
- 設定憑證
開啟 App.config 並編輯下列機碼:
<add key="ApplicationName" value="INSERT_YOUR_APPLICATION_NAME_HERE" /> <add key="NetworkCode" value="INSERT_YOUR_NETWORK_CODE_HERE" /> <add key="OAuth2Mode" value="SERVICE_ACCOUNT" /> <add key="OAuth2SecretsJsonPath" value="INSERT_OAUTH2_SECRETS_JSON_FILE_PATH_HERE" />
- 呼叫程式庫
您可以呼叫程式庫,如以下 C# 程式碼片段所示
AdManagerUser user = new AdManagerUser(); using (InventoryService inventoryService = user.GetService<InventoryService>()) { // Create a statement to select ad units. int pageSize = StatementBuilder.SUGGESTED_PAGE_LIMIT; StatementBuilder statementBuilder = new StatementBuilder().OrderBy("id ASC").Limit(pageSize); // Retrieve a small amount of ad units at a time, paging through until all // ad units have been retrieved. int totalResultSetSize = 0; do { AdUnitPage page = inventoryService.getAdUnitsByStatement(statementBuilder.ToStatement()); // Print out some information for each ad unit. if (page.results != null) { totalResultSetSize = page.totalResultSetSize; int i = page.startIndex; foreach (AdUnit adUnit in page.results) { Console.WriteLine( "{0}) Ad unit with ID \"{1}\" and name \"{2}\" was found.", i++, adUnit.id, adUnit.name); } } statementBuilder.IncreaseOffsetBy(pageSize); } while (statementBuilder.GetOffset() < totalResultSetSize); Console.WriteLine("Number of results found: {0}", totalResultSetSize); }
如果您不想在 App.config 中設定憑證,請參閱這篇維基文章,瞭解使用 AdManagerUser 類別的替代方式。如要進一步瞭解如何使用 .NET 用戶端程式庫,請參閱 README 。如果您想在沒有用戶端程式庫的情況下,使用 .NET 進行開發,請參閱 NoClientLibrary 維基文章。
Ruby
以下提供基本範例,說明如何使用 Ruby 用戶端程式庫。Ruby 用戶端程式庫需要 Ruby 2.1 以上版本。
-
安裝 Ruby Gem 並取得設定檔。
在殼層中執行下列指令:
gem install google-dfp-api
curl https://raw.githubusercontent.com/googleads/google-api-ads-ruby/main/ad_manager_api/ad_manager_api.yml -o ~/ad_manager_api.yml
-
設定憑證
在
~/ad_manager_api.yml
檔案中填入必填欄位。如果您還沒有 OAuth2 金鑰檔案,則必須按照建立 OAuth2 憑證的步驟進行。:authentication: :oauth2_keyfile: INSERT_PATH_TO_JSON_KEY_FILE_HERE :application_name: INSERT_APPLICATION_NAME_HERE :network_code: INSERT_NETWORK_CODE_HERE
-
撰寫程式碼並提出要求!
# Import the library. require 'ad_manager_api' # Initialize an Ad Manager client instance (uses credentials in ~/ad_manager_api.yml by default). ad_manager = AdManagerApi::Api.new # Get a service instance. network_service = ad_manager.service(:NetworkService, :v202405) # Make a request. network = network_service.get_current_network() puts "The current network is %s (%d)." % [network[:display_name], network[:network_code]]
如需更詳細的入門步驟,請參閱與 Ruby 用戶端程式庫一起發布的 README 檔案。另請參閱 Ruby 的完整範例程式庫。
後續步驟
當您能夠啟動並執行用戶端程式庫後,請修改提供的範例,根據需求擴充這些範例。
如要進一步瞭解 API,請參閱參考說明文件。
如需相關協助,請造訪我們的支援網頁。