Reputation: 77
i have this question, i try to send a request to one API, this APPI expect an application/json so i first test in postman to see the results and works as i expected, but in my code no, next my code, public function myfunctiion()
{ $req = '{ "myparams": myvalues, "myparams": myvalues, "myparams": myvalues, "myparams": { "myparams": myvalues, "myparams": "myvalues", "myparams": "myvalues", "myparams": myvalues }'; $jsonRequest = json_decode($req, TRUE); ;
try{
self::setWsdl('API url');
$context =[
'Content-Type: application/json',
'Accept: application/json',
];
self::setContext($context);
self::setRequest($jsonRequest);
return InstanceCurlClient::curlClientInit();
} catch(\Exception $error){
return $error->getMessage();
}
}
and y let my curl config
public static function curlClientInit(){
try{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL, self::getWsdl());
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, self::getContext());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POSTFIELDS, self::getRequest());
$response = curl_exec($ch);
return $response;
}catch(\Exception $error) {
if (empty($response)) {
throw new SoapFault('CURL error: '.curl_error($ch), curl_errno($ch));
}
}
curl_close($ch);
}
so my result if i test this return to me a 0 and i expect this error { "error": "Credenciales no válidas" } and if past an asociative array instance a json and i use json_enconde so return false and i dont now why cause if do the same in postman i give the error cuse i expected
Upvotes: 0
Views: 92
Reputation: 146
It is correct to use json_encode instead of putting in an array for the CURL_POSTFIELDS if you are accessing a JSON api.
The built-in json_encode function often fails to encode a data, if you did not set the proper $options flag for the data. This is quite annoying actually.
When it returns false, you can call json_last_error_msg()
to learn the reason why it cannot encode your data. That would hopefully let us dig more into the problem.
Upvotes: 1