现在的位置: 首页 > Web设计> 正文
Google Plus API 之 程序设计
2011年09月17日 Web设计 评论数 3 ⁄ 被围观 13,577+

昨天Google官方发布新闻(Getting started on the Google+ API),Google Plus开放了一个只读的API,允许抓取用户的公开Profile和公开的Activity信息流,其中Google+ Platform的具体开发API介绍详见官网。

今天我就带领大家熟悉一下基于Google+ 开放API的程序设计,本程序基于SAE平台,采用PHP语言开发,基于Java语言和Python语言也都比较好开发,google官方都有开放的lib可以直接使用,不用自己再做底层封装了。

实现步骤

  1. 访问 Google API Console 开启Google+ API权限.
  2. 访问 Google API Console 生成  developer key, OAuth2 client id, OAuth2 client secret, 和 注册 OAuth2 redirect uri.

  3. 下载 google api的php开发库,google-api-php-client.
  4. 更新google api开发库,因为我的运行环境基于新浪云SAE平台,所以要做一些特别的改动:
    1. 实现SAE平台的MemCache,在google-api-php-clientsrccache中建立apiSAEMemcacheCache.php文件,具体内容如下

    <?php
    /**
     * SAE Memcache
     *
     * @author Carey Zhou <zhourunsheng2008@google.com>
     */
    class apiSAEMemcacheCache extends apiCache {
      private $connection = false;
    
      public function __construct() {
    	//do nothing
      }
    
      private function connect() {
        if (! $this->connection = @memcache_init()) {
          throw new apiCacheException("Memcache init failed");
        }
      }
    
      private function check() {
        if (! $this->connection) {
          $this->connect();
        }
      }
    
      /**
       * @inheritDoc
       */
      public function get($key, $expiration = false) {
        $this->check();
        if (($ret = @memcache_get($this->connection, $key)) === false) {
          return false;
        }
        if (! $expiration || (time() - $ret['time'] > $expiration)) {
          $this->delete($key);
          return false;
        }
        return $ret['data'];
      }
    
      /**
       * @inheritDoc
       */
      public function set($key, $value) {
        $this->check();
        // we store it with the cache_time default expiration so objects will at least get cleaned eventually.
        if (@memcache_set($this->connection, $key, array('time' => time(),
            'data' => $value), false) == false) {
          throw new apiCacheException("Couldn't store data in cache");
        }
      }
    
      /**
       * @inheritDoc
       */
      public function delete($key) {
        $this->check();
        @memcache_delete($this->connection, $key);
      }
    }

    2. 更新 google-api-php-clientsrccacheapiCache.php文件,将我们新添加的SAEMemcache加进去,代码如下:

    require_once "apiSAEMemcacheCache.php";

    3. 更新 google-api-php-clientsrcioapiCurlIO.php文件,修正一个bug【当Header中出现"HTTP/1.1 100 Continue"的时候,原程序会出现解析错误,导致程序崩溃,估计也是SAE环境的特殊性导致的】,具体改正如下:

    原来的代码:

    // Parse out the raw response into usable bits
        list($rawResponseHeaders, $responseBody) = explode("rnrn", $data, 2);

    现在的代码:

    // Parse out the raw response into usable bits
        list($rawResponseHeaders, $responseBody) = explode("rnrn", $data, 2);
        if ($rawResponseHeaders == "HTTP/1.1 100 Continue") {
    	list($rawResponseHeaders, $responseBody) = explode("rnrn", $responseBody, 2);
        }

    更改原因:如果出现了"HTTP/1.1 100 Continue"的时候,还要继续向下解析一次,即出现了特殊的“双Header现象”,否则的话就会导致Header解析出错,真正的Header没有被解析出来,也混到body里面去了。

  5. google plus 代码编写,获取用户公开的Activity信息流,核心代码如下:
    <?php
    /*
     * Google Plus
     *
     * @author Carey Zhou(zhourunsheng2008@gmail.com)
     */
    require_once '../libs/google-api-php-client/src/apiClient.php';
    require_once '../libs/google-api-php-client/src/contrib/apiPlusService.php';
    
    //sae_set_display_errors(true);
    
    session_start();
    
    $client = new apiClient();
    $client->setApplicationName("Google Plus Application");
    
    $client->setClientId('800611776987-kp6h5nfv5l9gp5v2qipqhc5l8dkqe0lu.apps.googleusercontent.com');
    $client->setClientSecret('5o-eK5M4iftPxB7_fhNqEAhm');
    $client->setRedirectUri('https://carey.sinaapp.com/googleplus/index.php');
    $client->setDeveloperKey('AIzaSyD6FERuKcWPn2xGUcgFmKW9Ush50nu6PYQ');
    
    $client->setScopes(array('https://www.googleapis.com/auth/plus.me'));
    $plus = new apiPlusService($client);
    
    if (isset($_REQUEST['logout'])) {
      unset($_SESSION['access_token']);
    }
    
    if (isset($_GET['code'])) {
      $client->authenticate();
      $_SESSION['access_token'] = $client->getAccessToken();
      //header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
      $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
      echo "<script language='javascript' type='text/javascript'>";
      echo "window.location.href='$url'";
      echo "</script>";
    }
    
    if (isset($_SESSION['access_token'])) {
      $client->setAccessToken($_SESSION['access_token']);
    }
    
    if ($client->getAccessToken()) {
      $me = $plus->people->get('me');
    
      $optParams = array('maxResults' => 100);
      $activities = $plus->activities->listActivities('me', 'public', $optParams);
    
      // The access token may have been updated lazily.
      $_SESSION['access_token'] = $client->getAccessToken();
    } else {
      $authUrl = $client->createAuthUrl();
    }
    ?>

    可以注意到,在程序中我们配置了ClientID,ClientSecret,RedirectUri,DeveloperKey和Google+的scope,然后通过OAuth2机制获取用户的授权,进而来获得用户公开的Activity信息流。

程序部署和验证

  1. 把上面的代码部署到SAE平台,https://carey.sinaapp.com/googleplus/index.php
  2. 点击Connet Me进行OAuth2用户授权
  3. 点击Allow Access允许访问,则会回到刚才的页面,把用户的信息流抓取出来

小结

到此为止,google plus 基于PHP开发的基本流程就都OK了,希望google过几天能开放出更多的API来,毕竟google+是个圈,所以圈子的API才是最核心的,O(∩_∩)O哈哈~,期待中

源码下载google_plus_sae_source

目前有 3 条留言 其中:访客:2 条, 博主:1 条

  1. : 2011年11月29日13:51:58  -49楼 @回复 回复

    不知道GOOGLE啥时候有更新,太慢了,

  2. bandit : 2011年09月18日04:02:43  -48楼 @回复 回复

    学长强大
    学长都用什么工具翻墙?

    • 润物无声 : 2011年09月18日09:01:57 @回复 回复

      普通的基于Http代理的翻墙方式都行,比如自由门和GoAgent,都还比较方便,这对于查资料浏览网站比较好,如果是要开发的话,设置代理比较麻烦,那就找几个免费的私有VPN用用,开发过后就丢弃了,动态变化,O(∩_∩)O哈哈~

给我留言

留言无头像?


×
腾讯微博