Google+ javascript/php login api


Google+ javascript/php login api

你能帮我如何使用G+Javascript和PHP登录吗?Javascript运行良好,但当我想在服务器上验证令牌时,它会抛出异常。我按照这一页走:https://developers.google.com/identity/sign-in/web/backend-auth但是只有Java/Python。Javscript代码:

function onSignIn(googleUser)
{
    var id_token = googleUser.getAuthResponse().id_token,
        profile = googleUser.getBasicProfile();
    console.log(id_token);
    $.ajax({
        url : "{link :Signgoogle:in}",
        accepts : 'json',
        type : 'post',
        data : {
            'token' : id_token
        },
...

PHP代码:

public function actionIn()
{
    $token = $_POST['token'];
    $client = new 'Google_Client();
    $client->setScopes('email');
    $client->setApplicationName(self::APP_NAME);
    $client->setDeveloperKey(self::SERVER_KEY);
    $client->setAccessToken($token); // This throws an exception
    $data = $client->verifyIdToken($token)->getAttributes();
...

$client->setAccessToken抛出异常:Could not json decode the token。你能告诉我如何验证用户登录吗?非常感谢。

我遇到了同样的问题,我为您的问题找到了以下解决方案:

auth2.attachClickHandler(element, {},
        function(googleUser) {
            var link = server+"user/google-plus-login"
            console.log(link)
            console.log(googleUser)
            var Name = googleUser['wc']['Ld']
            var mail = googleUser['wc']['wc']
            var image = googleUser['wc']['zt']
            var access_token = googleUser['Ka']['access_token']
        }, function(error) {
            alert(JSON.stringify(error, undefined, 2));
        });

希望这也适用于你!

要获取客户端详细信息,只需将令牌传递给此apihttps://www.googleapis.com/oauth2/v3/tokeninfo?id_token=<your_token>

if (isset ( $_REQUEST['token'] ) && $_REQUEST['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>";
}

在这里找到一个例子:http://wiki.workassis.com/implementing-google-sign-in-for-websites

嘿,原因是您通过ajax传递id_token,而在php中,您在setAccessToken($token)中验证access_token。因此,为了验证和设置access_token,您必须发送access_token以及以下内容:

function onSignIn(googleUser)
{
    var id_token = googleUser.getAuthResponse().id_token,
    var access_token = googleUser.getAuthResponse(true).access_token,
        profile = googleUser.getBasicProfile();
    console.log(id_token);
    $.ajax({
        url : "{link :Signgoogle:in}",
        accepts : 'json',
        type : 'post',
        data : {
            'token' : id_token,
            'access_token' : access_token
        },

在像这样的后端检查中

public function actionIn()
{
    $token = $_POST['token'];
    $access_token = $_POST['access_token'];
    $client = new 'Google_Client();
    $client->setScopes('email');
    $client->setApplicationName(self::APP_NAME);
    $client->setDeveloperKey(self::SERVER_KEY);
    $client->setAccessToken($access_token); // This will not throw exception
    $data = $client->verifyIdToken($token)->getAttributes();
...