我一直在处理这些文档,到目前为止,我已设法使用Google Developers Console的授权凭据和此处的代码段将新事件添加到我的日历中
https://developers.google.com/google-apps/calendar/v3/reference/events/insert
<?php
$client = new Google_Client();
// OAuth2 client ID and secret can be found in the Google Developers Console.
$client->setClientId('xxxxx.apps.googleusercontent.com');
$client->setClientSecret(xxxxx);
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->addScope('https://www.googleapis.com/auth/calendar');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$service = new Google_Service_Calendar($client);
$authUrl = $client->createAuthUrl();
//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
//$authCode = trim(fgets(STDIN));
$authCode = '';
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
$event = new Google_Service_Calendar_Event();
$event->setSummary('Appointment);
$event->setLocation('Somewhere');
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime('2014-12-22T10:00:00.000-07:00');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime('2014-12-22T10:00:00.000-08:00');
$event->setEnd($end);
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setEmail(xxx@gmail.com');
// ...
$attendees = array($attendee1);
$event->attendees = $attendees;
$createdEvent = $service->events->insert('xxxxx@group.calendar.google.com', $event);
echo $createdEvent->getId();
?>
这很有效,但我每次都需要获得一个新的OAuth2.0访问令牌。 我想要做的是使用刷新令牌自动生成一个新的访问令牌,所以我可以从我的网页添加新的gcal事件
如果我运行以下代码,我可以使用刷新令牌
成功重新生成新的访问令牌<?php
function getAccessToken(){
$tokenURL = 'https://accounts.google.com/o/oauth2/token';
$postData = array(
'client_secret'=>'xxxxx',
'grant_type'=>'refresh_token',
'refresh_token'=>'xxxxx',
'client_id'=>'xxxx.apps.googleusercontent.com'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $tokenURL);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//need this otherwise you get an ssl error
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$tokenReturn = curl_exec($ch);
$token = json_decode($tokenReturn);
//var_dump($tokenReturn);
$accessToken = $token->access_token;
return ($accessToken);
}
?>
这总是给我一个新的访问令牌,但是如果我把这个令牌放到页面顶部的代码中,我就会收到错误。 Google_Auth_Exception'并显示消息'OAuth 2.0访问令牌已过期,并且刷新令牌不可用
我已经尝试仅返回访问令牌,返回值,json解码返回值,但我总是得到某种错误
任何人都可以指出我正确的方向,或者是否允许我在我的日历中插入新事件的代码段?
由于
感谢SGC链接
我认为最初失败的原因是,使用刷新令牌创建新访问令牌的功能只返回3个值,'access_token'本身,'token_type'和'expires_in'。
调用setAccessToken()时需要的是'refresh_token'和'created'值。
我已经有了刷新令牌,但我不清楚“已创建”,创建刷新令牌或访问令牌时是否会更改?