USPS suggests to send request XML to
secure.shippingapis.com/ShippingAPI.dll?API=MerchandiseReturnV4&XML=
I have tried with the example XML given at
https://www.usps.com/business/web-tools-apis/merchandise-return-service-labels-v10-2a.htm
$url="https://secure.shippingapis.com/ShippingAPI.dll";
$api="API=MerchandiseReturnV4&XML=";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $api . $xml);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
$error = curl_error($ch);
echo result;
but it is returning nothing.....
If the request is approaching the API then it would return the response which can be the proper expected response or the error code with some error detail.
The problem for not getting the proper response might be of the following here-
Wrong XML passed to the query string
Missed some required fields in the XML
Invalid Web Tools Credentials
In order to know the exact Error Code and Details you need to parse the returned XML from the API Server.
You can get the response stream and read the stream to the Stream Reader
string result = null;
using (HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
}
However I implemented this in .Net MVC but it might help for a head start to find the exact problem.
I forget to put the answers after solving my problem.
Function for connect to usps :-
public function connectToUSPS($url, $api, $xml) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $api . $xml);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
$error = curl_error($ch);
if (empty($error)) {
return $result;
} else {
return false;
}
}
Function to generate USPS label :-
function create_UspsLabel($shipId, $userId) {
$row = 'contains user data';
$uspsUserName = 'a valid usps user name';
$uspsPassword = 'a valid usps user password';
$retailerName = 'retailer name';
$retailerAddress ='retailer address';
$permitNumber = 'a valid permit number';
$retailerState = 'retailer state;
$retailerCity = 'retailer city';
$retailerZip = 'retailer zip code';
$PDUPoBox = 'pdu box number';
$PDUCity = 'pdu city name';
$PDUState = 'pdu state name';
$PDUZip = 'pdu zip code';
$PDUZip2 = 'pdu zip code2';
$oid = 'order id';
$packageId = "KR" . str_pad(($oid + 1), 5, "0", STR_PAD_LEFT);
$state = 'state';
$xml = '<EMRSV4.0Request USERID="' . $uspsUserName . '" PASSWORD="' . $uspsPassword . '">
<Option>RIGHTWINDOW</Option>
<CustomerName>' . $row->name.' '.$row->lastName . '</CustomerName>
<CustomerAddress1>' . $row->suit . '</CustomerAddress1>';
$xml.=' <CustomerAddress2>' . $row->address1 . '</CustomerAddress2>
<CustomerCity>' . $row->city . '</CustomerCity>
<CustomerState>' . $state . '</CustomerState>
<CustomerZip5>' . $row->zipcode . '</CustomerZip5>
<CustomerZip4 />
<RetailerName>' . $retailerName . '</RetailerName>
<RetailerAddress>' . $retailerAddress . '</RetailerAddress>
<PermitNumber>' . $permitNumber . '</PermitNumber>
<PermitIssuingPOCity>' . $retailerCity . '</PermitIssuingPOCity>
<PermitIssuingPOState>' . $retailerState . '</PermitIssuingPOState>
<PermitIssuingPOZip5>' . $retailerZip . '</PermitIssuingPOZip5>
<PDUPOBox>' . $PDUPoBox . '</PDUPOBox>
<PDUCity>' . $PDUCity . '</PDUCity>
<PDUState>' . $PDUState . '</PDUState>
<PDUZip5>' . $PDUZip . '</PDUZip5>
<PDUZip4>' . $PDUZip2 . '</PDUZip4>
<ServiceType>Priority Mail</ServiceType>
<DeliveryConfirmation>False</DeliveryConfirmation>
<InsuranceValue />
<MailingAckPackageID>' . $packageId . '</MailingAckPackageID>
<WeightInPounds>0</WeightInPounds>
<WeightInOunces>10</WeightInOunces>
<RMA>RMA 123456</RMA>
<RMAPICFlag>False</RMAPICFlag>
<ImageType>TIF</ImageType>
<RMABarcode>False</RMABarcode>
<AllowNonCleansedDestAddr>False</AllowNonCleansedDestAddr>
</EMRSV4.0Request>';
$result = $this->connectToUSPS('https://secure.shippingapis.com/ShippingAPI.dll', 'API=MerchandiseReturnV4&XML=', $xml);
$xml = new SimpleXMLElement($result);
$string = base64_decode($xml->MerchandiseReturnLabel);
if ($string) {
$img_file = fopen(__USPSLABELIMAGE__ . "uspsLabel.tif", "w");
fwrite($img_file, $string);
fclose($img_file);
$imageMagickPath = "/usr/bin/convert";
$dest = __USPSLABELIMAGE__ . "uspsLabel.tif";
$filename = time() . ".png";
$pngDestPath = __USPSLABELIMAGE__ . $filename;
exec("$imageMagickPath -density 72 -channel RGBA -colorspace RGB -background none -fill none -dither None $dest $pngDestPath");
return $filename;
} else {
return "error";
}
}
Related
I am trying to download a folder which is not compressed in any format like .zip,7-zip. I took code from Get azure blob files from inside Sub Directories using php.
My Folder structure on azure blob storage like that parentFolder>childFolder>1.pdf,2.pdf,3.pdf.
I am trying to download childFolder. I am using below code But I am getting error BlobNotFoundThe specified blob does not exist.
<?php
$storageAccount = 'XXXXXXX';
$containerName = 'XXXXXXX';
$blobName = 'parentFolder/childFolder';
$account_key = 'XXXXXXXXXXXXXXXXXXXXX';
$date = gmdate('D, d M Y H:i:s \G\M\T');
$version = "2019-12-12";
$stringtosign = "GET\n\n\n\n\n\n\n\n\n\n\n\nx-ms-date:". $date . "\nx-ms-version:".$version."\n/".$storageAccount."/".$containerName."/".$blobName;
$signature = 'SharedKey'.' '.$storageAccount.':'.base64_encode(hash_hmac('sha256', $stringtosign, base64_decode($account_key), true));
echo "\n\n" . $signature;
$header = array (
"x-ms-date: " . $date,
"x-ms-version: " . $version,
"Authorization: " . $signature
);
$url="https://$storageAccount.blob.core.windows.net/$containerName/$blobName";
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header);
curl_exec ( $ch );
$result = curl_exec($ch);
echo "\n\n" . $result;
if(curl_errno($ch)){
throw new Exception(curl_error($ch));
}
file_put_contents('C://demo//childFolder', $result); // save the string to a file
curl_close($ch);
Just try the code below that using sasToken and cURL to download all blobs under a folder:
<?php
function generateSharedAccessSignature($accountName,
$storageKey,
$signedPermissions,
$signedService,
$signedResourceType,
$signedStart,
$signedExpiry,
$signedIP,
$signedProtocol,
$signedVersion){
if(empty($accountName)){
trigger_error("The account name is required.");
return;
}
if(empty($storageKey)){
trigger_error("The account key is required.");
return;
}
if(empty($signedPermissions)){
trigger_error("The permissions are required.");
return;
}
if(empty($signedService)){
trigger_error("The services are required.");
return;
}
if(empty($signedResourceType)){
trigger_error("The resource types are required.");
return;
}
if(empty($signedExpiry)){
trigger_error("The expiration time is required.");
return;
}
if(empty($signedVersion)){
trigger_error("The service version is required.");
return;
}
// generate the string to sign
$_toSign = urldecode($accountName) . "\n" .
urldecode($signedPermissions) . "\n" .
urldecode($signedService) . "\n" .
urldecode($signedResourceType) . "\n" .
urldecode($signedStart) . "\n" .
urldecode($signedExpiry) . "\n" .
urldecode($signedIP) . "\n" .
urldecode($signedProtocol) . "\n" .
urldecode($signedVersion) . "\n";
// sign the string using hmac sha256 and get a base64 encoded version_compare
$_signature = base64_encode(hash_hmac("sha256", utf8_encode($_toSign), base64_decode($storageKey), true));
return $_signature;
}
$key= "";
$storageAccount = "";
$containerName = "";
$directoryName = "";
$destDir = "d:/temp/";
$_signedPermissions = "rl"; //read and list permission
$_signedService = "b"; // for blob service
$_signedResourceType = "oc"; //only for access container and object
$_signedStart = "2021-05-31T00:00:00Z"; //sas token start time
$_signedExpiry = "2021-06-10T00:00:00Z"; //sas token expairy time
$_signedIP = NULL; // no IP limit
$_signedProtocol = "https";
$_signedVersion = "2020-02-10";
$_signature = generateSharedAccessSignature($storageAccount,
$key,
$_signedPermissions,
$_signedService,
$_signedResourceType,
$_signedStart,
$_signedExpiry,
$_signedIP,
$_signedProtocol,
$_signedVersion);
$sig = urlencode($_signature);
$sasToken = "sp=$_signedPermissions&srt=$_signedResourceType&ss=$_signedService&st=$_signedStart&se=$_signedExpiry&sv=$_signedVersion&spr=$_signedProtocol&sig=$sig";
$destinationURL = "https://$storageAccount.blob.core.windows.net/$containerName?restype=container&comp=list&prefix=$directoryName&$sasToken";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $destinationURL);
$content = curl_exec($ch);
$xml = simplexml_load_string($content);
foreach ($xml->Blobs->Blob as $i) {
$url ="https://$storageAccount.blob.core.windows.net/$containerName/$i->Name";
//Use basename() function to return the base name of file
$file_name = $destDir.basename($url) ;
//Use file_get_contents() function to get the file
//from url and use file_put_contents() function to
//save the file by using base name
if(file_put_contents( $file_name,file_get_contents($url."?".$sasToken ))) {
echo "$url:File downloaded successfully\n";
}
else {
echo "File downloading failed.";
}
}
?>
I have tested on my side, see result below:
my blobs :
Your approach will not work because the folders in Azure Blob Storage are not real folders. They are virtual folders. Your blob names are parentFolder/childFolder/1.pdf and so on.
To download blobs from a virtual folder, here's what you would need to do:
List blobs in your blob container. Since you only want to download blobs from parentFolder/childFolder, you will have to do prefix search. That will list all the blobs in the desired folder.
Once you have the list, then you can download each blob from that list.
Unfortunately I am not that much knowledgeable about PHP thus I am only giving you some guidance (and not code).
I would also recommend using Azure Storage SDK for PHP instead of consuming the REST API directly. That will make your job much easier. You can find more information about the SDK here: https://github.com/Azure/azure-storage-php.
Here is my code, I have two cURL statements in the same program. The first one uses $ch and second uses $ch1. The problem is first one is getting executed and showing the output but second one does nothing.
<?php
include ('DBconnect.php');
if (isset($_POST['submit'])) {
$verified = "1";
$error = array();
if (empty($_POST['name'])) {
$error[] = 'I am sure you have a name!';
}
else {
$name = $_POST['name'];
}
if (empty($_POST['phone'])) {
$error[] = 'Please enter your phone number with country code';
}
else {
$Phone = $_POST['phone'];
}
if (empty($_POST['Password'])) {
$error[] = 'Please choose a password ';
}
else {
$Password = $_POST['Password'];
}
if (empty($error)) //send to Database if there's no error '
{ // If everything's OK...
// Make sure the phone number is available:
$query_verify_phone = "SELECT * FROM members WHERE Phone ='$Phone'";
$result_verify_phone = mysqli_query($dbc, $query_verify_phone);
if (!$result_verify_phone) { //if the Query Failed ,similar to if($result_verify_phone==false)
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_phone) == 0) { // IF no previous user is using this phone number.
$query_insert_user = "INSERT INTO `members` ( `Name`, `Phone`, `Password`, `Verified`) VALUES ( '$name', '$Phone', '$Password', '$verified')";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
$customerToken = "TOKEN HERE";
$clientTransactionId = rand(55555, 77777);
$duration = "180";
$countryCode = "91";
$z2vToken = "TOKEN HERE";
$postData = array(
'customerToken' => $customerToken,
'clientTransactionId' => $clientTransactionId,
'callerid' => $Phone,
'duration' => $duration,
'countryCode' => $countryCode,
'z2vToken' => $z2vToken,
);
// create post body
$post_body = '';
foreach($postData as $key => $value) {
$post_body.= urlencode($key) . '=' . urlencode($value) . '&';
}
$post_body = rtrim($post_body, '&');
// Initialize CURL data to send via POST to the API
// FIRST ONE CURL REQUEST- WORKING
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.zipdial.com/z2v/startTransaction.action");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_body);
// Execute CURL command and return into variable ch
$string = curl_exec($ch);
curl_close($ch);
$json = json_decode($string);
// now the json has been decoded
// echo "Please do a missed call on: ";
// echo "<img src=' ".$json->img."'>";
$pf = 'fl' . uniqid();
$un = uniqid($pf);
$fpl = 'img' . $un . '.png';
file_put_contents($fpl, file_get_contents($json->img));
Everything above goes fine but the second curl request is not working:
// EVERYTHING ABOVE GOES FINE. BELOW IS SECOND REQUEST- NOT WORKING
$url = "https://api.idolondemand.com/1/api/sync/ocrdocument/v1";
$post = array(
'apikey' => "MY KEY HERE",
'url' => "http://site.ext/users/$fpl",
'mode' => "document_photo"
);
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL, $url);
curl_setopt($ch1, CURLOPT_POST, 1);
curl_setopt($ch1, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
$ocr = curl_exec($ch1);
$jsonocr = json_decode($ocr, true);
$textblock = $jsonocr['text'][0];
echo '<div class="success">Please give a missed call to ' . $textblock['text'] . ' from your registered phone number to activate account. </div>';
curl_close($ch1);
}
else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system error. We apologize for any inconvenience.</div>';
}
}
else { // The phone number is not available.
echo '<div class="errormsgbox" >That phone number has already been registered. </div>';
}
}
else { //If the "error" array contains error msg , display them
echo '<div class="errormsgbox"> <ol>';
foreach($error as $key => $values) {
echo ' <li>' . $values . '</li>';
}
echo '</ol></div>';
}
mysqli_close($dbc); //Close the DB Connection
} // End of the main Submit conditional.
?>
I can make request to second curl request manually from my browser and it works but it isn't working here. What's wrong?
I think you get this error when you dump curl_error($ch1) :
Unknown SSL protocol error in connection to api.idolondemand.com
You can add this line when you curl https if you have no sensitive transiting data :
curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
Here is the code which works for me :
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL, $url);
curl_setopt($ch1, CURLOPT_POST, 1);
curl_setopt($ch1, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, 1);
$ocr = curl_exec($ch1);
var_dump($ocr);
var_dump(curl_error($ch1));
When I do this, I get :
string(97) "{ "message": "Unknown API key", "detail": { "error": 2002, "key": "MY KEY HERE" } }" string(0) ""
I have set VERIFYPEER to false and VERIFYHOST to 1 and it worked.
I need to convert doc file in pdf format
for that I am following saaspose functions mentioned below
(http://api.saaspose.com/v1.0/words/help)
I am not getting an error and a garbage file is uploaded along with doc file but I need to upload pdf file with same doc contents.
private function convertDocToPdf($inputFileName,$outputFileName)
{
$doc = new WordDocument("");//Word document is a class to create new document
$result = $doc->ConvertLocalFile($inputFileName, $outputFileName,"pdf");
}
private function ConvertLocalFile($input_path, $output_path, $output_format) {
try {
$str_uri = "http://api.saaspose.com/v1.0/words/convert?format=" + $output_format;
$signed_uri = Sign($str_uri);
$responseStream = uploadFileBinary($signed_uri, $input_path, "xml");
$v_output = ValidateOutput($responseStream);
if ($v_output === "") {
if ($output_format == "html")
$save_format = "zip";
else
$save_format = $output_format;
saveFile($responseStream,$outputFilename);
return "";
}
else
return $v_output;
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
public static function saveFile($input, $fileName){
$fh = fopen($fileName, 'w') or die("can't open file");
fwrite($fh, $input);
fclose($fh);
}
public static function Sign($UrlToSign) {
// parse the url
$url = parse_url($UrlToSign);
if (isset($url['query']) == "")
$urlPartToSign = $url['path'] . "?appSID=" . 1fc17cb5-6c47-462e-9dfd-d1a9525220fa;
else
$urlPartToSign = $url['path'] . "?" . str_replace(" ","%20",$url["query"]) . "&appSID=" . SaasposeApp::$AppSID;
// Decode the private key into its binary format
$decodedKey = self::decodeBase64UrlSafe(87c027855aebf72e204b3bcd710de1c0);
// Create a signature using the private key and the URL-encoded
// string using HMAC SHA1. This signature will be binary.
$signature = hash_hmac("sha1", $urlPartToSign, $decodedKey, true);
$encodedSignature = self::encodeBase64UrlSafe($signature);
if (isset($url['query']) == "")
return $url["scheme"] . "://" . $url["host"] . str_replace(" ", "%20",$url["path"]) . "?appSID=" . 1fc17cb5-6c47-462e-9dfd-d1a9525220fa . "&signature=" . $encodedSignature;
else
return $url["scheme"] . "://" . $url["host"] . str_replace(" ", "%20",$url["path"]) . "?" . str_replace(" ","%20",$url["query"]) . "&appSID=" . 1fc17cb5-6c47-462e-9dfd-d1a9525220fa . "&signature=" . $encodedSignature;
}
public static function uploadFileBinary($url, $localfile, $headerType="XML") {
$headerType = strtoupper($headerType);
$fp = fopen($localfile, "r");
$session = curl_init();
curl_setopt($session, CURLOPT_VERBOSE, 1);
curl_setopt($session, CURLOPT_URL, $url);
curl_setopt($session, CURLOPT_PUT, 1);
curl_setopt($session, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($session, CURLOPT_HEADER, false);
if ($headerType == "XML") {
curl_setopt($session, CURLOPT_HTTPHEADER, array('Accept: application/xml', 'Content-Type: application/xml'));
} else {
curl_setopt($session, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
}
curl_setopt($session, CURLOPT_INFILE, $fp);
curl_setopt($session, CURLOPT_INFILESIZE, filesize($localfile));
$result = curl_exec($session);
//$error = curl_error($session);
//$http_code = curl_getinfo($session, CURLINFO_HTTP_CODE);
curl_close($session);
fclose($fp);
return $result;
}
public static function ValidateOutput($result)
{
$string = (string)$result;
$validate = array("Unknown file format.", "Unable to read beyond the end of the stream",
"Index was out of range", "Cannot read that as a ZipFile", "Not a Microsoft PowerPoint 2007 presentation",
"Index was outside the bounds of the array", "An attempt was made to move the position before the beginning of the stream",
);
$invalid = 0;
foreach ($validate as $key => $value) {
$pos = strpos($string, $value);
if ($pos === 1)
{
$invalid = 1;
}
}
if($invalid == 1)
return $string;
else
return "";
}
Kindly provide me the solution because this error hampers my work terribly.
I've been putting this off for a while as I just don't seem to have a clue with what I'm doing. I'm trying to use PHP and Curl to talk to the Barclaycard ePDQ MPI. I've done this before using the HSBC XML API but the Barclaycard ePDQ MPI seems to be giving me a few headaches. I have a form which posts card details/address details and the to a page that contains the following functions Please note that I have SSL set up on the domain, CURL is installed on the server, I had the HSBC XML API working just fine on the same box/URL.
<?php
function process_card($users_ip, $Temp_Order_ID, $User_NameX, $First_Name, $Surname, $Address_Line1, $Address_Line2, $Town, $Country, $Postcode, $CardNumber, $CardExpiryDate, $issue_node, $CardCVV, $totalCost ) {
if ($CardCVV == "")
$cvvindicator = 0;
else
$cvvindicator=1;
global $status;
//$amount = $amount * 100;
$xml = '
<?XML version="1.0" encoding="UTF-8"?>
<EngineDocList>
<DocVersion>1.0</DocVersion>
<EngineDoc>
<IPAddress>' . $users_ip . '</IPAddress>
<ContentType>OrderFormDoc</ContentType>
<User>
<Name>XXXXX</Name>
<Password>XXXXXXX</Password>
<ClientId DataType="S32">12345</ClientId>
</User>
<Instructions>
<Pipeline>Payment</Pipeline>
</Instructions>
<OrderFormDoc>
<Mode>T</Mode>
<Id>' . $Temp_Order_ID. '</Id>
<Consumer>
<Email>' . $User_NameX . '</Email>
<BillTo>
<Location>
<Address>
<FirstName>' . $First_Name . '</FirstName>
<LastName>' . $Surname .'</LastName>
<Street1>' . $Address_Line1 . '</Street1>
<Street2>' . $Address_Line2 . '</Street2>
<Street3></Street3>
<City>' . $Town . '</City>
<StateProv>' . $Country . '</StateProv>
<PostalCode>' . $Postcode . '</PostalCode>
<Country>' . getCuntCode($Country) . '</Country>
</Address>
</Location>
</BillTo>
<ShipTo>
<Location>
<Address>
<FirstName>' . $First_Name . '</FirstName>
<LastName>' . $Surname .'</LastName>
<Street1>' . $Address_Line1 . '</Street1>
<Street2>' . $Address_Line2 . '</Street2>
<Street3></Street3>
<City>' . $Town . '</City>
<StateProv>' . $Country . '</StateProv>
<PostalCode>' . $Postcode . '</PostalCode>
<Country>' . getCuntCode($Country) . '</Country>
</Address>
</Location>
</ShipTo>
<PaymentMech>
<CreditCard>
<Type DataType="S32">1</Type>
<Number>' . $CardNumber . '</Number>
<Expires DataType="ExpirationDate" Locale="826">' . $CardExpiryDate . '</Expires>
' . $issue_node . '
<Cvv2Indicator>' . $cvvindicator . '</Cvv2Indicator>
<Cvv2Val>' . $CardCVV . '</Cvv2Val>
</CreditCard>
</PaymentMech>
</Consumer>
<Transaction>
<Type>Auth</Type>
<CurrentTotals>
<Totals>
<Total DataType="Money" Currency="826">' . $totalCost . '</Total>
</Totals>
</CurrentTotals>
<CardholderPresentCode DataType="S32"></CardholderPresentCode>
<PayerSecurityLevel DataType="S32"></PayerSecurityLevel>
<PayerAuthenticationCode></PayerAuthenticationCode>
<PayerTxnId></PayerTxnId>
</Transaction>
</OrderFormDoc>
</EngineDoc>
</EngineDocList>';
$url = "https://secure2.epdq.co.uk:11500";
$params = array("CLRCMRC_XML" => $xml);
$params = formatData($params);
$response = post_to_epdq($url, $xml);
$auth_code = strstr($response, "<AuthCode>");
echo "auth_code=" . $auth_code;
if ($auth_code <> "") {
$splt = split("</AuthCode>", $auth_code);
$status = strip_tags($splt[0]);
return $xml . "<hr/>" . $response . "Good";
} else {
$error = strstr($response, "<Text>");
$splt = split("</Text>", $error);
$status = strip_tags($splt[0]);
return $xml . "<hr/>" . $response . "Bad";
}
}
function post_to_epdq($url, $data) {
set_time_limit(120);
$output = array();
$curlSession = curl_init();
curl_setopt($curlSession, CURLOPT_URL, $url);
curl_setopt($curlSession, CURLOPT_PORT, 443);
curl_setopt($curlSession, CURLOPT_HEADER, 0);
curl_setopt($curlSession, CURLOPT_POST, 1);
curl_setopt($curlSession, CURLOPT_POSTFIELDS, $data);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlSession, CURLOPT_TIMEOUT, 60);
#$response = split(chr(10),curl_exec ($curlSession));
$response = curl_exec($curlSession);
if (curl_error($curlSession)) {
$this->error = curl_error($curlSession);
return "ERROR";
}
curl_close($curlSession);
return $response;
}
function formatData($data) {
$output = "";
foreach ($data as $key => $value)
$output .= "&" . $key . "=" . urlencode($value);
$output = substr($output, 1);
return $output;
}
Needless to say I validate the user input, generate their IP and determine a country code, I then call the above function:
process_card($users_ip,$Temp_Order_ID,$User_NameX,$First_Name,$Surname,$Address_Line1,$Address_Line2,$Town,$Country,$Postcode,$CardNumber, $CardExpiryDate, $issue_node, $CardCVV, $totalCost );
I don't get a response? I'm unsure if the port and url items are incorrect or if the whole CURL request is wrong. Nothing is returned from the request.
Sorry about this being a long post but this is really doing my head in!
Has anyone done this before?
I've managed to fix my problem now. It turned out that the CURL connection to the Barclays website was blocked by a firewall on the server which was why I was getting no error message back.
I modified the CURL code a bit to check for errors:
$data = curl_exec($ch);
if(curl_errno($ch)) {
print curl_error($ch);
}
curl_close ($ch);
This then says: couldn't connect to host at which point I tried it on another server and it got past this error.
The error I am getting now is: "Insufficient permissions to perform requested operation." I have tried all the accounts I have been given but if I log into the EPDQ control panel I seem to only be able to assign up to EPDQ Level 4 and CPI access with no mention of MPI and even though it says technical support is available from 8AM until 12PM, it is not. It is really just office hours for anything but the most basic queries.
Is there any advantage to using this over SagePay? SagePay allows you to send through the individual transaction details as well where Barclays only lets you send the total amount payable and they really do offer support out of office hours.
The only reason I am changing the site to MPI is the fact that with CPI the customer can close the browser before returning to the website so the order details and invoice are not sent so there is no way of knowing what has been purchased.
Thanks
Robin
Howdy, after some playing around here's the correct CURL set up you have to do...
I realise that the variables could be better and I should make this as an object but I just want to get a quick answer up there. The script also needs to sift through the different accept and error messages but this is what I've got so far...
$ch = curl_init();
$url = "https://secure2.epdq.co.uk:11500"; // Don't need to add curl_setopt($curlSession, CURLOPT_PORT, 443); as port is included
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars); // $vars is your XML
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$data = curl_exec($ch);
curl_close ($ch);
$xml = new domDocument;
$xml->loadXML($data);
if (!$xml) {
echo 'Error while parsing the document - Please Contact to determine if payment has gone though';
exit;
}
$x = $xml->getElementsByTagName( "CcErrCode" );
$approved = $x->item(0)->nodeValue;
$xx = $xml->getElementsByTagName( "CcReturnMsg" );
$CcReturnMsg = $xx->item(0)->nodeValue;
if($approved) {
// the card is valid.
$y = $xml->getElementsByTagName( "Id" );
$BCardId = $y->item(1)->nodeValue;
$z = $xml->getElementsByTagName( "MessageList" );
$MessageList = $z->item(0)->nodeValue;
$zz = $xml->getElementsByTagName( "AvsRespCode" );
$AvsRespCode = $zz->item(0)->nodeValue;
$zzz = $xml->getElementsByTagName( "AvsDisplay" );
$AvsDisplay = $zzz->item(0)->nodeValue;
$zzzz = $xml->getElementsByTagName( "ProcReturnMsg" );
$ProcReturnMsg = $zzzz->item(0)->nodeValue;
if($approved == "1"){
echo "approved!<br />";
echo "BCardId: " . $BCardId . ", MessageList=" . $MessageList . ", " . $AvsRespCode . ", " . $AvsDisplay . ", " . $ProcReturnMsg;
die();
}else{
// raise that it's been partially accepted,
echo "partially approved";
echo "BCardId: " . $BCardId . ", MessageList=" . $MessageList . ", " . $AvsRespCode . ", " . $AvsDisplay . ", " . $ProcReturnMsg;
die();
}
}else{
echo "you have been completely knocked back";
$zzzzz = $xml->getElementsByTagName( "Text" );
$BCard_Text = $zzzzz->item(0)->nodeValue;
echo "The reason:" . $BCard_Text;
die();
}
hope this helps other people who have to set this up!
I want to use API of the constant contact and want to insert user email using PHP while user register to the site.
please reply if any help.
Thanks in advance.
// fill in your Constant Contact login and API key
$ccuser = 'USERNAME_HERE';
$ccpass = 'PASS_HERE';
$cckey = 'APIKEY_HERE';
// fill in these values
$firstName = "";
$lastName = "";
$emailAddr = "";
$zip = "";
// represents the contact list identification number(s)
$contactListId = INTEGER_OR_ARRAY_OF_INTEGERS_HERE;
$contactListId = (!is_array($contactListId)) ? array($contactListId) : $contactListId;
$post = new SimpleXMLElement('<entry></entry>');
$post->addAttribute('xmlns', 'http://www.w3.org/2005/Atom');
$title = $post->addChild('title', "");
$title->addAttribute('type', 'text');
$post->addChild('updated', date('c'));
$post->addChild('author', "");
$post->addChild('id', 'data:,none');
$summary = $post->addChild('summary', 'Contact');
$summary->addAttribute('type', 'text');
$content = $post->addChild('content');
$content->addAttribute('type', 'application/vnd.ctct+xml');
$contact = $content->addChild('Contact');
$contact->addAttribute('xmlns', 'http://ws.constantcontact.com/ns/1.0/');
$contact->addChild('EmailAddress', $emailAddr);
$contact->addChild('FirstName', $firstName);
$contact->addChild('LastName', $lastName);
$contact->addChild('PostalCode', $zip);
$contact->addChild('OptInSource', 'ACTION_BY_CUSTOMER');
$contactlists = $contact->addChild('ContactLists');
// loop through each of the defined contact lists
foreach($contactListId AS $listId) {
$contactlist = $contactlists->addChild('ContactList');
$contactlist->addAttribute('id', 'http://api.constantcontact.com/ws/customers/' . $ccuser . '/lists/' . $listId);
}
$posturl = "https://api.constantcontact.com/ws/customers/{$ccuser}/contacts";
$authstr = $cckey . '%' . $ccuser . ':' . $ccpass;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $posturl);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $authstr);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post->asXML());
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/atom+xml"));
curl_setopt($ch, CURLOPT_HEADER, false); // Do not return headers
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0); // If you set this to 0, it will take you to a page with the http response
$response = curl_exec($ch);
curl_close($ch);
// returns true on success, false on error
return (!is_numeric($response));
The developers of ConstantContact have launched PHP library to handle such kind of tasks.
Following version is for older PHP versions (5.2 or lesser). Download code from here: https://github.com/constantcontact/ctct_php_library
Following is an example to add a subscriber's email in your constant contact lists.
After downloading the above library, use following code to add an email in Constant Contact list(s).
session_start();
include_once('ConstantContact.php'); // Set path accordingly
$username = 'YOUR_CONSTANT_CONTACT_USER_NAME';
$apiKey = 'YOUR_API_KEY';
$password = 'YOUR_CONSTANT_CONTACT_PASSWORD';
$ConstantContact = new Constantcontact("basic", $apiKey, $username, $password);
$emailAddress = "new_email#test.com";
// Search for our new Email address
$search = $ConstantContact->searchContactsByEmail($emailAddress);
// If the search did not return a contact object
if($search == false){
$Contact = new Contact();
$Contact->emailAddress = $emailAddress;
//$Contact->firstName = $firstName;
//$Contact->lastName = $lastName;
// represents the contact list identification link(s)
$contactList = LINK_OR_ARRAY_OF_LINKS_HERE;
// For example,
// "http://api.constantcontact.com/ws/customers/USER_NAME/lists/14";
$Contact->lists = (!is_array($contactList)) ? array($contactList) : $contactList;
$NewContact = $ConstantContact->addContact($Contact);
if($NewContact){
echo "Contact Added. This is your newly created contact's information<br /><pre>";
print_r($NewContact);
echo "</pre>";
}
} else {
echo "Contact already exist.";
}
Note: The latest version can be found on the GitHub links given in following URL: http://developer.constantcontact.com/libraries/sample-code.html
But I am not sure if the above example code works with the newer library or not.
If you can't get this to work, you might have to add this curl_setopt:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);