Skip to content

Instantly share code, notes, and snippets.

@HakamRaza
Last active December 21, 2022 08:11
Show Gist options
  • Save HakamRaza/71dc6a6a2e943ec0ad7669c5b380a497 to your computer and use it in GitHub Desktop.
Save HakamRaza/71dc6a6a2e943ec0ad7669c5b380a497 to your computer and use it in GitHub Desktop.
Google API Oauth Access Token (Laravel PHP)
<?php
# composer require firebase/php-jwt
use Firebase\JWT\JWT;
use Illuminate\Support\Facades\Http;
class GoogleOauthHelper
{
/**
* JSON file downloaded when creating Google Cloud Service Account
* at https://console.cloud.google.com/apis/credentials?project=
*
* @var string
*/
protected $credentialFilePath;
/**
*
*/
public function __construct()
{
// eg: "google_service_account.json" if located at base path
$this->credentialFilePath = config('services.google.credential_file_path');
}
/**
* Create OAuth JWT Token
* Maximum validity is 1 Hour
*
*/
private function createJWTToken($validSeconds = 3600)
{
if($validSeconds > 3600) {
throw new Exception('Valid JWT period cannot more than 1 Hour.');
}
$iat = time();
$exp = $iat + $validSeconds;
$content = file_get_contents($this->credentialFilePath);
$jsonObj = json_decode($content);
$payload = [
"iss" => $jsonObj->client_email, // eg: "xxxxxxxxxxxxxxxxx.iam.gserviceaccount.com",
"aud" => $jsonObj->token_uri, // eg: "https://oauth2.googleapis.com/token"
"scope" => "xxxxxxxxxxxxx" // eg: 'https://www.googleapis.com/auth/firebase.messaging' for Cloud Messaging
'iat' => $iat,
'exp' => $exp
];
return JWT::encode(
$payload,
$jsonObj->private_key, // eg: "-----BEGIN PRIVATE KEY----- .........",
"RS256"
);
}
/**
* Fetch API access token
*/
public function getAccessToken(): string
{
$jwtToken = $this->createJWTToken();
$res = Http::asForm()
->post('https://oauth2.googleapis.com/token', [
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion' => $jwtToken
]);
if($res->successful()) {
/**
* Sometimes, trailing dots returned, need trim
* https://stackoverflow.com/questions/68654502/why-am-i-getting-a-jwt-with-a-bunch-of-periods-dots-back-from-google-oauth
*
*/
$body = $res->json();
return rtrim($body["access_token"], '.');
}
throw new Exception('Failed to fetch access token. Body: ' . $res->body());
}
}
<?php
namespace App\Http\Controllers;
use App\Helpers\GoogleOauthHelper;
class SomeController extends Controller
{
$helper = new GoogleOauthHelper;
return $helper->getAccessToken();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment