OAUTH2 использует PHP для получения контактов Google - PullRequest
0 голосов
/ 16 июня 2011

Я почти закончил с моим PHP-скриптом, который будет захватывать контакты Google, используя 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/02010-01-28T02:12:46.705Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/12010-01-28T02:12:46.705Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/42010-01-28T02:12:46.705Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/52010-01-28T02:12:46.705Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/62010-01-28T02:12:46.705Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/72010-01-28T02:12:46.705Zhttp://www.google.com/m8/feeds/contacts/email%40gmail.com/base/82010-01-28T02: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-27T13: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-28T02: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-10-28T05: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. после того, как пользователь одобрит, Google перенаправит на oauth_callback_google.php, где я и остался висеть.

Ответы [ 2 ]

1 голос
/ 13 апреля 2012

В случае, если кто-то еще столкнется с этим вопросом, я опубликую ответ:

Вы получаете полностью сформированный XML, который содержит всю информацию.Однако ваш браузер пытается отобразить этот XML как HTML.Чтобы увидеть полностью возвращенный XML, right-click - > View Source.

В конце концов, вы захотите передать возвращенный XML в библиотеку XML и проанализировать его.

0 голосов
/ 03 июля 2013
 $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;

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...