내 코드가 약간 길어서 최적화 할 수 있습니까? 1 시간 후에 내 토큰이 새로 고쳐지지 않을지 확실하지 않습니다. x 인증을 요청하지 않고 Google 캘린더 API를 사용할 수 있습니까?
<?php
public function calendarAction()
{
define('APPLICATION_NAME', 'RK THE BEST');
define('CREDENTIALS_PATH', __DIR__ . '/credentials/calendar-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
define('SCOPES', implode(' ', array(
\Google_Service_Calendar::CALENDAR)
));
/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
function getClient()
{
$client = new \Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
$client->setApprovalPrompt ("force");
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if(file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
echo "WIN :)";
if (isset($_GET['code'])){
$credentials = $client->authenticate($_GET['code']);
$code = trim($_GET['code']);
$authCode = $code;
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
// save refresh token to some variable
$refreshTokenSaved = $client->getRefreshToken();
// update access token
$client->fetchAccessTokenWithRefreshToken($refreshTokenSaved);
// pass access token to some variable
$accessTokenUpdated = $client->getAccessToken();
// append refresh token
$accessTokenUpdated['refresh_token'] = $refreshTokenSaved;
// save to file
file_put_contents($credentialsPath, json_encode($accessTokenUpdated));
}
// Service creation
$service = new \Google_Service_Calendar($client);
$calendarList = $service->calendarList->listCalendarList();
$googleApievent = new \Google_Service_Calendar_Event();
$googleApievent->setSummary('google api');
$googleApievent->setLocation('google api');
$start = new \Google_Service_Calendar_EventDateTime();
$start->setDate('2017-02-20');
$start->setTimeZone('Europe/London');
$start->setDate('2017-02-20');
$end = new \Google_Service_Calendar_EventDateTime();
$end->setDate('2017-02-17');
$end->setTimeZone('Europe/London');
$end->setDate('2017-02-17');
$googleApievent->setStart($start);
$googleApievent->setEnd($end);
$calendarId = "primary";
$createdEvent = $service->events->insert($calendarId, $googleApievent);
echo $createdEvent->getId();
while (true) {
foreach ($calendarList->getItems() as $calendarListEntry) {
echo $calendarListEntry->getSummary() . "\n";
// get events
$events = $service->events->listEvents($calendarListEntry->id);
foreach ($events->getItems() as $event) {
echo "<br/>" . $event->getSummary() . "";
echo " ID : " . $event->getId() . "<br/>";
echo "***********************" . "<br/> ";
}
}
$pageToken = $calendarList->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$calendarList = $service->calendarList->listCalendarList($optParams);
} else {
break;
}
}
}
}else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n<a href='%s' > ici </a>\n", $authUrl);
print 'Enter verification code: ';
/****TOKEN***********************/
if(!empty($_GET['code'])) {
$code = trim($_GET['code']);
$authCode = $code;
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
// Store the credentials to disk.
if (!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
$token = $client->getAccessToken();
if($client->isAccessTokenExpired()){ // if token expired
// refresh the token
$test=$client->refreshToken($token);
}
$accessToken = $client->getAccessToken();
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
$client->authenticate($code);
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
print "LogOut";
$service = new \Google_Service_Calendar($client);
$calendarList = $service->calendarList->listCalendarList();
$googleApievent = new \Google_Service_Calendar_Event();
$googleApievent->setSummary('wake up');
$googleApievent->setLocation('wake up');
$start = new \Google_Service_Calendar_EventDateTime();
$start->setDate('2017-02-16');
$start->setTimeZone('Europe/London');
$start->setDate('2017-02-16');
$end = new \Google_Service_Calendar_EventDateTime();
$end->setDate('2017-02-17');
$end->setTimeZone('Europe/London');
$end->setDate('2017-02-17');
$googleApievent->setStart($start);
$googleApievent->setEnd($end);
$calendarId = "primary";
$createdEvent = $service->events->insert($calendarId, $googleApievent);
echo $createdEvent->getId();
while (true) {
foreach ($calendarList->getItems() as $calendarListEntry) {
echo $calendarListEntry->getSummary() . "\n";
// get events
$events = $service->events->listEvents($calendarListEntry->id);
foreach ($events->getItems() as $event) {
echo "<br/>" . $event->getSummary() . "";
echo " ID : " . $event->getId() . "<br/>";
echo "***********************" . "<br/> ";
}
}
$pageToken = $calendarList->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$calendarList = $service->calendarList->listCalendarList($optParams);
} else {
break;
}
}
}
}
return $client;
}
}
}
오류가 발생하거나 출력 되나요? – MrDarkLynx
예 2 개의 오류가 있습니다. 치명적인 오류 : '/var/www/html/mysite/www/vendors/google-api-php-client/src/Google/Http/REST.php에'의 'Google_Service_Exception'예외가 캐치되지 않았습니다. 줄 118 && Google_Service_Exception : { "오류": { "오류": [{ "도메인": "글로벌", "이유": "필수", "메시지": "로그인 필요", "locationType": "헤더" "location": "Authorization"}], "code": 401, "message": "Login Required"}} – MasterSinge
이벤트를 삽입하려면 먼저 로그인/허가해야합니다. – MrDarkLynx