אחרי יצירת פרטי הכניסה ל-OAuth 2.0 והתקנת ספריית לקוח, אתם מוכנים להתחיל להשתמש ב-Display & Video 360 API. במדריך למתחילים שבהמשך מוסבר איך להעניק הרשאה ללקוח, להגדיר אותו ולשלוח את הבקשה הראשונה.
Java
מייבאים את הספריות הנחוצות.
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.v4.DisplayVideo; import com.google.api.services.displayvideo.v4.DisplayVideo.Advertisers; import com.google.api.services.displayvideo.v4.model.Advertiser; import com.google.api.services.displayvideo.v4.model.ListAdvertisersResponse; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Paths;
טעינה של קובץ הסודות של הלקוח ויצירת פרטי כניסה להרשאה
בפעם הראשונה שתבצעו את השלב הזה, תתבקשו לאשר בקשה להרשאה בדפדפן. לפני שמאשרים, חשוב לוודא שנכנסתם לחשבון Google שיש לו גישה ל-Display & Video 360. לאפליקציה תהיה הרשאה לגשת לנתונים מטעם החשבון שאליו אתם מחוברים כרגע. למידע נוסף על הרשאות משתמשים ב-Display & 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");
יוצרים לקוח API מורשה.
// Create authorized API client. DisplayVideo service = new DisplayVideo.Builder(credential.getTransport(), credential.getJsonFactory(), credential) .setApplicationName("displayvideo-java-installed-app-sample") .build();
ביצוע פעולה
// 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
מייבאים את הספריות הנחוצות.
from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient import discovery
טעינה של קובץ הסודות של הלקוח ויצירת פרטי כניסה להרשאה
בפעם הראשונה שתבצעו את השלב הזה, תתבקשו לאשר בקשה להרשאה בדפדפן. לפני שמאשרים, חשוב לוודא שנכנסתם לחשבון Google שיש לו גישה ל-Display & Video 360. לאפליקציה תהיה הרשאה לגשת לנתונים מטעם החשבון שאליו אתם מחוברים כרגע. למידע נוסף על הרשאות משתמשים ב-Display & 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()
יוצרים לקוח API מורשה.
# Build the discovery document URL. discovery_url = f'https://displayvideo.googleapis.com/$discovery/rest?version=v4' # Build the API service. service = discovery.build( 'displayvideo', 'v4', discoveryServiceUrl=discovery_url, credentials=credentials)
ביצוע פעולה
# 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
בדוגמה הזו, ההנחה היא שאתם מריצים את ה-PHP עם שרת אינטרנט מובנה והגדרתם את פרטי הכניסה להפניה אוטומטית לדף האינטרנט הרלוונטי. לדוגמה, אפשר להריץ את הקוד הזה בקובץ index.php
באמצעות הפקודה הבאה ופרטי הכניסה שמוגדרים להפניה אוטומטית אל http://localhost:8000
אחרי האימות:
php -S localhost:8000 -t ./
מורידים ומתקינים את לקוח Google API ל-PHP.
השיטה המועדפת היא להשתמש ב-Composer:
composer require google/apiclient:^2.18.2 google/apiclient-services:=0.396.0
אחרי ההתקנה, חשוב לכלול את הטעינה האוטומטית:
require_once '/path/to/your-project/vendor/autoload.php';
יוצרים אובייקט Google_Client.
$client = new Google_Client();
מגדירים את הלקוח, מפנים לכתובת ה-URL לאימות אם צריך ומאחזרים אסימון גישה.
בפעם הראשונה שתבצעו את השלב הזה, תתבקשו לאשר בקשה להרשאה בדפדפן. לפני שמאשרים, חשוב לוודא שנכנסתם לחשבון Google שיש לו גישה ל-Display & Video 360. לאפליקציה תהיה הרשאה לגשת לנתונים מטעם החשבון שאליו אתם מחוברים כרגע. למידע נוסף על הרשאות משתמשים ב-Display & 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);
יצירת לקוח לשירות Display & Video 360 API
$service = new Google_Service_DisplayVideo($client);
ביצוע פעולה
// 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>'; }