開始使用

您可以使用 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. 在專案選單中選擇「Create project」(建立專案),輸入專案名稱,並視需要編輯系統提供的專案 ID。點選「Create」(建立)。

  3. 在「憑證」頁面上,依序選取「建立憑證」和「服務帳戶金鑰」。

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

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

設定 Ad Manager 聯播網

  1. 登入 Google Ad Manager。

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

  3. 在「一般設定」>「API 存取權」下方,將滑桿切換為「啟用」。

  4. 點選頁面底部的「儲存」按鈕。

設定用戶端

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

下列分頁提供快速入門導覽課程,說明如何使用用戶端程式庫支援的各種語言編寫程式碼。

Java

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

  1. 設定憑證

    在殼層中執行下列指令:

    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 中設定憑證,請參閱這篇維基文章,瞭解使用 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。

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