Войти через Google, выбрасывая invalid_grant - PullRequest
0 голосов
/ 24 сентября 2019

Вход в Google с помощью Google+ API не работает на сервере, но работает правильно на локальном хосте.

он не перенаправляет на файл domains.php после аутентификации.получение приведенного ниже URL-адреса в панели браузера.

site.com/domains/domains.php?code=4%2FsrQHdwzRfgdf4isoIuxgfddgRvhgfdfg0WbQ6eV5gfyj7I8ER

Ошибка: неустранимая ошибка: Uncaught/login_with_google/src/auth/Google_OAuth2.php

Кто-нибудь подскажет мне решение.

Ниже приведен код:

<?php
//Include GP config file && User class
include_once 'gpConfig.php';
include_once 'User.php';

if(isset($_GET['code'])){
    $gClient->authenticate($_GET['code']);
    $_SESSION['token'] = $gClient->getAccessToken();
    header('Location: ' . filter_var($redirectURL, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['token'])) {
    $gClient->setAccessToken($_SESSION['token']);
}

if ($gClient->getAccessToken()) {
    //Get user profile data from google
    $gpUserProfile = $google_oauthV2->userinfo->get();

    //Initialize User class
    $user = new User();

    //Insert or update user data to the database
    $gpUserData = array(
        'oauth_provider'=> 'google',
        'oauth_uid'     => $gpUserProfile['id'],
        'first_name'    => $gpUserProfile['given_name'],
        'last_name'     => $gpUserProfile['family_name'],
        'email'         => $gpUserProfile['email'],
        'picture'       => $gpUserProfile['picture'],
    );
    $userData = $user->checkUser($gpUserData);

    //Storing user data into session
    $_SESSION['userData'] = $userData;

    //Render facebook profile data
    // if(!empty($userData)){
    //     $output = '<h1>Google+ Profile Details </h1>';
    //     $output .= '<img src="'.$userData['picture'].'" width="300" height="220">';
    //     $output .= '<br/>Google ID : ' . $userData['oauth_uid'];
    //     $output .= '<br/>Name : ' . $userData['first_name'].' '.$userData['last_name'];
    //     $output .= '<br/>Email : ' . $userData['email'];
    //     $output .= '<br/>Logged in with : Google';
    //     $output .= '<br/>Logout from <a href="logout.php">Google</a>'; 
    // }else{
    //     $output = '<h3 style="color:red">Some problem occurred, please try again.</h3>';
    // }
} else {
    $authUrl = $gClient->createAuthUrl();
    $output = '<a href="'.filter_var($authUrl, FILTER_SANITIZE_URL).'"><img src="images/glogin.png" alt=""/></a>';
    echo $output;
}
?>

1 Ответ

0 голосов
/ 24 сентября 2019

Я не могу сказать вам, почему он не работает только на сервере.Это должно произойти сбой каждый раз, когда вы пытаетесь получить новый токен доступа.Вы отправляете токен доступа в getAccesstoken (). Вам необходимо отправить токен обновления

токен обновления для обновления.

function getOauth2Client() {
try {

    $client = buildClient();

    // Set the refresh token on the client. 
    if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
        $client->refreshToken($_SESSION['refresh_token']);
    }

    // If the user has already authorized this app then get an access token
    // else redirect to ask the user to authorize access to Google Analytics.
    if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {

        // Set the access token on the client.
        $client->setAccessToken($_SESSION['access_token']);                 

        // Refresh the access token if it's expired.
        if ($client->isAccessTokenExpired()) {              
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            $client->setAccessToken($client->getAccessToken()); 
            $_SESSION['access_token'] = $client->getAccessToken();              
        }           
        return $client; 
    } else {
        // We do not have access request access.
        header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
    }
} catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
}
}

создать клиента

$client = buildClient();
$client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
// Add access token and refresh token to seession.
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['refresh_token'] = $client->getRefreshToken();    
//Redirect back to main script
$redirect_uri = str_replace("oauth2callback.php",$_SESSION['mainScript'],$client->getRedirectUri());    
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));

Пример кода здесь Google-APIs-PHP-Samples

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...