開始使用

您可以使用 Google Ad Manager SOAP API 建立應用程式,管理廣告空間、建立訂單、製作報表等。

為協助您開始使用,我們提供 Java、.NET、Python、PHP 和 Ruby 的用戶端程式庫

如要發出第一個 API 要求,請按照下列步驟操作:

取得 Ad Manager 聯播網的存取權

如果還沒有,請註冊 Ad Manager 帳戶。如要在獨立環境中測試 API,也可以建立測試聯播網。請注意,測試時不需要 AdSense 帳戶。

記下網路代碼。登入網路時,您可以在網址中找到這項資訊。舉例來說,在網址 https://admanager.google.com/1234#home 中,1234 是您的聯播網代碼。

建立驗證憑證

您必須使用 OAuth 2.0 驗證所有 Ad Manager SOAP API 要求。以下步驟說明如何存取自己的 Ad Manager 資料。如要瞭解詳情和其他選項,請參閱「驗證」。

  1. 開啟 Google API 控制台的「憑證」頁面

  2. 從專案選單中選擇「建立專案」,輸入專案名稱,並視需要編輯提供的專案 ID。點選「Create」(建立)

  3. 在「憑證」頁面中,選取「建立憑證」,然後選取「服務帳戶金鑰」

  4. 選取「新增服務帳戶」,然後選取 JSON 做為金鑰類型。

  5. 按一下「建立」,下載內含私密金鑰的檔案。

設定 Ad Manager 聯播網

  1. 登入 Google Ad Manager。

  2. 在側欄中,依序點按「管理」>「通用設定」

  3. 依序點選「一般設定」>「API 存取權」,然後點選滑桿來「啟用」

  4. 按一下頁面底部的「儲存」按鈕。

為客戶設定服務

下載其中一個 Ad Manager 用戶端程式庫。這些程式庫提供包裝函式和功能,可讓您更輕鬆快速地開發應用程式。

下列分頁提供各語言的程式設計快速入門指南,方便您瞭解如何使用用戶端程式庫。

Java

以下是基本範例,說明如何使用 Java 用戶端程式庫。如需更詳細的使用資訊,請參閱用戶端程式庫發布內容中的 README 檔案。

  1. 設定憑證

    在 Shell 中執行下列指令:

    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
    [...]
  2. 指定依附元件

    編輯 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>
  3. 編寫一些程式碼並發出要求!

    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.v202608.Network;
    import com.google.api.ads.admanager.axis.v202608.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 檔案。

  1. 安裝程式庫並設定憑證。

    在殼層中執行下列指令:

    python3 -m pip install googleads
    curl https://raw.githubusercontent.com/googleads/googleads-python-lib/main/googleads.yaml \
         -o ~/googleads.yaml
  2. 設定 ~/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
  3. 執行一些程式碼並發出要求。
    # 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='v202608')
    
    # 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 用戶端程式庫

  1. 安裝程式庫並設定憑證。

    在殼層中執行下列指令,安裝用戶端程式庫並將 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
  2. 設定 ~/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"
  3. 執行一些程式碼並發出要求!
    <?php
    require 'vendor/autoload.php';
    use Google\AdsApi\AdManager\AdManagerSession;
    use Google\AdsApi\AdManager\AdManagerSessionBuilder;
    use Google\AdsApi\AdManager\v202608\ApiException;
    use Google\AdsApi\AdManager\v202608\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 用戶端程式庫

  1. 建立新專案

    開啟 Visual Studio 並建立新專案 (主控台應用程式)。

  2. 在專案中加入必要的程式庫參照

    新增 Google.Dfp 的 NuGet 依附元件。

  3. 設定 App.config

    將 src\App.config 複製到專案目錄,並新增至專案。如果應用程式有自己的 App.config,您可以將下列節點複製到 App.config:

    • configuration/AdManagerApi
    • configuration/configSections/section[name="AdManagerApi"]
    • configuration/system.net
  4. 設定憑證

    開啟 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" />
  5. 呼叫程式庫

    您可以呼叫程式庫,如以下 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 中設定憑證,請參閱這篇 Wiki 文章,瞭解使用 AdManagerUser 類別的替代方法。如要進一步瞭解如何使用 .NET 用戶端程式庫,請參閱 README 。如要在沒有用戶端程式庫的情況下使用 .NET 開發,請參閱NoClientLibrary Wiki 文章

小茹

以下基本範例說明如何使用 Ruby 用戶端程式庫。Ruby 用戶端程式庫需要 Ruby 2.1 以上版本。

  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
  2. 設定憑證

    在檔案中填寫必填欄位。~/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
  3. 編寫一些程式碼並發出要求!
    # 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, :v202608)
    
    # 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。

如需協助,請前往支援頁面