透過 Campaign Manager 360 API,您可以透過程式輔助的方式存取 Campaign Manager 360 帳戶中的資訊。您可透過這項服務管理及建立廣告活動和報表,就像使用 Campaign Manager 360 和報表製作工具網路服務一樣。
本指南說明如何開始使用 Campaign Manager 360 API。
必要條件
使用 Campaign Manager 360 API 前,請先完成下列前置步驟:
您必須擁有 Campaign Manager 360 帳戶。 如需註冊資訊,請參閱「廣告主/代理商」。
您的 Campaign Manager 360 帳戶必須啟用 API 存取權。大多數帳戶預設會啟用這項功能。如果不確定,請洽詢帳戶代表或 Campaign Manager 360 支援團隊。
你必須擁有可存取這個帳戶的使用者設定檔。請 Campaign Manager 360 帳戶管理員建立與這個帳戶相關聯的使用者設定檔。
在 Campaign Manager 360 使用者介面中檢查使用者設定檔權限。這些控制項可決定使用者設定檔可透過 API 存取哪些內容。沒有個別的 API 權限。
建立專案
如要開始使用 Campaign Manager 360 API,請先在 Google API 控制台中建立或選取專案,然後啟用 API。使用這個連結可逐步完成程序,並自動啟用 Campaign Manager 360 API。
產生憑證
您向 Campaign Manager 360 API 發出的所有要求都必須獲得授權。如要簡要瞭解授權程序,請參閱如何授權要求並讓 Google 能識別您的應用程式。
請按照下列操作說明建立 OAuth 2.0 用戶端 ID,以便搭配已安裝應用程式流程使用。如需產生憑證的操作說明,以便搭配服務帳戶流程使用,請參閱「服務帳戶」指南。
按照步驟設定 Google API 控制台專案。
- 在 API 控制台中開啟「憑證」頁面。
依序點選「建立憑證」>「OAuth 用戶端 ID」。
如果您先前未設定這個專案的 OAuth 同意畫面,系統會引導您進行設定。點選「設定同意畫面」。
選取使用者類型,然後按一下「建立」。
填寫初步表單。日後可視需要編輯。完成後,請按一下「儲存」。
返回「憑證」>「建立憑證」>「OAuth 用戶端 ID」,然後繼續操作。
將應用程式類型設為「桌面應用程式」,然後命名並按一下「建立」。
完成後,系統會顯示 OAuth 2.0 用戶端 ID 和用戶端密鑰,您可以下載 JSON 格式並儲存,以供日後使用。
安裝用戶端程式庫
Campaign Manager 360 API 是以 HTTP 和 JSON 做為建構基礎,因此所有標準 HTTP 用戶端都可以向 Campaign Manager 360 API 傳送要求並剖析回應。
不過,Google API 用戶端程式庫不但提供更出色的語言整合功能,安全性也更高,還能執行授權要求。用戶端程式庫支援多種程式語言,只要善加利用,您就不必再手動設定 HTTP 要求及剖析回應。
首先,請選擇要用於開發作業的程式設計語言。
C#
安裝最新版的 Campaign Manager 360 API .NET 用戶端程式庫。建議使用 NuGet 管理安裝作業。
開啟 NuGet 套件管理員主控台,然後執行下列指令:
Install-Package Google.Apis.Dfareporting.v3_4
瞭解詳情
Java
安裝最新版適用於 Java 的 Campaign Manager 360 API 用戶端程式庫。建議使用 Maven 管理安裝作業。
在 pom.xml 檔案中加入以下依附元件:
<dependency> <groupId>com.google.apis</groupId> <artifactId>google-api-services-dfareporting</artifactId> <version>v4-rev20250722-2.0.0</version> <exclusions> <exclusion> <groupId>com.google.guava</groupId> <artifactId>guava-jdk5</artifactId> </exclusion> </exclusions> </dependency>
瞭解詳情
PHP
安裝最新版適用於 PHP 的 Campaign Manager 360 API 用戶端程式庫。建議使用 Composer 管理安裝作業。
開啟終端機並執行下列指令:
composer require google/apiclient
如果您已安裝程式庫,只想更新至最新版本,請執行下列指令:
composer update google/apiclient
視您的系統而定,您可能必須在這些指令前加上 sudo。
瞭解詳情
Python
安裝最新版 Campaign Manager 360 API Python 專用用戶端程式庫。建議使用 pip 管理安裝作業。
開啟終端機並執行下列指令:
pip install --upgrade google-api-python-client
視您的系統而定,您可能必須在這些指令前加上 sudo。
瞭解詳情
Ruby
安裝最新版的 Campaign Manager 360 API Ruby 用戶端程式庫。建議使用 RubyGems 管理安裝作業。
開啟終端機並執行下列指令:
gem install google-api-client
如果您已安裝程式庫,只想更新至最新版本,請執行下列指令:
gem update -y google-api-client
視您的系統而定,您可能必須在這些指令前加上 sudo。
瞭解詳情
如要查看更多支援的語言,請前往用戶端程式庫頁面。
提出要求
建立 OAuth 2.0 憑證並安裝用戶端程式庫後,即可開始使用 Campaign Manager 360 API。請按照下方的快速入門指南,瞭解如何授權、設定用戶端,以及發出第一個要求。
C#
載入用戶端密鑰檔案,並產生授權憑證。
首次執行這個步驟時,系統會要求您在瀏覽器中接受授權提示。接受前,請務必使用有權存取 Campaign Manager 360 的 Google 帳戶登入。您的應用程式將有權代表目前登入的帳戶存取資料。
// Load client secrets from the specified JSON file. GoogleClientSecrets clientSecrets; using(Stream json = new FileStream(pathToJsonFile, FileMode.Open, FileAccess.Read)) { clientSecrets = GoogleClientSecrets.Load(json); } // Create an asynchronous authorization task. // // Note: providing a data store allows auth credentials to be cached, so they survive multiple // runs of the application. This avoids prompting the user for authorization every time the // access token expires, by remembering the refresh token. The "user" value is used to // identify a specific set of credentials within the data store. You may provide different // values here to persist credentials for multiple users to the same data store. Task<UserCredential> authorizationTask = GoogleWebAuthorizationBroker.AuthorizeAsync( clientSecrets.Secrets, OAuthScopes, "user", CancellationToken.None, dataStore); // Authorize and persist credentials to the data store. UserCredential credential = authorizationTask.Result;
建立授權的 Dfareporting 用戶端。
// Create a Dfareporting service object. // // Note: application name should be replaced with a value that identifies your application. service = new DfareportingService( new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "C# installed app sample" } );
執行作業。
// Retrieve and print all user profiles for the current authorized user. UserProfileList profiles = service.UserProfiles.List().Execute(); foreach (UserProfile profile in profiles.Items) { Console.WriteLine("Found user profile with ID {0} and name \"{1}\".", profile.ProfileId, profile.UserName); }
Java
載入用戶端密鑰檔案,並產生授權憑證。
首次執行這個步驟時,系統會要求您在瀏覽器中接受授權提示。接受前,請務必使用有權存取 Campaign Manager 360 的 Google 帳戶登入。您的應用程式將有權代表目前登入的帳戶存取資料。
// Load the client secrets JSON file. GoogleClientSecrets clientSecrets = GoogleClientSecrets.load( jsonFactory, Files.newBufferedReader(Paths.get(pathToClientSecretsFile), UTF_8)); // Set up the authorization code flow. // // Note: providing a DataStoreFactory allows auth credentials to be cached, so they survive // multiple runs of the program. This avoids prompting the user for authorization every time the // access token expires, by remembering the refresh token. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( httpTransport, jsonFactory, clientSecrets, OAUTH_SCOPES) .setDataStoreFactory(dataStoreFactory) .build(); // Authorize and persist credentials to the data store. // // Note: the "user" value below is used to identify a specific set of credentials in the data // store. You may provide different values here to persist credentials for multiple users to // the same data store. Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
建立授權的 Dfareporting 用戶端。
// Create a Dfareporting client instance. // // Note: application name below should be replaced with a value that identifies your // application. Suggested format is "MyCompany-ProductName/Version.MinorVersion". Dfareporting reporting = new Dfareporting.Builder(credential.getTransport(), credential.getJsonFactory(), credential) .setApplicationName("dfareporting-java-installed-app-sample") .build();
執行作業。
// Retrieve and print all user profiles for the current authorized user. UserProfileList profiles = reporting.userProfiles().list().execute(); for (int i = 0; i < profiles.getItems().size(); i++) { System.out.printf("%d) %s%n", i + 1, profiles.getItems().get(i).getUserName()); }
PHP
載入用戶端密鑰檔案,並產生授權憑證。
首次執行這個步驟時,系統會要求您在瀏覽器中接受授權提示。接受前,請務必使用有權存取 Campaign Manager 360 的 Google 帳戶登入。您的應用程式將有權代表目前登入的帳戶存取資料。
// Create a Google_Client instance. // // Note: application name should be replaced with a value that identifies // your application. Suggested format is "MyCompany-ProductName". $client = new Google_Client(); $client->setAccessType('offline'); $client->setApplicationName('PHP installed app sample'); $client->setRedirectUri(self::OAUTH_REDIRECT_URI); $client->setScopes(self::$OAUTH_SCOPES); // Load the client secrets file. $client->setAuthConfig($pathToJsonFile); // Try to load cached credentials from the token store. Using a token store // allows auth credentials to be cached, so they survive multiple runs of // the application. This avoids prompting the user for authorization every // time the access token expires, by remembering the refresh token. if (file_exists($tokenStore) && filesize($tokenStore) > 0) { $client->setAccessToken(file_get_contents($tokenStore)); } else { // If no cached credentials were found, authorize and persist // credentials to the token store. print 'Open this URL in your browser and authorize the application.'; printf("\n\n%s\n\n", $client->createAuthUrl()); print 'Enter the authorization code: '; $code = trim(fgets(STDIN)); $client->authenticate($code); file_put_contents($tokenStore, json_encode($client->getAccessToken())); }
建立授權的 Dfareporting 用戶端。
// Create a Dfareporting service object. $service = new Google_Service_Dfareporting($client);
執行作業。
// Retrieve and print all user profiles for the current authorized user. $result = $service->userProfiles->listUserProfiles(); foreach ($result['items'] as $userProfile) { printf( "User profile \"%s\" (ID: %d) found for account %d.\n", $userProfile->getUserName(), $userProfile->getProfileId(), $userProfile->getAccountId() ); }
Python
載入用戶端密鑰檔案,並產生授權憑證。
首次執行這個步驟時,系統會要求您在瀏覽器中接受授權提示。接受前,請務必使用有權存取 Campaign Manager 360 的 Google 帳戶登入。您的應用程式將有權代表目前登入的帳戶存取資料。
# Set up a Flow object to be used if we need to authenticate. flow = client.flow_from_clientsecrets( path_to_client_secrets_file, scope=OAUTH_SCOPES) # Check whether credentials exist in the credential store. Using a credential # store allows auth credentials to be cached, so they survive multiple runs # of the application. This avoids prompting the user for authorization every # time the access token expires, by remembering the refresh token. storage = Storage(CREDENTIAL_STORE_FILE) credentials = storage.get() # If no credentials were found, go through the authorization process and # persist credentials to the credential store. if credentials is None or credentials.invalid: credentials = tools.run_flow(flow, storage, tools.argparser.parse_known_args()[0]) # Use the credentials to authorize an httplib2.Http instance. http = credentials.authorize(httplib2.Http())
建立授權的 Dfareporting 用戶端。
# Construct a service object via the discovery service. service = discovery.build('dfareporting', 'v4', http=http)
執行作業。
# Construct the request. request = service.userProfiles().list() # Execute request and print response. response = request.execute() for profile in response['items']: print('Found user profile with ID %s and user name "%s".' % (profile['profileId'], profile['userName']))
Ruby
載入用戶端密鑰檔案,並產生授權憑證。
首次執行這個步驟時,系統會要求您在瀏覽器中接受授權提示。接受前,請務必使用有權存取 Campaign Manager 360 的 Google 帳戶登入。您的應用程式將有權代表目前登入的帳戶存取資料。
# Load client ID from the specified file. client_id = Google::Auth::ClientId.from_file(path_to_json_file) # Set up the user authorizer. # # Note: providing a token store allows auth credentials to be cached, so they # survive multiple runs of the application. This avoids prompting the user for # authorization every time the access token expires, by remembering the # refresh token. authorizer = Google::Auth::UserAuthorizer.new( client_id, [API_NAMESPACE::AUTH_DFAREPORTING], token_store ) # Authorize and persist credentials to the data store. # # Note: the 'user' value below is used to identify a specific set of # credentials in the token store. You may provide different values here to # persist credentials for multiple users to the same token store. authorization = authorizer.get_credentials('user') if authorization.nil? puts format( "Open this URL in your browser and authorize the application.\n\n%s" \ "\n\nEnter the authorization code:", authorizer.get_authorization_url(base_url: OAUTH_REDIRECT_URI) ) code = STDIN.gets.chomp authorization = authorizer.get_and_store_credentials_from_code( base_url: OAUTH_REDIRECT_URI, code: code, user_id: 'user' ) end
建立授權的 Dfareporting 用戶端。
# Create a Dfareporting service object. # # Note: application name should be replaced with a value that identifies # your application. Suggested format is "MyCompany-ProductName". service = API_NAMESPACE::DfareportingService.new service.authorization = authorization service.client_options.application_name = 'Ruby installed app sample' service.client_options.application_version = '1.0.0'
執行作業。
// Retrieve and print all user profiles for the current authorized user. UserProfileList profiles = service.UserProfiles.List().Execute(); foreach (UserProfile profile in profiles.Items) { Console.WriteLine("Found user profile with ID {0} and name \"{1}\".", profile.ProfileId, profile.UserName); }
瞭解詳情
請參閱 API 參考資料,瞭解 API 提供的所有服務。每個方法詳細資料頁面都內嵌 API Explorer,您可以使用這個工具直接從瀏覽器發出測試要求。
請參閱其他指南,瞭解進階主題,以及常見工作的端對端範例。
準備好開始撰寫程式碼時,歡迎瀏覽我們豐富的程式碼範例,您可以修改及擴充這些範例,以符合自身需求。