如您所知,在Oauth 1的情况下,对于离线使用存在令牌和令牌秘密(每次用户不需要授予访问权限)。同样地,我需要Oauth 2的Token和Token秘密。
使用Google提供的PHP客户端库。 还可以在Google API控制台中使用Web应用程序。
在下面提到我的代码。
我需要它用于我的应用程序(用于访问Admin SDK API)
$client = new Google_Client();
$client->setAccessType('offline'); // default: offline
$client->setApplicationName('SysCloud.com => For User Creation');
$client->setClientId('107XXXXXXXXXXXsercontent.com');
$client->setClientSecret('aeh-gQ33zXXXXXXX4K2T5K');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('AIzaSyBOXXXXXXXXXX7WBZ4p4'); // API key
$client->setScopes(array(
'https://apps-apis.google.com/a/feeds/user/',
'https://apps-apis.google.com/a/feeds/groups/',
'https://apps-apis.google.com/a/feeds/alias/',
'https://apps-apis.google.com/a/feeds/emailsettings/2.0/',
'https://www.googleapis.com/auth/userinfo#email',
'https://apps-apis.google.com/a/feeds/domain/'
));
$service = new Google_AnalyticsService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
die('Logged out.');
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) {
$token = $_SESSION['token'];
$client->setAccessToken($token);
}
if (!$client->getAccessToken()) {
$authUrl = $client->createAuthUrl();
header("Location: " . $authUrl);
die;
}
Print_r($_SESSION);
if (isset($_REQUEST['code'])) {
$_SESSION['accessToken'] = get_oauth2_token($_REQUEST['code']);
}
Print_r($_SESSION);
function get_oauth2_token($code) {
$oauth2token_url = "https://accounts.google.com/o/oauth2/token";
$clienttoken_post = array(
"code" => $code,
"client_id" => "1xXxxxXxxxX.apps.googleusercontent.com",
"client_secret" => "aehXXXXXXXXVDiXXXXX4K2T5K",
"redirect_uri" => "http://localhost:1137/POC/UserCreation/googleapitest.php",
"grant_type" => "authorization_code"
);
$curl = curl_init($oauth2token_url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $clienttoken_post);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CAINFO, 'c:/Poc/ca-bundle.crt');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$json_response = curl_exec($curl);
curl_close($curl);
$authObj = json_decode($json_response);
if (isset($authObj->refresh_token)) {
//refresh token only granted on first authorization for offline access
//save to db for future use (db saving not included in example)
global $refreshToken;
$refreshToken = $authObj->refresh_token;
}
$accessToken = $authObj->access_token;
return $accessToken;
}
谢谢, 的Gowtham