Home > Mobile >  Google calendar api configuration
Google calendar api configuration

Time:11-18

I'm trying to make a call to the Google Calendar api, but I can't figure out how to configure it. The documentation on Google is very confusing (it says to add api key to params, but now they're no longer supported???). I have the Oauth creds, but have no idea where to put them. Anyone have any experience with this?

<?php 
/**
 * Template Name: API Test Page
 * 
 */


get_header();



$url = 'https://www.googleapis.com/calendar/v3/calendars/[calendarID]';


$response = wp_remote_get( esc_url_raw( $url ) );

$api_response = json_decode( wp_remote_retrieve_body( $response ), true );

print_r($api_response);


get_footer();

CodePudding user response:

you should consider following the Quickstart for php This example will show you how to work with Authorization from the point of an installed application to start.

require __DIR__ . '/vendor/autoload.php';

if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Google Calendar API PHP Quickstart');
    $client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));

            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
}


// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Calendar($client);

// Print the next 10 events on the user's calendar.
$calendarId = 'primary';
$optParams = array(
  'maxResults' => 10,
  'orderBy' => 'startTime',
  'singleEvents' => true,
  'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
$events = $results->getItems();

if (empty($events)) {
    print "No upcoming events found.\n";
} else {
    print "Upcoming events:\n";
    foreach ($events as $event) {
        $start = $event->start->dateTime;
        if (empty($start)) {
            $start = $event->start->date;
        }
        printf("%s (%s)\n", $event->getSummary(), $start);
    }
}

CodePudding user response:

You don't seem to be setting any of the relevant headers and don't have the api key defined in the url.

GET https://www.googleapis.com/calendar/v3/calendars/[CALENDARID]?key=[YOUR_API_KEY] HTTP/1.1

Authorization: Bearer [YOUR_ACCESS_TOKEN]
Accept: application/json

As per Google Docs.

To do this with wp_remote_get you need to set the arguments for it.

So something like this :

$args = array(
      'headers' => array(
        'Authorization' => 'Bearer [YOUR_ACCESS_TOKEN]',
        'Accept' => 'pplication/json'
      );

Which is the second parameter for the wp_remote_get function.

wp_remote_get( string $url, array $args = array() )

wp_remote_get Docs

  • Related