Thực hiện lệnh gọi API

Hướng dẫn này yêu cầu một số chế độ cài đặt điều kiện tiên quyết đã được định cấu hình trong các bước trước đó. Bắt đầu với phần Giới thiệu nếu bạn chưa làm như vậy.

Hướng dẫn này cũng sử dụng mã thông báo làm mới, một quy trình làm việc trong đó người dùng có đủ quyền truy cập vào tài khoản Google Ads có thể uỷ quyền cho ứng dụng của bạn (trong một lần thiết lập) để thực hiện các lệnh gọi API ngoại tuyến đến tài khoản mà không cần người dùng can thiệp thêm. Bạn có thể sử dụng mã thông báo làm mới để xây dựng cả quy trình làm việc ngoại tuyến (chẳng hạn như công việc cron hoặc quy trình dữ liệu) và quy trình làm việc tương tác (chẳng hạn như ứng dụng web hoặc ứng dụng di động).

Tìm nạp mã làm mới

API Google Ads sử dụng OAuth 2.0 làm cơ chế uỷ quyền. Theo mặc định, OAuth Phương thức xác thực 2.0 đưa ra một mã truy cập sẽ hết hạn sau một khoảng thời gian có hạn. Để tự động gia hạn mã truy cập, hãy tạo mã làm mới thay thế.

OAuth2l

  1. Tạo mã làm mới bằng cách chạy lệnh Công cụ oauth2l:

    oauth2l fetch --credentials credentials.json --scope adwords \
        --output_format refresh_token
    ``` The `credentials.json` file is from a [previous
    step](/google-ads/api/docs/get-started/oauth-cloud-project#id-secret).
    
  1. Lệnh oauth2l sẽ mở ra một cửa sổ đăng nhập Tài khoản Google trong một cửa sổ mới cửa sổ trình duyệt và hướng dẫn bạn các bước xác thực OAuth 2.0.

    Hãy đảm bảo bạn đăng nhập bằng địa chỉ email trong bước mà bạn đã xác định mã khách hàng đăng nhập.

    Nếu ứng dụng chưa được xác minh, bạn có thể thấy màn hình cảnh báo. Trong phạm vi như vậy trong trường hợp an toàn, hãy nhấp vào liên kết Hiển thị nâng cao rồi nhấp vào Chuyển đến lựa chọn PROJECT_NAME (chưa được xác minh).

  2. Sau khi bạn xác minh các phạm vi, hãy cấp quyền bằng cách nhấp vào nút Tiếp tục.

    Một lời nhắc sẽ xuất hiện trong trình duyệt với văn bản sau:

    Authorization code granted. Please close this tab.
    

    Lệnh oauth2l sẽ xuất ra đoạn mã JSON sau:

    {
      "client_id": "******.apps.googleusercontent.com",
      "client_secret": "******",
      "token_uri": "https://oauth2.googleapis.com/token",
      "auth_uri": "https://accounts.google.com/o/oauth2/auth",
      "refresh_token": "******",
      "type": "authorized_user"
    }
    

gcloud CLI

  1. Tạo mã thông báo làm mới bằng cách chạy công cụ gcloud CLI:

    gcloud auth application-default \
      login --scopes=https://www.googleapis.com/auth/adwords,https://www.googleapis.com/auth/cloud-platform \
      --client-id-file=<path_to_credentials.json>
    ``` The `credentials.json` file is from a [previous
    step](/google-ads/api/docs/get-started/oauth-cloud-project#id-secret).
    
  1. Lệnh gcloud sẽ mở cửa sổ đăng nhập Tài khoản Google trong một cửa sổ trình duyệt mới và đưa bạn qua các bước xác thực OAuth 2.0.

    Hãy đảm bảo bạn đăng nhập bằng địa chỉ email trong bước mà bạn đã xác định mã khách hàng đăng nhập.

    Nếu ứng dụng của bạn chưa được xác minh, bạn có thể thấy màn hình cảnh báo. Trong phạm vi như vậy trong trường hợp an toàn, hãy nhấp vào liên kết Hiển thị nâng cao rồi nhấp vào Chuyển đến lựa chọn PROJECT_NAME (chưa được xác minh).

  2. Sau khi bạn xác minh các phạm vi, hãy nhấp vào nút Tiếp tục để cấp quyền.

    Trình duyệt sẽ chuyển đến https://cloud.google.com/sdk/auth_Thành công, cho biết quá trình xác thực đã thành công.

    Authorization code granted. Please close this tab.
    

    Lệnh gcloud sẽ in ra kết quả như sau:

    Credentials saved to file: [/****/.config/gcloud/application_default_credentials.json]
    

    Bây giờ, hãy mở tệp application_default_credentials.json. Nội dung sẽ tương tự như sau:

    {
      "account": "",
      "client_id": "******.apps.googleusercontent.com",
      "client_secret": "******",
      "refresh_token": "******",
      "type": "authorized_user",
      "universe_domain": "googleapis.com"
    }
    

Khác

Nếu bạn muốn sử dụng curl hoặc ứng dụng HTTP của riêng mình, hãy tham khảo Hướng dẫn về OAuth 2.0 cho ứng dụng dành cho thiết bị di động và máy tính để biết ví dụ.

Thực hiện lệnh gọi API

Chọn ứng dụng bạn muốn để xem hướng dẫn cách thực hiện lệnh gọi API:

Java

Cấu phần phần mềm thư viện ứng dụng được phát hành vào kho lưu trữ trung tâm Maven. Thêm thư viện ứng dụng làm phần phụ thuộc vào dự án của bạn như sau:

Phần phụ thuộc Maven là:

<dependency>
  <groupId>com.google.api-ads</groupId>
  <artifactId>google-ads</artifactId>
  <version>33.0.0</version>
</dependency>

Phần phụ thuộc Gradle là:

implementation 'com.google.api-ads:google-ads:33.0.0'

Tạo tệp ~/ads.properties có nội dung sau:

api.googleads.clientId=INSERT_CLIENT_ID_HERE
api.googleads.clientSecret=INSERT_CLIENT_SECRET_HERE
api.googleads.refreshToken=INSERT_REFRESH_TOKEN_HERE
api.googleads.developerToken=INSERT_DEVELOPER_TOKEN_HERE
api.googleads.loginCustomerId=INSERT_LOGIN_CUSTOMER_ID_HERE

Tạo đối tượng GoogleAdsClient như sau:

GoogleAdsClient googleAdsClient = null;
try {
  googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
} catch (FileNotFoundException fnfe) {
  System.err.printf(
      "Failed to load GoogleAdsClient configuration from file. Exception: %s%n",
      fnfe);
  System.exit(1);
} catch (IOException ioe) {
  System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
  System.exit(1);
}

Tiếp theo, hãy chạy báo cáo chiến dịch bằng phương thức GoogleAdsService.SearchStream để truy xuất các chiến dịch trong tài khoản của bạn. Hướng dẫn này không đề cập chi tiết về báo cáo.

    private void runExample(GoogleAdsClient googleAdsClient, long customerId) {
  try (GoogleAdsServiceClient googleAdsServiceClient =
      googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
    String query = "SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id";
    // Constructs the SearchGoogleAdsStreamRequest.
    SearchGoogleAdsStreamRequest request =
        SearchGoogleAdsStreamRequest.newBuilder()
            .setCustomerId(Long.toString(customerId))
            .setQuery(query)
            .build();

    // Creates and issues a search Google Ads stream request that will retrieve all campaigns.
    ServerStream<SearchGoogleAdsStreamResponse> stream =
        googleAdsServiceClient.searchStreamCallable().call(request);

    // Iterates through and prints all of the results in the stream response.
    for (SearchGoogleAdsStreamResponse response : stream) {
      for (GoogleAdsRow googleAdsRow : response.getResultsList()) {
        System.out.printf(
            "Campaign with ID %d and name '%s' was found.%n",
            googleAdsRow.getCampaign().getId(), googleAdsRow.getCampaign().getName());
      }
    }
  }
}

C#

Các gói thư viện ứng dụng được xuất bản lên Nuget.org kho lưu trữ. Bắt đầu bằng cách thêm một tham chiếu nuget đến gói Google.Ads.GoogleAds.

dotnet add package Google.Ads.GoogleAds --version 18.1.0

Tạo đối tượng GoogleAdsConfig có các chế độ cài đặt liên quan và sử dụng đối tượng đó để tạo đối tượng GoogleAdsClient.

GoogleAdsConfig config = new GoogleAdsConfig()
{
    DeveloperToken = "******",
    OAuth2Mode = "APPLICATION",
    OAuth2ClientId = "******.apps.googleusercontent.com",
    OAuth2ClientSecret = "******",
    OAuth2RefreshToken = "******",
    LoginCustomerId = ******
};
GoogleAdsClient client = new GoogleAdsClient(config);

Tiếp theo, hãy chạy báo cáo chiến dịch bằng cách sử dụng phương thức GoogleAdsService.SearchStream để truy xuất các chiến dịch trong tài khoản của mình. Hướng dẫn này không đề cập chi tiết về báo cáo.

    public void Run(GoogleAdsClient client, long customerId)
{
    // Get the GoogleAdsService.
    GoogleAdsServiceClient googleAdsService = client.GetService(
        Services.V17.GoogleAdsService);

    // Create a query that will retrieve all campaigns.
    string query = @"SELECT
                    campaign.id,
                    campaign.name,
                    campaign.network_settings.target_content_network
                FROM campaign
                ORDER BY campaign.id";

    try
    {
        // Issue a search request.
        googleAdsService.SearchStream(customerId.ToString(), query,
            delegate (SearchGoogleAdsStreamResponse resp)
            {
                foreach (GoogleAdsRow googleAdsRow in resp.Results)
                {
                    Console.WriteLine("Campaign with ID {0} and name '{1}' was found.",
                        googleAdsRow.Campaign.Id, googleAdsRow.Campaign.Name);
                }
            }
        );
    }
    catch (GoogleAdsException e)
    {
        Console.WriteLine("Failure:");
        Console.WriteLine($"Message: {e.Message}");
        Console.WriteLine($"Failure: {e.Failure}");
        Console.WriteLine($"Request ID: {e.RequestId}");
        throw;
    }
}

PHP

Các gói thư viện ứng dụng được phát hành vào kho lưu trữ Packagist. Chuyển sang thư mục gốc của dự án và chạy lệnh sau để cài đặt thư viện và tất cả phần phụ thuộc của thư viện trong thư mục vendor/ của thư mục gốc của dự án.

composer require googleads/google-ads-php:25.0.0

Tạo bản sao của google_ads_php.ini từ kho lưu trữ GitHub và sửa đổi tệp đó để bao gồm thông tin đăng nhập của bạn.

[GOOGLE_ADS]
developerToken = "INSERT_DEVELOPER_TOKEN_HERE"
loginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"

[OAUTH2]
clientId = "INSERT_OAUTH2_CLIENT_ID_HERE"
clientSecret = "INSERT_OAUTH2_CLIENT_SECRET_HERE"
refreshToken = "INSERT_OAUTH2_REFRESH_TOKEN_HERE"

Tạo một bản sao của đối tượng GoogleAdsClient.

$oAuth2Credential = (new OAuth2TokenBuilder())
    ->fromFile('/path/to/google_ads_php.ini')
    ->build();

$googleAdsClient = (new GoogleAdsClientBuilder())
    ->fromFile('/path/to/google_ads_php.ini')
    ->withOAuth2Credential($oAuth2Credential)
    ->build();

Tiếp theo, hãy chạy báo cáo chiến dịch bằng cách sử dụng phương thức GoogleAdsService.SearchStream để truy xuất các chiến dịch trong tài khoản của mình. Hướng dẫn này không đề cập đến thông tin chi tiết về hoạt động báo cáo.

    public static function runExample(GoogleAdsClient $googleAdsClient, int $customerId)
{
    $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
    // Creates a query that retrieves all campaigns.
    $query = 'SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id';
    // Issues a search stream request.
    /** @var GoogleAdsServerStreamDecorator $stream */
    $stream = $googleAdsServiceClient->searchStream(
        SearchGoogleAdsStreamRequest::build($customerId, $query)
    );

    // Iterates over all rows in all messages and prints the requested field values for
    // the campaign in each row.
    foreach ($stream->iterateAllElements() as $googleAdsRow) {
        /** @var GoogleAdsRow $googleAdsRow */
        printf(
            "Campaign with ID %d and name '%s' was found.%s",
            $googleAdsRow->getCampaign()->getId(),
            $googleAdsRow->getCampaign()->getName(),
            PHP_EOL
        );
    }
}

Python

Thư viện ứng dụng được phân phối trên PyPI. Bạn có thể cài đặt thư viện này bằng lệnh pip như sau:

python -m pip install google-ads==21.3.0

Tạo bản sao của tệp google-ads.yaml từ kho lưu trữ GitHub và sửa đổi tệp đó để thêm thông tin xác thực của bạn.

client_id: INSERT_OAUTH2_CLIENT_ID_HERE
client_secret: INSERT_OAUTH2_CLIENT_SECRET_HERE
refresh_token: INSERT_REFRESH_TOKEN_HERE
developer_token: INSERT_DEVELOPER_TOKEN_HERE
login_customer_id: INSERT_LOGIN_CUSTOMER_ID_HERE

Tạo một thực thể GoogleAdsClient bằng cách gọi phương thức GoogleAdsClient.load_from_storage. Truyền đường dẫn đến google-ads.yaml dưới dạng chuỗi vào phương thức khi gọi phương thức đó:

from google.ads.googleads.client import GoogleAdsClient
client = GoogleAdsClient.load_from_storage("path/to/google-ads.yaml")

Tiếp theo, hãy chạy báo cáo chiến dịch bằng cách sử dụng phương thức GoogleAdsService.SearchStream để truy xuất các chiến dịch trong tài khoản của mình. Hướng dẫn này không đề cập chi tiết về báo cáo.

def main(client, customer_id):
    ga_service = client.get_service("GoogleAdsService")

    query = """
        SELECT
          campaign.id,
          campaign.name
        FROM campaign
        ORDER BY campaign.id"""

    # Issues a search request using streaming.
    stream = ga_service.search_stream(customer_id=customer_id, query=query)

    for batch in stream:
        for row in batch.results:
            print(
                f"Campaign with ID {row.campaign.id} and name "
                f'"{row.campaign.name}" was found.'
            )

Ruby

Ngọc hồng ngọc cho thư viện ứng dụng được xuất bản lên gem đá quý Rubygems lưu trữ trang web. Bạn nên cài đặt bằng trình tạo gói. Thêm một dòng vào Gemfile:

gem 'google-ads-googleads', '~> 30.0.0'

Sau đó, hãy chạy:

bundle install

Tạo bản sao của google_ads_config.rb từ kho lưu trữ GitHub và sửa đổi tệp đó để bao gồm thông tin đăng nhập của bạn.

Google::Ads::GoogleAds::Config.new do |c|
  c.client_id = 'INSERT_CLIENT_ID_HERE'
  c.client_secret = 'INSERT_CLIENT_SECRET_HERE'
  c.refresh_token = 'INSERT_REFRESH_TOKEN_HERE'
  c.developer_token = 'INSERT_DEVELOPER_TOKEN_HERE'
  c.login_customer_id = 'INSERT_LOGIN_CUSTOMER_ID_HERE'
end

Tạo một thực thể GoogleAdsClient bằng cách truyền đường dẫn đến nơi bạn lưu trữ tệp này.

client = Google::Ads::GoogleAds::GoogleAdsClient.new('path/to/google_ads_config.rb')

Tiếp theo, hãy chạy báo cáo chiến dịch bằng phương thức GoogleAdsService.SearchStream để truy xuất các chiến dịch trong tài khoản của bạn. Hướng dẫn này không đề cập đến thông tin chi tiết về hoạt động báo cáo.

    def get_campaigns(customer_id)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  responses = client.service.google_ads.search_stream(
    customer_id: customer_id,
    query: 'SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id',
  )

  responses.each do |response|
    response.results.each do |row|
      puts "Campaign with ID #{row.campaign.id} and name '#{row.campaign.name}' was found."
    end
  end
end

Perl

Thư viện này được phân phối trên CPAN. Bắt đầu bằng cách nhân bản kho lưu trữ google-ads-perl trong thư mục bạn chọn.

git clone https://github.com/googleads/google-ads-perl.git

Chuyển sang thư mục google-ads-perl và chạy lệnh sau tại lời nhắc lệnh để cài đặt tất cả phần phụ thuộc cần thiết cho việc sử dụng thư viện.

cd google-ads-perl
cpan install Module::Build
perl Build.PL
perl Build installdeps

Tạo bản sao của tệp googleads.properties từ kho lưu trữ GitHub và sửa đổi tệp đó để thêm thông tin xác thực của bạn.

clientId=INSERT_OAUTH2_CLIENT_ID_HERE
clientSecret=INSERT_OAUTH2_CLIENT_SECRET_HERE
refreshToken=INSERT_OAUTH2_REFRESH_TOKEN_HERE
developerToken=INSERT_DEVELOPER_TOKEN_HERE
loginCustomerId=INSERT_LOGIN_CUSTOMER_ID_HERE

Tạo một thực thể Client bằng cách truyền đường dẫn đến nơi bạn lưu trữ tệp này.

my $properties_file = "/path/to/googleads.properties";

my $api_client = Google::Ads::GoogleAds::Client->new({
  properties_file => $properties_file
});

Tiếp theo, hãy chạy báo cáo chiến dịch bằng phương thức GoogleAdsService.SearchStream để truy xuất các chiến dịch trong tài khoản của bạn. Hướng dẫn này không đề cập đến thông tin chi tiết về hoạt động báo cáo.

    sub get_campaigns {
  my ($api_client, $customer_id) = @_;

  # Create a search Google Ads stream request that will retrieve all campaigns.
  my $search_stream_request =
    Google::Ads::GoogleAds::V17::Services::GoogleAdsService::SearchGoogleAdsStreamRequest
    ->new({
      customerId => $customer_id,
      query      =>
        "SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id"
    });

  # Get the GoogleAdsService.
  my $google_ads_service = $api_client->GoogleAdsService();

  my $search_stream_handler =
    Google::Ads::GoogleAds::Utils::SearchStreamHandler->new({
      service => $google_ads_service,
      request => $search_stream_request
    });

  # Issue a search request and process the stream response to print the requested
  # field values for the campaign in each row.
  $search_stream_handler->process_contents(
    sub {
      my $google_ads_row = shift;
      printf "Campaign with ID %d and name '%s' was found.\n",
        $google_ads_row->{campaign}{id}, $google_ads_row->{campaign}{name};
    });

  return 1;
}

REST

Bắt đầu bằng cách sử dụng ứng dụng HTTP để tìm nạp mã truy cập OAuth 2.0. Hướng dẫn này sử dụng lệnh curl.

curl \
  --data "grant_type=refresh_token" \
  --data "client_id=CLIENT_ID" \
  --data "client_secret=CLIENT_SECRET" \
  --data "refresh_token=REFRESH_TOKEN" \
  https://www.googleapis.com/oauth2/v3/token

Tiếp theo, hãy chạy báo cáo chiến dịch bằng phương thức GoogleAdsService.SearchStream để truy xuất các chiến dịch trong tài khoản của bạn. Hướng dẫn này không đề cập đến thông tin chi tiết về hoạt động báo cáo.

curl -i -X POST https://googleads.googleapis.com/v18/customers/CUSTOMER_ID/googleAds:searchStream \
   -H "Content-Type: application/json" \
   -H "Authorization: Bearer ACCESS_TOKEN" \
   -H "developer-token: DEVELOPER_TOKEN" \
   -H "login-customer-id: LOGIN_CUSTOMER_ID" \
   --data-binary "@query.json"

Nội dung của query.json như sau:

{
  "query": "SELECT campaign.id, campaign.name, campaign.network_settings.target_content_network FROM campaign ORDER BY campaign.id"
}