Assist with USPS API using PHP Curl - php

Hello I am trying to do API call to USPS API using PHP Curl.
I get the following response:
[Number] => 80040B19
[Description] => XML Syntax Error: Please check the XML request to see if it can be parsed.
[Source] => USPSCOM::DoAuth
I put together my code for the API call from some sample code on here and also the sample on the USPS site; but cannot get it to work (getting error above); here is my code:
$input_xml = '<AddressValidateRequest USERID="xxxxxxx">
<Address ID="0">
<Address1></Address1>
<Address2>6406 Ivy Lane</Address2><City>Greenbelt</City>
<State>MD</State>
<Zip5></Zip5>
<Zip4></Zip4>
</Address>
</AddressValidateRequest>';
$url = "http://production.shippingapis.com/ShippingAPITest.dll?API=Verify";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"xmlRequest=" . $input_xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
$data = curl_exec($ch);
curl_close($ch);
//convert the XML result into array
$array_data = json_decode(json_encode(simplexml_load_string($data)), true);
print_r('<pre>');
print_r($array_data);
print_r('</pre>');
I am hoping someone can help with what I am doing wrong...

According to the documentation, you're supposed to pass the XML in a field named XML, not xmlRequest. Try something like this instead:
<?php
$input_xml = <<<EOXML
<AddressValidateRequest USERID="xxxxxxx">
<Address ID="0">
<Address1></Address1>
<Address2>6406 Ivy Lane</Address2>
<City>Greenbelt</City>
<State>MD</State>
<Zip5></Zip5>
<Zip4></Zip4>
</Address>
</AddressValidateRequest>
EOXML;
$fields = array(
'API' => 'Verify',
'XML' => $input_xml
);
$url = 'http://production.shippingapis.com/ShippingAPITest.dll?' . http_build_query($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
$data = curl_exec($ch);
curl_close($ch);
// Convert the XML result into array
$array_data = json_decode(json_encode(simplexml_load_string($data)), true);
print_r('<pre>');
print_r($array_data);
print_r('</pre>');
?>

Related

Why isn't my XML API request accepted by the API?

I have been trying, for days, to send a simple XML request to an API. Even with the help of the tech support, absolutely nothing works. I still get an error telling me that my XML isn't well-formed or is invalid.
Here is my cURL request:
$data = array_merge([
'ssl_transaction_type' => "$transactionType",
'ssl_merchant_id' => $this->merchant_id,
'ssl_user_id' => $this->user_id,
'ssl_pin' => $this->pin
], $data);
$xml = new \SimpleXMLElement('<txn/>');
$data = array_flip($data);
array_walk_recursive($data, array ($xml, 'addChild'));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->getXMLUrl());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/x-www-form-urlencoded'
));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array("xmldata=" . explode(PHP_EOL, $xml->asXML())[1])));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
Why do I explode the XML? It's because I need to only get the part with the root, not the version, etc. according to the tech support.
I followed this: XML request is not well-formed or request is incomplete but it still doesn't work.

Api response not showing with curl in php

I want to fetch Api response (created in nodejs) in website using Php,So for this i am using
curl but its not working,I tried with following code but not working for me (showing blank page),Where i am wrong ? Here is my code
$post = ['email'=> "example#xyz.com",'password'=> "testing"];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://35.154.149.228:8000/api/admin/login');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
$result = json_decode($response);
print_R($result);
Change
$result = json_decode($response);
To
$result = json_decode($response, true);
Then
echo '<pre>';
print_r($result);
Response:-
Array
(
[statusCode] => 401
[error] => Unauthorized
[message] => Invalid username or password
[responseType] => INVALID_USER_PASS
)
change your post array
$post = array('email'=> "example#xyz.com",'password'=> "testing");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://35.154.149.228:8000/api/admin/login');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
$result = json_decode($response);
print_r($result);
Try displaying errors just in case the errors/warnings are suppressed.
use these at the top of the file, just after the php tags
ini_set("display_errors", "On");
error_reporting(E_ALL);
Also try to print the raw response before json_decoding it, this is because if the response you are getting is not valid json nothing would be printed out after decoding it.
Use this
print_r("The response is: " . $response);
In summarry your code should look like
ini_set("display_errors", "On");
error_reporting(E_ALL);
$post = ['email'=> "example#xyz.com",'password'=> "testing"];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://35.154.149.228:8000/api/admin/login');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
//Printing the original response before trying to decode it
//$result = json_decode($response);
print_r("The response from the server before decoding is: " . $response);
Let us know what the exact response you get from this is

Parsing XML Response with xml schema

Edit
The code given below will work in localhost as it is, if anyone want to copy and try it.The given credentials are valid.
I have a php code which requests data from an API service. An XML request is sent and in response XML data is recieved. I have stored the respose data in a variable $output. When doing echo $output, the details in the XML response is printed. But now I need to parse this response and store the required data in variables. E.g: I need to save $customer_id = value from the <customer_id>12345</customer_id>. I did a thorough google search and tried all the snippets provided by different developers, but no use.
I tried var_dump(simplexml_load_string($output)); and it is returning object(SimpleXMLElement)#1 (0) { }. I even tried converting the XML data to array.
index.php
<?php
$appId ="MFS149250";
$appPass ="5TEBRPCZ";
$brokeCode ="ARN-149250";
$iin = "5011217983";
$xml_data = '<?xml version="1.0" encoding="UTF-8"?>
<NMFIIService>
<service_request>
<appln_id>'.$appId.'</appln_id>
<password>'.$appPass.'</password>
<broker_code>'.$brokeCode.'</broker_code>
<iin>'.$iin.'</iin>
</service_request>
</NMFIIService>';
$URL = "https://uat.nsenmf.com/NMFIITrxnService/NMFTrxnService/IINDETAILS";
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_MUTE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
//echo "<textarea>".$output."</textarea>";
echo $output;
var_dump(simplexml_load_string($output));
curl_close($ch);
?>

Server Side script for cURL request

I use cURL but untill now I used it for requesting data from servers. But now I want ot write API and data will be requested with cURL. But I don't know how Server reads data from cURL request.
This is my "client server" side request:
function sendRequest($site_name,$send_xml,$header_type=array('Content-Type: text/xml'))
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$site_name);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$send_xml);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPHEADER,$header_type);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
$result = curl_exec($ch);
return $result;
}
$xml = "<request>
<session>
<user>exampleuser</user>
<pass>examplepass</pass>
</session>
</request>";
$sendreq = sendRequest("http://sitename.com/example.php",$xml);
echo $sendreq;
How do I need to write "main server" side script so I can read what user and pass from request are???
Thank you a lot.
To just be able to read it try this
curl_setopt($ch, CURLOPT_POSTFIELDS,array('data'=>$send_xml));
Then
print_r($_POST['data'])
Alternatively skip the XML and try something like this:
$data = array(
'request' => array(
'session' => array(
'user'=>'exampleuser',
'pass'=>'examplepass')
)
);
$sendreq = sendRequest("http://sitename.com/example.php",$data);
In example.php
print_r($_POST)

Posting JSON data to API using CURL

When I'm posting json data to API using curl - I'm not getting any output. I would like to send email invitation to recipient.
$url_send ="http://api.address.com/SendInvitation?";
$str_data = json_encode($data);
function sendPostData ($url, $post) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
return curl_exec($ch);
}
And here is JSON $str_data
[
{
"authorizedKey" : "abbad35c5c01-xxxx-xxx",
"senderEmail" : "myemail#yahoo.com",
"recipientEmail" : "jaketalledo86#yahoo.com",
"comment" : "Invitation",
"forceDebitCard" : "false"
}
]
And calling function:
$response = sendPostData($url_send, $str_data);
This is the API: https://api.payquicker.com/Help/Api/POST-api-SendInvitation
Try adding curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
And changing http_build_query($post) to $post
The implementation:
<?php
$data = array(
"authorizedKey" => "abbad35c5c01-xxxx-xxx",
"senderEmail" => "myemail#yahoo.com",
"recipientEmail" => "jaketalledo86#yahoo.com",
"comment" => "Invitation",
"forceDebitCard" => "false"
);
$url_send ="http://api.payquicker.com/api/SendInvitation?authorizedKey=xxxxx";
$str_data = json_encode($data);
function sendPostData($url, $post){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
curl_close($ch); // Seems like good practice
return $result;
}
echo " " . sendPostData($url_send, $str_data);
?>
The response I get is:
{"success":false,"errorMessage":"Object reference not set to an instance of an object.","status":"N/A"}
But maybe it will work with valid data....
Edit:
For posting xml,
it's the same as on their site, except in a string:
$xml = '
<SendInvitationRequest xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/PQApi.Models">
<authorizedKey>80c587b9-caa9-4e56-8750-a34b17dba0a2</authorizedKey>
<comment>sample string 4</comment>
<forceDebitCard>true</forceDebitCard>
<recipientEmail>sample string 3</recipientEmail>
<senderEmail>sample string 2</senderEmail>
</SendInvitationRequest>';
Then:
sendPostData($url_send, $xml)
You have to add header:
$headers= array('Accept: application/json','Content-Type: application/json');
And:
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
Otherwise ...
HTTP Status 415 - Unsupported Media Type
... may happen.
You don't need to add headers as you already do json_encode.
just print_r (curl_getinfo($ch)); and see the content type info in it.

Categories