I need to read and write Google contacts with PHP via Google People API. I connect to a Google account:
function get_google_client( array $params ): Google_Client {
$app_name = $params['application_name'] ?? 'My App';
$creds_file = $params['credentials_file'] ?? 'credentials.json';
$redirect_uri = $params['redirect_uri'] ?? home_url();
$access_type = $params['access_type'] ?? 'offline';
$scopes = $params['scopes'] ?? array(
Google\Service\Oauth2::USERINFO_EMAIL,
Google\Service\PeopleService::USERINFO_PROFILE,
Google\Service\PeopleService::CONTACTS,
Google\Service\PeopleService::CONTACTS_READONLY
);
$state = $params['state'] ?? null;
$client = new Google_Client();
$client->setApplicationName( $app_name );
$client->setAuthConfig( $creds_file );
$client->setRedirectUri( $redirect_uri );
$client->setAccessType( $access_type );
$client->setScopes( $scopes );
if ( $state ) {
$client->setState( $state );
}
return $client;
}
$client = get_google_client( array() );
$token = $_SESSION['google_token'] ?? null;
if ( $token ) {
$client->setAccessToken( $token );
}
if ( $client->isAccessTokenExpired() ) {
if ( $client->getRefreshToken() ) {
$client->fetchAccessTokenWithRefreshToken( $client->getRefreshToken() );
} else {
$auth_code = filter_input( INPUT_GET, 'code', FILTER_SANITIZE_STRING );
if ( $auth_code ) {
$token = $client->fetchAccessTokenWithAuthCode( $auth_code );
$client->setAccessToken( $token );
}
}
}
Authentication works but token expires after 1 hour so I need to refresh it but $client->getRefreshToken() always return null so I can't.
What's wrong?