谷歌API PHP客户端-联系人服务

9

经过长时间的深入研究,我终于对Google API PHP客户端的配置和使用有了更深入地了解,这是基于分析数据的此教程

所以,现在我终于以一种看起来合法和官方的方式进行了身份验证。我的自然想法是应该存在一个contrib/Google_ContactsService.php文件,但令我惊讶的是,在其他32个服务类中都找不到它。

我感觉回到了原点。是否有任何方法可以以合法和官方的方式获取特定用户的联系人?(有很多教程,但都已过时且方法不当)。

编辑:我注意到库中有一个更新版本可用 此处,但在.../Service/文件夹中仍然找不到“联系人”服务。

编辑: 我的进展如下。最后一行由于从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.';
3个回答

5

以下内容来自此处

很遗憾,联系人API是较旧的GData API之一,而这个库是用于新型API的。您可以使用库中的OAuth部分请求范围(https://www.googleapis.com/auth/contacts.readonly)并使用令牌进行请求,但您必须手动解析数据。Zend框架确实有Zend_Gdata类,可以使读取结果变得更容易!

我在这里找到了一个使用旧库的示例。


好的,谢谢!它会被弃用吗?我现在使用最新版本,并已成功设置了API。将来会有官方API吗?还是? - FooBar
1
有人已经在新库中实现了这个吗?我正在尝试进行“自定义”请求,但我还没有成功:https://github.com/google/google-api-php-client/issues/446 - user1226868

4

更新,2018年3月28日:

我创建了一个基于较新的Google People API来管理Google联系人的新包。如果您正在启动一个新项目,我建议您使用此包,而不是下面我原始帖子中提到的那个。

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


原始帖子:

最近我不得不处理这个问题,发现官方PHP Google客户端缺少联系人服务,因此我创建了一个(MIT许可)用于Google Contacts API的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"
   }
}

Further setup instructions and examples are available on GitHub.
GitHub链接: https://github.com/rapidwebltd/php-google-contacts-v3-api

2
我能通过新库使这个工作起来...大多数情况下。显然,它不像完整的服务实现那样流畅,但它可以让事情运转起来。
按照上面的帖子中提到的方式获取Git库。 我从这里的示例开始:https://developers.google.com/api-client-library/php/auth/web-app oauth2callback.php(请注意,必须在您的开发人员控制台的API和身份验证/凭据部分中列出此文件的完整路径,否则您的调用将失败):
<?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));
}

?>

祝你好运!这篇文章已经有一段时间没有更新了,如果有人编写了服务,请让我知道。与此同时,以下内容应该可以帮助你入门!


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