用戶端程式庫

我們的用戶端程式庫提供 Google Ads API 功能的高階檢視畫面和基本構件,讓您更輕鬆地快速開發應用程式。如果您是 API 新手,建議您從這類應用程式著手。

用戶端程式庫 來源 分布 程式碼範例
Java google-ads-java Maventar.gz 前往 GitHub 查看
.NET google-ads-dotnet nugettar.gz、zip 前往 GitHub 查看
PHP google-ads-php tar.gz 前往 GitHub 查看
Python google-ads-python tar.gz、zip 前往 GitHub 查看
Ruby google-ads-ruby gem、tar.gz、zip 前往 GitHub 查看
Perl google-ads-perl tar.gz、zip 前往 GitHub 查看

社群程式庫

我們知道有幾個由開放原始碼社群維護的程式庫。我們會維護這份清單,方便有興趣的開發人員找到這些項目。我們不會測試、貢獻或維護這些程式庫,請自行承擔使用這些程式庫的風險。如有任何問題,請直接向開放原始碼專案的擁有者洽詢。

如果您知道我們遺漏了哪些圖書館,請按一下頁面頂端的「提供意見」與我們分享。

支援的 API 版本

表格中列出哪些用戶端程式庫可搭配哪些 API 版本運作。

Java

適用於 Java 的用戶端程式庫
v18 Min: 34.0.0
Max: -
v17 Min: 32.0.0
Max: -
v16 Min: 30.0.0
Max: -

C#

.NET 專用的用戶端程式庫
v18 Min: 21.1.0
Max: -
v17 Min: 20.1.0
Max: -
v16 Min: 18.1.0
Max: -

PHP

PHP 用戶端程式庫
v18 Min: 25.0.0
Max: -
v17 Min: 23.1.0
Max: -
v16 Min: 22.1.0
Max: -

Python

Python 專用的用戶端程式庫
v18 Min: 25.1.0
Max: -
v17 Min: 24.1.0
Max: -
v16 Min: 23.1.0
Max: -

小茹

Ruby 適用的用戶端程式庫
v18 Min: 31.0.0
Max: -
v17 Min: 29.0.0
Max: -
v16 Min: 27.0.0
Max: -

Perl

適用於 Perl 的用戶端程式庫
v18 Min: 25.0.1
Max: -
v17 Min: 23.0.0
Max: -
v16 Min: 21.0.0
Max: -

設定

每個 Ads API 用戶端程式庫都提供不同的設定和載入方法,可用於自訂行為。

以下是所有用戶端程式庫都通用的環境變數,可載入來設定設定:

  • 用戶端程式庫
    • GOOGLE_ADS_CONFIGURATION_FILE_PATH:設定檔路徑。
  • OAuth2
    • 應用程式模式
      • GOOGLE_ADS_CLIENT_ID:將這個值設為 OAuth2 用戶端 ID。
      • GOOGLE_ADS_CLIENT_SECRET:將這個值設為 OAuth2 用戶端機密金鑰。
      • GOOGLE_ADS_REFRESH_TOKEN:如要重複使用 OAuth2 權杖,請將這個值設為預先產生的 OAuth2 更新權杖。這項設定為選用。
    • 服務帳戶模式
      • GOOGLE_ADS_JSON_KEY_FILE_PATH:將這個值設為 OAuth2 JSON 設定檔路徑。
      • GOOGLE_ADS_IMPERSONATED_EMAIL:將這個值設為要冒用帳戶的電子郵件地址。
  • Google Ads API
    • GOOGLE_ADS_DEVELOPER_TOKEN:將此設為開發人員權杖。
    • GOOGLE_ADS_LOGIN_CUSTOMER_ID:這是授權客戶的客戶 ID,用於要求中,不含連字號 (-)。
    • GOOGLE_ADS_LINKED_CUSTOMER_ID:只有在 Google Ads 使用者介面 (Google Ads API 中的 AccountLink 資源) 中透過連結帳戶授予權限時,才需要使用這個標頭,以更新實體的資源。將這個值設為更新指定客戶 ID 資源的資料提供者客戶 ID。請勿設定連字號 (-)。如要進一步瞭解已連結帳戶,請造訪說明中心

環境變數通常會在 bash 設定檔中定義,例如位於 $HOME 目錄中的 .bashrc.bash_profile 檔案。也可以使用指令列定義。

以下是使用終端機透過 .bashrc 檔案定義環境變數的幾個基本步驟:

# Append the line "export GOOGLE_ADS_CLIENT_ID=1234567890" to
# the bottom of your .bashrc file.
echo "export GOOGLE_ADS_CLIENT_ID=1234567890" >> ~/.bashrc

# Update your bash environment to use the most recently updated
# version of your .bashrc file.
src ~/.bashrc

您也可以直接透過指令列,在終端機例項中設定環境變數:

export GOOGLE_ADS_CLIENT_ID=1234567890

另一種做法是在呼叫使用環境變數的指令時設定環境變數:

GOOGLE_ADS_CLIENT_ID=1234567890 php /path/to/script/that/uses/envvar.php

擷取實體

GoogleAdsService.SearchStream 通常用於擷取實體,且結果會以資料列串流的形式傳回。或者,您也可以使用 GoogleAdsService.Search 透過不可靠的網際網路連線擷取實體。GoogleAdsService.Search 會以固定的頁面大小傳回結果,每頁 10,000 列。

當您重複執行結果時,我們的用戶端程式庫會自動實作分頁,讓您可以依序下載並一次處理所有結果。

Java

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#

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

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

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.'
            )
      

小茹

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

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::V18::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;
}
      

程式碼範例

查看 Google Ads API 中常見函式的程式碼範例