新しいアプリケーションで Google カレンダーの設定を始めました。Google 開発者に表示された認証コードをほぼそのままコピーしました (https://developers.google.com/google-apps/calendar/instantiate) ですが、次のエラーが引き続き発生します。
OAuth2 アクセス トークンの取得中にエラーが発生しました。メッセージ: 'invalid_grant'
私は現在Fork-CMS(http://www.fork-cms.com)、まだ新しい軽量 CMS です。google-api-php-client の config.php ファイルを正しく構成しました。(クライアント ID、クライアント シークレット、リダイレクト URI、開発キーなど) また、リダイレクト URI は Google API のコンソールで正しく設定されています。コードは次のようになります。
<?php
/**
* This is a widget with a calendar implementation.
*
* @package frontend
* @subpackage events
*
* @author Michiel Vlaminck <[email protected]>
*/
class FrontendEventsWidgetCalendar extends FrontendBaseWidget
{
private $events = array();
private $authUrl = array();
/**
* Execute the extra
*
* @return void
*/
public function execute()
{
// call parent
parent::execute();
// load template
$this->loadTemplate();
// get data
$this->getData();
// parse
$this->parse();
}
/**
* Get the data from Google Calendar
* This method is only executed if the template isn't cached
*
* @return void
*/
private function getData()
{
require_once PATH_LIBRARY . '/external/google-api-php-client/src/apiClient.php';
require_once PATH_LIBRARY . '/external/google-api-php-client/src/contrib/apiCalendarService.php';
$client = new apiClient();
$service = new apiCalendarService($client);
if (isset($_SESSION['oauth_access_token'])) {
$client->setAccessToken($_SESSION['oauth_access_token']);
} else {
$token = $client->authenticate();
$_SESSION['oauth_access_token'] = $token;
}
if ($client->getAccessToken()) {
$calId = FrontendEventsModel::getCalendarId((int) $this->data['id']);
$calId = $calId[0]['calendar_id'];
$events = $service->events->listEvents($calId);
$this->events = $events['items'];
$_SESSION['oauth_access_token'] = $client->getAccessToken();
} else {
$this->authUrl = $client->createAuthUrl();
}
}
/**
* Parse
*
* @return void
*/
private function parse()
{
$this->tpl->assign('events', $this->events);
$this->tpl->assign('authUrl', $this->authUrl);
}
}
?>
このウィジェット ページを初めて開くと、アプリケーションの認証のために Google に誘導されます。同意すると、アプリケーションにリダイレクトされ、次の画面が表示されます。
apiAuthException » Main
Message Error fetching OAuth2 access token, message: 'invalid_grant'
File C:\wamp\www\Officevibes\library/external\google-api-php-client\src\auth\apiOAuth2.php
Line 105
Date Thu, 05 Apr 2012 08:34:47 +0000
URL http://localhost/calendar?code=4/YPUpFklKvhEeTcMm4moRth3x49oe
Referring URL (Unknown)
Request Method GET
User-agent Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.142 Safari/535.19
ベストアンサー1
最初の認証が成功した後に取得したアクセス トークンを再利用する必要があります。invalid_grant
以前のトークンの有効期限がまだ切れていない場合はエラーが発生します。再利用できるようにどこかにキャッシュしてください。