简体   繁体   中英

Understanding my code, Where are the tokens coming from?

i need to add events to the google calendar with the api, on my localhost i made it work, however i cant remember where the token comes from, can you guys remind me this? the toke.json file

<?php

error_reporting(E_ALL);

ini_set('display_errors', 1);

// If you've used composer to include the library
require '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('Calendar API Test');

    $client->setScopes( ['https://www.googleapis.com/auth/calendar'] );
    // $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.
    // 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: ';

            // Check Param on redirected URL, for ?code=#############  
            // you have to copy only ?code= $_GET parms data and paste in console
            $authCode = trim(fgets(STDIN)); // Get code after Authentication

            // 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;
}

$client = getClient();


$accessToken = $client->getAccessToken();

$service = new Google_Service_Calendar($client);

$summary = $_POST['summary'];
$description = $_POST['description'];
$fecha_inicio = $_POST['fecha_inicio'];
$hora_inicio = $_POST['hora_inicio'];
$fecha_fin = $_POST['fecha_fin'];

$h_inicio = explode(" ",$hora_inicio); 
$hora = $h_inicio[0].":00";
$minutos = "00:30:00";

$secs = strtotime($minutos)-strtotime("00:00:00");
$result = date("H:i:s",strtotime($hora)+$secs);


$inicio = $fecha_inicio."T".$hora_inicio;
$fin = $fecha_fin."T".$result;

$attendee = $_POST['attendee'];

$_info = array(
  'summary' => $summary,
  'location' => 'address',
  'description' => $description,
  'start' => array(
    'dateTime' => $inicio,
    'timeZone' => 'America/Bogota',
  ),
  'end' => array(
    'dateTime' => $fin,
    'timeZone' => 'America/Bogota',
  ),
  'attendees' => array(
    array('email' => $attendee)
  ),
  'reminders' => array(
    'useDefault' => FALSE,
    'overrides' => array(
      array('method' => 'email', 'minutes' => 24 * 60),
      array('method' => 'popup', 'minutes' => 10),
    ),
  ),
);

//die(var_dump($_info));

$event = new Google_Service_Calendar_Event($_info);

$opts = array('sendNotifications' => true, 'conferenceDataVersion' => true); // send Notification immediately by Mail or Stop Hangout Call Link

$event = $service->events->insert( 'primary', $event, $opts ); 
die(var_dump($event));
printf('Event created: %s\n', $event->htmlLink);

?>

When your code runs the first time the user will be asked to consent to your application accessing their data. If the user consents then your code is storing the access token and refresh token in a file called token.json.

The next time the code runs it will check isAccessTokenExpired if it is it will use the refresh token stored in token.json to request a new access token and grant you access to the users data.

The way your code is written this will only be working for a single user as you are only storing to a single token.json file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM