Hizmet hesabı kullan

Hizmet hesabı, bir uygulama tarafından kullanılabilen Google Hesabı türüdür. Google API'lerine OAuth 2.0 aracılığıyla programatik olarak erişmek için. Bunu gerektirmez yalnızca uygulamanızın sizin tarafından otomatik olarak çalıştırabileceği bir anahtar dosyası erişim.

Hizmet hesapları hakkında daha fazla bilgi edinmeden önce daha basit ve OAuth 2.0 yüklü uygulama akışı şiddetle önerilir. Bu sırada Bu akış, uygulamanızı yetkilendirmek için manuel kullanıcı etkileşimi gerektirir. Bu Bu adım yalnızca bir kez yapılmalıdır ve üretim ortamınızda gerekmez. Bu akış tarafından oluşturulan yenileme jetonlarının süresi hiçbir zaman dolmaz, önbelleğe alınabilir ve farklı ortamlara dağıtılır ve aşağıdaki alanlarda erişim jetonları oluşturmak için kullanılır: en az 14 gün sürer.

Okumaya devam ediyor musunuz? Tamam, hizmet hesabını aşağıdakilerden birinde kullanabilirsiniz yöntemler:

  • Görüntülü Reklam Ağı ve hizmet hesabı. Bu senaryoda, hizmet hesabınız normal bir şekilde ve gerekli tüm ortak ve reklamverenlere erişmenize olanak tanır. temel hazırlık yapılmış olur. Hizmeti kullanmak için tercih edilen yöntem budur Görüntülü Reklam Ağı ve Video 360.
  • Bir veya iki taraf adına istekte bulunmak için alan genelinde yetkiyi diğer Görüntülü Reklam Ağı ve G Suite kapsamındaki hesaplara bağlı Video 360 kullanıcıları alan. Bu durumda, hedef alana yönetici erişiminiz olmalıdır. G Suite ve/veya alan yapılandırmasıyla ilgili yardım için şu sayfaya göz atın: G Suite destek sayfası.

Ön koşullar

Bir Display &Video 360 ile ilişkilendirilmiş hizmet hesabı kullanmak Video 360 kullanıcısı, DV360 kullanıcısı sekmesini ziyaret edin. Alan genelinde yetkiyi kullanmak için Delegation (Yetki) sekmesini seçin.

DV360 kullanıcısı

Bunun için Display &Video 360'a Hizmet hesabınıza bağlı Video 360 kullanıcısı.

Yetki

  1. Kayıtlı bir alana yönetici erişiminizin olması gerekir. G Suite
  2. En az bir Görüntülü Reklam Ağı ve Hesaplara bağlı Video 360 kullanıcıları (G Suite kayıtlı alanınızın altında) Şu hesaptaki hesaplara bağlı kullanıcılar: diğer alan adları (örneğin, gmail.com) kullanılamaz.

Hizmet hesabını yapılandırma ve kullanma

DV360 kullanıcısı

  1. Şurada hizmet hesabı anahtarı oluştur: Google API Konsolu.

  2. Ekranı ilişkilendirin ve Hizmet hesabı e-posta adresine sahip Video 360 kullanıcısı önceki adımda elde edilen, Görüntülü Reklam Ağı'nda ve Video 360 Yardım Merkezi makalesine göz atın.

  3. Sunucudan sunucuya OAuth 2.0 akışını uygulamanızda kullanmak için yeni oluşturulan hizmet hesabınıza eklenir. Daha fazla bilgi için examples bölümüne bakın.

Yetki

  1. Şurada hizmet hesabı anahtarı oluştur: Google API Konsolu.

  2. Bu hizmet hesabına alan genelinde yetki verin: alanınızdaki kullanıcıların kimliğine bürünmesine izin verir. İstendiğinde şu API kapsamları:

    Kapsam Anlamı
    https://www.googleapis.com/auth/display-video Okuma/yazma erişimi.
    https://www.googleapis.com/auth/display-video-user-management users hizmeti için okuma/yazma erişimi. Yalnızca hizmet hesabı kullanıcıları tarafından kullanılabilir.

  3. Sunucudan sunucuya OAuth 2.0 akışını uygulamanızda kullanmak için yeni oluşturulan hizmet hesabınıza eklenir. Daha fazla bilgi için examples bölümüne bakın. Bunun için bir hesap tarafından kullanılan bir alan (hizmetinizin ait olduğu alan adına ait olmalıdır) hesabına alan genelinde yetki verildi.

G Suite ve / veya alan yapılandırmasıyla ilgili yardım için şu sayfaya göz atın: G Suite destek sayfası.

Örnekler

Java

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.services.displayvideo.v3.DisplayVideo;
import com.google.api.services.displayvideo.v3.DisplayVideoScopes;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import java.io.FileInputStream;

/**
 * This example demonstrates how to authenticate using a service account.
 */
public class AuthenticateUsingServiceAccount {
  // Path to a JSON file containing service account credentials for this application. This file can
  // be downloaded from the Credentials tab on the Google API Console.
  private static final String PATH_TO_JSON_FILE = "ENTER_PATH_TO_CLIENT_SECRETS_HERE";

  /**
   * An optional Google account email to impersonate. Only applicable to service accounts which have
   * enabled domain-wide delegation and wish to make API requests on behalf of an account within
   * their domain. Setting this field will not allow you to impersonate a user from a domain you
   * don't own (e.g., gmail.com).
   */
  private static final String EMAIL_TO_IMPERSONATE = "";

  // The OAuth 2.0 scopes to request.
  private static final ImmutableSet OAUTH_SCOPES =
      ImmutableSet.copyOf(DisplayVideoScopes.all());

  private static Credential getServiceAccountCredential(
      String pathToJsonFile, String emailToImpersonate) throws Exception {
    // Generate a credential object from the specified JSON file.
    GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(pathToJsonFile));

    // Update the credential object with appropriate scopes and impersonation info (if applicable).
    if (Strings.isNullOrEmpty(emailToImpersonate)) {
      credential = credential.createScoped(OAUTH_SCOPES);
    } else {
      credential =
          new GoogleCredential.Builder()
              .setTransport(credential.getTransport())
              .setJsonFactory(credential.getJsonFactory())
              .setServiceAccountId(credential.getServiceAccountId())
              .setServiceAccountPrivateKey(credential.getServiceAccountPrivateKey())
              .setServiceAccountScopes(OAUTH_SCOPES)
              // Set the email of the user you are impersonating (this can be yourself).
              .setServiceAccountUser(emailToImpersonate)
              .build();
    }

    return credential;
  }

  public static void main(String[] args) throws Exception {
    // Build service account credential.
    Credential credential = getServiceAccountCredential(PATH_TO_JSON_FILE, EMAIL_TO_IMPERSONATE);

    // Create a DisplayVideo service instance.
    //
    // Note: application name below should be replaced with a value that identifies your
    // application. Suggested format is "MyCompany-ProductName/Version.MinorVersion".
    DisplayVideo service =
        new DisplayVideo.Builder(credential.getTransport(), credential.getJsonFactory(), credential)
            .setApplicationName("displayvideo-java-service-acct-sample")
            .build();

    // Make API requests.
  }
}

Python

"""This example demonstrates how to authenticate using a service account.

An optional Google account email to impersonate may be specified as follows:
    authenticate_using_service_account.py <path_to_json_file> -i <email>

This optional flag only applies to service accounts which have domain-wide
delegation enabled and wish to make API requests on behalf of an account
within that domain. Using this flag will not allow you to impersonate a
user from a domain you don't own (e.g., gmail.com).
"""

import argparse
import sys

from googleapiclient import discovery
import httplib2
from oauth2client import client
from oauth2client import tools
from oauth2client.service_account import ServiceAccountCredentials

# Declare command-line flags.
argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument(
    'path_to_service_account_json_file',
    help='Path to the service account JSON file to use for authenticating.')
argparser.add_argument(
    '-i',
    '--impersonation_email',
    help='Google account email to impersonate.')

API_NAME = 'displayvideo'
API_VERSION = 'v3'
API_SCOPES = ['https://www.googleapis.com/auth/display-video']


def main(argv):
  # Retrieve command line arguments.
  parser = argparse.ArgumentParser(
      description=__doc__,
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=[tools.argparser, argparser])
  flags = parser.parse_args(argv[1:])

  # Authenticate using the supplied service account credentials
  http = authenticate_using_service_account(
      flags.path_to_service_account_json_file,
      flags.impersonation_email)

  # Build a service object for interacting with the API.
  service = discovery.build(API_NAME, API_VERSION, http=http)

  # Make API requests.

def authenticate_using_service_account(path_to_service_account_json_file,
                                       impersonation_email):
  """Authorizes an httplib2.Http instance using service account credentials."""
  # Load the service account credentials from the specified JSON keyfile.
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      path_to_service_account_json_file,
      scopes=API_SCOPES)

  # Configure impersonation (if applicable).
  if impersonation_email:
    credentials = credentials.create_delegated(impersonation_email)

  # Use the credentials to authorize an httplib2.Http instance.
  http = credentials.authorize(httplib2.Http())

  return http


if __name__ == '__main__':
  main(sys.argv)

PHP

/**
 * This example demonstrates how to authenticate using a service account.
 *
 * The optional flag email parameter only applies to service accounts which have
 * domain-wide delegation enabled and wish to make API requests on behalf of an
 * account within that domain. Using this flag will not allow you to impersonate
 * a user from a domain that you don't own (e.g., gmail.com).
 */
class AuthenticateUsingServiceAccount
{
    // The OAuth 2.0 scopes to request.
    private static $OAUTH_SCOPES = [Google_Service_DisplayVideo::DISPLAY_VIDEO];

    public function run($pathToJsonFile, $email = null)
    {
        // Create an authenticated client object.
        $client = $this->createAuthenticatedClient($pathToJsonFile, $email);

        // Create a Dfareporting service object.
        $service = new Google_Service_DisplayVideo($client);

        // Make API requests.
    }

    private function createAuthenticatedClient($pathToJsonFile, $email)
    {
        // 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->setApplicationName('PHP service account sample');
        $client->setScopes(self::$OAUTH_SCOPES);

        // Load the service account credentials.
        $client->setAuthConfig($pathToJsonFile);

        // Configure impersonation (if applicable).
        if (!is_null($email)) {
            $client->setSubject($email);
        }

        return $client;
    }
}