OAUTH2使用PHP获取Google联系人


OAUTH2 using PHP to get Google Contacts

我的php脚本即将完成,它将使用OAuth2获取谷歌联系人。我指的是医生@http://code.google.com/apis/accounts/docs/OAuth2.html

我丢弃了联系人,我得到了这些:

字符串(23704)"email@gmail.com2011-06-16T06:52:20.113Zusernameemail@gmail.comContacts127125http://www.google.com/m8/feeds/contacts/email%40gmail.com/base/0210-01-28T02:12:46.705Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/12010-01-28t22:12:46.705Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/42010-01-28t22:12:46.705Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/52010-01-28t22:12:46.705Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/62010-01-28t22:12:46.705Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/72010-01-28t22:12:46.705Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/82010-01-28t22:12:46.705Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/92007-08-03T00:28:51.761Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/a2007-08-03T00:28:51.761Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/b2011-03-27 t13:04:13.929Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/d2007-08-03T00:28:51.761Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/e2009-09-22T06:00:55.117Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/f2009-09-22T06:00:55.117Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/102007-08-03T00:28:51.761Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/112009-09-22T06:00:55.117Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/122009-09-22T06:00:55.117Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/132009-09-22T06:00:55.117Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/142007-08-03T00:28:51.761Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/172007-08-03T00:28:51.761Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/182007-08-03T00:28:51.761Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/192007-08-03T00:28:51.761Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/1f84bcc8c755f912010-01-28t22:12:46.705Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/288c63e8bbcb04d2010-11-07T04:40:15.185Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/59573d50dfd5afd2010-2005年10月28日:29分23.690Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/65b55458913d29f2010-06-07T15:53:28.946Z"

呃,那么我应该如何获得联系信息,比如电子邮件、姓名等??

以下是代码:oauth_config.php

<?php
define('AUTHORIZATION_ENDPOINT', 'https://accounts.google.com/o/oauth2/auth');
define('ACCESS_TOKEN_ENDPOINT', 'https://accounts.google.com/o/oauth2/token');
define('CLIENT_ID', 'MY CLIENT_ID');
define('CLIENT_SECRET', 'WMY CLIENT_SECRET');
define('CALLBACK_URI', 'http://example.com/oauth2_callback_google.php');
/***************************************************************************
 * Function: Run CURL
 * Description: Executes a CURL request
 * Parameters: url (string) - URL to make request to
 *             method (string) - HTTP transfer method
 *             headers - HTTP transfer headers
 *             postvals - post values
 **************************************************************************/
function runCurl($url, $method = 'GET', $postvals = null) {
    $ch = curl_init($url);
    //GET request: send headers and return data transfer
    if ($method == 'GET'){
        $options = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => 1
        );
        $result = curl_setopt_array($ch, $options);
    //POST / PUT request: send post object and return data transfer
    } else {
        $options = array(
            CURLOPT_URL => $url,
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => $postvals,
            CURLOPT_RETURNTRANSFER => 1
        );
        $result = curl_setopt_array($ch, $options);
    }
    $response = curl_exec($ch);     
    curl_close($ch);
    return $response;
}
/***************************************************************************
 * Function: Refresh Access Token
 * Description: Refreshes an expired access token
 * Parameters: key (string) - application consumer key
 *             secret (string) - application consumer secret
 *             refresh_token (string) - refresh_token parameter passed in
 *                to fetch access token request.
 **************************************************************************/
function refreshToken($refresh_token) {
    //construct POST object required for refresh token fetch
    $postvals = array('grant_type' => 'refresh_token',
                      'client_id' => CLIENT_ID,
                      'client_secret' => CLIENT_SECRET,
                      'refresh_token' => $refresh_token);
    //return JSON refreshed access token object
    return json_decode(runCurl(ACCESS_TOKEN_ENDPOINT, 'POST', $postvals));
}

?>

oauth_index.php

/**
 * This script will be the first to be initiated
 * It will call Google
 */
require_once('oauth2_config.php');
$accessTokenUri = AUTHORIZATION_ENDPOINT
                  ."?client_id=".CLIENT_ID
                  ."&redirect_uri=".CALLBACK_URI
                  ."&scope=https://www.google.com/m8/feeds/"
                  ."&response_type=code";
// Redirect user to Google to get access token
header("Location:".$accessTokenUri);
exit();

oauth_callback_google.php

/**
 * This is the google callback script.
 * After user approves / decline with the Google application,
 * Google will redirect to this script (as define in Google APIs settings)
 */
require_once('oauth2_config.php');
$code = $_GET['code'];
$error = $_GET['error'];
if (isset($error)) {
    exit();
}
if (!isset($code)) {
    exit();
}
//construct POST object for access token fetch request
$post = array('code' => $code,
              'client_id' => CLIENT_ID,
              'client_secret' => CLIENT_SECRET,
              'redirect_uri' => CALLBACK_URI,
              'grant_type' => 'authorization_code',);
//get JSON access token object (with refresh_token parameter)
$token = json_decode(runCurl(ACCESS_TOKEN_ENDPOINT, 'POST', $post));
//set request headers for signed OAuth request
$headers = array("Accept: application/json");
//construct URI to fetch contact information for current user
$contact_url = "https://www.google.com/m8/feeds/contacts/default/full?"
               ."oauth_token=".$token->access_token;
//fetch profile of current user
$contacts = runCurl($contact_url, 'GET', $headers);
var_dump($contacts);
//echo "<h1>REFRESHING TOKEN</h1>";
var_dump(refreshToken($token->refresh_token));

因此,运行oauth_index.php。在用户批准后,谷歌将重定向到oauth_callback_google.php,这就是我挂起的地方。

如果其他人遇到这个问题,我会发布答案:

您得到的是包含所有信息的完全格式的XML。但是,您的浏览器正试图将此XML呈现为HTML。要查看完全返回的XML,请参阅right-click - > View Source

最终,您需要将返回的XML传递给XML库并对其进行解析

 $url = 'https://www.google.com/m8/feeds/contacts/usermail/full?max-results='.$max_results.'&oauth_token='.$accesstoken.'&alt=json&updated-min=2007-03-16T00:00:00';
 function curl_file_get_contents($url)
 {
 $curl = curl_init();
 $userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)';
 curl_setopt($curl,CURLOPT_URL,$url);   //The URL to fetch. This can also be set when initializing a session with curl_init().
 curl_setopt($curl, CURLOPT_HTTPHEADER,array('GData-Version: 2.0'));
 curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE);    //TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
 curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,5);   //The number of seconds to wait while trying to connect.    
 curl_setopt($curl,CURLOPT_HTTPGET,true);
 curl_setopt($curl, CURLOPT_USERAGENT, $userAgent); //The contents of the "User-Agent: " header to be used in a HTTP request.
//curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); //To follow any "Location: " header that the server sends as part of the HTTP header.
//curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE);    //To automatically set the Referer: field in requests where it follows a Location: redirect.
curl_setopt($curl, CURLOPT_TIMEOUT, 10);    //The maximum number of seconds to allow cURL functions to execute.

//curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE)//阻止cURL验证对等方的证书。

$contents=curl_exec($curl);

curl_close($curl);
return $contents;

}