3

I am trying to obtain an API token from Twitter using Unirest.io PHP. My code is as follows:

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

);

What I get from Twitter is:

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

As I understand it, it requires the "body" of the request to contain "grant_type":"client_credentials", which I thought is included in the unirest request above, but apparently this is not the case. Any help or comments?

Nixlim
  • 31
  • 2
  • Why are you putting it in a separate array? – Charlie Jul 19 '14 at 19:37
  • Well, the Unirest syntax for a POST request is: Unirest::post($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL) And Twitter API requires grant_type to be in body of the request. I have tried using it in the headers array as well and the error message is the same. – Nixlim Jul 19 '14 at 21:21

1 Answers1

1

This is coming really late but might help someone else in the future. Had this issue a while ago, but here is how I fixed it. I basically passed the "grant_type" as a string instead of an array like so

$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);

it returned the expected result as twitter documented.