Định cấu hình ứng dụng

Khi tạo thông tin xác thực OAuth 2.0thư viện ứng dụng , bạn đã sẵn sàng bắt đầu sử dụng chiến dịch Hiển thị API Video 360. Tìm hiểu cách uỷ quyền, định cấu hình ứng dụng và đưa ra yêu cầu đầu tiên bằng cách hãy làm theo hướng dẫn bắt đầu nhanh bên dưới.

Java

  1. Nhập các thư viện cần thiết.

    import static java.nio.charset.StandardCharsets.UTF_8;
    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.util.Utils;
    import com.google.api.services.displayvideo.v3.DisplayVideo;
    import com.google.api.services.displayvideo.v3.DisplayVideo.Advertisers;
    import com.google.api.services.displayvideo.v3.model.Advertiser;
    import com.google.api.services.displayvideo.v3.model.ListAdvertisersResponse;
    import java.io.Reader;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    
  2. Tải tệp bí mật ứng dụng khách và tạo thông tin xác thực uỷ quyền.

    Vào lần đầu tiên thực hiện bước này, bạn sẽ được yêu cầu chấp nhận một khoản uỷ quyền trên trình duyệt. Trước khi chấp nhận, hãy đảm bảo bạn đã đăng nhập bằng Tài khoản Google có quyền truy cập vào Mạng Hiển thị và Video 360. Ứng dụng của bạn sẽ được cấp phép để truy cập dữ liệu thay mặt cho bất kỳ tài khoản nào hiện đang đăng nhập. Xem Uỷ quyền Hướng dẫn về yêu cầu để biết thêm chi tiết về chiến dịch Hiển thị & Các quyền của người dùng đối với Video 360.

    // Read client secrets file.
    GoogleClientSecrets clientSecrets;
    try (Reader reader = Files.newBufferedReader(Paths.get(path-to-client-secrets-file), UTF_8)) {
      clientSecrets = GoogleClientSecrets.load(Utils.getDefaultJsonFactory(), reader);
    }
    
    // Generate authorization credentials.
    // Set up the authorization code flow.
    GoogleAuthorizationCodeFlow flow =
        new GoogleAuthorizationCodeFlow.Builder(
            Utils.getDefaultTransport(),
            Utils.getDefaultJsonFactory(),
            clientSecrets,
            oauth-scopes)
        .build();
    
    Credential credential =
        new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    
  3. Tạo một ứng dụng API được uỷ quyền.

    // Create authorized API client.
    DisplayVideo service =
        new DisplayVideo.Builder(credential.getTransport(), credential.getJsonFactory(), credential)
            .setApplicationName("displayvideo-java-installed-app-sample")
            .build();
    
  4. Thực hiện thao tác.

    // Perform an operation.
    // Retrieve and print the first ten advertisers under a partner.
    ListAdvertisersResponse response =
        service
            .advertisers()
            .list()
            .setPartnerId(partner-id)
            .setPageSize(10)
            .execute();
    if (response.getAdvertisers().size() > 0) {
      for (int i = 0; i < response.getAdvertisers().size(); i++) {
        System.out.printf(
            "ID: %s Display Name: %s%n",
            response.getAdvertisers().get(i).getAdvertiserId(),
            response.getAdvertisers().get(i).getDisplayName());
      }
    } else {
      System.out.print("No advertisers found.");
    }
    

Python

  1. Nhập các thư viện cần thiết.

    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient import discovery
    
  2. Tải tệp bí mật ứng dụng khách và tạo thông tin xác thực uỷ quyền.

    Vào lần đầu tiên thực hiện bước này, bạn sẽ được yêu cầu chấp nhận một khoản uỷ quyền trên trình duyệt. Trước khi chấp nhận, hãy đảm bảo bạn đã đăng nhập bằng Tài khoản Google có quyền truy cập vào Mạng Hiển thị và Video 360. Ứng dụng của bạn sẽ được cấp phép để truy cập dữ liệu thay mặt cho bất kỳ tài khoản nào hiện đang đăng nhập. Xem Uỷ quyền Hướng dẫn về yêu cầu để biết thêm chi tiết về chiến dịch Hiển thị & Các quyền của người dùng đối với Video 360.

    # Set up a flow object to create the credentials using the
    # client secrets file and OAuth scopes.
    credentials = InstalledAppFlow.from_client_secrets_file(
        path-to-client-secrets-file, oauth-scopes).run_local_server()
    
  3. Tạo một ứng dụng API được uỷ quyền.

    # Build the discovery document URL.
    discovery_url = f'https://displayvideo.googleapis.com/$discovery/rest?version=v3'
    
    # Build the API service.
    service = discovery.build(
        'displayvideo',
        'v3',
        discoveryServiceUrl=discovery_url,
        credentials=credentials)
    
  4. Thực hiện thao tác.

    # Build advertisers.list request.
    request = service.advertisers().list(
        partnerId=partner-id, pageSize='10')
    
    # Execute request.
    response = request.execute()
    
    # Print response.
    if len(response['advertisers']) > 0:
      for advertiser in response['advertisers']:
        print(f'ID: {advertiser["advertiserId"]} Display Name: {advertiser["displayName"]}')
    else:
      print('No advertisers found.')
    

PHP

Mẫu này giả định rằng bạn đang chạy PHP bằng máy chủ web tích hợp và đã định cấu hình thông tin xác thực của mình để chuyển hướng tới trang web có liên quan. Cho ví dụ: mã này, trong tệp index.php, có thể được chạy bằng cách sử dụng lệnh sau đã định cấu hình lệnh và thông tin đăng nhập để chuyển hướng đến http://localhost:8000 sau xác thực:

php -S localhost:8000 -t ./

  1. Tải và cài đặt Ứng dụng PHP của Google API.

    Phương thức ưu tiên là sử dụng Composer:

    composer require google/apiclient:^2.15.1 google/apiclient-services:=0.332.0
    

    Sau khi cài đặt, hãy nhớ bao gồm trình tải tự động:

    require_once '/path/to/your-project/vendor/autoload.php';
    
  2. Tạo đối tượng Google_Client.

    $client = new Google_Client();
    
  3. Thiết lập ứng dụng, chuyển hướng đến URL xác thực nếu cần và truy xuất mã truy cập.

    Vào lần đầu tiên thực hiện bước này, bạn sẽ được yêu cầu chấp nhận một khoản uỷ quyền trên trình duyệt. Trước khi chấp nhận, hãy đảm bảo bạn đã đăng nhập bằng Tài khoản Google có quyền truy cập vào Mạng Hiển thị và Video 360. Ứng dụng của bạn sẽ được cấp phép để truy cập dữ liệu thay mặt cho bất kỳ tài khoản nào hiện đang đăng nhập. Xem Uỷ quyền Hướng dẫn về yêu cầu để biết thêm chi tiết về chiến dịch Hiển thị & Các quyền của người dùng đối với Video 360.

    // Set up the client.
    $client->setApplicationName('DV360 API PHP Samples');
    $client->addScope(oauth-scope);
    $client->setAccessType('offline');
    $client->setAuthConfigFile(path-to-client-secrets-file);
    
    // If the code is passed, authenticate. If not, redirect to authentication page.
    if (isset($_GET['code'])) {
      $client->authenticate($_GET['code']);
    } else {
      $authUrl = $client->createAuthUrl();
      header('Location: ' . $authUrl);
    }
    
    // Exchange authorization code for an access token.
    $accessToken = $client->getAccessToken();
    $client->setAccessToken($accessToken);
    
  4. Xây dựng ứng dụng cho chiến dịch Hiển thị và Dịch vụ API Video 360.

    $service = new Google_Service_DisplayVideo($client);
    
  5. Thực hiện thao tác.

    // Configure params for the advertisers.list request.
    $optParams = array('pageSize' => 10, 'partnerId' => partner-id);
    
    // Execute the request.
    $result = $service->advertisers->listAdvertisers($optParams);
    
    // Print the retrieved advertisers.
    if (!empty($result->getAdvertisers())) {
      print('<pre>');
      foreach ($result->getAdvertisers() as $advertiser) {
        printf('<p>ID: %s, Display Name: %s</p>', $advertiser->advertiserId, $advertiser->displayName);
      }
      print('</pre>');
    } else {
      print '<p>No advertisers found.</p>';
    }