はじめに

このガイドでは、Google Ads API の利用を開始する方法を概説します 使用できます。

インストール

クライアント ライブラリのバイナリは、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 ファイルは詳細にドキュメント化されていますが、 構成ガイド クライアント ライブラリを構成する別の方法も確認します。 使用できます。

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.

GoogleAdsClient インスタンスを作成する

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 メソッドを提供します。 Google 広告サービス。

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

サポートされているすべての API バージョンを列挙し、Services 提供します。GetService メソッドは、これらの列挙型オブジェクトを引数として受け取ります。 指定する必要があります。たとえば、Cloud Storage バケットを Google Ads API バージョン V17 向けの CampaignServiceClient 次のように GoogleAdsClient.GetService メソッドを呼び出す必要があります。 次のように、引数として Services.V17.CampaignService を指定します。 説明しました。

スレッドの安全性

複数のスレッド間で GoogleAdsClient インスタンスを共有することは安全ではありません。 1 つのスレッドでインスタンスの構成変更を行うと、 他のスレッドで作成するサービスに影響します。たとえば、 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 呼び出しを行う 作成します

この問題に対処するには、次の 2 つの方法があります。

  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 エラーをキャプチャして処理することが重要です。 適切に分類します

GoogleAdsException インスタンスは、API エラーが発生するとスローされます。機能 問題を特定するための詳細が表示されます。

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