php - 了解我的代码,令牌来自哪里?
问题描述
我需要使用 api 将事件添加到谷歌日历,在我的本地主机上我让它工作了,但是我不记得令牌来自哪里,你们能提醒我吗?toke.json 文件
<?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);
?>
解决方案
当您的代码第一次运行时,系统会要求用户同意您的应用程序访问他们的数据。如果用户同意,那么您的代码会将访问令牌和刷新令牌存储在名为 token.json 的文件中。
下次代码运行时,它将检查 isAccessTokenExpired 是否是,它将使用存储在 token.json 中的刷新令牌来请求新的访问令牌并授予您对用户数据的访问权限。
您的代码编写方式仅适用于单个用户,因为您仅存储到单个 token.json 文件。
推荐阅读
- javascript - 是否可以在自定义 HTML 表单上记录有关“来源”、“媒体”和“活动”的潜在客户分析?
- amazon-s3 - 是否可以使用 Spring Cloud for AWS 按前缀过滤存储桶?
- java - 单击列表视图中自定义单元格中按钮的侦听器
- bash - 将 Beeline 生成的表格重定向到没有网格的文本文件(Shell 脚本)
- python - 如何从字符串列表中删除双引号?
- sql-server - 无法通过 Web API .NET Core 连接到 SQL Server Docker 容器
- javascript - 如何遍历由休息服务返回的javascript中的json数组?
- mysql - MySql:更新几何点
- python - 如何调用存储在我的网络上的不同 python 脚本?
- c - 运行动态测试时发生错误:“运行动态测试:error::Error: Exit code with code: 1 and signal: null”