我正在尝试使用Unirest.io PHP从Twitter获取API令牌。我的代码如下:
[in PHP]
$response = Unirest::post("https://api.twitter.com//oauth2/token",
array(
"Authorization" => "Basic [AUTH_KEY]",
"Content-Type" => "application/x-www-form-urlencoded;charset=UTF-8"
),
array("grant_type" => "client_credentials")
);
我从Twitter获得的是:
{
errors: [
{
code: 170,
label: "forbidden_missing_parameter",
message: "Missing required parameter: grant_type"
}
]
}
据我了解,它要求请求的“正文”包含“grant_type”:“client_credentials”,我认为它包含在上面的unirest请求中,但显然情况并非如此。任何帮助或评论?
答案 0 :(得分:0)
这种情况来得太晚了,但未来可能会帮助其他人。刚才有这个问题,但这是我如何解决它。我基本上将“grant_type”作为字符串而不是像这样的数组传递
$uri = "https://api.twitter.com/oauth2/token";
$headers = [
"Authorization: Basic ".XXXXXXX,
"Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
];
$verb = "POST";
//here is where i replaced the value of body with a string instead of an array
$body = 'grant_type=client_credentials';
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $verb);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLINFO_HTTP_CODE, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
$result = curl_exec($ch);
$response = json_decode($result);
它以twitter记录的方式返回了预期的结果。