我有一个服务帐户。
我写了一个PHP脚本来接收一个token:
<?php
require_once 'JWT_1.php';
require_once 'JWT_KEY_1.php';
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
$privateKey = <<<EOD
-----BEGIN PRIVATE KEY-----
someKey
-----END PRIVATE KEY-----
EOD;
$publicKey = <<<EOD
-----BEGIN PUBLIC KEY-----
someKey
-----END PUBLIC KEY-----
EOD;
$payload = array(
"iss" => "myName@name.iam.gserviceaccount.com",
"scope" => "https://www.googleapis.com/auth/postmaster.readonly",
"aud" => "https://oauth2.googleapis.com/token",
"exp" => (time() + 600),
"iat" => time()
);
$jwt = JWT::encode($payload, $privateKey, 'RS256');
$urlToken = 'https://oauth2.googleapis.com/token';
$url = 'https://gmailpostmastertools.googleapis.com/v1/domains';
$payloadToken = array(
"grant_type" => "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion" => $jwt
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $urlToken);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payloadToken);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$tokenAnswer = json_decode(curl_exec($ch), true);
$token = $tokenAnswer['access_token'];
curl_close($ch);
$ch = curl_init();
$headers = array(
'Authorization: Bearer ' . $token,
'Accept: application/json'
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING , "");
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
echo curl_exec($ch);
当尝试获取域列表https://gmailpostmastertools.googleapis.com/v1/domains时,响应是一个空数组。
与此同时,如果我对该方法进行测试检查,我会得到一个列表:https://i.imgur.com/XqgtnHV.png
有什么问题吗?
2条答案
按热度按时间guykilcj1#
你用了两个不同的身份。只有其中一个身份将获取域列表。您正在使用服务帐户进行身份验证。域注册到用户的身份。由于服务帐户没有注册域,因此列表为空。
解决方案是使用用户的身份来授权此API调用。这意味着使用Google OAuth 2.0
Postmaster Tools API声明:
对Postmaster Tools API的所有请求都必须由经过身份验证的用户授权。
Authorizing requests with OAuth 2.0
jm81lzqq2#
管理用户-> adduser(+)->输入您的服务帐户电子邮件