您可以借助 Campaign Manager 360 API 以编程方式访问 Campaign Manager 360 账号中的信息。该 API 可用于管理和创建广告系列及报表,功能与 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(以便在“已安装的应用”流程中使用)的整个过程。如需生成用于在“服务账号”流程中访问 API 的凭据,请参阅服务账号指南。
按照相应步骤配置一个 Google API 控制台项目。
- 打开 API 控制台中的“凭据”页面。
依次点击创建凭据 > OAuth 客户端 ID。
如果您先前未曾为此项目配置过 OAuth 同意屏幕,系统会引导您立即执行此操作。点击配置意见征求页面。
选择用户类型,然后点击创建。
填写初始表单。日后若有需要,您可以修改。完成后,点击保存。
返回到凭据 > 创建凭据 > OAuth 客户端 ID 以继续操作。
选择桌面应用作为应用类型,为其命名,然后点击创建。
完成后,系统会显示一个 OAuth 2.0 客户端 ID 和客户端密钥,您可以将其下载为 JSON 格式进行保存,以备日后使用。
安装客户端库
Campaign Manager 360 API 是基于 HTTP 和 JSON 构建的,因此任何标准 HTTP 客户端均可向其发送请求并解析响应。
不过,使用 Google API 客户端库将为您带来优势,例如语言集成更出色、安全性更高,且支持发出经过授权的请求。客户端库支持多种编程语言;使用客户端库可以避免手动设置 HTTP 请求和手动解析响应。
首先,请选择您要在开发过程中使用的编程语言。
C#
安装适用于 .NET 的最新 Campaign Manager 360 API 客户端库。建议使用 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-rev20220611-1.32.1</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
安装适用于 Python 的最新 Campaign Manager 360 API 客户端库。建议使用 pip 管理安装过程。
打开终端并运行以下命令:
pip install --upgrade google-api-python-client
根据所用的系统,您可能需要在这些命令前面加上 sudo
。
了解详情
Ruby
安装适用于 Ruby 的最新 Campaign Manager 360 API 客户端库。建议使用 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,让您可以直接通过浏览器发出测试请求。
此外,也欢迎您查看我们的其他指南,这些指南对一些高级主题进行了讲解,并就经常执行的一些任务提供了完整的示例。
当您准备好开始编写代码时,可随时参考我们收集的大量代码示例。您可以根据自己的需要,在这些代码的基础上进行修改和扩展。