this 페이지에서 다운로드 할 수 있습니다 .this page에는 Google+ 용이지만 원리는 같습니다.
처음으로 항상 인증이 필요합니다. 그 주위에 방법이 없습니다. 아래 예에서 access_token 및 refresh_token을 포함하여 인증 후 token
이 다시 전송됩니다. access_token은 3600 초 동안 만 유효하며 직접 액세스에 사용됩니다. access_token이 만료되면 401 오류가 발생하고 refresh_token (client_id, client_secret 및 올바른 grant_type과 함께)을 사용하여 새 access_token을 요청할 수 있습니다.
this page에 대한 자세한 내용은 아래 "새로 고침 토큰 사용"을 참조하십시오. 해당 페이지의 하단에 언급 된 번호를 요청하는 데 몇 가지 제한이 있습니다.
이것은 내가 마지막으로 내가 이것을 도와 준 몇 가지 테스트 코드입니다. 인증을 받고 쿠키에 token
을 저장하는 것만 보여줍니다. 만기 된 후 새 access_token을 요청하지 않습니다.
token
(데이터베이스에?)을 저장해야하고 401이 생기면 client_id, client_secret, grant_type 및 refresh_token으로 새 access_token을 요청해야합니다. 거기에 필요한 (재) 인증이 필요하지 않습니다.
<?php
error_reporting(E_ALL);
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_CalendarService.php';
session_start();
if ((isset($_SESSION)) && (!empty($_SESSION))) {
echo "There are cookies<br>";
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
}
$client = new Google_Client();
$client->setApplicationName("Google Calendar PHP Starter Application");
$client->setClientId('###');
$client->setClientSecret('###');
$client->setRedirectUri('http://###/add_calendar.php'); // <- registered web-page
//$client->setDeveloperKey('###'); // <- not always needed
$cal = new Google_CalendarService($client);
if (isset($_GET['logout'])) {
echo "<br><br><font size=+2>Logging out</font>";
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
echo "<br>I got a code from Google = ".$_GET['code']; // You won't see this if redirected later
$client->authenticate(); // $_GET['code']
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
// not strictly necessary to redirect but cleaner for the url in address-bar
echo "<br>I got the token = ".$_SESSION['token']; // <-- not needed to get here unless location uncommented
}
if (isset($_SESSION['token'])) {
echo "<br>Getting access";
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()){
echo "<hr><font size=+1>I have access to your calendar</font>";
$event = new Google_Event();
$event->setSummary('=== I ADDED THIS ===');
$event->setLocation('The Neighbourhood');
$start = new Google_EventDateTime();
$start->setDateTime('2013-11-29T10:00:00.000-05:00');
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDateTime('2013-11-29T10:25:00.000-05:00');
$event->setEnd($end);
$createdEvent = $cal->events->insert('###', $event); // <- ### = email of calendar
echo "<br><font size=+1>Event created</font>";
echo "<hr><br><font size=+1>Already connected</font> (No need to login)";
} else {
$authUrl = $client->createAuthUrl();
print "<hr><br><font size=+2><a href='$authUrl'>Connect Me!</a></font>";
}
$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
echo "<br><br><font size=+2><a href=$url?logout>Logout</a></font>";
?>
편집 :
당신이 지적했듯이 구글이 자사의 "서비스 된 계정은"가 초기 인증을하지 않으려면.
(나는 이것들에 대해 몰랐다.)
나는 키 파일을 얻은 후에 사용할 코드를 찾을 수있는 링크를 팠다. https://groups.google.com/forum/?fromgroups#!topic/google-api-php-client/IiwRBKZMZxw
Google OAuth 2.0 Service Account - Calendar API (PHP Client)
https://groups.google.com/forum/#!topic/google-api-php-client/B7KXVQvx1k8
Access Google calendar events from with service account: { "error" : "access_denied" }. No google apps
Edit Google calendar events from Google service account: 403
편집 # 2 : 예, 그것은 작업을 얻었다.
<?
error_reporting(E_ALL);
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_CalendarService.php';
session_start();
echo "Busy<br>";
const CLIENT_ID = 'xxxxxxxxxx.apps.googleusercontent.com';
const SERVICE_ACCOUNT_NAME = '[email protected]';
const KEY_FILE = 'xxxxxxxxxxxxxxxxxxx-privatekey.p12';
const CALENDAR_NAME = '[email protected]';
$client = new Google_Client();
$client->setApplicationName("mycal");
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
$key = file_get_contents(KEY_FILE);
$client->setClientId(CLIENT_ID);
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
array('https://www.google.com/calendar/feeds/'),
$key)
);
$client->setClientId(CLIENT_ID);
$service = new Google_CalendarService($client);
$event = new Google_Event();
$event->setSummary('=== I MADE THIS ===');
$event->setLocation('Somewhere else');
$start = new Google_EventDateTime();
$start->setDateTime('2013-11-30T10:00:00.000-02:00');
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDateTime('2013-11-30T10:25:00.000-02:00');
$event->setEnd($end);
$createdEvent = $service->events->insert(CALENDAR_NAME, $event);
echo "Done<br>";
?>
내가 https://cloud.google.com/console#/project에 "새 프로젝트"를 만드는 데 필요한 : (심지어 내 무료 Google 계정)
감사에서 작동하는 것 같군,하지만 refresh_token도를 사용하여 (1) 직원이 액세스를 허용해야하기 때문에이 질문을 해결하지 않습니다 최소한 처음 (2) refresh_token을 사용한 요청 수가 제한됩니다. 내가 필요한 것은 영구적 인 액세스 제한이 있고 직원에게 액세스를 허용 할 필요가없는 경우입니다. 그리고 Google Apps for Business에서 가능해야한다고 생각합니다. 그러나 나는 그것을 할 수있는 정보를 찾을 수 없습니다. – valieand
저는 "Apps for Business"에 익숙하지 않지만 직원이 처음 액세스를 허용하는 경우 시간 제한없이 ** ** 동일한 ** refresh_token **을 사용하여 ** 유지해야합니다. 직원이 토큰에 대한 액세스 권한을 취소 함). 제한은 refresh_token의 ** 숫자 **에 대한 것입니다 : '클라이언트/사용자 조합 당 하나의 제한, 모든 클라이언트에서 사용자 당 하나의 제한'입니다. access_token을 요청할 수있는 횟수는 제한이 없습니다. 따라서 ** refresh_token을 유지하고 새로운 refresh_tokens를 요청하지 마십시오. (** 당신이 ** refresh_tokens **을 계속 묻는다면 ** 오래된 것들이 무효가 될 수 있습니다.) (1/2) – Rik
(2/2) 나는 이것이 대부분의 앱 (예 : Android)이 작동하는 방식이라고 생각합니다 Google 서비스 인증. 웹을 통한 일회성 인증이며 그들이 가지고있는 refresh_token을 사용하여 access_tokens를 요청하기 때문에 만료되지 않습니다. – Rik