시작하기

이 가이드에서는 Google Ads API .NET 라이브러리를 시작하는 방법을 간략하게 설명합니다.

설치

클라이언트 라이브러리 바이너리는 NuGet을 사용하여 배포됩니다. 클라이언트 라이브러리를 사용하려면 프로젝트의 Google.Ads.GoogleAds 패키지에 Nuget 참조를 추가합니다.

승인 설정하기

API 호출을 승인하려면 클라이언트 ID, 클라이언트 보안 비밀번호, 갱신 토큰, 개발자 토큰을 라이브러리에 지정해야 합니다.

사용자 인증 정보가 이미 있는 경우...

  • GitHub의 App.config 파일에서 configSections 노드 아래에 있는 GoogleAdsApi 노드와 GoogleAdsApi 섹션을 App.config / Web.config 파일로 복사합니다. NuGet을 사용하여 패키지를 설치한 경우 이러한 노드가 App.config / Web.config 파일에 자동으로 삽입됩니다.
  • 앱의 App.config / Web.config에 개발자 토큰, 클라이언트 ID, 클라이언트 비밀번호, 갱신 토큰을 포함합니다. GitHub에 포함된 App.config 파일은 문서화가 잘 되어 있지만, 구성 가이드를 참고하여 자세히 알아보고 대체 구성 설정을 사용할 수도 있습니다.

사용자 인증 정보를 생성해야 하는 경우

  • 개발자 토큰이 없는 경우 개발자 토큰 가이드에 따라 개발자 토큰을 받으세요.
  • OAuth 데스크톱 앱 흐름 가이드에 따라 클라이언트 ID, 클라이언트 비밀번호, 갱신 토큰을 생성합니다.
  • GitHub의 App.config 파일에서 configSections 노드 아래에 있는 GoogleAdsApi 노드와 GoogleAdsApi 섹션을 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.V16.CampaignService);

// Make more calls to service class.

GoogleAdsClient 인스턴스 만들기

Google Ads API .NET 라이브러리에서 가장 중요한 클래스는 GoogleAdsClient 클래스입니다. 이 API를 사용하면 API 호출에 사용할 수 있는 사전 구성된 서비스 클래스를 만들 수 있습니다. GoogleAdsClient는 앱의 App.config / Web.config에 지정된 설정을 사용하여 사용자 객체를 만드는 기본 생성자를 제공합니다. 다양한 구성 옵션은 구성 가이드를 참고하세요.

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

서비스 만들기

GoogleAdsClient는 Google Ads 서비스를 만드는 데 사용할 수 있는 GetService 메서드를 제공합니다.

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

Google에서는 지원되는 모든 API 버전과 서비스를 열거하는 Services 클래스를 제공합니다. GetService 메서드는 서비스를 만들 때 이러한 열거형 객체를 인수로 허용합니다. 예를 들어 Google Ads API의 버전 V16에 대한 CampaignServiceClient 인스턴스를 만들려면 위와 같이 Services.V16.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 호출을 실행하는 것입니다.

이 문제를 해결하는 방법에는 두 가지가 있습니다.

  1. 기존 GRPC 라이브러리를 사용합니다.

    기본 Grpc.Net.Client 라이브러리 대신 기존 Grpc.Core 라이브러리를 사용하도록 GoogleAdsConfigUseGrpcCore 속성을 설정할 수 있습니다. 이 방법은 .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}");
}