Symfony2 Google API,如何使用Google客户端

时间:2013-06-19 21:57:04

标签: php api rest symfony google-calendar-api

我正在使用Symfony2.3,我想访问Google Calendar API,这就是我所做的 1-I安装了HIWO BundleFOSUser Bundle
2 - 集成两个捆绑包,现在我已经过用户身份验证,并使用访问令牌插入数据库 3 - 我已安装Google API library并自动加载它 4创建了一个服务包装类来访问

问题1: 现在似乎我在登录时使用了HIWO Bundle中的Oauth2,我将在提出请求时在Google API库中使用Oauth2,这有点任何意义并且不确定应该在这件事上做些什么

试验: - 我发现HIW Oauth提供的令牌与URL中的code参数中的令牌不同,同时重定向回 - 尝试手动设置令牌并尝试模拟Google客户端请求$cal = new \Google_Calendar($this->googleClient),如下所示

    $this->googleClient->authenticate('4/PmsUDPCbxWgL1X_akVYAhvnVWqpn.ErqFdB3R6wMTOl05ti8ZT3Zpgre8fgI');
    return $cal->calendarList->listCalendarList();`

收到错误:

  

获取OAuth2访问令牌时出错,消息:'redirect_uri_mismatch'

我确保我redirect_uri匹配

我的服务代码如下:

<?php

namespace Clinic\MainBundle\Services;

use Clinic\MainBundle\Entity\Patient;
use Doctrine\Common\Persistence\ObjectManager;

/*
 * @author: Ahmed Samy
 */

class GoogleInterfaceService {
    /*
     * Entity manager
     */

    protected $em;
    /*
     * instance of Symfphony session
     */
    protected $session;
    /*
     * Service container
     */
    protected $container;

    /*
     * Google client instance
     */
    protected $googleClient;

    public function __construct(ObjectManager $em, $container) {
        $this->em = $em;
        $this->container = $container;
        $this->googleClient = new \Google_Client();

        $this->googleClient->setClientId('xxxxxxxx.apps.googleusercontent.com');
        $this->googleClient->setClientSecret('uNnaK1o-sGH_pa6Je2jfahpz');
        $this->googleClient->setRedirectUri('http://hacdc.com/app_dev.php/login/check-google');
        $this->googleClient->setDeveloperKey('xxxxxxxxxxxxxxxxxxxx');
        $this->googleClient->setApplicationName("Google Calendar PHP Starter Application");
    }

    public function getCalendar() {

        $cal = new \Google_Calendar($this->googleClient);

        //setting token manually 
        $this->googleClient->authenticate('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
        return $cal->calendarList->listCalendarList();
    }

}

当我转储$this->googleClient时,我得到了

protected 'scopes' => 
    array (size=0)
      empty
  protected 'useObjects' => boolean false
  protected 'services' => 
    array (size=0)
      empty
  private 'authenticated' => boolean false

1 个答案:

答案 0 :(得分:0)

HWIOAuthBundle的令牌缺少created数组段,但您可以在那里强制执行,然后只需将该令牌提供给客户端,如下所示:

    $googleAccessToken = $this->get('security.context')->getToken()->getRawToken();
    $googleAccessToken['created'] = time(); // This is obviously wrong... but you get the poing

    $this->google_client->setAccessToken(json_encode($googleAccessToken));

    $activities = $this->google_plusservice->activities->listActivities('me', 'public');

    var_dump($activities);die();