PhpTips

Retrieving Access Token using Service Account for PHP without using googleapis

Gists This is a sample PHP script to retrieve the access token from Service Account of Google without using googleapis. Sample script <?php $private_key = "-----BEGIN PRIVATE KEY-----\n###-----END PRIVATE KEY-----\n"; // private_key of JSON file retrieved by creating Service Account $client_email = "###"; // client_email of JSON file retrieved by creating Service Account $scopes = ["https://www.googleapis.com/auth/drive.readonly"]; // Sample scope $url = "https://www.googleapis.com/oauth2/v4/token"; $header = array("alg" => "RS256", "typ" => "JWT"); $now = floor(time()); $claim = array( "iss" => $client_email, "sub" => $client_email, "scope" => implode(" ", $scopes), "aud" => $url, "exp" => (string)($now + 3600), "iat" => (string)$now, ); $signature = base64_encode(json_encode($header, JSON_UNESCAPED_SLASHES)) .