【问题标题】:Twitter API error "Missing required parameter: grant_type" using Unirest.io使用 Unirest.io 的 Twitter API 错误“缺少必需的参数:grant_type”
【发布时间】:2014-09-10 17:19:28
【问题描述】:

我正在尝试使用 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”,我认为它包含在上面的唯一请求中,但显然情况并非如此。有什么帮助或cmets?

【问题讨论】:

  • 你为什么要把它放在一个单独的数组中?
  • 好吧,一个 POST 请求的 Unirest 语法是: Unirest::post($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL) 并且Twitter API 要求 grant_type 在请求的正文中。我也尝试在 headers 数组中使用它,错误消息是一样的。

标签: php twitter-oauth unirest


【解决方案1】:

这来得太晚了,但将来可能会对其他人有所帮助。前段时间有这个问题,但这是我解决它的方法。我基本上将“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 记录的预期结果。

【讨论】:

    猜你喜欢
    • 2012-06-27
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    • 2019-12-11
    相关资源
    最近更新 更多