获取Google Oauth2 JWT签名


首先获取服务账号密钥文件 google-gce.json

use Google\Auth\OAuth2;

require 'vendor/autoload.php';

function getGoogleJWT($scopes, $jsonKey) {
    $jsonKey = json_decode(file_get_contents($jsonKey), true);
    $config = [
        'audience' => 'https://oauth2.googleapis.com/token',
        'issuer' => $jsonKey['client_email'],
        'scope' => $scopes,
        'signingAlgorithm' => 'RS256',
        'signingKey' => $jsonKey['private_key'],
        'sub' => NULL,
        'tokenCredentialUri' => 'https://oauth2.googleapis.com/token'
    ];
    $auth = new OAuth2($config);
    return $auth->toJWT();
}

$scopes = ['https://www.googleapis.com/auth/drive.readonly'];

echo getGoogleJWT($scopes, 'google-gce.json');

然后用 JWT 签名就可以获取 Access Token 密钥,有效期为一小时

function getAccessToken($jwt) {
    $params = ['grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assertion' => $jwt];
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, 'https://oauth2.googleapis.com/token');
    curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
    $data = curl_exec($curl);
    curl_close($curl);
    return $data;
}

$jwt = 'JWT';

echo getAccessToken($jwt);