เรียก API

คู่มือนี้ต้องมีการตั้งค่าเบื้องต้นหลายรายการซึ่งได้รับการกำหนดค่าไว้ในขั้นตอนก่อนหน้า เริ่มต้นด้วยบทนำ หากยังไม่ได้ทำ

คู่มือนี้ยังใช้โทเค็นการรีเฟรช ซึ่งเป็นเวิร์กโฟลว์ที่ผู้ใช้ซึ่งมีสิทธิ์เข้าถึงบัญชี Google Ads อย่างเพียงพอสามารถให้สิทธิ์แอปของคุณในการเรียก API ออฟไลน์ไปยังบัญชีได้ โดยไม่ต้องให้ผู้ใช้จัดการเพิ่มเติม คุณสามารถใช้โทเค็นการรีเฟรชเพื่อสร้างเวิร์กโฟลว์ออฟไลน์ได้ เช่น งาน Cron หรือไปป์ไลน์ข้อมูล และเวิร์กโฟลว์แบบอินเทอร์แอกทีฟ เช่น เว็บหรือแอปบนอุปกรณ์เคลื่อนที่

ดึงข้อมูลโทเค็นการรีเฟรช

Google Ads API ใช้ OAuth 2.0 เป็นกลไกการให้สิทธิ์ โดยค่าเริ่มต้น การตรวจสอบสิทธิ์ OAuth 2.0 จะออกโทเค็นเพื่อการเข้าถึงที่หมดอายุหลังจากเวลาที่จำกัด หากต้องการต่ออายุโทเค็นเพื่อการเข้าถึงโดยอัตโนมัติ คุณควรออกโทเค็นการรีเฟรชแทน

  1. สร้างโทเค็นการรีเฟรชโดยเรียกใช้เครื่องมือ oauth2l ดังนี้

    oauth2l fetch --credentials credentials.json --scope adwords \
        --output_format refresh_token
    

    ไฟล์ credentials.json มาจากขั้นตอนก่อนหน้า

  2. คำสั่ง oauth2l จะเปิดหน้าต่างการเข้าสู่ระบบบัญชี Google ในหน้าต่างเบราว์เซอร์ใหม่และนำคุณผ่านขั้นตอนการตรวจสอบสิทธิ์ OAuth 2.0

    ลงชื่อเข้าใช้ด้วยอีเมลจากขั้นตอนที่ระบุรหัสลูกค้าในการเข้าสู่ระบบ

    หากแอปไม่ได้รับการยืนยัน คุณอาจเห็นหน้าจอคำเตือน ในกรณีดังกล่าว คุณสามารถคลิกลิงก์แสดงขั้นสูง แล้วคลิกตัวเลือกไปที่ PROJECT_NAME (ไม่ได้รับการยืนยัน) ได้

  3. หลังจากยืนยันขอบเขตแล้ว ให้มอบสิทธิ์โดยคลิกปุ่มต่อไป

    ข้อความแจ้งจะปรากฏในเบราว์เซอร์พร้อมด้วยข้อความต่อไปนี้

    Authorization code granted. Please close this tab.
    

    คำสั่ง oauth2l จะแสดงผลข้อมูลโค้ด JSON ต่อไปนี้

    {
      "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"
    }
    

เรียก API

เลือกไคลเอ็นต์ที่ต้องการเพื่อดูวิธีการเรียก API

Java

อาร์ติแฟกต์ไลบรารีของไคลเอ็นต์จะเผยแพร่ไปยังที่เก็บส่วนกลาง Maven เพิ่มไลบรารีของไคลเอ็นต์เป็นทรัพยากร Dependency ให้กับโปรเจ็กต์ดังนี้

ทรัพยากร Dependency ของ Maven มีดังนี้

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

ทรัพยากร Dependency ของ Gradle มีดังนี้

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

สร้างไฟล์ ~/ads.properties ที่มีเนื้อหาต่อไปนี้

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

สร้างออบเจ็กต์ GoogleAdsClient ดังนี้

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

จากนั้นเรียกใช้รายงานแคมเปญโดยใช้วิธีการ GoogleAdsService.SearchStream เพื่อดึงข้อมูลแคมเปญในบัญชี คู่มือนี้ไม่ครอบคลุมรายละเอียดของการรายงาน

  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#

แพ็กเกจไลบรารีของไคลเอ็นต์จะเผยแพร่ไปยังที่เก็บ Nuget.org เริ่มต้นด้วยการเพิ่มการอ้างอิง Nuget ในแพ็กเกจ Google.Ads.GoogleAds

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

สร้างออบเจ็กต์ GoogleAdsConfig ด้วยการตั้งค่าที่เกี่ยวข้อง แล้วใช้ออบเจ็กต์ดังกล่าวเพื่อสร้างออบเจ็กต์ GoogleAdsClient

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

จากนั้นเรียกใช้รายงานแคมเปญโดยใช้วิธีการ GoogleAdsService.SearchStream เพื่อดึงข้อมูลแคมเปญในบัญชี คู่มือนี้ไม่ครอบคลุมรายละเอียดของการรายงาน

  public void Run(GoogleAdsClient client, long customerId)
{
    // Get the GoogleAdsService.
    GoogleAdsServiceClient googleAdsService = client.GetService(
        Services.V16.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

แพ็กเกจไลบรารีของไคลเอ็นต์จะเผยแพร่ไปยังที่เก็บ Packagist เปลี่ยนเป็นไดเรกทอรีรูทของโปรเจ็กต์และเรียกใช้คำสั่งต่อไปนี้เพื่อติดตั้งไลบรารีและทรัพยากร Dependency ทั้งหมดของโปรเจ็กต์ในไดเรกทอรี vendor/ ของไดเรกทอรีรูทของโปรเจ็กต์

composer require googleads/google-ads-php:22.0.0

ทำสำเนาไฟล์ google_ads_php.ini จากที่เก็บ GitHub และแก้ไขไฟล์เพื่อใส่ข้อมูลเข้าสู่ระบบของคุณ

[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"

สร้างอินสแตนซ์ของออบเจ็กต์ 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();

จากนั้นเรียกใช้รายงานแคมเปญโดยใช้วิธีการ GoogleAdsService.SearchStream เพื่อดึงข้อมูลแคมเปญในบัญชี คู่มือนี้ไม่ครอบคลุมรายละเอียดของการรายงาน

  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

ไลบรารีของไคลเอ็นต์มีการกระจายใน PyPI คุณติดตั้งได้โดยใช้คำสั่ง pip ดังนี้

python -m pip install google-ads==21.3.0

ทำสำเนาไฟล์ google-ads.yaml จากที่เก็บ GitHub และแก้ไขไฟล์เพื่อใส่ข้อมูลเข้าสู่ระบบของคุณ

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

สร้างอินสแตนซ์ GoogleAdsClient โดยเรียกใช้เมธอด GoogleAdsClient.load_from_storage ส่งเส้นทางไปยัง google-ads.yaml เป็นสตริงไปยังเมธอดเมื่อเรียกใช้

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

จากนั้นเรียกใช้รายงานแคมเปญโดยใช้วิธีการ GoogleAdsService.SearchStream เพื่อดึงข้อมูลแคมเปญในบัญชี คู่มือนี้ไม่ครอบคลุมรายละเอียดของการรายงาน

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

มีการเผยแพร่ gems ของ Ruby สำหรับไลบรารีของไคลเอ็นต์ไปยังเว็บไซต์ที่โฮสต์อัญมณี Rubygems วิธีที่แนะนำในการติดตั้งคือการใช้ Bundler เพิ่มบรรทัดไปยัง Gemfile:

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

จากนั้นเรียกใช้

bundle install

ทำสำเนาไฟล์ google_ads_config.rb จากที่เก็บ GitHub และแก้ไขไฟล์เพื่อใส่ข้อมูลเข้าสู่ระบบของคุณ

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

สร้างอินสแตนซ์ GoogleAdsClient โดยการส่งเส้นทางไปยังตำแหน่งที่คุณเก็บไฟล์นี้

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

จากนั้นเรียกใช้รายงานแคมเปญโดยใช้วิธีการ GoogleAdsService.SearchStream เพื่อดึงข้อมูลแคมเปญในบัญชี คู่มือนี้ไม่ครอบคลุมรายละเอียดของการรายงาน

  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

ไลบรารีเผยแพร่บน CPAN เริ่มต้นด้วยการโคลนที่เก็บ google-ads-perl ในไดเรกทอรีที่ต้องการ

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

เปลี่ยนเป็นไดเรกทอรี google-ads-perl แล้วเรียกใช้คำสั่งต่อไปนี้ที่พรอมต์คำสั่งเพื่อติดตั้งทรัพยากร Dependency ทั้งหมดที่จำเป็นสำหรับการใช้ไลบรารี

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

ทำสำเนาไฟล์ googleads.properties จากที่เก็บ GitHub และแก้ไขไฟล์เพื่อใส่ข้อมูลเข้าสู่ระบบของคุณ

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

สร้างอินสแตนซ์ Client โดยการส่งเส้นทางไปยังตำแหน่งที่คุณเก็บไฟล์นี้ไว้

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

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

จากนั้นเรียกใช้รายงานแคมเปญโดยใช้วิธีการ GoogleAdsService.SearchStream เพื่อดึงข้อมูลแคมเปญในบัญชี คู่มือนี้ไม่ครอบคลุมรายละเอียดของการรายงาน

  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::V16::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

เริ่มต้นโดยใช้ไคลเอ็นต์ HTTP เพื่อดึงโทเค็นเพื่อการเข้าถึง OAuth 2.0 คู่มือนี้ใช้คำสั่ง 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

จากนั้นเรียกใช้รายงานแคมเปญโดยใช้วิธีการ GoogleAdsService.SearchStream เพื่อดึงข้อมูลแคมเปญในบัญชี คู่มือนี้ไม่ครอบคลุมรายละเอียดของการรายงาน

curl -i -X POST https://googleads.googleapis.com/v16/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"

เนื้อหาของ query.json มีดังนี้

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