1
<?php

$client_id = "XXXXXXXXX1";
$client_secret = "XXXXXXXXXX2";
$redirect_URI = "XXXXXXXXX3";
$auth_code = htmlspecialchars($_GET["code"]);

$post_field_array = array(
  'client_id'     => $client_id,
  'client_secret' => $client_secret,
  'grant_type'    => 'authorization_code',
  'code'          => $auth_code,
  'redirect_uri'  => $redirect_uri,
  'scope'         => 'basic genomes');

$post_fields = '';
foreach ($post_field_array as $key => $value)
  $post_fields .= "$key=" . urlencode($value) . '&';
$post_fields = rtrim($post_fields, '&');

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.23andme.com/token/');
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'];

print $access_token;
?>

根据 23andMe API ( https://api.23andme.com/docs/authentication/ )的规范,此脚本从与 $redirect_URI 相同的 URL 运行。但是,无论我尝试什么,脚本都不会输出任何内容。我在这里做错了什么?

4

2 回答 2

1

我不知道为什么它不起作用,但我建议您进行一些调试。从...开始

print_r($encoded_json)

(或使用 var_dump)并查看它的输出可能是什么。curl_exec 会失败吗?

尝试将详细标志设置为 curl 并查看是否会引发任何可能将您推向问题的错误(警告)

curl_setopt($ch, CURLOPT_VERBOSE, true);
于 2018-02-11T01:13:35.960 回答
1

首先,我收到这 3 个通知,除非我在查询字符串上传递代码,否则代码不存在,redirect_uri 在两种用途中都有不同的大小写,access_token 可能不存在,因为发生了错误验证

注意:未定义索引:第 6 行 test.php 中的代码

注意:未定义变量:第 13 行 test.php 中的 redirect_uri

注意:未定义索引:第 29 行 test.php 中的 access_token

<?php

$client_id = "XXXXXXXXX1";
$client_secret = "XXXXXXXXXX2";
$redirect_uri = "XXXXXXXXX3";  // FIXED VARIABLE NAMING HERE
$auth_code = htmlspecialchars($_GET["code"]);

$post_field_array = array(
    'client_id'     => $client_id,
    'client_secret' => $client_secret,
    'grant_type'    => 'authorization_code',
    'code'          => $auth_code,
    'redirect_uri'  => $redirect_uri,
    'scope'         => 'basic genomes');

$post_fields = '';
foreach ($post_field_array as $key => $value)
    $post_fields .= "$key=" . urlencode($value) . '&';
$post_fields = rtrim($post_fields, '&');

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.23andme.com/token/');
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);

// DUMP RESPONSE IF ERROR OCCURS, ACCESS WON'T EXIST
var_dump($response);

$access_token = $response['access_token'];

print $access_token;
于 2018-02-11T01:14:19.700 回答