php - Twitter API 错误 "Missing required parameter: grant_type"使用 Unirest.io

标签 php twitter-oauth unirest

我正在尝试使用 Unirest.io PHP 从 Twitter 获取 API token 。我的代码如下:

[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")

);

我从推特上得到的是:

{
 errors: [
 {
 code: 170,
 label: "forbidden_missing_parameter",
 message: "Missing required parameter: grant_type"
  }
 ]
 }

据我了解,它要求请求的“主体”包含“grant_type”:“client_credentials”,我认为这包含在上面的unirest请求中,但显然不是这样。有任何帮助或意见吗?

最佳答案

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

关于php - Twitter API 错误 "Missing required parameter: grant_type"使用 Unirest.io,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24844149/

相关文章:

javascript - 我正在使用 javascript 提交表单,但我无法在 php 页面中获取值

python - mashape python unirest库

php - 需要 mysql_close 和 pg_close 吗?

php - 试图在从 php 脚本发送的短信中获取新行

android - Android 应用程序的 Twitter 登录

grails - Grails 的 Twitter 插件 - 登录失败

python - Ubuntu Box 偶尔使用 Twitter API 浪费时间

java - 用于 Java 的 Unirest

java - 推特授权

php - 如何在不删除并重新安装的情况下解决 MySQL 无法在 MAMP 中启动的问题?