2012-06-29 2 views
3

Я использую php 5.3.3 и codeigniter 2.1.0. что я хочу сделать, это настроить учетную запись службы, поэтому пользователь может добавить встречу в текстовое поле ввода на моем веб-сайте, а затем назначить эту встречу в общий общий календарь Google.Аутентификация учетной записи google-сервиса с помощью google-api-php-client с использованием календаря api

У меня есть учетная запись Google, и с помощью: https://code.google.com/apis/console Я создал новый проект под названием «ПКЭ» на услуги: включен в календарь апи на доступ к API: я создал клятва клиент 2.0 ID ... название товара = ПКЭ, приложение type = учетная запись службы.

загружен ключ 46 ... -privatekey.p12. есть скриншот настроек:

preview

Я получил Svn проверку в Google-апи-PHP-клиент (28/6/2012) В Google-апи-PHP-клиент/ЦСИ /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','[email protected]'); 
     // 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('[email protected]'); 
     $attendees = array($attendee1); 
     $event->attendees = $attendees; 
     $createdEvent = $service->events->insert('primary', $event); 
     return $createdEvent->getId(); 

    } 
} 

Pastie на выходе here:

за $ объект клиента не аутентифицирован, getAccessToken не установлен, а событие не вставлен.

Мне сложно определить, какие настройки в файле $ config будут изменены, потому что существует другая номенклатура. Я думаю, это артефакт того, как продвигался код. Правильные настройки в src/config.php? мне нужно изменить любые настройки?

Я понимаю, что если я создаю учетную запись службы, загрузите файл ключа и содержимое этого файла с идентификатором моего разработчика, он должен вернуть токен, и нет необходимости настраивать uri перенаправления. . это верно? это функциональность, которую я хочу. я не хочу, чтобы пользователь должен был разрешать доступ, потому что веб-сайт будет взаимодействовать только с одной учетной записью google.

Итак, вопрос в том, как получить этот календарь api для аутентификации с помощью учетной записи службы google?

ответ

0

Вы можете попробовать this если вы уже не ...

EDIT:this один, но если интересную вы все еще чувствуете, как написать одну себя, то попробуйте this мать OAuth2. helpful

О учетной записи службы на Google-апи-PHP-клиенте, который вы используете (всегда берут ствол один с SVN) Я не могу нашел в этом коде манипуляциях любых ссылок apiAssertionCredentials::generateAssertion() определенно нет вызова авторизовать там

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); 
} 

EDIT: помилование. В свежем вер. похоже, что это Google_OAuth2::refreshTokenWithAssertion() актуальным, кто должен начать настоящие процессы

Смежные вопросы