使用Google API PHP客户端进行Google服务账号身份验证来使用日历API

3
我正在使用PHP 5.3.3和CodeIgniter 2.1.0。我想要做的是设置一个服务帐号,这样用户就可以在我的网站上的文本输入框中添加约会,然后将该约会添加到共享的Google日历中。
我有一个Google帐户,并且使用:https://code.google.com/apis/console 我创建了一个名为“pqp”的新项目 在服务中:启用了日历API 在API访问中:我创建了一个OAuth 2.0客户端ID…产品名称=pqp,应用程序类型=服务帐号。
下载了密钥46…-privatekey.p12。这里有一张设置的截图:

preview

我获得了一个google-api-php-client的svn检出副本(2012年6月28日)。在google-api-php-client/src/config.php文件中,我更改了以下行:
25: 'application_name' => 'pqp',
28: 'oauth2_client_id' => '373xxx730.apps.googleusercontent.com',
57: 'ioFileCache_directory'  => 'tmp/apiClient',  // my apache user does not have access to the system /tmp folder.  + tmp/apiClient has permissions of 777 on the server.

使用此链接:
http://code.google.com/p/google-api-php-client/source/browse/trunk/examples/prediction/serviceAccount.php?spec=svn445&r=395

我将其修改为:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test extends CI_Controller{
    function __construct()
    {
        parent::__construct();
    }
    function index()
    {
        set_include_path(get_include_path() . PATH_SEPARATOR .dirname(__FILE__).'/../libraries/google-api-php-client/src');
        ini_set('error_reporting',E_ALL);
        ini_set('display_errors','1');
        // Set your client id, service account name, and the path to your private key.
        // For more information about obtaining these keys, visit:
        // https://developers.google.com/console/help/#service_accounts
        define('CLIENT_ID','3731xxx44730.apps.googleusercontent.com');
        define('SERVICE_ACCOUNT_NAME','373xxx244730@developer.gserviceaccount.com');
        // Make sure you keep your key.p12 file in a secure location, and isn't
        // readable by others.
        define('KEY_FILE',dirname(__FILE__).'/../../461290xxx796c0b7db9582c-privatekey.p12');

        require_once "apiClient.php";
        require_once "contrib/apiCalendarService.php";

        $client = new apiClient();
        $client->setApplicationName("pqp");     
        // Set your cached access token. Remember to replace $_SESSION with a
        // real database or memcached.
        session_start();
        if (isset($_SESSION['token'])) {
            $client->setAccessToken($_SESSION['token']);
            echo 'client access token is set.<br/>';
        }

        // Load the key in PKCS 12 format (you need to download this from the
        // Google API Console when the service account was created.
        $key = file_get_contents(KEY_FILE);
        $creds = new apiAssertionCredentials(SERVICE_ACCOUNT_NAME,array('https://www.googleapis.com/auth/calendar'),$key);
        $client->setAssertionCredentials($creds);
        $client->setClientId(CLIENT_ID);
        $service = new apiCalendarService($client);
        echo 'client:<br/>';
        var_dump($client);
        echo 'service:<br/>';
        var_dump($service);
        // We're not done yet. Remember to update the cached access token.
        // Remember to replace $_SESSION with a real database or memcached.
        if ($client->getAccessToken()) {
            $_SESSION['token'] = $client->getAccessToken();
            echo 'token is good!, so creating an event....';
            echo $this->insert_event($service,'testing summary','my location','2012-06-29T10:00:00.000+10:00','2012-06-29T10:00:00.000+10:00');
        }
    }


    function insert_event($service,$summary,$location,$from,$to){
        $event = new Event();
        $event->setSummary($summary);
        $event->setLocation($location);
        $start = new EventDateTime();
        $start->setDateTime($from);
        $event->setStart($start);
        $end = new EventDateTime();
        $end->setDateTime($to);
        $event->setEnd($end);
        $attendee1 = new EventAttendee();
        $attendee1->setEmail('test@example.com');
        $attendees = array($attendee1);
        $event->attendees = $attendees;
        $createdEvent = $service->events->insert('primary', $event);
        return $createdEvent->getId();

    }
}

这里是输出结果的链接

$client对象未经过身份验证,getAccessToken未设置,事件未被插入。

我发现很难确定在$config文件中更改哪些设置,因为有不同的术语。我猜这是代码进展的副产品。src/config.php中的设置是否正确?我需要修改更多的设置吗?

我的理解是,如果我创建了服务帐户,下载了密钥文件,并将此文件的内容与我的开发者ID一起使用,它应该返回一个令牌,并且无需设置重定向URI。这是我想要的功能。我不希望用户授权访问,因为网站只会与一个Google帐户进行交互。

那么,问题是,如何使用Google服务帐户对此日历API进行身份验证?

1个回答

0

如果你还没有尝试过this,可以试一下...

编辑:this很有趣,但如果你仍然想自己编写一个,那么试试this,它是oauth2的母亲。有帮助

关于使用google-api-php-client的服务账户(始终使用SVN中的主干版本),我在代码操作中找不到任何对apiAssertionCredentials::generateAssertion()的引用,肯定没有调用auth。

public function __construct(
      $serviceAccountName,
      $scopes,
      $privateKey,
      $privateKeyPassword = 'notasecret',
      $assertionType = 'http://oauth.net/grant_type/jwt/1.0/bearer',
      $prn = false) {
    $this->serviceAccountName = $serviceAccountName;
    $this->scopes = is_string($scopes) ? $scopes : implode(' ', $scopes);
    $this->privateKey = $privateKey;
    $this->privateKeyPassword = $privateKeyPassword;
    $this->assertionType = $assertionType;
    $this->prn = $prn;
}

我猜应该调用这个方法...

public function generateAssertion() {
    $now = time();

    $jwtParams = array(
          'aud' => apiOAuth2::OAUTH2_TOKEN_URI,
          'scope' => $this->scopes,
          'iat' => $now,
          'exp' => $now + self::MAX_TOKEN_LIFETIME_SECS,
          'iss' => $this->serviceAccountName,
    );

    if ($this->prn !== false) {
      $jwtParams['prn'] = $this->prn;
    }

    return $this->makeSignedJwt($jwtParams);
}

编辑: 抱歉。在新版本中,看起来实际上应该由Google_OAuth2::refreshTokenWithAssertion()开始真正的过程。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接