Google oAuth:redirect_uri_mismatch - php

尝试从Google获取oAuth令牌时,我们收到“ redirect_uri_mismatch”错误:

[client 127.0.0.1:49892] {\n  "error" : "redirect_uri_mismatch"\n}, referer: `http://localhost/oAuth/chess-login.html`

使用了两个文件:chess-login.html和plus.php(下面的代码)。

Google API具有以下URI:

http://localhost/oAuth/chess-login.html

谁能指出解决方案?

plus.php:

<?php

    $client_id = "XXX.apps.googleusercontent.com"; //your client id
    $client_secret = "XXX"; //your client secret
    $redirect_uri = "http://localhost/chess-login.html";
    $scope = "https://www.googleapis.com/auth/plus.login"; //google scope to access
    $state = "profile"; //optional
    $access_type = "offline"; //optional - allows for retrieval of refresh_token for offline access

    if(isset($_POST['results'])){
        $_SESSION['accessToken'] = get_oauth2_token($_POST['results']);
    }

    //returns session token for calls to API using oauth 2.0
    function get_oauth2_token($code) {
        global $client_id;
        global $client_secret;
        global $redirect_uri;

        $oauth2token_url = "https://accounts.google.com/o/oauth2/token";
        $clienttoken_post = array(
        "code" => $code,
        "client_id" => $client_id,
        "client_secret" => $client_secret,
        "redirect_uri" => $redirect_uri,
        "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($curl, CURLOPT_RETURNTRANSFER, 1);

        $json_response = curl_exec($curl);
        error_log($json_response);
        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;
    }
?>

Chess-login.html:

<!DOCTYPE html>
<html>

<html itemscope itemtype="http://schema.org/Article">
<head>
  <!-- BEGIN Pre-requisites -->
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  
  <script type="text/javascript">
    (function () {
      var po = document.createElement('script');
      po.type = 'text/javascript';
      po.async = true;
      po.src = 'https://plus.google.com/js/client:plusone.js?onload=start';
      var s = document.getElementsByTagName('script')[0];
      s.parentNode.insertBefore(po, s);
    })();
  </script>
  <!-- END Pre-requisites -->
</head>


<body>

<div id="signinButton">
  <span class="g-signin"
    data-scope="https://www.googleapis.com/auth/plus.login"
    data-clientid="XXX.apps.googleusercontent.com"
    data-redirecturi="postmessage"
    data-accesstype="offline"
    data-cookiepolicy="single_host_origin"
    data-callback="signInCallback">
  </span>
</div>
<div id="result"></div>

<p id="onSignInText"></p>

</body>

<!-- Last part of BODY element in file index.html -->
<script type="text/javascript">
function signInCallback(authResult) {

  if (authResult['code']) {

    // Hide the sign-in button now that the user is authorized, for example:
    $('#signinButton').attr('style', 'display: none');
    //document.getElementById("onSignInText").innerHTML = "Sign in successful";

    $.post("plus.php", {results: authResult['code']},
        function(data){alert(data); });


    // Send the code to the server
    $.ajax({
      type: 'POST',
      url: 'plus.php?storeToken',
      contentType: 'application/octet-stream; charset=utf-8',
      success: function(result) {
        // Handle or verify the server response if necessary.

        // Prints the list of people that the user has allowed the app to know
        // to the console.
        console.log(result);
        if (result['profile'] && result['people']){
          $('#results').html('Hello ' + result['profile']['displayName'] + '. You successfully made a server side call to people.get and people.list');
        } else {
          $('#results').html('Failed to make a server-side call. Check your configuration and console.');
        }
      },
      processData: false,
      data: authResult['code']
    });



  } else if (authResult['error']) {
    // There was an error.
    // Possible error codes:
    //   "access_denied" - User denied access to your app
    //   "immediate_failed" - Could not automatially log in the user
    // console.log('There was an error: ' + authResult['error']);
  }
}
</script>


</html>

参考方案

您应该在服务器中设置redirect_uri使其与客户端中的data-redirecturi="postmessage"相匹配(您的流程不需要重定向,因此不会使用Google API控制台中的值...)

. . .
$clienttoken_post = array(
  "code" => $code,
  "client_id" => $client_id,
  "client_secret" => $client_secret,
  "redirect_uri" => "postmessage",  // <== Change here!
  "grant_type" => "authorization_code"
);
. . .

如何从php中获取datatables jQuery插件的json数据 - php

我是PHP的新手,正在尝试使用Datatables jQuery插件。我知道我必须从.php文件中获取数据,然后在数据表中使用它,但是我似乎无法通过ajax将其传递给数据表。我设法从数据库中获取数据,并对其进行json编码,但是后来我不知道如何在我的index.php文件中调用它,并在其中显示它。我究竟做错了什么?这是我的代码:HTML(已编辑): <…

PHP Count数组元素 - php

嗨,有人可以解释为什么这会返回“数组由0个元素组成”。 :$arr = array(1,3,5); $count = count($arr); if ($count = 0) { echo "An array is empty."; } else { echo "An array has $count elements.…

PHP:从函数返回值并直接回显它? - php

这可能是一个愚蠢的问题,但是……的PHPfunction get_info() { $something = "test"; return $something; } html<div class="test"><?php echo get_info(); ?></div> 有没有办…

PHP:将数据从二维数组复制到一维数组的最快方法 - php

我有一个巨大的二维PHP数组,带有500万行。$t = [ [ "id" => 1, "name" => "foo" ], [ "id" => 2, "name" => "bar" ] ]; 现在,我必须将此数组的I…

php-printf和sprintf具有不同的输出 - php

我编写了以下微型php程序来测试printf和sprintf:<?php $str_1 = printf("%x%x%x", 65, 127, 245); $str_2 = sprintf("%x%x%x", 65, 127, 245); echo $str_1 . "\n"; echo $s…