@Joyce,
Thank you for your response!
Yes, I am using a Web App flow.
First, I generated OAuth Credentials as "Other" type and used the sample code from GitHub on my localhost. Worked fine! I could authorise with different users. When I uploaded it did not work, got URI Mismatch error.
So then I created a OAuth Credentials as explained here and used Authorised redirect URIs with my domain (ie. www.domain.com/app/oauth) . This time the code from the sample (pasting below) does not redirect my to User Consent Screen at all. Therefore there is no refresh_token in $authToken.
P.S: This code snippet works perfectly on my localhost if I use this combination;
1.OAuth Client ID Type : "Other"
Then I am redirected to consent screen and get a refresh token.
When I change the redirectUri and upload to my server, it does not work.
Also;
1.OAuth Client ID Type : "Web Application"
I am not redirected to Consent Screen, therefore do not have a refresh_token.
use Google\Auth\OAuth2;
session_start();
$oauth2 = new OAuth2([
'authorizationUri' => 'https://accounts.google.com/o/oauth2/v2/auth',
'tokenCredentialUri' => 'https://www.googleapis.com/oauth2/v4/token',
'redirectUri' => '****',
'clientId' => '****',
'clientSecret' => '****',
'scope' => '****'
]);
if (!isset($_GET['code'])) {
// Create a 'state' token to prevent request forgery.
// Store it in the session for later validation.
$oauth2->setState(sha1(openssl_random_pseudo_bytes(1024)));
$_SESSION['oauth2state'] = $oauth2->getState();
// Redirect the user to the authorization URL.
$config = [
// Set to 'offline' if you require offline access.
'access_type' => 'online'
];
header('Location: ' . $oauth2->buildFullAuthorizationUri($config));
exit;
}elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
exit('Invalid state.');
} else {
$oauth2->setCode($_GET['code']);
$authToken = $oauth2->fetchAuthToken();
// Store the refresh token for your user in your local storage if you
// requested offline access.
$refreshToken = $authToken['refresh_token'];
}