I have a requirement to post a REST call in the following JSON formt. Note the payload variable is XML. I'm using PHP 5 with CURL. Looking for what I'm doing wrong. Thanks
{
"processDefId":"testing~SimpleApplication!1.0~SimpleProcess",
"serviceName":"SimpleProcess.service",
"operation":"start",
"payload":"<payload><formArg><p0:WebForm1 xmlns:p0=\"http://www.frevvo.com/schemas/_N5J6IBUOEeWgf4K8GSSanA\"/></formArg></payload>",
"action":"Submit"
}
Constructed the following but am not getting a response nor seeing anything actioned on the called application.
try {
echo '<br>Curl Start<br>';
echo file_put_contents($log, "Start \n", FILE_APPEND);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,"http://192.168.56.151:7003/bpm/api/3.0/processes");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_FAILONERROR);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json') );
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json') );
curl_setopt($curl, CURLOPT_USERPWD, "jstein:welcome1");
$xml = '<ns1:start xmlns:ns1=\http://xmlns.oracle.com/bpm/webform/formsData/requestTravelAccount\">';
$xml .= '<formArg xmlns:ns2=\"http://www.frevvo.com/schemas/_1g73gMt3EeWsKsy3N_19_Q\">';
$xml .= '<ns2:RequestTravelAccount>';
$xml .= '<EmployeeId>1771</EmployeeId>';
$xml .= '<FirstName>Aaron</FirstName>';
$xml .= '<LastName>Thompson</LastName>';
$xml .= '<PersonId>300000087953021</PersonId>';
$xml .= '</ns2:RequestTravelAccount>';
$xml .= '</formArg>';
$xml .= '</ns1:start>';
$xml_e = htmlspecialchars($xml, ENT_QUOTES);
echo file_put_contents($log, $xml_e ."\n", FILE_APPEND);
$post_data = array(
"processDefId"=>"testing~HCM!1.0~NewEmployeeTravelSetupProcess",
"serviceName"=>"NewEmployeeTravelSetupProcess.service",
"operation"=>"start",
"action"=>"Submit",
"payload" => $xml_e
);
$curl_post_data = json_encode($post_data);
echo file_put_contents($log, "$curl_post_data"."\n", FILE_APPEND);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$curl_response = curl_exec($curl);
echo '<br> CURL_EXEC return: ' . curl_error($curl);
} catch (Exception $e) {
echo 'Caught exception" ',$e->getMessage(), "\n";
}
curl_close($curl);
echo '<br>CURL done';
You are initializing the CURLOPT_HTTPHEADER option twice. Whereas you need to initialize it only once with all headers.
Wrong:
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json') );
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json') ); // resetting above one for this line.
Correct:
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Accept: application/json') );
Related
I'm trying to POST an image on Mastodon (specifically on Humblr) but I cannot get the media_id, the response is null, but I'm not sure where the problem is.
I can publish text, no problem, so the authentication part is fine, I only have the problem with the image, the only difference I can see in the documentation is that "Media file encoded using multipart/form-data".
Here's my code so far...
$headers = ['Authorization: Bearer '.$settings['access_token'] , 'Content-Type: multipart/form-data'];
$mime_type = mime_content_type($urlImage);
$cf = curl_file_create($urlImage,$mime_type,'file');
$media_data = array( "file" => $cf);
$ch_status = curl_init();
curl_setopt($ch_status, CURLOPT_URL, "https://humblr.social/api/v1/media");
curl_setopt($ch_status, CURLOPT_POST, 1);
curl_setopt($ch_status, CURLOPT_POSTFIELDS, $media_data);
curl_setopt($ch_status, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch_status, CURLOPT_HTTPHEADER, $headers);
$media_status = json_decode(curl_exec($ch_status));
echo "Response: ".json_encode($media_status);
From this I want to extract the $media_status-> media_id
I don't really know much about 'multipart/form-data' to be honest.
Am I missing something?
This took some trial and error for me as well. Here's what worked for me (PHP 7.3):
$curl_file = curl_file_create('/path/to/file.jpg','image/jpg','file.jpg');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://instanceurl.com/api/v1/media');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer YOUR_TOKEN_HERE',
'Content-Type: multipart/form-data'
]);
$body = [
'file' => $curl_file
];
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$response = curl_exec($ch);
if (!$response) {
die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
echo 'HTTP Status Code: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL;
echo 'Response Body: ' . $response . PHP_EOL;
curl_close($ch);
How to extract the "SALECODE" and "PRICE" from this curl get request in php for later MySql compare and insert if it's different, and what type of JSON is the result?
?php
$url = 'http://everywhere.smartcash.ro/everywhere/rest/TSmartCashMethods/GetArticleInfo/4/1/1/1/';
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, $url); curl_setopt($cURL, CURLOPT_HTTPGET, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json' ));
$result = curl_exec($cURL);
curl_close($cURL);
//print_r($result);
$json = json_decode($result, true); print_r($json);
echo $json["SALECODE"];
?>
Sample Response:
{
"result":[
{
"DATASET":[
{
"SUPP_UM":"Kg",
"DETAILS":"70025",
"PRICE":"1.5",
"REC":1,
"CATEG_10":"-",
"NOTES":"",
"LASTSUPPLIER":"Furnizor 2",
"CATEG_9":"-",
"CATEG_8":"-",
"CATEG_7":"-",
"CATEG_6":"-",
"CATEG_5":"-",
"CATEG_4":"-",
"CATEG_3":"-",
"CATEG_2":"Paine",
"CATEG_1":"Panificatie",
"DIVISIBLE":0,
"SALECODE":"12",
"VAT_LETTER":"B",
"ISALT_PRICE":0,
"VAT_VALUE":"9",
"LISTED":1,
"LASTSUPPLY_UNIT_COST":"4",
"SUPP_UM_RATIO":"3.33",
"IDEXTAPP":"70025",
"IDSMARTCASH":1,
"DESCRIPTION":"12",
"LASTSUPPLY_DATE":"2015.01.05 00:00:00",
"SALE_UM":"Buc",
"IDSMARTCASH_LASTSUPPLIER":2,
"ALT_UM":"Kg",
"DISCOUNT":"0",
"LASTSUPPLY_QTY":"3",
"LASTSUPPLY_NIR":5,
"RECVERSION":284,
"NAME":"PAINE DE SECARA 300G",
"ITEM_CODES":[
{
"SALECODE":"12",
"ITEM":1,
"SALECODE_NAME":"PLU"
}
],
"SALECODE_NAME":"PLU",
"ALT_UM_RATIO":"0.3",
"IDEXTAPP_LASTSUPPLIER":"",
"CODWITHCRC":"12"
}
]
}
]
}
Try using $json['result'][0]['DATASET'][0]['SALECODE'] instead.
If you look at your response data closely, you'll see it's heavily nested. result is also an array, so you'll need to choose an item from it. In this case, there's only one. If there are others, you'll need to loop over $json['result'].
<?php
$url = 'http://everywhere.smartcash.ro/everywhere/rest/TSmartCashMethods/GetArticleInfo/4/1/1/1/';
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_HTTPGET, true);
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json' ));
$result = curl_exec($cURL);
curl_close($cURL);
$json = json_decode($result, true);
echo "Price: " . $json['result'][0]['DATASET'][0]['PRICE'];
echo "<hr>";
echo "Sales code: " . $json['result'][0]['DATASET'][0]['SALECODE'];
?>
I am trying to pass a json string into a curlopt_postfield.
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
I have a working hard coded example. However I am having trouble making it dynamic.
$test = "84560";
$data = "{\"id\":\"" .$test. "\"}";
$data2 = "{\"id\":\"84560\"}";
curl_setopt($ch, CURLOPT_POSTFIELDS, $data2);
Why does $data2 work and $data fail?
I have tried json encoding, utf8 encoding, and lots of variations of escaping the quotes all to no avail. What am I missing? I do not get an error simply a NULL response.
Here is the full code. Still not able to get it working. Any additional suggestions as I have tried everything I have found.
$test = "84560";
$data = "{\"id\":\"" .$test. "\"}";
$data2 = "{\"id\":\"84560\"}";
$result2 = getJson("results.json?", $data2);
function getJson($endpoint, $postfields)
{
$URL = "https://app.mobilecause.com/api/v2/reports/". $endpoint;
$ch = curl_init();
$headers = [];
$headers[] = "Authorization: Token token=\"[token goes here]\"";
$headers[] = "Accept: application/json";
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
if (curl_errno($ch))
{
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);;
return $result;
}
You should simply try:
<?php
$data = array('id' => 84560);
$json = json_encode($data);
echo $json; // Will print { id: 84560 }
I have a sand box account in fortnox and i am trying to get the access token using following code, but i keep getting same error:
$requestMethod = "GET";
$ch = curl_init();
$options = array(
'Authorization-Code: '. AUTHORIZATION_CODE .'',
'Client-Secret: '. CLIENT_SECRET .'',
'Content-Type: '. CONTENT_TYPE .'',
'Accept: '. ACCEPTS .''
);
curl_setopt ($ch, CURLOPT_CAINFO, "/xampp/htdocs/cacert.pem");
curl_setopt($ch, CURLOPT_URL, "https://api.fortnox.se/3/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, $options);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $requestMethod);
$curlResponse = curl_exec($ch);
$info = curl_getinfo($ch);
//echo 'Took ' . $info['total_time'] . ' seconds for url ' . $info['url'];
echo $curlResponse;
if ($curlResponse === FALSE) {
echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);
Error: PHP / 4.5.37 Can not sign in , access tokens , or client- secret missing ( 2000311 ) .
I get the Access-Token using the following code which is very close to your code. It worked fine for me.
Your error is described on the Errors page, but it adds nothing new to the text you already shown.
Please note that you can retrive the Access-Token only once, check Authentication section in the Fortnox documentation.
An Access-Token can only be retrieved once with every Authorization-Code, multiple requests with the same Authorization-Code will make both the Authorization-Code and the Access-Token invalid.
public function actionRetrieveAccessToken($authCode, $clientSecret)
{
$headers = [
'Authorization-Code: ' . $authCode,
'Client-Secret: ' . $clientSecret,
'Content-Type: application/json',
'Accept: application/json',
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://api.fortnox.se/3/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$responseText = curl_exec($curl);
$response = json_decode($responseText, true);
if (isset($response['ErrorInformation'])) {
echo 'Request failed with error messages:' . PHP_EOL;
echo $response['ErrorInformation']['Error'] . ': ';
echo $response['ErrorInformation']['Message'];
echo ' (' . $response['ErrorInformation']['Code'] . ')' . PHP_EOL;
} else {
echo 'Access Token: ' . $response['Authorization']['AccessToken'] . PHP_EOL;
}
}
$content_type = 'application/json';
$api_url="api url here";
$curl = curl_init();
$headers = array(
'Content-Type: '.$content_type.'',
'Authorization : '.'Bearer ' . $this->access_token
);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
if (!empty($data))
{
$data = json_encode($data);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
$response = curl_exec($curl);
logthis($response,"utils");
curl_close($curl);
Here is my code to POST data:
<?php
$data = array("account" => "1234", "dob" => "30051987", "site" => "mytestsite.com");
$data_string = json_encode($data);
$url = 'http://mydomain.com/curl.php';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
curl_close($ch);
$json_result = json_decode($result, true);
?>
<p>Your confirmation number is: <strong><?php echo $json_result['ConfirmationCode']; ?></strong></p>
Whereas on domain/server curl.php file code as under:
<?php
// header
header("content-type: application/json");
if($_POST):
echo json_encode(array('ConfirmationCode' => 'somecode'));
else:
echo json_encode(array('ConfirmationCode' => 'none'));
endif;
?>
But it always return 'none'. Am I missing something?
The actual problem is in grabbing it..
<?php
$data = array("account" => "1234", "dob" => "30051987", "site" => "mytestsite.com");
$data_string = json_encode($data);
$url = 'http://mydomain.com/curl.php';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
//$json_result = json_decode($result, true);
?>
your code for curl.php
<?php
$fp = fopen('php://input', 'r');
$rawData = stream_get_contents($fp);
echo "<pre>";
print_r($rawData);
echo "</pre>";
/*if($rawData):
echo json_encode(array('ConfirmationCode' => 'somecode'));;
else:
echo json_encode(array('ConfirmationCode' => 'none'));
endif;*/
?>
Since You are sending the data as raw JSON in the body, it will not populate the $_POST variable
Hope this will help you
The function on this link will work.
<?php
function post_to_url($url, $data) {
$fields = '';
foreach ($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, count($data));
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($post);
curl_close($post);
return $result;
}
$data = array(
"name" => "new Name",
"website" => "http://bavotasan.com",
"twitterID" => "bavotasan"
);
$surl = 'http://mydomain.com/curl.php';
echo post_to_url($surl, $data);
?>
Whereas, on curl.php
<?php
file_put_contents('abc.text', "here is my data " . implode('->', $_POST));
if ($_POST['name']):
print_r($_POST['name']);
endif;
?>
The "correct" Content-Type header for a POST request should be application/x-www-form-urlencoded, but you overrode it with application/json (which is only needed from the server side).
Change your code to below:
<?php
$data = array("account" => "1234", "dob" => "30051987", "site" => "mytestsite.com");
$data_string = json_encode($data);
$url = 'http://mydomain.com/curl.php';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true); // no need to use custom request method
// ----- METHOD #1: no need to "stringify"
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_array);
// ----- METHOD #2: or if you really like to JOSN-ify
curl_setopt($ch, CURLOPT_POSTFIELDS, array("json"=>$data_string));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
/* ------ this will be handled by PHP/cURL
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
*/
$result = curl_exec($ch);
curl_close($ch);
$json_result = json_decode($result, true);
?>