我正在尝试验证我从重定向 Uri 上的“使用 Apple 登录”服务获得的代码。我使用文档中的信息来创建发布数据并生成“client_secret”。
我得到的回应是:{"error":"invalid_client"}
。
我生成“client_secret”的函数可以在下面找到:
function encode($data) {
$encoded = strtr(base64_encode($data), '+/', '-_');
return rtrim($encoded, '=');
}
function generateJWT($kid, $iss, $sub, $key) {
$header = [
'alg' => 'ES256',
'kid' => $kid
];
$body = [
'iss' => $iss,
'iat' => time(),
'exp' => time() + 3600,
'aud' => 'https://appleid.apple.com',
'sub' => $sub
];
$privKey = openssl_pkey_get_private($key);
if (!$privKey) return false;
$payload = encode(json_encode($header)).'.'.encode(json_encode($body));
$signature = '';
$success = openssl_sign($payloads, $signature, $privKey, OPENSSL_ALGO_SHA256);
if (!$success) return false;
return $payload.'.'.encode($signature);
}
我在这个例子中的变量:
$kid是我的私钥标识符。在本例中为 JYJ5GS7N9K。我从这里得到了标识符https://developer.apple.com/account/resources/authkeys/list
$iss是我的开发者帐户中的团队标识符。在本例中,它是 WGL33ABCD6。
$sub与“client_id”的值相同。在这个例子中我的“client_id”是“dev.hanashi.sign-in-with-apple”。我从这里的应用标识符中获取了客户端 ID:https ://developer.apple.com/account/resources/identifiers/list
$key是我由开发者帐户生成的私钥。密钥的格式如下:
-----BEGIN PRIVATE KEY-----
myrandomgeneratedkeybyappledeveloperaccount
-----END PRIVATE KEY-----
这是发出请求的 php 代码:
$key = <<<EOD
-----BEGIN PRIVATE KEY-----
myrandomgeneratedkeybyappledeveloperaccount
-----END PRIVATE KEY-----
EOD; // replaced with correct key
$kid = 'JYJ5GS7N9K'; // identifier for private key
$iss = 'WGL33ABCD6'; // team identifier
$sub = 'dev.hanashi.sign-in-with-apple'; // my app id
$jwt = generateJWT($kid, $iss, $sub, $key);
$data = [
'client_id' => $sub,
'client_secret' => $jwt,
'code' => $_POST['code'],
'grant_type' => 'authorization_code',
'request_uri' => 'https://myurl.tld/redirect.php'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://appleid.apple.com/auth/token');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6');
$serverOutput = curl_exec($ch);
curl_close ($ch);
echo $serverOutput;
{"error":"invalid_client"}
我现在得到来自苹果服务器的响应。我究竟做错了什么?会不会是我生成错误的 JWT 令牌?