T
T
The-TS2020-08-16 15:54:13
Google
The-TS, 2020-08-16 15:54:13

Google OAuth2.0 returns invalid_grant?

Here is my code:
<?php
if (!empty($_GET['code'])) {
  // Отправляем код для получения токена (POST-запрос).
  $params = array(
    'client_id'     => '782016323201-ktsn3*****oogleusercontent.com',
    'client_secret' => 'nbaAc****TIaCpo',
    'redirect_uri'  => 'https://test-server.tsecret.net/AUTH-2/redirect.php',
    'grant_type'    => 'authorization_code',
    'code'          => $_GET['code'],
    'access_type'   => 'offline'
  );
  var_dump($params);

  $ch = curl_init('https://accounts.google.com/o/oauth2/token');
  var_dump($ch);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_HEADER, false);
  $data = curl_exec($ch);
  curl_close($ch);

  $data = json_decode($data, true);
  var_dump($data);
  if (!empty($data['access_token'])) {
    // Токен получили, получаем данные пользователя.
    $params = array(
      'access_token' => $data['access_token'],
      'id_token'     => $data['id_token'],
      'token_type'   => 'Bearer',
      'expires_in'   => 3599
    );

    $info = file_get_contents('https://www.googleapis.com/oauth2/v1/userinfo?' . urldecode(http_build_query($params)));
    $info = json_decode($info, true);
    print_r($info);
  }
}


After this I get an error, how to fix it?
PS
Да, в Google я искал. Как исправить не нашел

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Spartak (Web-StyleStudio), 2020-08-16
@Pyhon3x

curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

Change to
curl_setopt($ch, CURLOPT_POSTFIELDS, urldecode(http_build_query($params)));

And this
$params = array(
      'access_token' => $data['access_token'],
      'id_token'     => $data['id_token'],
      'token_type'   => 'Bearer',
      'expires_in'   => 3599
    );

On this
$params = array('access_token' => $data['access_token']);

* (only a token is needed to get information about a user)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question