使用入门

您可以借助 DCM/DFA Reporting and Trafficking API 以编程方式访问 Campaign Manager 帐号中的信息。该 API 可用于管理和创建广告系列及报表,功能与基于网页服务的 Campaign Manager 和报表制作工具基本无二。

本指南介绍了如何上手使用 DCM/DFA Reporting and Trafficking API。

前提条件

您需要满足以下前提条件,才能使用 DCM/DFA Reporting and Trafficking API:

  1. 您必须拥有 Campaign Manager 帐号。如需注册方面的信息,请参阅广告客户/代理机构

  2. 您的 Campaign Manager 帐号必须已启用 API 访问权限。大多数帐号在默认情况下都启用了此权限;如果您不确定自己的帐号是否已启用,可向客户代表或 Campaign Manager 支持团队寻求帮助。

  3. 您必须具备有权访问该帐号的用户个人资料。请让您的 Campaign Manager 帐号管理员创建一份与该帐号相关联的用户个人资料。

  4. 在 Campaign Manager 界面中查看用户个人资料权限。这些权限可控制用户个人资料能够通过该 API 访问哪些内容。您无法为 API 访问单独设置权限。

创建项目

若要开始使用 DCM/DFA Reporting and Trafficking API,您需要先在 Google API 控制台中创建或选择一个项目,并启用该 API。请点击下面的链接,按照显示的说明逐步完成这一流程,并自动启用 DCM/DFA Reporting and Trafficking API。

生成凭据

向 DCM/DFA Reporting and Trafficking API 发出的所有请求都必须获得授权。如需简要了解授权,请参阅如何进行授权和让 Google 识别您的应用

以下说明将引导您完成创建 OAuth 2.0 客户端 ID(以便在“已安装的应用”流程中使用)的整个过程。如需生成用于在“服务帐号”流程中访问 API 的凭据,请参阅服务帐号指南。

  1. 按照相应步骤配置一个 Google API 控制台项目

  2. 在 API 控制台中打开“凭据”页面
  3. 依次点击创建凭据 > OAuth 客户端 ID

    1. 如果您先前未曾为此项目配置过 OAuth 同意屏幕,系统会引导您立即执行此操作。点击配置同意屏幕

    2. 选择用户类型,然后点击创建

    3. 填写初始表单。日后若有需要,您可以修改。完成后,点击保存

    4. 返回到凭据 > 创建凭据 > OAuth 客户端 ID 以继续操作。

  4. 选择桌面应用作为应用类型,为其命名,然后点击创建

完成后,系统会显示一个 OAuth 2.0 客户端 ID 和客户端密钥 - 您可将其下载为 JSON 格式进行保存以备后用。

安装客户端库

DCM/DFA Reporting and Trafficking API 的通信方式基于 HTTP 和 JSON,因此任何标准 HTTP 客户端均可向其发送请求并解析响应。

不过,使用 Google API 客户端库将为您带来优势,例如语言集成更出色、安全性更高,且支持发出经过授权的请求。客户端库支持多种编程语言;使用客户端库可以避免手动设置 HTTP 请求和手动解析响应。

首先,请选择您要在开发过程中使用的编程语言。

C#

安装适用于 .NET 的最新 DCM/DFA Reporting and Trafficking API 客户端库。建议使用 NuGet 管理安装过程。

打开 NuGet 软件包管理器控制台并运行以下命令:

Install-Package Google.Apis.Dfareporting.v3_2

了解详情

Java

安装适用于 Java 的最新 DCM/DFA Reporting and Trafficking API 客户端库。建议使用 Maven 管理安装过程。

将以下依赖项添加到您的 pom.xml 文件中:

<dependency>
  <groupId>com.google.apis</groupId>
  <artifactId>google-api-services-dfareporting</artifactId>
  <version>v3.3-rev20190124-1.28.0</version>
  <exclusions>
    <exclusion>
      <groupId>com.google.guava</groupId>
      <artifactId>guava-jdk5</artifactId>
    </exclusion>
  </exclusions>
</dependency>

了解详情

PHP

安装适用于 PHP 的最新 DCM/DFA Reporting and Trafficking API 客户端库。建议使用 Composer 管理安装过程。

打开终端并运行以下命令:

composer require google/apiclient

如果您已安装该库,并且只是想更新到最新版本,请运行以下命令:

composer update google/apiclient

根据所用的系统,您可能需要在这些命令前面加上 sudo

了解详情

Python

安装适用于 Python 的最新 DCM/DFA Reporting and Trafficking API 客户端库。建议使用 pip 管理安装过程。

打开终端并运行以下命令:

pip install --upgrade google-api-python-client

根据所用的系统,您可能需要在这些命令前面加上 sudo

了解详情

Ruby

安装适用于 Ruby 的最新 DCM/DFA Reporting and Trafficking API 客户端库。建议使用 RubyGems 管理安装过程。

打开终端并运行以下命令:

gem install google-api-client

如果您已安装该库,并且只是想更新到最新版本,请运行以下命令:

gem update -y google-api-client

根据所用的系统,您可能需要在这些命令前面加上 sudo

了解详情

您可以在客户端库页面上找到更多支持的语言。

发出请求

创建 OAuth 2.0 凭据安装客户端库后,您便可以开始使用 DCM/DFA Reporting and Trafficking API 了。按照以下快速入门指南进行操作,可以了解如何授权、如何配置客户端,以及如何发出第一个请求。

C#

  1. 加载客户端密钥文件并生成授权凭据

    第一次执行此步骤时,系统会在浏览器中提示您接受授权。接受之前,请务必使用可访问 Campaign Manager 的 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;
    
  2. 创建已获授权的 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"
        }
    );
    
  3. 执行以下操作

    // 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

  1. 加载客户端密钥文件并生成授权凭据

    第一次执行此步骤时,系统会在浏览器中提示您接受授权。接受之前,请务必使用可访问 Campaign Manager 的 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");
    
  2. 创建已获授权的 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();
    
  3. 执行以下操作

    // 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

  1. 加载客户端密钥文件并生成授权凭据

    第一次执行此步骤时,系统会在浏览器中提示您接受授权。接受之前,请务必使用可访问 Campaign Manager 的 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()));
    }
    
  2. 创建已获授权的 Dfareporting 客户端

    // Create a Dfareporting service object.
    $service = new Google_Service_Dfareporting($client);
    
  3. 执行以下操作

    // 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

  1. 加载客户端密钥文件并生成授权凭据

    第一次执行此步骤时,系统会在浏览器中提示您接受授权。接受之前,请务必使用可访问 Campaign Manager 的 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())
    
  2. 创建已获授权的 Dfareporting 客户端

    # Construct a service object via the discovery service.
    service = discovery.build('dfareporting', 'v3.3', http=http)
    
  3. 执行以下操作

    # 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

  1. 加载客户端密钥文件并生成授权凭据

    第一次执行此步骤时,系统会在浏览器中提示您接受授权。接受之前,请务必使用可访问 Campaign Manager 的 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
    
  2. 创建已获授权的 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'
    
  3. 执行以下操作

    // 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,让您可以直接通过浏览器发出测试请求。

此外,也欢迎您查看我们的其他指南,这些指南对一些高级主题进行了讲解,并就经常执行的一些任务提供了完整的示例。

当您准备好开始编写代码时,可随时参考我们收集的大量代码示例。您可以根据自己的需要,在这些代码的基础上进行修改和扩展。