json post to an API using curl in php - php

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

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.

Related

How can I access the json returned in PHP by my Web Api?

I am using the following code to send and retrieve data from my Web API
//data
$data = array("Id_Empresa" => 1);
try {
$ch = curl_init($url);
$data_string = json_encode($data);
if (FALSE === $ch)
throw new Exception('failed to initialize');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
var_dump($data);
$json = json_decode($data);
foreach ($json->msg as $item) {
echo "$item->Nombre, $item->Descripcion" . PHP_EOL;
}
// ...process $output now
} catch(Exception $e) {
trigger_error(sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()),
E_USER_ERROR);
}
this is what I get in response
{"ok":true,"msg":[{"Nombre":"Carnicerias","Descripcion":"Comercio al por menor de carnes rojas","H_Open":"01:00:00","H_Close":"02:00:00"}]}bool(true)
I am trying to access the JSON with the following code (Because it worked for me on a similar request):
$json = json_decode($data);
foreach ($json->msg as $item) {
echo "$item->Nombre, $item->Descripcion" . PHP_EOL;
}
But as you can see the variable $data stopped being a JSON and became a bool(true).
Does anyone know how I can access the JSON msj or why the $data variable changed from JSON to bool?
The return values section of the PHP manual for curl_exec says
Returns true on success or false on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, false on failure.
Maybe it could be more specific - that option must be set to true. See the definition of the option in the curl_setopt documentation:
true to return the transfer as a string of the return value of curl_exec() instead of outputting it directly.
So, you're seeing the JSON response because it's being output directly by curl_exec, then bool(true) because curl_exec has returned true to the $data variable you're dumping.
Set CURLOPT_RETURNTRANSFER to true instead to get what you're expecting.

Json Code Validation Error Curl Post Request

I am getting following JSON output using curl in PHP
CURL:
$request = curl_init("{$config['root']}/api/tickets");
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_POSTFIELDS, json_encode($body));
curl_setopt($request, CURLOPT_TIMEOUT, 30);
add_headers($request);
$response = curl_exec($request);
Function:
function add_headers($request) {
global $config;
$headers = array('Content-Type: application/json');
if (empty($config['accessClient'])) {
curl_setopt($request, CURLOPT_USERPWD, "{$config['user']}:{$config['password']}");
} else {
array_push($headers, "Access-Client-Token: {$config['accessClient']}");
}
curl_setopt($request, CURLOPT_HTTPHEADER, $headers);
}
Output:
"{"amount":"100","description":"A ticket of 100.","payer":null,"successUrl":"http:\/\/localhost\/wordpress5\/ticket-confirmed.php","successWebhook":"http:\/\/localhost\/wordpress5\/ticket-confirmed-webhook.php","cancelUrl":"http:\/\/localhost\/wordpress5\/shop","orderId":"OID-1","expiresAfter":{"amount":1,"field":"hours"},"customValues":{}}"
and curl response is "
"{"Code":"Validation"}"
Developer Console:
Malformed JSON Ouput
Note: Values got from NetBeans Variables.
When I check output from Json validator it gets invalid only because of double quotes in start and end of output that I think is not bad in php when we assign a json output into variable.
Test Cyclos API here. U: demo P: 1234
So it turned out to be an issue with the demo account they provide.
The error validation has this description on their documentation site: Input error. Either a validation error or the maximum allowed items was exceeded
I created a new account and it is working fine, below is the code that i am using:
function add_headers($request) {
global $config;
$headers = array('Content-Type: application/json');
if (true || empty($config['accessClient'])) {
curl_setopt($request, CURLOPT_USERPWD, "geeky:1234");
} else {
array_push($headers, "Access-Client-Token: {$config['accessClient']}");
}
curl_setopt($request, CURLOPT_HTTPHEADER, $headers);
}
$body = '{"amount":"100","description":"A ticket of 100.","payer":null,"successUrl":"http:\/\/localhost\/wordpress5\/ticket-confirmed.php","successWebhook":"http:\/\/localhost\/wordpress5\/ticket-confirmed-webhook.php","cancelUrl":"http:\/\/localhost\/wordpress5\/shop","orderId":"OID-1","expiresAfter":{"amount":1,"field":"hours"},"customValues":{}}';
$request = curl_init("https://demo.cyclos.org/api/tickets");
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_POSTFIELDS, $body);
curl_setopt($request, CURLOPT_TIMEOUT, 30);
add_headers($request);
$response = curl_exec($request);
$response = json_decode($response);
var_dump($response);
I have hardcoded the URL and also changed the username to my demo one.
Thank You.

Issuing with making a post request with php curl

I'm trying to make a post request with php using curl however the json is not getting delivered to the REST API. Here is my code. In the webservice all I get is null value. I'm not sure where I'm going wrong.
$email_json_data = json_encode($email_data);
$header[] = "Content-type: application/json";
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $email_json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
return $response;
Webservice code:
$email_json_data = $this->post('email_json_data');
$email_data = json_decode($email_json_data);
Check PHP: curl_errno
There's probably a problem connecting to the server, and it's probably in one of your $header. To find out more, you need to show (in production, LOG it) the curl error.
In the future, please try to include a complete code sample, rather than just snippets
Code added from PHP: curl_strerror
class CurlAdapter
{
private $api_url = 'www.somewhere.com/api/server.php';
private $error = "";
private function jsonPost($data)
{
// init curl
$ch = curl_init($this->api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl header
$header[] = "Content-type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// build post data
$post_data = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
// execute
if (empty($response = curl_exec($ch)) {
// Check for errors and display the error message
if($errno = curl_errno($ch)) {
$error_message = curl_strerror($errno);
$this->error = "cURL error ({$errno}):\n {$error_message}";
// #todo log curl error
}
}
// Close the handle
curl_close($ch);
return $response;
}
public function post( mixed $data )
{
if (empty($this->jsonPost($data))) {
return $this->error;
}
return $response;
}
}
$ca = new CurlAdapter();
echo $ca->post(['data' => 'testdata']);
Figured out a way to make this work.
Replaced $email_json_data = $this->post('email_json_data');
with $email_json_data = file_get_contents("php://input");

PHP Simple Api post request

Hi there I never develop in php but I have to create a small function to do a post request to my meteor node application. The end point works fine I have been testing it. I am trying to use the post request to get my login token back. Providing username and password it should return json data even it is incorrect it returns json data saying login refused.
It seem noting is happening tho. My return data seems to always be null.
As I said I never really used php nore do I plan on using it much. But here is my code probably very easy mistake to fix.
<?php
$ch = curl_init();
$params = array(
"username" => "apilogin",
"password" => "12345"
);
echo httpPost("http://127.0.0.1:3000/api/login", $params);
function httpPost($url,$params)
{
$postData = http_build_query($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
$output=curl_exec($ch);
// Check for errors
if($output === FALSE){
echo "false";
die(curl_error($ch));
}
// Decode the response
$output = json_decode($response, TRUE);
curl_close($ch);
return $output;
}
?>
change:
$output = json_decode($response, TRUE);
into:
$output = json_decode($output, TRUE);
you never made a variable $response

JSON to PHP Array error

i am having trouble getting a JSON file to a php-array.
i got a json-file as response from an api (request done with curl)
and want to make an array out of it but it won't work.
Here is my code:
<?php
class modExpose{
public static function getFunction($id){
//In my code i am "preparing" the request here
// *********** cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url.$qry_str);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
}
$id = $_GET['id'];
$data = modExpose::getFunction($id);
$array = json_decode($data,true);
print_r($array);
?>
the print_r function only delivers: 1. (same does the var_dump() function).
I also tried adding html_entity_decode() but the problem still remains.
Thank's for helping!
That is probably because the return value of your curl_exec() call is true on success and that is all you are returning from your method.
If you want to get the data that was returned by the curl call, you need to set the CURLOPT_RETURNTRANSFER option:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url.$qry_str);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// Return the result on success
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
// Now response will contain the results of your curl call
$response = curl_exec($ch);
Apart from that I assume you have checked the variables that seem to be undefined in your example code.

Categories