Как использовать Google_API для получения событий календаря? - PullRequest
0 голосов
/ 13 ноября 2018

Я пытаюсь использовать API Google через PHP для получения событий календаря.Моя среда

  • Windows: 10
  • PHP: 7.0
  • Apache: 2.4
  • Google API загружается с помощью команды: composer требуется google / apiclient:"^ 2.0"

Я использую следующее в качестве тестового кода (test2.php):

<html>
 <head>
 <title>PHP Test</title>
 </head>
 <body>
This is a line of text in test2.php
<?php
require_once 'C:\PHP\vendor\autoload.php';
$client = new Google_Client();

// $credentialsJson should contain the path to the json file downloaded from the API site
$credentialsJson = 'C:\Apache24\htdocs\credentials.json';
$credentials = $client->loadServiceAccountJson(
   $credentialJson,
   'https://www.googleapis.com/auth/calendar'
);

$client->setAssertionCredentials($credentials);

$service = new Google_Service_Calendar($client);

// $calendarId should contain the calendar id found on the settings page of the calendar
$calendarId = '*****myCalendarID*****';

$events = $service->events->listEvents($calendarId);
echo $events;
?>
</body>
</html>

Я помещаю файл test2.php в C: \ Apache24 \htdocs.
Когда я просматриваю: localhost / test2.php, браузер отображает:

This is a line of text in test2.php
Fatal error: Uncaught Error: Call to undefined method Google_Client::loadServiceAccountJson() in C:\Apache24\htdocs\test2.php:14 Stack trace: #0 {main} thrown in C:\Apache24\htdocs\test2.php on line 14

Почему бы не найти метод "loadServiceAccountJson"?Спасибо за просмотр.

1 Ответ

0 голосов
/ 13 ноября 2018

Я не уверен, какой учебник вы читаете.это код, который я использую.

ServiceAccount.php

require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    return getServiceAccountClient();
}
/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
 * Scopes will need to be changed depending upon the API's being accessed. 
 * array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function getServiceAccountClient() {
    try {   
        // Create and configure a new client object.        
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope([YOUR SCOPES HERE]);
        return $client;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

Примечание: служебная учетная запись, которую вы не используете, будет запрашивать данные из учетных записей службы Googleучетная запись календаря.если вы хотите, чтобы он имел доступ к вашему личному календарю, вам придется взять адрес электронной почты учетной записи службы и поделиться им с ним, как и любому другому пользователю.

...