เริ่มต้นใช้งาน

คู่มือนี้จะอธิบายภาพรวมคร่าวๆ เกี่ยวกับวิธีเริ่มต้นใช้งานไลบรารี Google Ads API .NET

การติดตั้ง

ไบนารีไลบรารีของไคลเอ็นต์จะมีการกระจายโดยใช้ NuGet เพิ่มการอ้างอิง Nuget ในแพ็กเกจ Google.Ads.GoogleAds ในโปรเจ็กต์เพื่อใช้ไลบรารีของไคลเอ็นต์

ตั้งค่าการให้สิทธิ์

หากต้องการให้สิทธิ์การเรียก API คุณต้องระบุรหัสไคลเอ็นต์ รหัสลับไคลเอ็นต์ โทเค็นการรีเฟรช และโทเค็นของนักพัฒนาไปยังไลบรารี

หากคุณมีข้อมูลเข้าสู่ระบบอยู่แล้ว...

  • คัดลอกโหนด GoogleAdsApi และส่วน GoogleAdsApi ใต้โหนด configSections จากไฟล์ App.config ใน GitHub ลงในไฟล์ App.config / Web.config หากคุณใช้ NuGet เพื่อติดตั้งแพ็กเกจ ระบบจะแทรกโหนดเหล่านี้ลงในไฟล์ App.config / Web.config โดยอัตโนมัติ
  • ใส่โทเค็นของนักพัฒนา รหัสไคลเอ็นต์ รหัสลับไคลเอ็นต์ และโทเค็นการรีเฟรชไว้ใน App.config / Web.config ของแอป ไฟล์ App.config ที่รวมอยู่ใน GitHub นั้นมีเอกสารประกอบเป็นอย่างดี แต่คุณจะดูคู่มือการกำหนดค่าและใช้การตั้งค่าการกำหนดค่าอื่นๆ ได้ด้วย

หากต้องการสร้างข้อมูลเข้าสู่ระบบ...

  • โปรดทำตามคู่มือโทเค็นของนักพัฒนาเพื่อรับโทเค็นของนักพัฒนา หากคุณยังไม่มี
  • ทำตามคำแนะนำในขั้นตอนการใช้แอป OAuth บนเดสก์ท็อปเพื่อสร้างรหัสไคลเอ็นต์ รหัสลับไคลเอ็นต์ และโทเค็นการรีเฟรช
  • คัดลอกโหนด GoogleAdsApi และส่วน GoogleAdsApi ใต้โหนด configSections จากไฟล์ App.config ใน GitHub ลงในไฟล์ App.config / Web.config หากคุณใช้ NuGet เพื่อติดตั้งแพ็กเกจ ระบบจะแทรกโหนดเหล่านี้ลงในไฟล์ App.config / Web.config โดยอัตโนมัติ
  • ใส่โทเค็นของนักพัฒนา รหัสไคลเอ็นต์ รหัสลับไคลเอ็นต์ และโทเค็นการรีเฟรชไว้ใน 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.V16.CampaignService);

// Make more calls to service class.

สร้างอินสแตนซ์ GoogleAdsClient

คลาสที่สำคัญที่สุดในไลบรารี .NET ของ Google Ads API คือคลาส GoogleAdsClient ซึ่งจะช่วยให้คุณสร้างคลาสบริการที่กำหนดค่าไว้ล่วงหน้าซึ่งใช้สำหรับการเรียก API ได้ GoogleAdsClient มีเครื่องมือสร้างเริ่มต้นที่สร้างออบเจ็กต์ผู้ใช้โดยใช้การตั้งค่าที่ระบุไว้ใน App.config / Web.config ของแอป โปรดดูตัวเลือกการกำหนดค่าต่างๆ ในคู่มือการกำหนดค่า

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

สร้างบริการ

GoogleAdsClient มีเมธอด GetService ที่ใช้สร้างบริการ Google Ads ได้

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

เรามีคลาส Services ที่แจกแจงเวอร์ชัน API และบริการที่รองรับทั้งหมด เมธอด GetService จะยอมรับออบเจ็กต์การแจกแจงเหล่านี้เป็นอาร์กิวเมนต์เมื่อสร้างบริการ เช่น หากต้องการสร้างอินสแตนซ์ของ CampaignServiceClient สำหรับ Google Ads API เวอร์ชัน V16 คุณต้องเรียกใช้เมธอด GoogleAdsClient.GetService ที่มี Services.V16.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

คุณแก้ไขปัญหานี้ได้ 2 วิธีดังนี้

  1. ใช้ไลบรารี Grpc เดิม

    คุณสามารถตั้งค่าพร็อพเพอร์ตี้ UseGrpcCore ของ GoogleAdsConfig ให้ใช้ไลบรารี 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 และจัดการอย่างเหมาะสม

ระบบส่งอินสแตนซ์ GoogleAdsException เมื่อเกิดข้อผิดพลาดของ API ซึ่งมีรายละเอียดที่จะช่วยให้คุณทราบว่าเกิดข้อผิดพลาดใด

// 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}");
}