Čam*_*amo 1 php google-login google-plus google-oauth
你能告诉我,我如何通过 Google+ Javascript/Php api 获取用户数据(姓名、电子邮件)?我按照这个教程去,它描述了如何authResult['code']通过 Javascript获取。
没关系,我有。我通过 Ajax 将它发送到服务器,但我不知道如何通过 PHP BUT 获取用户数据,如姓名和电子邮件,而无需任何重定向。以下是 Javascript 代码示例:
function googleStart()
{
console.log('googleStart');
gapi.load('auth2', function()
{
auth2 = gapi.auth2.init({
client_id: '811214467813-v3fmui5dfghte5m0kmohsf6dl11ori3tg.apps.googleusercontent.com',
// Scopes to request in addition to 'profile' and 'email'
fetch_basic_profile: false,
scope: 'profile email'
});
});
}
function googleSignIn(authResult)
{
console.log(authResult);
if (authResult['code']) {
console.log(authResult);
// Hide the sign-in button now that the user is authorized, for example:
$('#signinButton').attr('style', 'display: none');
// Send the code to the server
$.ajax({
type: 'POST',
url : "{link :Signgoogle:in}",
accepts : 'json',
// Spýta? sa na DJPW ?o to tu je zakomentované
//contentType: 'application/octet-stream; charset=utf-8',
//processData: false,
data : {
'code' : authResult['code'],
'id_token' : authResult.getAuthResponse().id_token
},
...
Run Code Online (Sandbox Code Playgroud)
PHP:
public function actionIn()
{
$code = $_POST['code'];
$client = new \Google_Client();
$client->setClientId(self::APP_ID);
$client->setClientSecret(self::APP_SECRET);
$client->setRedirectUri(self::REDIRECT_URI);
$client->authenticate($code);
$access_token = $client->getAccessToken();
$client->setAccessToken($access_token);
$client->getAuth();
$data = $access_token;
if($data)
{
$this->sendJson(array($data));
}
else
{
$data = array('error' => '$client->verifyIdToken($id) sko?il chybou.');
$this->sendJson($data);
}
}
....
Run Code Online (Sandbox Code Playgroud)
PHP 检索一个access_token但没有用户数据。当然,这是一个 ajax 调用,所以我不能像谷歌在每个页面上描述的那样进行任何重定向。你能帮我吗,我找不到任何解决方案。
非常感谢。
如果您不使用谷歌客户端库,您可以使用此 google api 要获取客户端详细信息,您只需将令牌传递给此 api https://www.googleapis.com/oauth2/v3/tokeninfo?id_token= < your_token >
$response = file_get_contents ( 'https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=' . $_REQUEST['token'] );
$response = json_decode ( $response );
echo "<pre>";
print_r ( $response );
echo "</pre>";
Run Code Online (Sandbox Code Playgroud)
这将验证用户并返回对象
stdClass Object
(
[iss] => accounts.google.com
[at_hash] => hE0R********nxg
[aud] => 79*********************p.apps.googleusercontent.com
[sub] => 1028*****2
[email_verified] => true
[azp] => 7945823****p.apps.googleusercontent.com
[email] => bik***@gmail.com
[iat] => 14***7
[exp] => 1***07
[name] => Bik****M
[picture] => https://lh6.googleusercontent.com/-W8cA***/photo.jpg
[given_name] => Bike***
[family_name] => M
[locale] => en
[alg] => RS256
[kid] => 70f6c4267*******cb
)
Run Code Online (Sandbox Code Playgroud)
在这里找到一个例子:http ://wiki.workassis.com/implementing-google-sign-in-for-websites