開始使用

本指南將簡要說明如何開始使用 Google Ads API .NET 程式庫。

安裝

用戶端程式庫二進位檔是使用 NuGet 發布。為專案中的 Google.Ads.GoogleAds 套件新增 Nuget 參照,以使用用戶端程式庫。

設定授權

如要授權 API 呼叫,您必須將用戶端 ID、用戶端密鑰、更新權杖和開發人員權杖指定至程式庫。

如果您已經有憑證...

  • GitHub 的 App.config 檔案中,將 GoogleAdsApi 節點和 configSections 節點下的 GoogleAdsApi 區段複製到 App.config / Web.config 檔案。如果您使用 NuGet 安裝套件,則這些節點將自動插入 App.config / Web.config 檔案。
  • 在應用程式的 App.config / Web.config 中加入開發人員權杖、用戶端 ID、用戶端密鑰和更新權杖。GitHub 中的 App.config 檔案附有詳盡記錄,但您也可以參閱「設定指南」以瞭解更多資訊及替代配置設定。

如果需要產生憑證...

  • 如果尚未取得開發人員權杖,請按照開發人員權杖指南的說明取得。
  • 按照 OAuth 電腦版應用程式流程指南的說明,產生用戶端 ID、用戶端密鑰和更新權杖。
  • GitHub 的 App.config 檔案中,將 GoogleAdsApi 節點和 configSections 節點下的 GoogleAdsApi 區段複製到 App.config / Web.config 檔案。如果您使用 NuGet 安裝套件,則這些節點將自動插入 App.config / Web.config 檔案。
  • 在應用程式的 App.config / Web.config 中加入開發人員權杖、用戶端 ID、用戶端密鑰和更新權杖。GitHub 中的 App.config 檔案附有詳盡記錄,但您也可以參閱「設定指南」以瞭解更多資訊及替代配置設定。

發出 API 呼叫

用戶端程式庫的基本用法如下:

// Create a Google Ads client.
GoogleAdsClient client = new GoogleAdsClient();

// Create the required service.
CampaignServiceClient campaignService =
    client.GetService(Services.V16.CampaignService);

// Make more calls to service class.

建立 GoogleAdsClient 例項

在 Google Ads API .NET 程式庫中,最重要的類別是 GoogleAdsClient 類別。可讓您建立可用於呼叫 API 的預先設定服務類別。GoogleAdsClient 提供預設建構函式,可根據應用程式的 App.config / Web.config 中指定的設定,建立使用者物件。如要瞭解各種設定選項,請參閱設定指南

// Create a new GoogleAdsClient with the App.config settings.
GoogleAdsClient user = new GoogleAdsClient();

建立服務

GoogleAdsClient 提供 GetService 方法,可用來建立廣告服務。

CampaignServiceClient campaignService = client.GetService(Services.V16.CampaignService);
// Now make calls to CampaignService.

我們提供 Services 類別,其中列舉了所有支援的 API 版本和服務。GetService 方法會在建立服務時接受這些列舉物件做為引數。舉例來說,如要為 Google Ads API 的 V16 版本建立 CampaignServiceClient 例項,您必須使用 Services.V16.CampaignService 做為引數呼叫 GoogleAdsClient.GetService 方法,如上所示。

執行緒安全

在多個執行緒之間共用 GoogleAdsClient 例項並不安全,因為您對某個執行緒執行個體的設定變更,可能會影響您在其他執行緒中建立的服務。像是從 GoogleAdsClient 執行個體取得新服務執行個體、同時呼叫多項服務等作業都是執行緒安全的。

多執行緒的應用程式看起來會像這樣:

GoogleAdsClient client1 = new GoogleAdsClient();
GoogleAdsClient client2 = new GoogleAdsClient();

Thread userThread1 = new Thread(addAdGroups);
Thread userThread2 = new Thread(addAdGroups);

userThread1.start(client1);
userThread2.start(client2);

userThread1.join();
userThread2.join();

public void addAdGroups(object data) {
  GoogleAdsClient client = (GoogleAdsClient) data;
  // Do more operations here.
  ...
}

避免 .NET Framework 應用程式停止運作

同步方法可能會導致您的部分 .NET Framework 應用程式凍結。常見的例子是透過 WinForm 應用程式的事件處理常式方法提出 API 呼叫。

有兩種方法可以解決這個問題:

  1. 使用舊版 Grpc 程式庫。

    您可以將 GoogleAdsConfigUseGrpcCore 屬性設為使用舊版 Grpc.Core 程式庫,而非預設的 Grpc.Net.Client 程式庫。這個方法尚未對 .NET Framework 應用程式進行廣泛測試,因此可能無法解決問題。以下提供程式碼片段範例:

    GoogleAdsConfig config = new GoogleAdsConfig();
    config.UseGrpcCore = true;
    GoogleAdsClient client = new GoogleAdsClient(config);
    
  2. 使用非同步方法。

    您可以使用非同步方法避免凍結。以下舉幾個例子說明:

    SearchStream

    系統會呼叫 SearchStream(),並將結果填入清單檢視中。

    private async void button1_Click(object sender, EventArgs e)
    {
    // 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";
     
    List items = new List();
    Task t =  googleAdsService.SearchStreamAsync(customerId.ToString(), query,
        delegate (SearchGoogleAdsStreamResponse resp)
        {
            foreach (GoogleAdsRow googleAdsRow in resp.Results)
            {
                ListViewItem item = new ListViewItem();
                item.Text = googleAdsRow.Campaign.Id.ToString();
                item.SubItems.Add(googleAdsRow.Campaign.Name);
                items.Add(item);
            }
        }
    );
    await t;
    listView1.Items.AddRange(items.ToArray());
    }
    

    廣告活動預算

    系統會建立 CampaignBudget 呼叫,並使用 MessageBox 快訊顯示新預算的資源名稱。

    private async void button2_Click(object sender, EventArgs e)
    {
    // Get the BudgetService.
    CampaignBudgetServiceClient budgetService = client.GetService(
        Services.V16.CampaignBudgetService);
     
    // Create the campaign budget.
    CampaignBudget budget = new CampaignBudget()
    {
        Name = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString(),
        DeliveryMethod = BudgetDeliveryMethod.Standard,
        AmountMicros = 500000
    };
     
    // Create the operation.
    CampaignBudgetOperation budgetOperation = new CampaignBudgetOperation()
    {
        Create = budget
    };
     
    // Create the campaign budget.
    Task t = budgetService.MutateCampaignBudgetsAsync(
        customerId.ToString(), new CampaignBudgetOperation[] { budgetOperation });
     
    await t;
    MutateCampaignBudgetsResponse response = t.Result;
    MessageBox.Show(response.Results[0].ResourceName);
    }
    

取消非同步方法

針對非同步程式設計,您可以使用 callSettings 參數傳遞 CancellationToken

CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.CancelAfter(3000);
CallSettings callSettings = CallSettings.FromCancellationToken(cancellationTokenSource.Token);

string query = "SELECT campaign.name FROM campaign";
var request = new SearchGoogleAdsStreamRequest()
{
    CustomerId = customerId.ToString(),
    Query = query,
};

GoogleAdsServiceClient googleAdsService = client.GetService(
    Services.V16.GoogleAdsService);

googleAdsService.SearchStream(request,
    delegate (SearchGoogleAdsStreamResponse resp)
    {
        foreach (GoogleAdsRow googleAdsRow in resp.Results)
        {
            // Process the row.
        }
    }, callSettings
);

處理錯誤

並非所有 API 呼叫都會成功。如果您的 API 呼叫因某些原因而失敗,伺服器可能會擲回錯誤。請務必擷取 API 錯誤,並適當處理。

發生 API 錯誤時,系統會擲回 GoogleAdsException 執行個體。此頁面會提供詳細資料,協助您找出問題所在:

// Get the CampaignService.
CampaignServiceClient campaignService = client.GetService(Services.V16.CampaignService);

// Create a campaign for update.
Campaign campaignToUpdate = new Campaign()
{
    ResourceName = ResourceNames.Campaign(customerId, campaignId),
    // More fields to update.
    // ...
};

// Create the operation.
CampaignOperation operation = new CampaignOperation()
{
    Update = campaignToUpdate,
    UpdateMask = FieldMasks.AllSetFieldsOf(campaignToUpdate)
};

try
{
    // Update the campaign.
    MutateCampaignsResponse response = campaignService.MutateCampaigns(
        customerId.ToString(), new CampaignOperation[] { operation });

    // Display the results.
    // ...
}
catch (GoogleAdsException e)
{
    Console.WriteLine("Failure:");
    Console.WriteLine($"Message: {e.Message}");

    // Can examine to get more error details.
    Console.WriteLine($"Failure: {e.Failure}");

    // Can be shared with Google for further troubleshooting.
    Console.WriteLine($"Request ID: {e.RequestId}");
}