开始使用

Campaign Manager 360 API 可让您以编程方式访问 Campaign Manager 360 账号。用于管理和创建广告系列和报告 就像通过 Campaign Manager 360 和报告制作工具网络服务进行操作一样。

本指南介绍了如何开始使用 Campaign Manager 360 API。

前提条件

在使用 Campaign Manager 360 API 之前,您需要 满足:

  1. 您必须拥有 Campaign Manager 360 账号。请参阅 广告客户/代理机构,用于提供注册信息。

  2. 您的 Campaign Manager 360 账号必须已启用 API 访问权限。大多数人 账号已默认启用此功能;如果您不确定,请与您的 客户代表或Campaign Manager 360 支持 团队寻求帮助。

  3. 您必须具备有权访问此账号的用户个人资料。备好您的 Campaign Manager 360 账号管理员创建与 此账号。

  4. 在 Campaign Manager 360 界面中查看用户个人资料权限。这些控件 用户个人资料可以通过该 API 访问的内容。没有单独的 API 权限。

创建项目

要开始使用 Campaign Manager 360 API,您需要先创建 或者在 Google API 控制台中选择一个项目并启用该 API。使用此 链接将指导您完成该流程并激活 Campaign Manager 360 API 。

<ph type="x-smartling-placeholder">

生成凭据

您向 Campaign Manager 360 API 发出的所有请求都必须获得授权。简要 请参阅如何授权和标识您的 向 Google 提供应用

以下说明将引导您完成 OAuth 密钥的创建过程 与已安装的应用搭配使用的 2.0 客户端 ID 数据流。有关如何生成使用凭据的说明 请参阅服务账号 指南。

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

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

    1. 如果您还没有为此项目配置 OAuth 同意屏幕 系统会引导您立即执行此操作点击配置同意 SCREEN

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

    3. 填写初始表单。如果需要,您以后可以进行修改。点击 完成后保存

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

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

完成后,您将看到一个 OAuth 2.0 客户端 ID 和客户端 Secret,您可以以 JSON 格式下载并保存以备后用。

<ph type="x-smartling-placeholder">

安装客户端库

Campaign Manager 360 API 是基于 HTTP 和 JSON 构建的,因此任何标准 HTTP 客户端均可 并解析响应。

不过,Google API 客户端库可提供更好的语言集成, 增强了安全性,并支持发出授权请求。客户 支持多种编程语言;使用它们 可以避免手动设置 HTTP 请求和解析响应。

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

C#

安装适用于 .NET 的最新 Campaign Manager 360 API 客户端库。使用 建议使用 NuGet 管理安装。

打开 NuGet Package Manager 控制台并运行以下命令:

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

了解详情

如需更多支持的语言,请访问 Client 库页面。

发出请求

创建了 OAuth 2.0 凭据客户端库 安装,您就可以开始使用 Campaign Manager 360 API 了。了解具体方法 授权、配置客户端并发出第一个请求,方法如下: 请参阅下面的快速入门。

C#

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

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

    # Construct a service object via the discovery service.
    service = discovery.build('dfareporting', 'v4', 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 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
    
  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 所提供的功能。每个方法详情页面都有一个嵌入式 API 您可以使用 Explorer 直接从您的 。

请查看我们的其他指南,这些指南介绍了一些高级主题, 常见任务示例。

当您准备好开始编写代码时,可以随时浏览我们的大量资源, 代码示例的集合,您可以在这些代码的基础上 以满足您的需求