Cách sử dụng cơ bản của thư viện ứng dụng .NET như sau:
// Initialize a GoogleAdsConfig instance.
GoogleAdsConfig config = new GoogleAdsConfig()
{
OAuth2Mode = OAuth2Flow.SERVICE_ACCOUNT,
OAuth2SecretsJsonPath = "PATH_TO_CREDENTIALS_JSON",
LoginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"
};
// Initialize a GoogleAdsClient instance.
GoogleAdsClient client = new GoogleAdsClient(config);
// Create the required service.
CampaignServiceClient campaignService =
client.GetService(Services.V26.CampaignService);
// Make calls to the service client.
Khởi chạy ứng dụng và dịch vụ
Để tương tác với API Google Ads, trước tiên, hãy định cấu hình và tạo thực thể cho một
GoogleAdsClient, sau đó sử dụng thực thể này để tạo các ứng dụng dịch vụ API cụ thể
mà bạn cần.
Tạo một thực thể GoogleAdsClient
Lớp quan trọng nhất trong thư viện .NET của Google Ads API là lớp GoogleAdsClient. Thư viện này cho phép bạn tạo một ứng dụng dịch vụ được định cấu hình sẵn, có thể dùng để thực hiện lệnh gọi API. Để định cấu hình đối tượng GoogleAdsClient, hãy tạo đối tượng GoogleAdsConfig và đặt các thuộc tính bắt buộc. Hãy tham khảo
Hướng dẫn định cấu hình để tìm hiểu thêm.
// Initialize a GoogleAdsConfig instance.
GoogleAdsConfig config = new GoogleAdsConfig()
{
OAuth2Mode = OAuth2Flow.SERVICE_ACCOUNT,
OAuth2SecretsJsonPath = "PATH_TO_CREDENTIALS_JSON",
LoginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"
};
// Initialize a GoogleAdsClient instance.
GoogleAdsClient client = new GoogleAdsClient(config);
// Modify the GoogleAdsClient configuration afterwards if needed.
client.Config.LoginCustomerId = "INSERT_UPDATED_LOGIN_CUSTOMER_ID_HERE";
Tạo dịch vụ
GoogleAdsClient cung cấp một phương thức GetService có thể dùng để tạo một ứng dụng dịch vụ API.
CampaignServiceClient campaignService = client.GetService(
Services.V26.CampaignService);
// Now make calls to CampaignService.
Thư viện này cung cấp một lớp Services liệt kê tất cả các phiên bản API được hỗ trợ (trong đó các bản phát hành nhỏ như v25.1 sử dụng enum phiên bản chính, Services.V25) và các dịch vụ. Phương thức GetService chấp nhận các đối tượng liệt kê này làm đối số khi tạo dịch vụ. Ví dụ: để tạo một thực thể của CampaignServiceClient cho phiên bản V26 của Google Ads API, hãy gọi phương thức GoogleAdsClient.GetService bằng đối số Services.V26.CampaignService, như trong ví dụ trước.
Xử lý lỗi
Không phải lệnh gọi API nào cũng thành công. Máy chủ có thể trả về lỗi nếu lệnh gọi API của bạn không thành công vì lý do nào đó. Bạn cần phải ghi lại các lỗi API và xử lý chúng một cách thích hợp.
Một thực thể GoogleAdsException sẽ được gửi khi xảy ra lỗi API. Thông báo này chứa thông tin chi tiết giúp bạn tìm ra vấn đề:
public void Run(GoogleAdsClient client, long customerId) { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V26.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; } }
Độ an toàn cho chuỗi
Việc sửa đổi trạng thái cấu hình của một thực thể GoogleAdsClient dùng chung trên nhiều luồng không an toàn cho luồng, vì những thay đổi về cấu hình mà bạn thực hiện trên một thực thể trong một luồng có thể ảnh hưởng đến các dịch vụ mà bạn tạo trên các luồng khác.
Tuy nhiên, các thao tác chỉ có thể đọc như lấy các phiên bản dịch vụ mới từ một phiên bản GoogleAdsClient không thay đổi và thực hiện lệnh gọi đến nhiều dịch vụ song song là an toàn cho luồng.
Để tách biệt các thay đổi về cấu hình theo từng luồng, hãy tạo một thực thể GoogleAdsClient riêng biệt cho mỗi tác vụ hoặc luồng của worker:
GoogleAdsClient client1 = new GoogleAdsClient();
GoogleAdsClient client2 = new GoogleAdsClient();
Task task1 = Task.Run(() => AddAdGroups(client1));
Task task2 = Task.Run(() => AddAdGroups(client2));
await Task.WhenAll(task1, task2);
public void AddAdGroups(GoogleAdsClient client)
{
// Perform operations with client.
}
Duy trì khả năng phản hồi của ứng dụng
Các lệnh gọi phương thức Google Ads API có thể mất một lúc để hoàn tất, tuỳ thuộc vào mức độ lớn của yêu cầu. Để đảm bảo ứng dụng của bạn luôn thích ứng, hãy làm theo các bước sau:
Sử dụng thư viện Grpc.Core cho các khung giao diện người dùng cũ
Nếu đang phát triển một ứng dụng nhắm đến .NET Framework và sử dụng công nghệ giao diện người dùng cũ như ASP.NET Web Forms hoặc WinForms, bạn có thể bật thư viện truyền tải Grpc.Core cũ như sau:
GoogleAdsConfig config = new GoogleAdsConfig();
config.UseGrpcCore = true;
GoogleAdsClient client = new GoogleAdsClient(config);
Sử dụng phương thức không đồng bộ
Bạn có thể sử dụng các phương thức không đồng bộ để duy trì khả năng thích ứng của ứng dụng. Sau đây là một vài ví dụ.
Truy xuất danh sách chiến dịch và điền vào ListView
private async void OnRetrieveCampaignsButtonClick(object sender, EventArgs e)
{
try
{
// Get the GoogleAdsService.
GoogleAdsServiceClient googleAdsService = client.GetService(
Services.V26.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<ListViewItem> items = new List<ListViewItem>();
await googleAdsService.SearchStreamAsync(
customerId.ToString(),
query,
(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);
}
}
);
listView1.Items.AddRange(items.ToArray());
}
catch (GoogleAdsException ex)
{
MessageBox.Show($"API Error: {ex.Message}");
}
}
Cập nhật ngân sách chiến dịch và hiển thị cảnh báo trong hộp thông báo
private async void OnUpdateBudgetButtonClick(object sender, EventArgs e)
{
try
{
// Get the CampaignBudgetService.
CampaignBudgetServiceClient budgetService = client.GetService(
Services.V26.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 asynchronously.
MutateCampaignBudgetsResponse response =
await budgetService.MutateCampaignBudgetsAsync(
customerId.ToString(),
new CampaignBudgetOperation[] { budgetOperation });
MessageBox.Show(response.Results[0].ResourceName);
}
catch (GoogleAdsException ex)
{
MessageBox.Show($"API Error: {ex.Message}");
}
}