이 가이드에는 Google Ads API를 시작하는 방법이 간략하게 나와 있습니다. .NET 라이브러리를 설치합니다.
설치
클라이언트 라이브러리 바이너리는 NuGet을 사용하여 배포됩니다. NuGet 참조 추가
Google.Ads.GoogleAds
(으)로
패키지를 생성합니다.
클라이언트 라이브러리로 이동하게 됩니다.
승인 설정하기
API 호출을 승인하려면 클라이언트 ID, 클라이언트 보안 비밀번호, 새로고침 토큰, 개발자 토큰을 라이브러리에 추가합니다.
사용자 인증 정보를 생성해야 하는 경우
- 개발자 토큰 가이드에 따라 개발자 토큰을 재설정합니다.
- OAuth 데스크톱 앱 흐름 따르기 클라이언트 ID, 클라이언트 비밀번호, 갱신 토큰 생성 가이드를 참조하세요.
이미 사용자 인증 정보가 있는 경우
- 다음에서
GoogleAdsApi
노드와GoogleAdsApi
섹션을 복사합니다. 다음 위치에 있는App.config
파일의configSections
노드 GitHubApp.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();
서비스 만들기
GoogleAdsClient
는 객체를 만드는 데 사용할 수 있는 GetService
메서드를 제공합니다.
광고 서비스입니다.
CampaignServiceClient campaignService = client.GetService(Services.V17.CampaignService);
// Now make calls to CampaignService.
지원되는 모든 API 버전을 열거하는 Services
클래스와
제공합니다 GetService
메서드는 이러한 열거형 객체를 인수로 허용합니다.
서비스 생성 시 사용됩니다. 예를 들어
Google Ads API V17
버전의 경우 CampaignServiceClient
다음과 같이 GoogleAdsClient.GetService
메서드를 호출해야 합니다.
Services.V17.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 애플리케이션입니다.
이 문제를 해결하는 방법에는 두 가지가 있습니다.
기존 Grpc 라이브러리를 사용합니다.
GoogleAdsConfig
의UseGrpcCore
속성을 설정하여 기본Grpc.Net.Client
라이브러리가 아닌 기존Grpc.Core
라이브러리를 사용합니다. 이 방법은 .NET Framework 애플리케이션에서 광범위하게 테스트되지는 않았지만, 문제가 해결되지 않을 수 있습니다 다음은 샘플 스니펫입니다.GoogleAdsConfig config = new GoogleAdsConfig(); config.UseGrpcCore = true; GoogleAdsClient client = new GoogleAdsClient(config);
gRPC 지원 페이지에 기존
Grpc.Core
라이브러리와 기본Grpc.Net.Client
라이브러리를 사용합니다.비동기 메서드를 사용합니다.
비동기 메서드를 사용하여 정지를 방지할 수 있습니다. 예를 들면 다음과 같습니다.
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}");
}