从XMLHttpRequest获取POST数据

时间:2018-08-30 03:12:56

标签: javascript php google-api xmlhttprequest

我正在尝试让Google登录才能在我的网站上运行。
当我手动设置令牌ID时,一切正常,但是我不知道如何从XMLHttpRequest中获取令牌ID。

glogin.js

function onSignIn(googleUser) {
      var profile = googleUser.getBasicProfile();
      var id_token = googleUser.getAuthResponse().id_token;
      console.log('ID: ' + id_token); 
      console.log('Name: ' + profile.getName());
      console.log('Image URL: ' + profile.getImageUrl());
      console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'https://example.com/signup.php');
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.send('idtoken='+id_token);

    }

signup.php

<?php 
require_once 'google-api-php-client/vendor/autoload.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (!empty($_POST["idtoken"]) && $_POST["idtoken"] != NULL) {
        $client = new Google_Client(['client_id' => $CLIENT_ID]);  // Specify the CLIENT_ID of the app that accesses the backend
        $payload = $client->verifyIdToken($_POST["idtoken"]);
    if ($payload) {
        $userid = $payload['sub'];
        echo 'valid';
    } else {
        // Invalid ID token
        echo 'invalid';
    }
    }
}
?>

1 个答案:

答案 0 :(得分:0)

function onSignIn(googleUser) {
  var profile = googleUser.getBasicProfile();
  var id_token = googleUser.getAuthResponse().id_token;
  console.log('ID: ' + id_token); 
  console.log('Name: ' + profile.getName());
  console.log('Image URL: ' + profile.getImageUrl());
  console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.

window.location.href = "https://example.com/signup.php?tokenid="+id_token;

}

我放弃了,为什么当我可以这样做的时候甚至还浪费我的XMLHttpRequest时间。