OAuth返回错误的请求消息

时间:2018-11-06 12:20:34

标签: php

我正在尝试使用OAuth 2.0生成令牌

我将用户重定向到给定的URL, 用户登录,授予权限, 然后将用户返回到我的RETURN_URL

下面是我的RETURN_URL的代码,它给出以下错误:

{"code":400,"status":"Bad Request","timestamp":"2018-11-06T17:41:08+05:30","message":"Bad Request","error":{"reason":"Something wrong in request"}}
$code= $_GET[code];
$url = 'https://api.example.com/index/oauth/token';

$auth = $API_KEY.":".$API_SECRET ;

$header = array();
 $header[] = 'Content-Type: application/json';
 $header[] = 'x-api-key: '.$API_KEY;
 $header[] = 'Authorization: Basic '. base64_encode($auth);

$data = array(
 'code' => $code,
 'grant_type' => 'authorization_code',
 'redirect_uri' => $RETURN_URL
 );


$data = trim(http_build_query($data));

$ch = curl_init($url);
 curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 

 curl_setopt($ch, CURLOPT_POST, 1);
 curl_setopt($ch, CURLOPT_POSTFIELDS, $data );

 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

 //curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
 //curl_setopt($ch, CURLOPT_USERPWD, $API_KEY.":".$API_SECRET );
 //curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
 //curl_setopt($curl, CURLOPT_USERPWD, "$API_KEY:$API_SECRET" );

 curl_setopt($ch, CURLOPT_HEADER, 0);
 $result= curl_exec($ch);
 $error = curl_error($ch);

echo $result; exit;

curl_close($ch);

这是他们的文档对必需参数的说明:

curl \
-u {your_api_key}:{your_api_secret} \
-H 'Content-Type: application/json' \
-H 'x-api-key: {your_api_key}' \
-d '{"code" : "{code_from_login_response}", "grant_type" : "authorization_code", "redirect_uri" : "{your_redirect_uri}"}' \

1 个答案:

答案 0 :(得分:2)

收到400错误请求的原因是,您所命中的API服务器无法理解您发送的$data并对其进行JSON解码。因此,以下步骤可能有助于使用正确的JSON-

发送正确的POST请求
  • $_GET[code]更改为$_GET['code']。它可以在不使用单引号的情况下工作,但是会生成notice of undefined constant 'code'。另外,出于安全原因,您可能希望过滤此数据。
  • 删除$data = trim(http_build_query($data));
  • 将此行curl_setopt($ch, CURLOPT_POSTFIELDS, $data );更改为curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data) );,您应该一切顺利。

据我所知可能发生这种情况的原因是,您击中的API Server可能正在以$json = file_get_contents('php://input');的形式接收JSON数据,有点像Webhook。因此,当您发出请求时,它无法将您的数据解析为JSON,因此向您发送了错误的请求错误。

相关问题