Bắt đầu

Bạn có thể sử dụng API Google Ad Manager để tạo ứng dụng quản lý khoảng không quảng cáo, tạo đơn đặt hàng, lấy báo cáo và làm nhiều việc khác.

API Ad Manager sử dụng SOAP. Để giúp bạn bắt đầu, chúng tôi cung cấp khách hàng các thư viện dành cho Java, .NET, Python, PHP và Ruby.

Để tạo yêu cầu API đầu tiên, hãy làm theo các bước sau:

Truy cập vào mạng Ad Manager

Nếu bạn chưa có tài khoản, hãy đăng ký Ad Manager tài khoản. Bạn cũng có thể tạo một kiểm thử mạng nếu bạn muốn kiểm thử API trong một môi trường riêng biệt. Xin lưu ý rằng bạn không cần có tài khoản AdSense để thử nghiệm .

Ghi lại mã mạng của bạn. Bạn có thể tìm thấy thông tin này trong URL khi đăng nhập vào mạng của bạn. Ví dụ: trong URL https://admanager.google.com/1234#home, 1234 là mã mạng của bạn.

Tạo thông tin xác thực

Bạn phải xác thực tất cả yêu cầu API Ad Manager bằng OAuth 2.0. Các bước thực hiện nội dung bên dưới trình bày trường hợp sử dụng quyền truy cập vào dữ liệu Ad Manager của riêng bạn. Để biết thêm chi tiết và các lựa chọn khác, hãy xem phần Xác thực.

  1. Mở Google API Console Trang Thông tin đăng nhập

  2. Trên trình đơn dự án, hãy chọn Create project (Tạo dự án), rồi nhập tên cho dự án và chỉnh sửa Mã dự án được cung cấp (không bắt buộc). Nhấp vào Create (Tạo).

  3. Trên trang Thông tin đăng nhập, hãy chọn Tạo thông tin xác thực rồi chọn Khoá tài khoản dịch vụ.

  4. Chọn Dịch vụ mới tài khoản rồi chọn JSON làm loại khoá.

  5. Nhấp vào Tạo để tải tệp chứa khoá riêng tư xuống.

Định cấu hình mạng Ad Manager

  1. Đăng nhập vào Google Ads Người quản lý.

  2. Trong thanh bên, hãy nhấp vào Quản trị > Cài đặt chung.

  3. Trong Cài đặt chung > Quyền truy cập API nhấp vào thanh trượt để Bật.

  4. Nhấp vào nút Lưu ở cuối trang.

Thiết lập cho khách hàng

Tải một trong các thư viện ứng dụng Ad Manager xuống. Chiến lược phát hành đĩa đơn thư viện cung cấp các chức năng và tính năng trình bao bọc giúp bạn dễ dàng và nhanh chóng phát triển ứng dụng.

Các thẻ bên dưới cung cấp hướng dẫn bắt đầu nhanh về lập trình cho mỗi ngôn ngữ có một thư viện ứng dụng.

Java

Dưới đây là một ví dụ cơ bản cho thấy cách sử dụng ứng dụng Java thư viện. Để biết thêm thông tin chi tiết về việc sử dụng, hãy tham khảo tệp README trong bản phân phối thư viện ứng dụng.

  1. Thiết lập thông tin đăng nhập

    Chạy lệnh sau trong một shell:

    curl https://raw.githubusercontent.com/googleads/googleads-java-lib/main/examples/admanager_axis/src/main/resources/ads.properties -o ~/ads.properties
    Mở tệp ~/ads.properties rồi điền vào các trường sau:
    [...]
    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. Chỉ định phần phụ thuộc

    Chỉnh sửa tệp pom.xml và thêm đoạn mã sau vào tệp Thẻ dependencies. Bạn có thể tìm thấy số phiên bản mới nhất trên 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. Hãy viết mã và đưa ra yêu cầu!

    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.v202408.Network;
    import com.google.api.ads.admanager.axis.v202408.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

Dưới đây là ví dụ cơ bản về cách sử dụng thư viện ứng dụng Python. Thư viện ứng dụng Python hỗ trợ Python phiên bản 3.6 trở lên. Để biết thêm thông tin về cách sử dụng thông tin, hãy tham khảo tệp README trong bản phân phối thư viện ứng dụng.

  1. Cài đặt thư viện và thiết lập thông tin đăng nhập của bạn.

    Chạy các lệnh sau trong một shell:

    pip install googleads
    curl https://raw.githubusercontent.com/googleads/googleads-python-lib/main/googleads.yaml \
         -o ~/googleads.yaml
    
  2. Thiết lập tệp ~/googleads.yaml.

    Điền vào các trường sau:

    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. Chạy một số mã và đưa ra yêu cầu.
    # 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='v202408')
    
    # 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

Dưới đây là ví dụ cơ bản cho thấy cách sử dụng Thư viện ứng dụng PHP.

  1. Cài đặt thư viện và thiết lập thông tin đăng nhập của bạn.

    Chạy các lệnh sau trong một shell để cài đặt thư viện ứng dụng và tải xuống adsapi_php.ini vào thư mục gốc của bạn:

    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. Thiết lập tệp ~/adsapi_php.ini.

    Điền vào các trường sau:

    [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. Chạy mã và đưa ra yêu cầu!
    <?php
    require 'vendor/autoload.php';
    use Google\AdsApi\AdManager\AdManagerSession;
    use Google\AdsApi\AdManager\AdManagerSessionBuilder;
    use Google\AdsApi\AdManager\v202408\ApiException;
    use Google\AdsApi\AdManager\v202408\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

Dưới đây là ví dụ cơ bản về cách sử dụng ứng dụng.NET thư viện

  1. Tạo dự án mới

    Mở Visual Studio rồi tạo một dự án mới (Ứng dụng Play Console).

  2. Thêm tệp tham chiếu bắt buộc từ thư viện vào dự án của bạn

    Thêm phần phụ thuộc nuget cho Google.Dfp.

  3. Thiết lập App.config

    Sao chép src\App.config vào thư mục dự án rồi thêm tệp này vào dự án. Nếu ứng dụng có App.config riêng, thì bạn có thể sao chép các nút sau vào ứng dụng App.config:

    • configuration/AdManagerApi
    • configuration/configSections/section[name=&quot;AdManagerApi&quot;]
    • configuration/system.net
  4. Thông tin đăng nhập thiết lập

    Mở App.config và chỉnh sửa các khoá sau:

    <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. Gọi điện đến thư viện

    Bạn có thể gọi thư viện như minh hoạ trong đoạn mã C# sau

    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);
                }
            

Nếu bạn không muốn đặt thông tin đăng nhập trong App.config, hãy tham khảo đến bài viết này trên wiki để biết những cách khác để sử dụng lớp AdManagerUser. Để biết thêm thông tin chi tiết về cách sử dụng Thư viện ứng dụng .NET, hãy tham khảo vào tệp README Nếu bạn muốn phát triển trong .NET mà không có thư viện ứng dụng, vui lòng tham khảo NoClientLibrary trên wiki.

Ruby

Dưới đây là ví dụ cơ bản về cách sử dụng ruby thư viện ứng dụng. Thư viện ứng dụng Ruby yêu cầu phiên bản Ruby 2.1 trở lên.

  1. Cài đặt đá quý Ruby và nhận tệp cấu hình.

    Chạy các lệnh sau trong một shell:

    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. Thiết lập thông tin đăng nhập

    Điền các trường bắt buộc trong ~/ad_manager_api.yml . Nếu chưa có tệp khoá OAuth2, bạn cần làm theo các bước để tạo OAuth2 thông tin xác thực.

    :authentication:
      :oauth2_keyfile: INSERT_PATH_TO_JSON_KEY_FILE_HERE
      :application_name: INSERT_APPLICATION_NAME_HERE
      :network_code: INSERT_NETWORK_CODE_HERE
    
  3. Hãy viết mã và đưa ra yêu cầu!
    # 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, :v202408)
    
    # Make a request.
    network = network_service.get_current_network()
    
    puts "The current network is %s (%d)." %
            [network[:display_name], network[:network_code]]
    

Bạn có thể xem các bước chi tiết hơn để bắt đầu trong tài liệu README được phân phối cùng với thư viện ứng dụng Ruby. Ngoài ra, hãy xem toàn bộ thư viện mẫu cho Ruby.

Các bước tiếp theo

Khi bạn đã thiết lập và chạy một thư viện ứng dụng, hãy sửa đổi các ví dụ được cung cấp để mở rộng chúng theo nhu cầu của bạn.

Duyệt qua tài liệu tham khảo để tìm hiểu thêm về API.

Nếu bạn cần trợ giúp, hãy truy cập vào Trang hỗ trợ của chúng tôi.