Cách dùng cơ bản

Sau đây là cách sử dụng cơ bản của thư viện ứng dụng .NET:

// 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.V25.CampaignService);

// Make calls to the service client.

Khởi chạy ứng dụng và các dịch vụ

Để tương tác với API Google Ads, trước tiên, hãy định cấu hình và khởi tạo một GoogleAdsClient, sau đó sử dụng 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 các 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 về 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 một dịch vụ

GoogleAdsClient cung cấp một phương thức GetService mà bạn có thể dùng để tạo một ứng dụng dịch vụ API.

CampaignServiceClient campaignService = client.GetService(
    Services.V25.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 phụ như v25.1 sử dụng enum phiên bản lớn, 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 phiên bản CampaignServiceClient cho phiên bản V25 của Google Ads API, hãy gọi phương thức GoogleAdsClient.GetService bằng Services.V25.CampaignService làm đối số, như minh hoạ 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 đó. Điều quan trọng là bạn phải nắm bắt và xử lý các lỗi API 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 tin này chứa các chi tiết giúp bạn xác định vấn đề:

public void Run(GoogleAdsClient client, long customerId)
{
    // Get the GoogleAdsService.
    GoogleAdsServiceClient googleAdsService = client.GetService(
        Services.V25.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 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 các 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 cho mỗi luồng, hãy khởi tạo một GoogleAdsClient riêng biệt cho mỗi tác vụ hoặc luồng 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 API Google Ads có thể mất một khoảng thời gian để hoàn tất, tuỳ thuộc vào quy mô của các yêu cầu. Để giữ cho ứng dụng của bạn phản hồi nhanh, 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ũ, chẳng hạn 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 các phương thức không đồng bộ

Bạn có thể dùng các phương thức không đồng bộ để duy trì khả năng phản hồi 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 sẵn ListView

private async void OnRetrieveCampaignsButtonClick(object sender, EventArgs e)
{
    try
    {
        // Get the GoogleAdsService.
        GoogleAdsServiceClient googleAdsService = client.GetService(
            Services.V25.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 hộp thông báo

private async void OnUpdateBudgetButtonClick(object sender, EventArgs e)
{
    try
    {
        // Get the CampaignBudgetService.
        CampaignBudgetServiceClient budgetService = client.GetService(
            Services.V25.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}");
    }
}