【发布时间】:2021-03-30 06:49:56
【问题描述】:
我正在关注 23andMe API authentication guidelines 并使用此代码将我的用户发送到 23andMe 进行身份验证和授权:
<?php
function base64url_encode($data)
{
$b64 = base64_encode($data);
if ($b64 === false) {
return false;
}
$url = strtr($b64, '+/', '-_');
return rtrim($url, '=');
}
$client_id = 'xxx';
$redirect_uri = 'https://customURL';
// this is needed for custom redirect scheme
$code_verifier = 'yyy';
$hash = hash('sha256', $code_verifier);
$code_challenge = base64url_encode(pack('H*', $hash));
header("Location: https://api.23andme.com/authorize/"
. "?redirect_uri=$redirect_uri"
. "&response_type=code"
. "&client_id=$client_id"
. "&scope=basic"
. "&code_challenge=$code_challenge");
?>
使用 Chrome DevTools 可以看到,一旦访问上述页面,就会获取以下 3 个 URL,并且用户授权访问:
https://auth.23andme.com/authorize/?scope=openid&response_type=code&client_id=api&redirect_uri=https%3A%2F%2Fapi.23andme.com%2Foauth_callback%2F
https://api.23andme.com/oauth_callback/?code=30edd45deb5f42d4bb7bd8413866cfc5&state=
https://api.23andme.com/authorize/?response_type=code&client_id=xxx&redirect_uri=https://customURL&scope=basic&code_challenge=wAYGGEPHpGhaG1gZTmyJ8M1Ly7JlGuoUVWBBVJ4OxTU
所以我可以看到代码参数已经生成(在这种情况下,给定值30edd45deb5f42d4bb7bd8413866。这个值应该给下面的代码(如$_GET["code"])但它会导致500错误:
<?php
$code = htmlspecialchars($_GET["code"]);
$code_verifier = 'yyy';
$post_field_array = array(
'client_id' => 'xxx',
'client_secret' => 'zzz',
'grant_type' => 'authorization_code',
'code' => $code,
'redirect_uri' => 'https://customURL',
'scope' => 'basic',
'code_verifier' => $code_verifier);
// Encode the field values for HTTP.
$post_fields = '';
foreach ($post_field_array as $key => $value)
$post_fields .= "$key=" . urlencode($value) . '&';
$post_fields = rtrim($post_fields, '&');
// Use cURL to get the JSON response from 23andMe.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.23andme.com/token/');
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_POST, count($post_field_array));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$encoded_json = curl_exec($ch);
$response = json_decode($encoded_json, true);
$access_token = $response['access_token'];
//show
print_r($encoded_json);
echo $access_token;
?>
现在 500 的响应是:
https://api.23andme.com/authorize_check?response_type=code&client_id=xxx&redirect_uri=https%3A%2F%2FcustomURL&scope=basic&select_profile=false
感谢任何有关故障排除的建议。
【问题讨论】:
-
我会先用 Curl 亲自测试一下。如果我查看示例(不知道此 api),我会看到在范围内给出了一个额外的参数(rs3094315)。文档中提到了这一点。 (api.23andme.com/docs/authentication) 和 (api.23andme.com/docs/authentication/#scopes)
-
谢谢 - 但除了确定要授予的权限外,范围似乎不会影响功能,例如,如果范围设置为“scope=rs3094315”,则权限页面仅请求访问该特定权限单核苷酸多态性
-
嗨 - 乍一看你在这一行缺少一个“=” $access_token $response['access_token'];应该是 $access_token=$response['access_token'];
-
感谢您接受这个!但似乎问题出在进程的早期 - 因为没有设置代码参数
-
也许是一个愚蠢的问题,但我不清楚
500错误发生在哪里 - 在您这边,还是在https://api.23andme.com/?如果这是你的结局,你的 Apache 和 PHP 日志说什么?
标签: php php-curl 23andme-api