本指南將概略說明如何開始使用 Google Ads API .NET 程式庫。
安裝
用戶端程式庫二進位檔是使用 NuGet 發布。將 Nuget 參照新增至專案的 Google.Ads.GoogleAds
套件,以使用用戶端程式庫。
設定授權
如要授權 API 呼叫,您必須為程式庫指定用戶端 ID、用戶端密鑰、更新權杖和開發人員權杖。
如果您已擁有憑證...
- 將
GoogleAdsApi
節點和configSections
節點下方的GoogleAdsApi
區段從 GitHub 中的App.config
檔案複製到App.config
/Web.config
檔案。如果您使用 NuGet 安裝套件,系統會自動將這些節點插入您的App.config
/Web.config
檔案。 - 在應用程式的
App.config
/Web.config
中加入開發人員權杖、用戶端 ID、用戶端密鑰和更新權杖。GitHub 中的App.config
檔案已妥善記錄下來,但您也可以參閱設定指南,進一步瞭解並使用替代配置設定。
如果您需要產生憑證...
- 如果您還沒有開發人員權杖,請按照開發人員權杖指南的說明取得。
- 按照 OAuth 電腦版應用程式流程指南操作,產生用戶端 ID、用戶端密鑰和更新憑證。
- 將
GoogleAdsApi
節點和configSections
節點下方的GoogleAdsApi
區段從 GitHub 中的App.config
檔案複製到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.V17.CampaignService);
// Make more calls to service class.
建立 Google AdsClient 執行個體
Google Ads API .NET 程式庫中最重要的類別是 GoogleAdsClient
類別。可讓您建立預先設定的服務類別,可用於發出 API 呼叫。GoogleAdsClient
會提供預設建構函式,以便使用應用程式 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 版本和服務。GetService
方法會在建立服務時接受這些列舉物件做為引數。舉例來說,如要為 Google Ads API 的 V17
版本建立 CampaignServiceClient
例項,您需要使用 Services.V17.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 呼叫。
解決問題的方式有兩種:
使用舊版 gRPC 程式庫。
您可以將
GoogleAdsConfig
的UseGrpcCore
屬性設為使用舊版Grpc.Core
程式庫,而非預設的Grpc.Net.Client
程式庫。此方法尚未在 .NET Framework 應用程式上經過廣泛測試,因此可能無法解決問題。以下為程式碼片段範例:GoogleAdsConfig config = new GoogleAdsConfig(); config.UseGrpcCore = true; GoogleAdsClient client = new GoogleAdsClient(config);
使用非同步方法。
您可以使用非同步方法避免凍結。以下舉幾個例子說明:
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); }
取消非同步方法
若是非同步程式設計,可以使用 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.V17.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.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}");
}