我正在编写一个 PHP Web 程序,它需要访问和编辑 lichess.org 上的人们的信息。他们的 api 使用 Oauth 2.0 来做到这一点。问题是无论我在请求中提出什么,它似乎只请求公共个人资料信息:重定向页面截图。我想我可能错误地格式化了 url,但我不知道是怎么回事,因为示例代码是用 JavaScript 编写的,我对此不太熟悉。这是我用来格式化字符串的代码片段:
$scopes = "email:read%20preference:write";
$state=generate_string(20);
$authorize_url = "https://oauth.lichess.org/oauth/authorize";
function getAuthorizationCode() {
global $authorize_url, $client_id, $callback_uri;
$authorization_redirect_url = $authorize_url . "?response_type=code&client_id=" . $client_id . "&redirect_uri=" . $callback_uri . "&scope=" . $scopes . "&state=".$state;
header("Location: " . $authorization_redirect_url);
}
为了生成状态字符串,我使用了这个辅助函数
function generate_string($strength,$charset='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
$Length = strlen($charset);
$random_string = '';
for($i = 0; $i < $strength; $i++) {
$random_character = $charset[mt_rand(0, $Length - 1)];
$random_string .= $random_character;
}
return $random_string;
}
果然,当我实际尝试请求资源时,响应是“缺少范围”。我在用着:
$lichessurl = "https://lichess.org/api/account/email";
function getAccessToken($authorization_code) {
global $token_url, $client_id, $client_secret, $callback_uri;
$authorization = base64_encode("$client_id:$client_secret");
$header = array("Authorization: Basic {$authorization}","Content-Type: application/x-www-form-urlencoded");
$content = "grant_type=authorization_code&code=$authorization_code&redirect_uri=$callback_uri";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $token_url,
CURLOPT_HTTPHEADER => $header,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $content
));
$response = curl_exec($curl);
curl_close($curl);
if ($response === false) {
echo "Failed";
echo curl_error($curl);
echo "Failed";
} elseif (json_decode($response)->error) {
echo "Error:<br />";
echo $authorization_code;
echo $response;
}
return json_decode($response)->access_token;
}
为了做到这一点。