Converting cURL to wp_remote_post not working viz privat24 API - php

trying to get the info from api by sending xml data to it.
The thing is that it is working great with cURL, but not working via wp_remote_post.
Here is the example of xml data:
<?xml version="1.0" encoding="UTF-8"?>
<request version="1.0">
<merchant>
<id>151880</id>
<signature>23f59a159bbc82</signature>
</merchant>
<data><oper>cmt</oper><wait>60</wait><test>0</test><payment
id="a9c71ad9a291209f8b77d851c4b46f9"><prop name="sd" value="07.11.2019" />
<prop name="ed" value="21.11.2019" /><prop name="card" value="4242424242424242" />
</payment></data>
</request>"
$api_uri = 'https://api.privatbank.ua/p24api/rest_fiz'
cURL working code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_uri);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: text/xml",
"Content-length: ".strlen($xml),
"Connection: close",
"Access-Control-Allow-Origin: *",
'Accept: text/xml'
));
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if(curl_errno($ch)){
echo curl_error($ch);
}else{
curl_close($ch);
}
return $response;
Not working wp_remote_post code:
$result = wp_remote_post($api_uri, array(
'headers' => array(
"Content-Type" => "text/xml",
"Content-length" => strlen($xml),
"Connection" => "close",
"Access-Control-Allow-Origin" => "*",
'Accept" => "text/xml'
),
'method' => 'POST',
'sslverify' => true,
'timeout' => 100,
'body' => $xml
));
$response = $result;
return $response['body'];
Also, it is working through Rest Client as well.
Please help.
Thank you.

Related

XML request is not being sent using wp_remote_post()

appologies in advance. I am trying to send XML request using wp_remote_post().
Im trying to send request to my SMS Provider to send one time OTP.
$url = "http://gate.payvand.tj/xml/";
$xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<request>
<request-type>9</request-type>
<terminal-id>".$termid."</terminal-id>
<login>".$login."</login>
<password-md5>".$pwd."</password-md5>
<message txn-id=\"".$txn."\" sign=\"".$sign."\">
<to>
<source-address>".$source_address."</source-address>
<destination-address>".$mobile_number."</destination-address>
<data-encoding>1</data-encoding>
<text>".$message."</text>
</to>
</message>
</request>";
$response = wp_remote_post(
$url,
array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'headers' => array(
'Content-Type' => 'text/xml'
),
'body' => array('postdata' => $xml, 'postfield' => 'value'),
'sslverify' => false
)
);
My provider is not recieving this request.
But he is recieving and executing it like this
$xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<request>
<request-type>9</request-type>
<terminal-id>".$termid."</terminal-id>
<login>".$login."</login>
<password-md5>".$pwd."</password-md5>
<message txn-id=\"".$txn."\" sign=\"".$sign."\">
<to>
<source-address>".$source_address."</source-address>
<destination-address>".$mobile_number."</destination-address>
<data-encoding>1</data-encoding>
<text>".$message."</text>
</to>
</message>
</request>";
$ch = curl_init();
$url = "http://gate.payvand.tj/xml/";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_FORBID_REUSE, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
Could you please explain the mistake in the first snippet?

CURLOPT_POSTFIELDS varaible format

I'm trying to post a parameter with cURL,
when I tried with this type of format :
CURLOPT_POSTFIELDS => "label=sample"
I exactly got "label" key in the server with "sample" as its value
but I get it empty in the server when I sent it out as a variable .
CURLOPT_POSTFIELDS => "label=$email"
$curl = curl_init();
$user_info=$this->web_model->retriveUserInfo();
$email=$user_info->email;
curl_setopt_array($curl, array(
CURLOPT_URL => "https://test.bitgo.com/api/v2/".$coin."/wallet/".$wallet_id."/address",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "label=$email",
CURLOPT_HTTPHEADER => array(
"Accept: */*",
"Accept-Encoding: gzip, deflate",
"Authorization: Bearer v2x4e7cf3fb7e6c2e87bf8103e49756b3892b2e350d6cdbaeb65757980",
"Cache-Control: no-cache",
"Connection: keep-alive",
"Content-Length: 11",
"Content-Type: application/x-www-form-urlencoded",
"Host: test.bitgo.com",
"Postman-Token: b3f2ee7c-9a19-479b-bfe2-27000c90e3c7,d611bde9-3eb1-4e2b-b8f5-a7a5f5485726",
"User-Agent: PostmanRuntime/7.15.2",
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$response = json_decode($response, true);
$err = curl_error($curl);
curl_close($curl);
my main problem is CURLOPT_POSTFIELDS format for variables !
Doc says about CURLOPT_POSTFIELDS:
This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value.
So you can:
Replace: CURLOPT_POSTFIELDS => "label=$email", with CURLOPT_POSTFIELDS => ['label' => $email], and if you'll need more data to pass as POST field you can just add another pair $key => $value to that array or prepare it before setting curl options.
Set POST fields via http_build_query:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); where $ch is curl handle and $data is array of $key => $value pairs where $key is field name.
But keep in mind:
Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.
Many thanks
Finally I had to use Guzzle library simply
$client = new GuzzleHttp\Client(['base_uri' => 'https://test.bitgo.com/api/v2/']);
$response = $client->post($coin.'/wallet/'.$wallet_id.'/address', [
'headers' => [
'Authorization' => 'Bearer v2x4e7cf3fb7e6c2e87bf8103e4975dsddbaeb65ba017b555757980'],
'form_params' => [
"label" => $email
]
very very useful
You can try this
function curl($post = array(), $url, $token = '', $method = "POST", $json = false, $ssl = false){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
if($method == 'POST'){
curl_setopt($ch, CURLOPT_POST, true);
}
if($json == true){
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer '.$token, 'Content-Length: ' . strlen(json_encode($post))));
}else{
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSLVERSION, 6);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
// Proxy example only
if (!empty($proxy)) {
curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:888');
if (!empty($proxyAuth)) {
curl_setopt($ch, CURLOPT_PROXYUSERPWD, 'user:password');
}
}
if($ssl == false){
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
$response = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$this->statusCode = $statusCode;
if (curl_error($ch)) {
$error = 'CURL_ERROR '.$statusCode.' - '.curl_error($ch);
// print_r('CURL_ERROR '.$statusCode.' - '.curl_error($ch));
throw new Exception('CURL_ERROR '.curl_error($ch), $statusCode);
}
curl_close($ch);
return $response;
}

Sending Push Notifications via OneSignal using PHP

I am using the following PHP Code to send push notification via One Signal:
function sendMessage(){
$content = array(
"en" => 'English Message'
);
$fields = array(
'app_id' => $appId,
'included_segments' => array('All'),
'data' => array("foo" => "bar"),
'contents' => $content
);
$fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
'Authorization: Basic '.$restKey));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage();
$return["allresponses"] = $response;
$return = json_encode( $return);
print("\n\nJSON received:\n");
print($return);
print("\n");
And I am getting the following response:
JSON sent: {"app_id":null,"included_segments":["All"],"data":{"foo":"bar"},"contents":{"en":"English Message"}} JSON received: "{\"allresponses\":\"{\\\"adm_big_picture\\\":null,\\\"adm_group\\\":null,\\\"adm_group_message\\\":null,\\\"adm_large_icon\\\":null,\\\"adm_small_icon\\\":null,\\\"adm_sound\\\":null,\\\"amazon_background_data\\\":false,\\\"android_accent_color\\\":null,\\\"android_group\\\":null,\\\"android_group_message\\\":null,\\\"android_led_color\\\":null,\\\"android_sound\\\":null,\\\"android_visibility\\\":null,\\\"app_id\\\":\\\"63c6c8f7-694b-4c68-abc1-d820d9bbbec1\\\",\\\"big_picture\\\":null,\\\"buttons\\\":null,\\\"canceled\\\":false,\\\"chrome_big_picture\\\":null,\\\"chrome_icon\\\":null,\\\"chrome_web_icon\\\":\\\"\\\",\\\"chrome_web_image\\\":\\\"\\\",\\\"content_available\\\":false,\\\"contents\\\":{\\\"en\\\":\\\"This is a new message.\\\"},\\\"converted\\\":0,\\\"data\\\":null,\\\"delayed_option\\\":\\\"immediate\\\",\\\"delivery_time_of_day\\\":\\\"4:00 PM\\\",\\\"errored\\\":0,\\\"excluded_segments\\\":[],\\\"failed\\\":0,\\\"firefox_icon\\\":\\\"\\\",\\\"headings\\\":{\\\"en\\\":\\\"New Message\\\"},\\\"id\\\":\\\"8d56f592-8f43-461a-94e8-2fe9922ba844\\\",\\\"include_player_ids\\\":null,\\\"included_segments\\\":[\\\"All\\\"],\\\"ios_badgeCount\\\":null,\\\"ios_badgeType\\\":null,\\\"ios_category\\\":null,\\\"ios_sound\\\":null,\\\"isAdm\\\":false,\\\"isAndroid\\\":false,\\\"isChrome\\\":false,\\\"isChromeWeb\\\":true,\\\"isFirefox\\\":true,\\\"isIos\\\":false,\\\"isSafari\\\":true,\\\"isWP\\\":false,\\\"isWP_WNS\\\":false,\\\"large_icon\\\":null,\\\"priority\\\":null,\\\"queued_at\\\":1492523636,\\\"remaining\\\":0,\\\"send_after\\\":1492523636,\\\"small_icon\\\":null,\\\"successful\\\":3,\\\"tags\\\":null,\\\"filters\\\":null,\\\"template_id\\\":null,\\\"ttl\\\":null,\\\"url\\\":\\\"\\\",\\\"web_buttons\\\":null,\\\"wp_sound\\\":null,\\\"wp_wns_sound\\\":null}\"}"
However the Push Notification is not appearing in the One Signal Dashboard and neither being received by those who subscribed.
Can someone help please :) ?
your mistake is here.
'Authorization: Basic '.$restKey));
Correct one is.....
'Authorization: Basic "'.$restKey."'"));
I am working this code and this is working fine
function SendOneSignalMessage($message,$empid){
// Your code here!
$fields = array(
'app_id' => 'xxxxxxxxxxxxxxxxxx',
'include_player_ids' => [$empid],
'contents' => array("en" =>$message),
'headings' => array("en"=>"etc"),
'largeIcon' => 'https://cdn4.iconfinder.com/data/icons/iconsimple-logotypes/512/github-512.png',
);
$fields = json_encode($fields);
//print("\nJSON sent:\n");
//print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
'Authorization: Basic xxxxxxxxxxxxx));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
}

curl to php to post a json and audio

I'm trying to convert a curl command to be used in a php script
curl -k -F "request={'timezone':'America/New_York','lang':'en'};type=application/json" -F "voiceData=#d8696c304d09eb1.wav;type=audio/wav" -H "Authorization: Bearer x" -H "ocp-apim-subscription-key:x" "http://example.com"
and here is my php script
<?
$data = array("timezone" => "America/New_York", "lang" => "en", "voiceData" => "d8696c304d09eb1.wav");
$data_string = json_encode($data);
$ch = curl_init('https://example.com');
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',
'Authorization: Bearer x',
'ocp-apim-subscription-key:x')
);
$result = curl_exec($ch);
?>
I understand that the send audio file bit is not right but i cant find an example how to post it.
I have edited this in response to the post fields but if I include $ch i get no output if don't include the output complains that no post request. Any ideas?
<?
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ch = curl_init('https://example.com');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'Authorization: Bearer x',
'ocp-apim-subscription-key:x')
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,
array('request' => json_encode(array('timezone' => 'America/New_York', 'lang' => 'en')),
'voicedata' => new CURLFile("d8696c304d09eb1.wav")
)
);
$result = curl_exec($ch);
echo $result;
?>
You're missing the request= in your POST fields. Also, sending files using #filename is deprecated, you should use the CURLFile class.
curl_setopt($ch, CURLOPT_POSTFIELDS,
array('request' => json_encode(array('timezone' => 'America/New_York', 'lang' => 'en')),
'voicedata' => new CURLFile("d8696c304d09eb1.wav")
)
);

php soap:ServerServer was unable to process request. ---> Sequence contains no elements

I need to send an XML as soap request using CURL. I have created xml using
$xml = "<?xml .............." blah blah
That looks like
<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><extLoginData xmlns='http://www.JOI.com/schemas/ViaSub.WMS/'><ThreePLKey>4dfdf34</ThreePLKey><Login>abv</Login><Password>abc</Password><FacilityID>1ee</FacilityID><CustomerID>xfs</CustomerID></extLoginData><orders xmlns='http://www.JOI.com/schemas/ViaSub.WMS/'><Order><TransInfo><ReferenceNum>Test</ReferenceNum><PONum>12345</PONum></TransInfo><ShipTo><Name></Name><CompanyName>Peter's Test</CompanyName><Address><Address1>7301 Lennox Ave Unit E3</Address1><Address2></Address2><City>Los Angeles</City><State>CA</State><Zip>90010</Zip><Country>US</Country></Address><PhoneNumber1>858-449-8022</PhoneNumber1><EmailAddress1>lshaules#mercatismedia.com</EmailAddress1><CustomerName>Elizabeth Shaules</CustomerName></ShipTo><ShippingInstructions><Carrier>USPS</Carrier><Mode>First Class Mail</Mode><BillingCode>Prepaid</BillingCode></ShippingInstructions><OrderLineItems><OrderLineItem><SKU>947</SKU><Qualifier>XXX</Qualifier><Qty>1</Qty></OrderLineItem></OrderLineItems></Order></orders></soap:Body></soap:Envelope>
And I am using following code to send CURL request
$url = 'http://someurl.com/Contracts.asmx';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 120);
curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'SOAPAction:"http://www.example.com/ViaSub.WMS/CreateOrders"',
'Content-Type: text/xml; charset=utf-8',
));
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $orderXml);
$result = curl_exec($curl);
But I am getting
soap:ServerServer was unable to process request. ---> Sequence contains no elements
I have searched but haven't found any thing related to it. Can you please let me know what I am doing wrong and how I do it?
This looks like a schema validation error. You don't provide a link to the definition, but a quick search showed me this documentation page. If this is the one you need take a look at the WSDL: https://secure-wms.com/webserviceexternal/contracts.asmx?WSDL
Look for instance the element PalletCount within Order. You see it has minOccurs="1", meaning it's mandatory. But in the xml string you copy there's no such element. That's indeed a sequence with missing elements. (There may be some other schema inconsistencies, have a close look).
Also, consider using the SoapClient PHP class
$WSDL = 'https://secure-wms.com/webserviceexternal/contracts.asmx?WSDL';
$options = [
'trace' => true,
'cache' => WSDL_CACHE_NONE,
'exceptions' => true
];
$client = new SoapClient($WSDL, $options);
$payload = [
'extLoginData' => [
'ThreePLKey' => '4dfdf34',
'Login' => 'abv',
'Password' => 'abc',
'FacilityID' => '1ee',
'CustomerID' => 'xfs'
],
'orders' => [
'Order' => [
// etc...
]
]
]);
$response = $client->CreateOrders($payload);
This way the client handles the schema validation, headers setting (you can set additional headers, though), the namespacing, and the array to xml conversion.
Use this
$xml = "<?xml ..............</soap:Envelope>";
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://www.example.com/ViaSub.WMS/CreateOrders",
"Content-length: ".strlen($xml),
); //SOAPAction: your op URL
$url = 'http://someurl.com/Contracts.asmx';
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);

Categories