使用 JSON 密钥使用 PHP curl 访问 GCP 存储桶文件



我是GCP的新手。我有一个将 CSV 文件输出到 GCP 云存储的函数。我正在尝试使用 PHP 访问该文件。

到目前为止我做了什么:

  1. 我使用 GCP IAM 创建了一个服务帐户,并授予其作为存储对象查看器的访问权限。

  2. 我还从 IAM 获得了 json 密钥。

我需要在我的 PHP 脚本(托管在不同的 Web 服务器上(中使用哪些命令来使用 CURL 检索文件以及如何使用 json 身份验证密钥?

如果这是在某处的文档中,我提前道歉,我发现它非常复杂且令人不知所措。任何建议或指示不胜感激。


更新:

根据下面的评论,这里是我找到的google-cloud-php github的链接。我不确定这是否是最好的开始资源。

您可以使用适用于 php 的云存储库,更具体地说,如何下载对象。

首先,您必须获得一个用于身份验证的访问令牌。为此,您需要 json 身份验证密钥。

这个页面对我有很大帮助: https://www.it-swarm.dev/de/curl/wie-kann-man-mit-curl-eine-verbindung-zum-google-drive-api-herstellen/806069468/

也许这个PHP代码对你有所帮助:

function get_Google_accesstoken($scope,$credfile,$proxy,$timetoexpiration){
#Developers Info at developers.google.com/identity/protocols/oauth2/service-account
$GoogleApiKeyInfo=GoogleApiKeyInfo($credfile);
$Header=array();
$Header["alg"]="RS256";
$Header["typ"]="JWT";
$ClaimSet["iss"]=$GoogleApiKeyInfo["client_email"];
$ClaimSet["scope"]=$scope;
$ClaimSet["aud"]=$GoogleApiKeyInfo["token_uri"];
$ClaimSet["iat"]=time();
$ClaimSet["exp"]=$ClaimSet["iat"]+($timetoexpiration);
$Jws=base64_encode(json_encode($Header)).".".base64_encode(json_encode($ClaimSet));
$OpenSslRslts=openssl_sign($Jws,$Signature,$GoogleApiKeyInfo["private_key"],OPENSSL_ALGO_SHA256);
$Jwt=$Jws.".".base64_encode($Signature);
$SendVars=array();
$SendVars["grant_type"]=("urn:ietf:params:oauth:grant-type:jwt-bearer");
$SendVars["assertion"]=$Jwt;
$SendVars=http_build_query($SendVars);


$ch=curl_init();

curl_setopt($ch, CURLOPT_URL, $GoogleApiKeyInfo["token_uri"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $SendVars);
$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
if (curl_errno($ch)){
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
$response=json_decode($response);
return $response;
}

您可以在 developers.google.com/identity/protocols/oauth2/scopes 中找到$scope提示 $proxy仅在您需要代理且$timetoexpiration没有影响时使用,因为您的访问令牌始终有效 60 分钟

最新更新