開始使用

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

安裝

用戶端程式庫二進位檔是使用 NuGet 發布。新增 NuGet 參照 至Google.Ads.GoogleAds 套件 用戶端程式庫

設定授權

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

如果您需要產生憑證

如果您已擁有憑證

  • 複製 GoogleAdsApi 節點和 GoogleAdsApi 區段下方的 來自以下位置的 App.config 檔案:configSections 個節點 GitHub 複製到 App.config / Web.config 檔案中如果您使用 NuGet 套件後,這些節點就會自動插入 第 App.config 個檔案,共 Web.config 個。
  • 加入開發人員權杖、用戶端 ID、用戶端密鑰和更新權杖 在應用程式的 App.config / Web.config 中。

App.config 已充分記錄您的 GitHub 檔案,但您也可以參考 設定指南 ,使用替代方法設定用戶端程式庫 例如環境變數

發出 API 呼叫

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

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

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

// Make more calls to service class.

建立 Google AdsClient 執行個體

在 Google Ads API .NET 程式庫中,最重要的類別是 GoogleAdsClient 類別。可讓您建立預先設定的服務類別 可用於執行 API 呼叫GoogleAdsClient 提供預設值 建構函式,可用於建立 User 物件的 應用程式的 App.config / Web.config。詳情請參閱設定 設定指南 只要設定成「自動重新啟動」 和「在主機維護期間」選項即可

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

建立 Service

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

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

我們提供 Services 類別,可列舉所有支援的 API 版本和 免費 Google Cloud 服務GetService 方法接受這些列舉物件做為引數 建立 Service 時舉例來說,假設要建立 Google Ads API V17CampaignServiceClient, 您必須呼叫 GoogleAdsClient.GetService 方法,且必須使用 Services.V17.CampaignService 做為引數,如所示 先前的範例

執行緒安全

在多個執行緒之間共用 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 應用程式 凍結了。常見的例子是透過事件處理常式方法發出 API 呼叫 就會產生 WinForm 應用程式範例

解決問題的方式有兩種:

  1. 使用舊版 gRPC 程式庫。

    您可以設定 GoogleAdsConfigUseGrpcCore 屬性,以便使用 舊版 Grpc.Core 程式庫,而非預設的 Grpc.Net.Client 程式庫。 此方法尚未在 .NET Framework 應用程式上經過廣泛測試。 這樣或許就無法解決問題以下為程式碼片段範例:

    GoogleAdsConfig config = new GoogleAdsConfig();
    config.UseGrpcCore = true;
    GoogleAdsClient client = new GoogleAdsClient(config);
    

    gRPC 支援頁面進一步 詳細瞭解舊版 Grpc.Core 程式庫和 預設的 Grpc.Net.Client 程式庫

  2. 使用非同步方法。

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

    SearchStream

    系統會執行對 SearchStream() 的呼叫,結果會 已填入清單檢視

    private async void button1_Click(object sender, EventArgs e)
    {
    // 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";
     
    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.V17.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);
    }
    

處理錯誤

並非所有 API 呼叫都會成功。如果您的 API 呼叫,伺服器可能會擲回錯誤 因此作業失敗務必擷取並處理 API 錯誤 才是正確的做法

發生 API 錯誤時,系統會擲回 GoogleAdsException 執行個體。它有 有助於釐清問題的詳細資訊:

// Get the CampaignService.
CampaignServiceClient campaignService = client.GetService(Services.V17.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}");
}