開始使用

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。

產生憑證

您必須授予所有傳送至 Campaign Manager 360 API 的要求。如需授權的簡短總覽,請參閱如何授權給 Google 以及識別您的應用程式

以下操作說明將引導您建立 OAuth 2.0 用戶端 ID 以用於已安裝應用程式流程。如需產生與服務帳戶流程搭配使用的憑證,請參閱服務帳戶指南。

  1. 按照步驟設定 Google API 控制台專案

  2. 在 API 控制台中開啟「憑證」頁面
  3. 依序按一下「Create CREDENTIALS」>「OAuth client ID」

    1. 如果您先前未為這項專案設定 OAuth 同意畫面,系統會引導您進行設定。按一下「CONCONGENT CONSENT」

    2. 選取使用者類型,然後按一下「建立」。

    3. 填寫初始表單。日後可視需求修改。完成後,按一下「Save」(儲存)

    4. 如要繼續,請返回「憑證」>「建立憑證」>「OAuth 用戶端 ID」

  4. 將應用程式類型設為「Desktop app」,為其命名,然後按一下「Create」。

完成後,系統會顯示 OAuth 2.0 用戶端 ID 和用戶端密鑰。您可以下載 JSON 格式的檔案,以供日後使用。

安裝用戶端程式庫

Campaign Manager 360 API 是以 HTTP 和 JSON 做為建構基礎,因此所有標準 HTTP 用戶端都可以向這個 API 傳送要求並剖析回應。

不同的是,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#

  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. 建立已授權的 Dfareport 用戶端。

    // 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. 建立已授權的 Dfareport 用戶端。

    // 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. 建立已授權的 Dfareport 用戶端。

    // 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. 建立已授權的 Dfareport 用戶端。

    # 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. 建立已授權的 Dfareport 用戶端。

    # 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,可用來直接從瀏覽器提出測試要求。

查看其他涵蓋進階主題的指南,並為一般工作提供端對端範例。

當您準備好開始編寫程式碼時,您可以瀏覽我們各種的程式碼範例,並視需要修改和擴充程式碼。