PHP Curl sent wrong Content
I am trying to sent a Post Request to VendHQ Api using oauth2 auth method. I've the correct code, client_id, client_secret etc as It work fine in Postman but when I try to sent the same data using PHP curl, I get the error:
Error
'error' => string 'invalid_request' (length=15)
'error_description' => string 'The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Check the "grant_type" parameter.' (length=179)
This is the documentation of Requesting Access Token and this is my code which is trying to get the access token.
PHP Code:
$prefix = $vend[0]['domain_prefix'];
$request_url = 'https://'.$prefix.'.vendhq.com/api/1.0/token';
$body['code'] = $vend[0]['code'];;
$body['client_id'] = $vend[0]['app_id'];;
$body['client_secret'] = $vend[0]['app_secret'];;
$body['grant_type'] = 'authorization_code';
$body['redirect_uri'] = $vend[0]['redirect_uri'];;
$response = $this->invoke($request_url, 'POST', $body);
Invoke function
private function invoke($url, $method, $data = null)
{
$ch = curl_init($url);
if($method=='POST'){
if(isset($data)){
$data_string = json_encode($data);
}
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
$headers = array();
$headers[] = "Content-Type: application/x-www-form-urlencoded;charset=UTF-8";
$headers[] = 'Content-Length: '.strlen($data_string);
echo '<br>Curl Headers';
var_dump($headers);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}//END POST
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
$info = curl_getinfo($ch);
echo '<pre>Curl Info<br>';
var_dump($info);
echo '</pre>';
curl_close($ch);
$json_output = json_decode($json, true);
return $json_output;
}//end function
I believe I am sending everything fine but the curl is sending but from curl info I get this
'content_type' => string 'application/json; charset=UTF-8' (length=31)
But VendAPI Documentation says to send post data as "application/x-www-form-urlencoded" .
NOTE Those parameters should be sent as “application/x-www-form-urlencoded” encoded body of a POST request
What I am doing wrong?
Solved the problem after posting the question here.
The problem is, I am trying to post the data with application/x-www-form-urlencode
content type but I was sending data in json format. I've removed this lines from invoke function
if(isset($data)){
$data_string = json_encode($data);
}
and set curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
and except creating a $body
array, I've created string:
$body = 'code='.$vend[0]['code'];
$body .= '&client_id='.$vend[0]['app_id'];
$body .= '&client_secret='.$vend[0]['app_secret'];
$body .= '&grant_type=authorization_code';
$body .= '&redirect_uri='.$vend[0]['redirect_uri'];
All worked fine :)
链接地址: http://www.djcxy.com/p/48874.html上一篇: PHP CURL不能设置内容
下一篇: PHP Curl发送错误的内容