【问题标题】:Google API PHP Client - Contacts ServiceGoogle API PHP 客户端 - 联系人服务
【发布时间】:2014-05-03 03:52:08
【问题描述】:

在经历了数小时的深深痛苦之后,我终于使用this tutorial(虽然基于 Analytics)更接近了 Google 的 API PHP 客户端的配置和使用。

所以,现在我终于以一种看起来合法和官方的方式验证了自己。我的自然想法是会有一个contrib/Google_ContactsService.php,但令我惊讶的是,在其他 32 个服务类中找不到它。

我想回到从头开始。有什么方法可以 - 合法且正式 - 获取特定用户的联系人? (那里有大量的教程,但都是过时的和hacky)。

编辑:我注意到here 有更新版本的库可用,但在.../Service/ folder 中仍然找不到任何“联系人”服务

编辑: 到目前为止我的进步。最后几行因 Google 的响应而失败:401. There was an error in your request. - 我想这是因为缺乏许可(我没有要求联系人许可)。但是,如果没有“Google_ContactsService.php”,我该怎么做?我迷路了。见代码:

<?php
session_start();

/**
 * Require the libaries
 */

    require_once 'assets/php/Google/Google_Client.php';
    require_once 'assets/php/Google/contrib/Google_AnalyticsService.php'; // from tutorial - I am supposed to get the Contacts Service, which is nowhere to find.

/**
 * Set up the Google_Client
 */

    $client = new Google_Client();
    $client->setAccessType('online'); // default: offline
    $client->setApplicationName($apiConfig['application_name']);
    $client->setClientId($apiConfig['oauth2_client_id']);
    $client->setClientSecret($apiConfig['oauth2_client_secret']);
    $client->setRedirectUri($apiConfig['oauth2_redirect_uri']);
    $client->setDeveloperKey($apiConfig['developer_key']); // API key

/**
 * $service implements the client interface, has to be set before auth call
 */

    $service = new Google_AnalyticsService($client);

/**
 * Log out
 */

    if (isset($_GET['logout'])) { // logout: destroy token
        unset($_SESSION['google_token']);
        exit('Logged out.');
    }

/**
 * Google auth code received
 *
 * Store access token
 */

    if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
        $client->authenticate();
        $_SESSION['google_token'] = $client->getAccessToken();
    }

/**
 * Set auth token
 */

    if (isset($_SESSION['token'])) { // extract token from session and configure client
        $token = $_SESSION['token'];
        $client->setAccessToken($token);
    }

/**
 * If no token, redirect and auth
 */

    if (!$client->getAccessToken()) { // auth call to google
        $authUrl = $client->createAuthUrl();
        header("Location: ".$authUrl);
        exit;
    }

/**
 * Get contacts
 */

    $access_token = json_decode($client->getAccessToken())->access_token;

    $url = 'https://www.google.com/m8/feeds/contacts/default/full?alt=json&v=3.0&oauth_token='.$access_token;

    $response =  file_get_contents($url);

    exit($response);

    echo 'Hello, world.';

【问题讨论】:

    标签: php api google-api google-api-php-client google-contacts-api


    【解决方案1】:

    来自here

    很遗憾,联系人 API 是较旧的 GData 之一,而 此库适用于较新的 API。您可以使用 OAuth 部分 图书馆请求范围 (https://www.googleapis.com/auth/contacts.readonly),并使用令牌 发出请求,但您必须手动解析数据。曾德 框架确实有 Zend_Gdata 类,可能会读取 结果容易一点!

    我找到了an example using the old library

    【讨论】:

    • 好的,谢谢!它会被弃用吗?我现在使用最新版本,并且已经成功设置了 API。将来会有官方API吗?还是?
    • 有人已经在新库中实现了这个吗?我正在尝试提出“自定义”请求,但尚未成功:github.com/google/google-api-php-client/issues/446
    【解决方案2】:

    2018 年 3 月 28 日更新:

    我创建了一个新包来管理基于更新的 Google People API 的 Google 通讯录。如果你开始一个新项目,我建议你使用这个包而不是我在下面的原始帖子中提到的那个。

    您可以在此处找到更多详细信息:https://github.com/rapidwebltd/php-google-people-api


    原帖:

    我最近不得不处理这个问题,在发现官方 PHP Google 客户端中缺少联系人服务后,我为 Google 联系人 API 创建了一个(MIT 许可)PHP 库。

    其中一个目标是真正简化所涉及的一些过程。因此,为了回答您的问题,在设置库后,只需以下代码即可检索联系人。

    require_once '../../../vendor/autoload.php';
    use rapidweb\googlecontacts\factories\ContactFactory;
    $contacts = ContactFactory::getAll();
    if (count($contacts)) {
        echo 'Test retrieved '.count($contacts).' contacts.';
    } else {
        echo 'No contacts retrieved!';
    }
    

    该库需要做一些工作,但可以很好地用于基本的联系人检索、创建和更新。如果需要,也可以通过composer 安装。只需将以下内容添加到您的 composer.json 并运行 composer update

    {
      "require": {
           "rapidwebltd/php-google-contacts-v3-api": "dev-master"
       }
    }
    

    GitHub 上提供了更多设置说明和示例。

    GitHub 链接:https://github.com/rapidwebltd/php-google-contacts-v3-api

    【讨论】:

      【解决方案3】:

      我能够通过新库来完成这项工作……主要是。显然,它不像完整的 Service 实现那么流畅,但它让事情发生了变化。

      Git 库,如上述帖子中所述。 我从这里的例子开始:https://developers.google.com/api-client-library/php/auth/web-app

      oauth2callback.php(请注意,完整路径必须列在开发者控制台的 APIs & Auth/Credentials 部分,否则您的调用将失败):

      <?php
      
      set_include_path(get_include_path() . PATH_SEPARATOR . '/data/www/unity/html/lib');  # The path where I git got google-api-php-client
      require_once 'google-api-php-client/src/Google/autoload.php';
      
      $APPPATH = "/Applications/GFContacts";
      
      session_start();
      
      $client = new Google_Client();
      $client->setAuthConfigFile('accountinfo.json'); # JSON config file downloaded from the credentials page of my project https://console.developers.google.com/project
      $client->setRedirectUri('https://' . $_SERVER['HTTP_HOST'] . $APPPATH . '/oauth2callback.php');
      $client->addScope("https://www.googleapis.com/auth/contacts.readonly");
      
      if (! isset($_GET['code'])) {
        $auth_url = $client->createAuthUrl();
        header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
      } else {
        $client->authenticate($_GET['code']);
        $_SESSION['access_token'] = $client->getAccessToken();
        $redirect_uri = 'https://' . $_SERVER['HTTP_HOST'] . $APPPATH;
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
      }
      
      ?>
      

      然后是index.php:

      <?php
      
      set_include_path(get_include_path() . PATH_SEPARATOR . '/data/www/unity/html/lib');  # The path where I git got google-api-php-client
      
      require_once 'google-api-php-client/src/Google/autoload.php';
      $APPPATH = "/Applications/GFContacts"; # relative path from server root
      
      session_start();
      
      $client = new Google_Client();
      $client->setAuthConfigFile('accountinfo.json'); # JSON config file downloaded from the credentials page of my project https://console.developers.google.com/project
      $client->addScope("https://www.googleapis.com/auth/contacts.readonly");
      
      # Allow a param 'logout' to remove the access token - sometimes doing this helps debug issues
      if (isset($_REQUEST['logout'])) {
          unset($_SESSION['access_token']);
          $client->revokeToken();
      
          print "You're logged out of Google";
      
          exit;
      }
      
      if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
      
          $access_token = json_decode($_SESSION['access_token'])->access_token;
      
          $client->setAccessToken($_SESSION['access_token']);
      
          $req = new Google_Http_Request("https://www.google.com/m8/feeds/contacts/default/full");
          $val = $client->getAuth()->authenticatedRequest($req);
      
          // The contacts api only returns XML responses.
          $response = json_encode(simplexml_load_string($val->getResponseBody()));
          print "<pre>" . print_r(json_decode($response, true), true) . "</pre>"; 
      
      } else {
          $redirect_uri = 'https://' . $_SERVER['HTTP_HOST'] . $APPPATH . '/oauth2callback.php';
          header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
      }
      
      ?>
      

      祝你好运!这篇文章更新已经有一段时间了,所以如果有人写了一个服务,我很想知道它。同时,这应该可以帮助您入门!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-11
        • 2021-12-08
        • 2013-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多