Developer Apis and Code examples

Last updated on
15 June 2020

These are few examples how developers can get the accounts which we authenticated in the configuration part.  To use google api php client api function we mainly need a Google_Client object so that we can create the sevice objects or get the access token.  We will consider simple examples to fetch the required objects.

The api again differs depending on whether you are using the OAuth Client or Service Accounts

1) OAuth Clients: First we use basic example of getting Service Objects and fetching one calendar using it.

// Load the account
$google_api_client = \Drupal::entityTypeManager()->getStorage('google_api_client')->load(ACCOUNT_ID);

// Get the service.
$googleService = \Drupal::service('google_api_client.client');
// Apply the account to the service
$googleService->setGoogleApiClient($google_api_client);

// Try your API Operations.
try {
   // Fetch calendar object.
   $object = $googleService->getServiceObjects();
   // $object['calendar'] is a object of Google_Service_Calendar
   $calendar = $object['calendar']->calendars->get(CAL_ID);
}
  catch (Exception $e) {
  // ksm($e);
}

You may also fetch the Google Client as

// Load the account
$google_api_client = \Drupal::entityTypeManager()->getStorage('google_api_client')->load(ACCOUNT_ID);

// Get the service.
$googleService = \Drupal::service('google_api_client.client');
// Apply the account to the service
$googleService->setGoogleApiClient($google_api_client);

// Fetch Client
$client = $googleService->googleClient;

// Fetch Access Token
$access_token = $googleService->googleClient->getAccessToken();

// Here $googleService->googleClient is Google_Client object

2) Service Accounts: One basic example of getting user's info

$google_api_service_client = \Drupal::entityTypeManager()->getStorage('google_api_service_client')->load('SERVICE_ACCOUNT_ID');
// Get the service.
$googleService = \Drupal::service('google_api_service_client.client');
// Set the account.
$googleService->setGoogleApiClient($google_api_service_client);
// Get objects
$serviceClasses = $googleService->getServiceObjects();
$my_info = $serviceClasses['oauth2']->userinfo_v2_me->get();

OR

$google_api_service_client = \Drupal::entityTypeManager()->getStorage('google_api_service_client')->load('SERVICE_ACCOUNT_ID');
// Get the service.
$googleService = \Drupal::service('google_api_service_client.client');
// Set the account.
$googleService->setGoogleApiClient($google_api_service_client);
// Make objects
$oauth = new Google_Service_Oauth2($googleService->googleClient);
$my_info = $oauth->userinfo_v2_me->get();

These apis are basic examples and cover everything which is required, feel free to report issues and help us to improve the module.

Help improve this page

Page status: No known problems

You can: