Something went wrong when I convert API code to PHP CURL - php

I am trying to convert API code to curl.
Here is the code.
url = config.ERPNEXT_URL + "/api/method/erpnext.hr.doctype.employee_checkin.employee_checkin.add_log_based_on_employee_field"
headers = {
'Authorization': "token "+ config.ERPNEXT_API_KEY + ":" + config.ERPNEXT_API_SECRET,
'Accept': 'application/json'
}
data = {
'employee_field_value' : employee_field_value,
'timestamp' : timestamp.__str__(),
'device_id' : device_id,
'log_type' : log_type
}
Here is what I have done.
$curl = config.ERPNEXT_URL . "/api/method/erpnext.hr.doctype.employee_checkin.employee_checkin.add_log_based_on_employee_field";
$data = array(
'employee_field_value' => employee_field_value,
'timestamp' => timestamp.__str__(),
'device_id' => device_id,
'log_type' => log_type
);
$tuCurl = curl_init();
curl_setopt($tuCurl, CURLOPT_URL, $curl);
curl_setopt($tuCurl, CURLOPT_HEADER, 0);
curl_setopt($tuCurl, CURLOPT_POST, 1);
curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($tuCurl, CURLOPT_POSTFIELDS, $data);
//set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization:token ' . config.ERPNEXT_API_KEY . ":" . config.ERPNEXT_API_SECRET));
$tuData = curl_exec($tuCurl);
if(!curl_errno($tuCurl)){
echo $tuCurl;
} else {
echo 'Curl error: ' . curl_error($tuCurl);
}
curl_close($tuCurl);
I want to know what is wrong with the CURL code?
Many thanks

curl_setopt($tuCurl, CURLOPT_HEADER, 0);
change it to
curl_setopt($tuCurl, CURLOPT_HEADER, $headers);
first store headres in $headers

Related

How to publish media (image) on Mastodon using API?

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

paypal MALFORMED REQUEST error in curl

I am facing MALFORMED_REQUEST in paypal API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.sandbox.paypal.com/v1/payments/payment");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{
\"intent\":\"authorize\",
\"payer\":{
\"payment_method\":\"credit_card\",
\"funding_instruments\":[{
\"credit_card\":{
\"number\":\"5555555555554444\",
\"type\":\"mastercard\",
\"expire_month\":07,
\"expire_year\":22,
\"cvv2\":123,
\"first_name\":\"FName\",
\"last_name\":\"Lname\",
\"billing_address\":{
\"line1\":\"address,\",
\"city\":\"City\",
\"state\":\"state\",
\"postal_code\":\"postal_code\",
\"country_code\":\"country_code\"
}
}
}]
},
\"transactions\":[{
\"amount\":{
\"total\":\"10\",
\"currency\":\"CAD\",
\"details\":{
\"subtotal\":\"10\",
\"tax\":\"0\",
\"shipping\":\"0\"
}
}
}]}");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Content-Type: application/json";
$headers[] = "Authorization: Bearer myAccessToken";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
Here I am calling curl for authorization with paypal
jsonlint.com shows this json format is ok
But still I am getting response like,
{"name":"MALFORMED_REQUEST","message":"The request JSON is not well formed.","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST","debug_id":"9d7454a8637ae"}
Not getting exactly where I am wrong? Does any one know? Thanks in advance!
Your problem is the 07 in "expire_month": 07. I assume this value is meant to be a string. Not sure what you pasted in to jsonlint but it wasn't the JSON in your question.
As indicated in the comments, don't roll your own JSON. Use the tools available
$data = [
'intent' => 'authorize',
'payer' => [
'payment_method' => 'credit_card',
'funding_instruments' => [[
'credit_card' => [
'number' => '5555555555554444',
'type' => 'mastercard',
'expire_month' => '07',
'expire_year' => '22',
'hopefully you get the idea' => 'by now'
]
]]
]
];
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
As the error indicates, your JSON is not formed correctly.You need not pass \ to escape your request parameters . Try removing those or try this sample code which works out of the box.
<?php
$data = 'response_type=token&grant_type=client_credentials';
$headers_arr = array();
$headers_arr[]="Accept-Encoding:application/json;charset=utf-8";
$headers_arr[]="Accept-Language:en_US";
// $headers_arr[]="Authorization:Bearer AZHFuBBAIG1rP98P7Svn2WOVatM5KAllu6KvrTE8GGT4gt9vdfj8TtR_1Cer:EBTMERCurtbf_4auykCeGWYGvwsy147bSb3xCuYpohmouVBGTaYFUIRwWgbx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.sandbox.paypal.com/v1/oauth2/token");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);// this is used to bypass the SSL protocol, not recommended.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);// this is used to bypass the SSL protocol, not recommended.
curl_setopt($ch, CURLOPT_TIMEOUT, 45);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "ARLg-BBMeTGLU5IHCsdIKEC_R_sMAkWM-yLsI5W5u9RuhvNhgolhYv-1cWmr:EJdAYxDx29McgMKOWjGK1OLHyaIxQBRuV9sWgfFSeMKGVBe-1jdiNgv5TLtP");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_arr);
$result = curl_exec($ch);
$res = json_decode($result);
$access_token = $res->access_token;
//now create a paypal payment
$headers_arr = array();
$headers_arr[]="Content-Type:application/json;charset=utf-8";
$headers_arr[] = "Authorization: Bearer $access_token";
// echo '<pre>';
// print_r($headers_arr);
$data_string = '{
"intent":"authorize",
"payer":{
"payment_method":"credit_card",
"funding_instruments":[
{
"credit_card":{
"number":"4446283285273500",
"type":"visa",
"expire_month":11,
"expire_year":2018,
"cvv2":"874",
"first_name":"Betsy",
"last_name":"Buyer",
"billing_address":{
"line1":"111 First Street",
"city":"Saratoga",
"state":"CA",
"postal_code":"95070",
"country_code":"US"
}
}
}
]
},
"transactions":[
{
"amount":{
"total":"7.47",
"currency":"USD",
"details":{
"subtotal":"7.41",
"tax":"0.03",
"shipping":"0.03"
}
},
"description":"This is the payment transaction description."
}
]
}';
// echo data_string;
$chs = curl_init();
curl_setopt($chs, CURLOPT_URL, 'https://api.sandbox.paypal.com/v1/payments/payment');
curl_setopt($chs, CURLOPT_POST, true);
curl_setopt($chs, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($chs, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($chs, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($chs, CURLOPT_TIMEOUT, 45);
curl_setopt($chs, CURLOPT_RETURNTRANSFER, true);
curl_setopt($chs, CURLOPT_POST, 1);
curl_setopt($chs, CURLOPT_HTTPHEADER, $headers_arr);
if(curl_exec($chs) === false)
{
echo 'Curl error: ' . curl_error($chs);
}
$results = curl_exec($chs);
$res = json_decode($results);
echo 'ress=<pre>';
print_r($results);

web API POST curl returns 'not found anything matching the request URI'

i try to access a web api with json encoded and $POST method in php. After a few tries, i get this message:
Not Found - The server has not found anything matching the request URI
.You can get technical details here. Please continue your visit at our
home page.
Why? thank you, my code is:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
//DADOS DE ACESSO
$id = "xxx";
$retailerName = "xxx";
$key = "xxx";
//PRODUTO
//vars of product:fictional data
$upc = "799366289999";
$amount = "20.00";
//URL DE ACESSO
$function = "requestActivateCode";
//usado pra criar a canonical
$resPath = "/v1/activateCode";
$url = "https://111.222.333.444/v1/";
$urlCall = $url.$function;
//HTTP HEADERS
$date = gmdate("M, d Y H:i:s \G\M\T", time());
$contentType = "Content-Type: application/json; charset=UTF-8";
$accept = "Accept: application/json";
$xIncommDateTime = substr(substr_replace(date('c'), substr(round(microtime(), 3), 1, 8), 19, 0), 0, -6) . "Z";
//authorization
$type = "application/json; charset=UTF-8";
$canonical = ($xIncommDateTime) + ($type) + ($resPath);
$signature = hash_hmac ('sha1', $key, $canonical);
$idEncoded = base64_encode($id);
$signatureEncoded = base64_encode($signature);
$authorization = "Incomm ". $idEncoded .':'. $signatureEncoded;
$header = array("Date: ".$date, $contentType, $accept, "X-Incomm-DateTime: ".$xIncommDateTime, "Authorization: ".$authorization);
//PARAMS example
$params = array("RetailTransactionRequest" =>
array(
"code" => "0000002381237220",
"amount" => $amount,
"upc" => $upc,
"transactionID" => "1234",
"dateTime" => $xIncommDateTime,
"retailerName" => $retailerName
)
);
$request = json_encode($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $urlCall);
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
//curl_setopt($ch, CURLOPT_SSLVERSION, 1);
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
curl_setopt($ch, CURLOPT_PORT, 443);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
echo curl_setopt($ch, CURLINFO_HEADER_OUT, true); // enable tracking
$result = curl_exec($ch);
echo $result;
$headerSent = curl_getinfo($ch, CURLINFO_HEADER_OUT ); // request headers
echo "<pre>";
print_r($headerSent);
echo "</pre>";
if($result === false)
{
echo 'Curl error: ' . curl_error($ch);
}
else
{
echo 'Operation completed without any errors';
echo "<pre>";
print_r($result);
echo "</pre>";
}
In netstat -l ip my port 443 is listening, but the host in ping dont. I want to know how to solve the problem, thank you
If the code is exactly what is shown I don't think that your server's ip address is correct. Instead of using the IP address (111.222.333.444) used in the example, substitute the IP address of your site or the domain name of your site.
$url = "https://111.222.333.444/v1/"

Curl POST attachment

I need to attach a pdf file form local drive and post it to the API using PHP CURL.
Here is the RingCentral FaxOut API Documentation
$url = "https://service.ringcentral.com/faxapi.asp";
$data = array(
'Username' => 'XXXXXXXXX',
'Password' => 'XXXXXXXXX',
'Recipient' => 'XXXXXXXXXX|Navneet',
'Coverpage' => 'Default',
'Coverpagetext' => 'Testing Faxout API ',
'Resolution' => 'High',
"Sendtime" => date('d:m:y H:i:s'),
'Attachment' => file_get_contents(PATH_TO_FILE)
);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch,CURLOPT_POST, count($data));
curl_setopt($ch,CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
API do not return anything in response. I think, I'm not sending the attachment properly. The attachment should be in binary stream. I tried base64_encode but no success.
As given in the Request body example, header for attachment should be like this
Content-Disposition: form-data; name="Attachment"; filename="C:\example.doc"
<Document content is here>
-----------------------------7d54b1fee05aa
You can POST anything to the api with CURL, $doc in my example is anything you want to post , it can be a json_encoded file , a base64_encoded image or pdf or anything else.
$baseUri = https://service.ringcentral.com/faxapi.asp;
$doc = file_get_contents(PATH_TO_FILE);
$ci = curl_init();
curl_setopt($ci, CURLOPT_URL, $baseUri);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ci, CURLOPT_FORBID_REUSE, 0);
curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ci, CURLOPT_POSTFIELDS, $doc);
// also you can specify any specific header like this :
$h1['Content-Disposition'] = 'Content-Disposition'. ': ' . 'form-data'; // headers are key-value pairs right ?
curl_setopt($ci, CURLOPT_HTTPHEADER, array_values($h1)); // you can use this line for each header as a new key-value pair
$h2['name'] = 'name'. ': ' . 'Attachment';
curl_setopt($ci, CURLOPT_HTTPHEADER, array_values($h2));
$h3['filename'] = 'filename'. ': ' . 'C:\example.doc';
curl_setopt($ci, CURLOPT_HTTPHEADER, array_values($h3));
$response = curl_exec($ci);
**NOTE ** : its a good Idea to first of all check to see if your file_get_contents function works :
so in another php file check to see this :
echo file_get_contents(PATH_TO_FILE);
See if it echoes correctly
This is the function and how I generated the info for the request
function send_curl_request_with_attachment($method, $headers, $url, $post_fields) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
if($headers != "" && count($headers) > 0){
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
} curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_VERBOSE,true);
$result = curl_exec($ch);
curl_close($ch);
return $result;}
$token_slams = "Authorization: Bearer " . $access_token;
$authHeader = array(
$token_slams,
'Accept: application/form-data');
$schedule_path ='../../documents/' . $docs_record["document"];
$cFile = curl_file_create($schedule_path);
$post = array(
'old_record' => $old_record,
'employer_number' => $employer_number,
'payment_date' => $payment_date,
'fund_year' => $fund_year,
'fund_month' => $fund_month,
'employer_schedule'=> $cFile
);
send_curl_request_with_attachment("POST", $authHeader, $my_url, $post);

How to set custom REQUEST header in PHP

In creating RESPONSE headers, using header() function will do the trick. How about for request headers?
Thanks in advance!
If you are talking about making a request and specifying your headers, one way to do it is using CURL:
$data = "<soap:Envelope>[...]</soap:Envelope>";
$tuCurl = curl_init();
curl_setopt($tuCurl, CURLOPT_HEADER, 0);
curl_setopt($tuCurl, CURLOPT_URL, "http://example.com/path/for/soap/url/");
curl_setopt($tuCurl, CURLOPT_POST, 1); // if post request
curl_setopt($tuCurl, CURLOPT_POSTFIELDS, $data);
curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($tuCurl, CURLOPT_HTTPHEADER, array("Content-Type: text/xml","SOAPAction: \"/soap/action/query\"", "Content-length: ".strlen($data)));
$tuData = curl_exec($tuCurl);
if(!curl_errno($tuCurl)){
$info = curl_getinfo($tuCurl);
echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
} else {
echo 'Curl error: ' . curl_error($tuCurl);
}
curl_close($tuCurl);
echo $tuData;

Categories