---
title: 'Google Ad Api quick-start(2)'
disqus: hackmd
---
###### tags: `Ads API` `Google Ads`
Google Ad Api quick-start(2)
===
[TOC]
## 筆記目的
完成串接Google Ad APi 的串接部分,具體來說可以執行官網上的
GetCampaigns.java範例
具體請參考:
* [Google Ad Api quickstart](https://developers.google.com/google-ads/api/docs/first-call/get-campaigns)
## 先備條件
請務必先拿到以下六個東西
1. Default_ClientId
2. Default_ClientSecret
3. Default_RefreshToken
4. Default_DeveloperToken
5. loginCustomerId (MCC)
6. requestCustomerId(廣告客戶)
## 程式碼部分
### 專案架構

總共會有兩個java檔案,分別是GetCampaings_Test以及Connect,
前者含有main方法,後者則有封裝後的參數
### Connect
```java=
package com.example.demo.util;
public class Connect {
public static final String Default_ClientId = "XXX";
public static final String Default_ClientSecret = "XXX";
public static final String Default_RefreshToken = "XXX";
public static final String Default_DeveloperToken = "XXX";
public static final Long loginCustomerId = XXXL;// mcc
public static final Long requestCustomerId = XXXL; //廣告客戶
}
```
### GetCampaings_Test
```java=
package com.example.demo;
//Copyright 2018 Google LLC
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.v8.errors.GoogleAdsException;
//import com.google.ads.googleads.v8.resources.AdGroup;
//import com.google.ads.googleads.v8.enums.AdGroupStatusEnum.AdGroupStatus;
import com.google.ads.googleads.v8.errors.GoogleAdsError;
import com.google.ads.googleads.v8.services.GoogleAdsRow;
import com.google.ads.googleads.v8.services.GoogleAdsServiceClient;
import com.google.ads.googleads.v8.services.GoogleAdsServiceClient.SearchPagedResponse;
import com.google.ads.googleads.v8.services.SearchGoogleAdsRequest;
//import com.google.ads.googleads.v8.utils.ResourceNames;
import com.google.auth.Credentials;
import com.google.auth.oauth2.UserCredentials;
//import com.google.protobuf.Int64Value;
//import java.io.FileNotFoundException;
import java.io.IOException;
import com.example.demo.util.Connect;
public class GetCampaigns_Test {
private static final int PAGE_SIZE = 1_000;
private static String MCCID = "yourloginCustomerId";
private static String CID = "yourrequestCustomerId";
public static void main(String[] args) throws IOException {
Long login_mcc_id = Long.parseLong(MCCID.replaceAll("-", ""));
Long customerId = Long.parseLong(CID.replaceAll("-", ""));
Credentials credentials = null;
GoogleAdsClient googleAdsClient = null;
try {
credentials = UserCredentials.newBuilder()
.setClientId(Connect.Default_ClientId)
.setClientSecret(Connect.Default_ClientSecret)
.setRefreshToken(Connect.Default_RefreshToken).build();
googleAdsClient = GoogleAdsClient.newBuilder().setCredentials(credentials)
.setDeveloperToken(Connect.Default_DeveloperToken).setLoginCustomerId(login_mcc_id) // Manager accounts
// only.
.build();
} catch (GoogleAdsException adse) {
System.out.println(adse.toString());
} catch (Exception e) {
System.out.println(e.toString());
}
try {
runExample(googleAdsClient, customerId);
} catch (GoogleAdsException gae) {
// GoogleAdsException is the base class for most exceptions thrown by an API
// request.
// Instances of this exception have a message and a GoogleAdsFailure that
// contains a
// collection of GoogleAdsErrors that indicate the underlying causes of the
// GoogleAdsException.
System.err.printf("Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
gae.getRequestId());
int i = 0;
for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
System.err.printf(" Error %d: %s%n", i++, googleAdsError);
}
}
}
/**
* Runs the example.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @throws GoogleAdsException if an API request failed with one or more service
* errors.
*/
private static void runExample(GoogleAdsClient googleAdsClient, long customerId) {
try (GoogleAdsServiceClient googleAdsServiceClient = googleAdsClient.getLatestVersion()
.createGoogleAdsServiceClient()) {
// Creates a request that will retrieve all campaigns using pages of the
// specified page size.
SearchGoogleAdsRequest request = SearchGoogleAdsRequest.newBuilder()
.setCustomerId(Long.toString(customerId)).setPageSize(PAGE_SIZE)
.setQuery("SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id").build();
// Issues the search request.
SearchPagedResponse searchPagedResponse = googleAdsServiceClient.search(request);
// Iterates over all rows in all pages and prints the requested field values for
// the campaign
// in each row.
for (GoogleAdsRow googleAdsRow : searchPagedResponse.iterateAll()) {
System.out.printf("Campaign with ID %d and name '%s' was found.%n", googleAdsRow.getCampaign().getId(),
googleAdsRow.getCampaign().getName());
}
}
}
}
```
### pom.xml
```
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.2</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>googleAdApi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>googleAdApi</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.google.api-ads</groupId>
<artifactId>google-ads</artifactId>
<version>14.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
```