設定應用程式

如果您使用的是用戶端程式庫,應用程式就需要將 Doubleclicksearch 服務物件例項化。所有與 Search Ads 360 API 的互動都會透過這個服務物件進行。如果您未使用用戶端程式庫,可以略過本節,但您需要編寫一些程式碼,才能傳送 HTTP 要求並剖析回應。

每個 Doubleclicksearch 例項都需要參照物件,該物件包含您的憑證和 OAuth 2.0 存取權杖。Doubleclicksearch 會在每次要求中將憑證和權杖傳送至 Search Ads 360 API。下列程式碼示範如何使用 OAuth 2.0 為已安裝的應用程式建立 Doubleclicksearch 服務物件例項。

如果您尚未取得 Search Ads 360 API 的 OAuth 2.0 憑證,請參閱「設定授權」一文。

Java

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.DataStoreFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.doubleclicksearch.Doubleclicksearch;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Arrays;

private static final String[] SCOPES =
    new String[] {
      "https://www.googleapis.com/auth/doubleclicksearch"
    };

/** File for storing user credentials. */
private static final java.io.File DATA_STORE_FILE =
    new File(System.getProperty("user.home"), ".credentials/doubleclicksearch.json");

/**
 * Global instance of the {DataStoreFactory}. The best practice is to make it a single
 * globally shared instance across your application.
 */
private static FileDataStoreFactory dataStoreFactory;

/**
 * Sets up a new Doubleclicksearch service. The builder for the service
 * requires a Credential object, which provides the credentials needed to
 * interact with Search Ads 360.
 */
private static Doubleclicksearch getService() throws Exception {
  JsonFactory jsonFactory = new JacksonFactory();
  NetHttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();

  Credential credential = readCredentialFromCommandLine(jsonFactory, transport);

  return new Doubleclicksearch.Builder(transport, jsonFactory, credential)
      .setApplicationName("Sample")
      .build();
}

/**
 * Generates a credential by reading client id, client secret and refresh
 * token from the command line. You could update this method to read the
 * data from a database or other secure location.
 */
private static Credential readCredentialFromCommandLine(
    JsonFactory jsonFactory,
    NetHttpTransport transport) {
  String clientId = System.console().readLine("Client id: ");
  String clientSecret = System.console().readLine("Client secret: ");
  String refreshToken = System.console().readLine("Refresh token: ");
  return new GoogleCredential.Builder()
      .setJsonFactory(jsonFactory)
      .setTransport(transport)
      .setClientSecrets(clientId, clientSecret)
      .build()
      .setRefreshToken(refreshToken);
}

/**
 * This method is an alternative to {@link #readCredentialFromCommandLine}. It reads
 * client secrets from a {@code client_secrets.json} file, interactively creates
 * the necessary authorization tokens on first run, and stores the tokens in the
 * {@code FileDataStore}. Subsequent runs will no longer require interactivity
 * as long as the {@code .credentials/doubleclicksearch.json} file is not removed.
 * You can download the {@code .credentials/doubleclicksearch.json} file from the
 * Google API Console.
 * Note that setting the {@link GoogleAuthorizationCodeFlow} access type
 * to {@code offline} is what causes {@code GoogleAuthorizationCodeFlow} to obtain
 * and store refresh tokens.
 */
private static Credential generateCredentialInteractively(
    JsonFactory jsonFactory,
    NetHttpTransport transport) throws Exception {
  dataStoreFactory = new FileDataStoreFactory(DATA_STORE_FILE);
  GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
      jsonFactory, new InputStreamReader(
          Doubleclicksearch.class.getResourceAsStream("/client_secrets.json")));
  GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
      transport, jsonFactory, clientSecrets, Arrays.asList(SCOPES))
          .setDataStoreFactory(dataStoreFactory)
          .setAccessType("offline")
          .build();
  return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}

.NET

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;

using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using api = Google.Apis.Doubleclicksearch.v2;

/// <summary>
/// Creates a Doubleclicksearch API service with static credentials.
/// </summary>
/// <param name="clientId">API project client ID.<param>
/// <param name="clientSecret">API project client secret.<param>
/// <param name="refreshToken">Refresh token generated for installed applications.<param>
private static api.DoubleclicksearchService CreateService(
    String clientId,
    String clientSecret,
    String refreshToken)
{
    var token = new Google.Apis.Auth.OAuth2.Responses.TokenResponse
    {
        RefreshToken = refreshToken,
    };
    var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
        new GoogleAuthorizationCodeFlow.Initializer
        {
            ClientSecrets = new ClientSecrets
            {
                ClientId = clientId,
                ClientSecret = clientSecret,
            },
         }), "user", token);

    return new api.DoubleclicksearchService(
        new Google.Apis.Services.BaseClientService.Initializer
        {
            HttpClientInitializer = credentials,
            ApplicationName = "Sample DS API client",
        });
}

Python

import argparse
import httplib2
from apiclient.discovery import build
from oauth2client import GOOGLE_TOKEN_URI
from oauth2client.client import OAuth2Credentials, HttpAccessTokenRefreshError


def create_credentials(client_id, client_secret, refresh_token):
  """Create Google OAuth2 credentials.

  Args:
    client_id: Client id of a Google Cloud console project.
    client_secret: Client secret of a Google Cloud console project.
    refresh_token: A refresh token authorizing the Google Cloud console project
      to access the DS data of some Google user.

  Returns:
    OAuth2Credentials
  """
  return OAuth2Credentials(access_token=None,
                           client_id=client_id,
                           client_secret=client_secret,
                           refresh_token=refresh_token,
                           token_expiry=None,
                           token_uri=GOOGLE_TOKEN_URI,
                           user_agent=None)


def get_service(credentials):
  """Set up a new Doubleclicksearch service.

  Args:
    credentials: An OAuth2Credentials generated with create_credentials, or
    flows in the oatuh2client.client package.
  Returns:
    An authorized Doubleclicksearch serivce.
  """
  # Use the authorize() function of OAuth2Credentials to apply necessary credential
  # headers to all requests.
  http = credentials.authorize(http = httplib2.Http())

  # Construct the service object for the interacting with the Search Ads 360 API.
  service = build('doubleclicksearch', 'v2', http=http)
  return service


if __name__ == '__main__':
  parser = argparse.ArgumentParser(description='Sample DS API code.')
  parser.add_argument('--client_id', dest='c_id', action='store',
                      help=('Specifies the DS API client_id. Looks like: '
                            '1234567890.apps.googleusercontent.com'),
                      required=True)
  parser.add_argument('--client_secret', dest='secret', action='store',
                      help=('Specifies the DS API client_secret. Looks like: '
                            '1ab2CDEfghigKlM3OPzyx2Q'),
                      required=True)
  parser.add_argument('--refresh_token', dest='token', action='store',
                      help=('Specifies the DS API refresh_token. Looks like: '
                            '4/abC1ddW3WJURhF7DUj-6FHq8kkE'),
                      required=True)
  args = parser.parse_args()

  creds = create_credentials(args.c_id, args.secret, args.token)
  try:
    service = get_service(creds)
    print 'Successfully loaded credentials.'
  except HttpAccessTokenRefreshError:
    print ('Error: Unable to get credentials. Please ensure that the '
           'credentials are correct. '
           'https://developers.google.com/search-ads/v2/authorizing'
          )