所以这是交易。
我已经通过 php 连接到 Google 联系人的 api,将所有内容存储在会话中,并检索了联系人列表。
我想要的是将所有必要的令牌存储在数据库中,并在以后检索它们以在同一用户上重新使用它们。我不知道要存储什么信息...我尝试将会话中的每一个小项目都存储到数据库中,并在尝试重新连接到 api 时重新加载它,但总是会出现一个或另一个错误,因为我的令牌是不正确。
我想对于非常了解 OAuth 的人来说答案很简单——这实际上只是我存储什么的问题。
下面的代码:
<?php
session_start();
include_once "../oauth-php/library/OAuthStore.php";
include_once "../oauth-php/library/OAuthRequester.php";
global $db;
$userid=$_SESSION['userid'];
define("GOOGLE_CONSUMER_KEY", "website.com"); //
define("GOOGLE_CONSUMER_SECRET", "----------------------"); //
define("GOOGLE_OAUTH_HOST", "https://www.google.com");
define("GOOGLE_REQUEST_TOKEN_URL", GOOGLE_OAUTH_HOST . "/accounts/OAuthGetRequestToken");
define("GOOGLE_AUTHORIZE_URL", GOOGLE_OAUTH_HOST . "/accounts/OAuthAuthorizeToken");
define("GOOGLE_ACCESS_TOKEN_URL", GOOGLE_OAUTH_HOST . "/accounts/OAuthGetAccessToken");
define('OAUTH_TMP_DIR', function_exists('sys_get_temp_dir') ? sys_get_temp_dir() : realpath($_ENV["TMP"]));
// Init the OAuthStore
$options = array(
'consumer_key' => GOOGLE_CONSUMER_KEY,
'consumer_secret' => GOOGLE_CONSUMER_SECRET,
'server_uri' => GOOGLE_OAUTH_HOST,
'request_token_uri' => GOOGLE_REQUEST_TOKEN_URL,
'authorize_uri' => GOOGLE_AUTHORIZE_URL,
'access_token_uri' => GOOGLE_ACCESS_TOKEN_URL
);
OAuthStore::instance("Session", $options);
try
{
// STEP 1: If we do not have an OAuth token yet, go get one
if (empty($_GET["oauth_token"]))
{
$getAuthTokenParams = array('scope' =>
'https://www.google.com/m8/feeds/',
'xoauth_displayname' => 'My web app',
'oauth_callback' => 'http://website.com/google.php');
// get a request token
$tokenResultParams = OAuthRequester::requestRequestToken(GOOGLE_CONSUMER_KEY, 0, $getAuthTokenParams);
// redirect to the google authorization page, they will redirect back
header("Location: " . GOOGLE_AUTHORIZE_URL . "?btmpl=mobile&oauth_token=" . $tokenResultParams['token']);
}
else {
// STEP 2: Get an access token
$oauthToken = $_GET["oauth_token"];
$oauthVerifier = $_GET["oauth_verifier"];
$tokenResultParams = $_GET;
//$db->query("UPDATE gmkeys SET token='$oauthToken', secrettoken='$oauthVerifier'");
try {
OAuthRequester::requestAccessToken(GOOGLE_CONSUMER_KEY, $oauthToken, 0, 'POST', $_GET);
}
catch (OAuthException2 $e)
{
var_dump($e);
// Something wrong with the oauth_token.
// Could be:
// 1. Was already ok
// 2. We were not authorized
return;
}
// make the request.
$request = new OAuthRequester("https://www.google.com/m8/feeds/contacts/default/full?max-results=1000&group=http%3A%2F%2Fwww.google.com%2Fm8%2Ffeeds%2Fgroups%2Fusernamehere%40gmail.com%2Fbase%2F6", 'GET', $tokenResultParams);
$result = $request->doRequest(0);
if ($result['code'] == 200)
{
$xml = new SimpleXMLElement($result['body']);
...
}
else
{
echo 'Error';
}
}
}
catch(OAuthException2 $e) {
echo "OAuthException: " . $e->getMessage();
var_dump($e);
}
?>