UPS Shipment API. Can't make multipackage shipment - php

I downloaded UPS Shipping API for PHP from DEV center.
Everything woks, except I can make only 1 package shipment. But i need to make multipackage shipments.
There has to be few tags with all Child info for each box in shipment.
But due to tags name are array keys, i can't make duplicate tags.
Can anyone help me to solve this?
<?php
//Configuration
$access = "xxx";
$userid = "xxx";
$passwd = "A123xxx
$wsdl = "WSDLs_Shipping/Ship.wsdl";
$operation = "ProcessShipment";
$endpointurl = 'https://wwwcie.ups.com/webservices/Ship';
//$endpointurl = 'https://onlinetools.ups.com/webservices/Ship';
$outputFileName = "XOLTResult.xml";
function processShipment()
{
//create soap request
$requestoption['RequestOption'] = 'nonvalidate'; //Valid values: nonvalidate = No street level address validation would be performed, but Postal Code/State combination validation would still be performed. validate = No street level address validation would be performed, but City/State/Postal Code/ combination validation would still be performed.
$request['Request'] = $requestoption;
$shipment['Description'] = 'Spare parts'; //The Description of Goods for the shipment. Applies to international and domestic shipments. Provide a detailed description of items being shipped for documents and non-documents. Examples: "annual reports" and "9 mm steel screws".
$shipper['Name'] = 'FD'; //Shippers company name. For forward Shipment 35 characters are accepted, but only 30 characters will be printed on the label.
$shipper['AttentionName'] = 'Andriy'; //попробую убрать Shippers Attention Name. For forward Shipment 35 characters are accepted, but only 30 characters will be printed on the label.
//$shipper['TaxIdentificationNumber'] = '123456'; //Shipper’s Tax Identification Number. Conditionally required if EEI form (International forms) is requested and ship From is not mentioned.
$shipper['ShipperNumber'] = 'xxxxxx'; //Account number
$address['AddressLine'] = 'Polevaya 61a'; //The Shipper street address including name and number (when applicable). Up to three occurrences are allowed; only the first is printed on the label. 35 characters are accepted, but for the first occurrence, only 30 characters will be printed on the label for return shipments.
$address['City'] = 'Kiev';
//$address['StateProvinceCode'] = 'MD'; //Shipper's state or province code. For forward Shipment 5 characters are accepted, but only 2 characters will be printed on the label.For US, PR and CA accounts, the account must be either a daily pickup account, an occasional account, or a customer B.I.N account.
$address['PostalCode'] = '03067';
$address['CountryCode'] = 'UA';
$shipper['Address'] = $address;
$phone['Number'] = '+38067611212';
$phone['Extension'] = '';
$shipper['Phone'] = $phone;
$shipment['Shipper'] = $shipper;
$shipment['ReturnService'] = '1';
$ReturnService['Code'] = '8'; //Return Service types: 2 = UPS Print and Mail (PNM) 3 = UPS Return Service 1-Attempt (RS1) 5 = UPS Return Service 3-Attempt (RS3) 8 = UPS Electronic Return Label (ERL)
$shipment['ReturnService'] = $ReturnService;
//$package['Description'] = 'descr';
$shipto['Name'] = 'Vitaliy '; //Consignee’s company name.
$shipto['AttentionName'] = 'Vitaliy '; //Contact name at the consignee’s location.
$addressTo['AddressLine'] = 'Polevaya 61A'; //Address Line of the consignee. Required: Yes Type: String Max Allowed: 3 Length: 1…35.Max occurrence: 3 Only first two Address Lines will be printed on the label.
$addressTo['City'] = 'Kiev';
$addressTo['PostalCode'] = '03058';
$addressTo['CountryCode'] = 'UA';
$phone2['Number'] = '064655544';
$shipto['Address'] = $addressTo;
$shipto['Phone'] = $phone2;
$shipment['ShipTo'] = $shipto;
$shipfrom['Name'] = ' Sender 1'; //The ship from location’s name or company name. 35 characters are accepted, but for return Shipment only 30 characters will be printed on the label.
$shipfrom['AttentionName'] = 'Sender 1'; //The ship from Attention name. 35 characters are accepted, but for return Shipment only 30 characters will be printed on the label.
$addressFrom['AddressLine'] = '2311 York Rd'; //The Ship from street address including name and number (when applicable). 35 characters are accepted, but for return Shipment only 30 characters will be printed on the label. Required: Yes* Type: String Max Allowed: 3 Length: 1…35. Max occurrence: 3
$addressFrom['City'] = 'Timonium';
//$addressFrom['StateProvinceCode'] = 'MD'; //Origin locations state or province code. Required if ShipFrom tag is in the XML, and ShipFrom Country or territory is US. If ShipFrom country or territory is US or CA, then the value must be a valid US State/ Canadian Province code. If the country or territory is Ireland, the StateProvinceCode will contain the county.
$addressFrom['PostalCode'] = '21093';
$addressFrom['CountryCode'] = 'CN';
$phone3['Number'] = '1234567890';
$phone3['Extension'] = '';
$shipfrom['Address'] = $addressFrom;
$shipfrom['Phone'] = $phone3;
$shipment['ShipFrom'] = $shipfrom;
$shipmentcharge['Type'] = '01';
//$billshipper['CreditCard'] = $creditcard;
$billshipper['AccountNumber'] = 'xxxxxx';
$shipmentcharge['BillShiper'] = 'xxxxxx';
$shipmentcharge['BillShipper'] = $billshipper;
$paymentinformation['ShipmentCharge'] = $shipmentcharge;
$shipment['PaymentInformation'] = $paymentinformation;
$service['Code'] = '65';
$service['Description'] = 'Express Saver';
$shipment['Service'] = $service;
$product['NumberOfPackagesPerCommodity'] = '2';
$internationalForm['Product'] = $product;
$shpServiceOptions['InternationalForms'] = $internationalForm;
$shipment['ShipmentServiceOptions'] = $shpServiceOptions;
$shpLabelDeliveryEmail[LabelLinksIndicator] = ''; //Попробуем, чтобы прислало ссылку на ярлык
$EmailLabelDelivery[EMailAddress] = 'admin#test.ua';
$EmailLabelDelivery[UndeliverableEMailAddress] = 'admin#test.ua';
$EmailLabelDelivery[FromEMailAddress] = 'admin#test.ua';
$shpLabelDeliveryEmail[EMail] = $EmailLabelDelivery;
$shpLabelDelivery[LabelDelivery] = $shpLabelDeliveryEmail;
$shipment['ShipmentServiceOptions'] = $shpLabelDelivery;
$package['Description'] = 'desc'; //Merchandise description of package.Required for shipment with return service.
$packaging['Code'] = '02'; //02 = Customer Supplied package
$packaging['Description'] = 'Nails'; //Description of packaging type. Examples are letter, customer supplied, express box.
$package['Packaging'] = $packaging;
$unit['Code'] = 'CM';
$unit['Description'] = 'CM';
$dimensions['UnitOfMeasurement'] = $unit;
$dimensions['Length'] = '50';
$dimensions['Width'] = '50';
$dimensions['Height'] = '20';
$package['Dimensions'] = $dimensions;
$unit2['Code'] = 'KGS';
$unit2['Description'] = 'KGS';
$packageweight['UnitOfMeasurement'] = $unit2;
$packageweight['Weight'] = '10';
$package['PackageWeight'] = $packageweight;
$shipment['Package'] = $package;
//$shipment['NumOfPiecesInShipment'] = '3';
$labelimageformat['Code'] = 'GIF';
$labelimageformat['Description'] = 'GIF';
$labelspecification['LabelImageFormat'] = $labelimageformat;
$labelspecification['HTTPUserAgent'] = 'Mozilla/4.5';
$shipment['LabelSpecification'] = $labelspecification;
//print_r($shipment1);
// $shipment['DocumentsOnlyIndicator'] = '1'; // IF ONLY documents
$request['Shipment'] = $shipment;
echo "Request.......\n";
print_r($request);
echo "\n\n";
return $request;
}
function processShipConfirm()
{
//create soap request
}
function processShipAccept()
{
//create soap request
}
try
{
$mode = array
(
'soap_version' => 'SOAP_1_1', // use soap 1.1 client
'trace' => 1
);
// initialize soap client
$client = new SoapClient($wsdl , $mode);
//set endpoint url
$client->__setLocation($endpointurl);
//create soap header
$usernameToken['Username'] = $userid;
$usernameToken['Password'] = $passwd;
$serviceAccessLicense['AccessLicenseNumber'] = $access;
$upss['UsernameToken'] = $usernameToken;
$upss['ServiceAccessToken'] = $serviceAccessLicense;
$header = new SoapHeader('http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0','UPSSecurity',$upss);
$client->__setSoapHeaders($header);
if(strcmp($operation,"ProcessShipment") == 0 )
{
//get response
$resp = $client->__soapCall('ProcessShipment',array(processShipment()));
//get status
echo "Response Status: " . $resp->Response->ResponseStatus->Description ."\n";
//save soap request and response to file
$fw = fopen($outputFileName , 'w');
fwrite($fw , "Request: \n" . $client->__getLastRequest() . "\n");
fwrite($fw , "Response: \n" . $client->__getLastResponse() . "\n");
fclose($fw);
}
else if (strcmp($operation , "ProcessShipConfirm") == 0)
{
//get response
$resp = $client->__soapCall('ProcessShipConfirm',array(processShipConfirm()));
//get status
echo "Response Status: " . $resp->Response->ResponseStatus->Description ."\n";
//save soap request and response to file
$fw = fopen($outputFileName , 'w');
fwrite($fw , "Request: \n" . $client->__getLastRequest() . "\n");
fwrite($fw , "Response: \n" . $client->__getLastResponse() . "\n");
fclose($fw);
}
else
{
$resp = $client->__soapCall('ProcessShipeAccept',array(processShipAccept()));
//get status
echo "Response Status: " . $resp->Response->ResponseStatus->Description ."\n";
//save soap request and response to file
$fw = fopen($outputFileName ,'w');
fwrite($fw , "Request: \n" . $client->__getLastRequest() . "\n");
fwrite($fw , "Response: \n" . $client->__getLastResponse() . "\n");
fclose($fw);
}
}
catch(Exception $ex)
{
print_r ($ex);
}
?>

Check this one UPS API wsdl soap call - cannot set multiple packages
Your problematic code:
$package['Description'] = 'desc'; //Merchandise description of package.Required for shipment with return service.
$packaging['Code'] = '02'; //02 = Customer Supplied package
$packaging['Description'] = 'Nails'; //Description of packaging type. Examples are letter, customer supplied, express box.
$package['Packaging'] = $packaging;
$unit['Code'] = 'CM';
$unit['Description'] = 'CM';
$dimensions['UnitOfMeasurement'] = $unit;
$dimensions['Length'] = '50';
$dimensions['Width'] = '50';
$dimensions['Height'] = '20';
$package['Dimensions'] = $dimensions;
$unit2['Code'] = 'KGS';
$unit2['Description'] = 'KGS';
$packageweight['UnitOfMeasurement'] = $unit2;
$packageweight['Weight'] = '10';
$package['PackageWeight'] = $packageweight;
$shipment['Package'] = $package; //Where is the second package?
Something like this should work:
$package['Shipment']['Package'] = array();
foreach ($packaging as $p) {
$pkg = array();
$pkg['PackagingType'] = array(
'Code' => '02',
'Description' => 'Nails'
);
$pkg['PackageWeight'] = array(
'Weight' => (int)$p["weight"],
'UnitOfMeasurement' => array('Code' => 'KGS', 'Description' => 'KGS')
);
$pkg['Dimensions'] = array(
'Length' => (int)$p["length"],
'Width' => (int)$p["width"],
'Height' => (int)$p["height"],
'UnitOfMeasurement' => array('Code' => 'CM', 'Description' => 'CM')
);
array_push($package['Shipment']['Package'], $pkg);
}

Related

Update multiple user details when new user is registered in laravel php

Here is register new user code in php laravel-5.4 mysql
public function store(Request $request)
{
$epincheck = $request->epin;
if (Epin::where('epin', '=', '75656565')->exists()) {
// DB::table('epins')->where('epin', $epincheck)->delete();
$post = new Admin();
$post->name = $request->name;
$post->email = $request->email;
$post->plan = $request->plan;
$post->epin = $epincheck;
$post->ref = $request->ref;
$post->mobile = $request->mobile;
$post->password = bcrypt($request->password);
$post->save();
//other trims
$referal_user = $request->ref;
$referal_email = DB::table('admins')->where('mobile', $referal_user)->first();
$referal_id = $referal_email->id;
$update_ref_user = Admin::find($referal_id);
$previous_users_left = $referal_email->user_left;
$previous_users_right = $referal_email->user_right;
$direct_referal = $referal_email->direct_referal;
$list_all_right_user = $referal_email->user_listing_right;
$list_all_left_user = $referal_email->user_listing_left;
$left_count = $referal_email->no_user_left;
$right_count = $referal_email->no_user_right;
$direct_count = $referal_email->no_direct_referal;
if(!$previous_users_right && $previous_users_left )
{
$update_ref_user->user_right = $request->email ;
$update_ref_user->no_user_right = $right_count+1 ;
$update_ref_user->user_listing_right = $request->email . ' , ' . $list_all_right_user ;
$update_ref_user->save();
$last_updated_id = $update_ref_user->id;
$update_up_line = DB::table('admins')->where('id', $last_updated_id);
$update_up_line_list = $update_up_line->id;
// $update_up_line = Admin::find($last_updated_id);
/* $update_up_line_update->user_listing_right = $request->email;
$update_up_line-> save();*/
//looping get referal id -> find referee -> update ;
//find last referal id -> find referee -> update ;
//find referal id -> find referee -> update ;
//find referal id -> find referee -> update ;
//find referal id -> find referee -> update ;
//when there is no ref_no loop ends
//stop when count ends;
}
if(!$previous_users_left)
{
$update_ref_user->user_left = $request->email ;
$update_ref_user->no_user_left = $left_count + 1 ;
$update_ref_user->user_listing_left = $request->email . ' , ' . $list_all_left_user ;
$update_ref_user->save();
}
if($previous_users_left && $previous_users_right)
{
$update_ref_user->direct_referal = $direct_referal . ' , ' . $request->email ;
$update_ref_user->no_direct_referal = $direct_count +1 ;
$update_ref_user->save();
}
//sms gatewat
/*Send SMS using PHP*/
return redirect('/admin/login');
// \Session::flash('msg', 'Changes Saved.' );
}
else {
echo "You Have Entered Invalid Pin";
}
}
When a new user is registered he inputs reference code in signup form.
I want that when a new user is registered with mobile->'123' and reference number '987' then
step 1) find "reference number" of new registered user then search "reference number" in "mobile" field of all registered user then add 50% of $200(it is currency)to his income add previous user's name in a database field name="user_under"
step 2) find "reference number" of previous user then search "reference number" in "mobile" field of all registered user then add 30% of $200(it is currency)to his income add previous user's name in a database field name="user_under"
step 3) find "reference number" of previous user then search "reference number" in "mobile" field of all registered user then add 10% of $200(it is currency) to his income and add previous user's name in a database field name="user_under"
step 4) find "reference number" of previous user then search "reference number" in "mobile" field of all registered user then add previous user's name in a database field name="user_under"
******step 4 continues till reference number= null/ no value
I cannot understand how to apply the logic
#####edit
#jeffrey
here is manual code for 5th level need to automate it using while recursive
public function store(Request $request)
{
$post = new Admin();
$post->name = 'nill';
$post->email = $request->email;
$post->plan = 'uuiuii';
$post->epin = '9999';
$post->ref = $request->ref;
$post->mobile = $request->mobile;
$post->password = bcrypt($request->password);
$post->save();
$referal_user = $request->ref;
$referal_email = DB::table('admins')->where('mobile', $referal_user)->first();
$referal_id = $referal_email->id;
$right_count = $referal_email->no_user_right;
$list_all_right_user = $referal_email->user_listing_right;
//first update
$update_ref_user = Admin::find($referal_id);
$get_user_previous = $referal_email->user_listing_right;
$update_ref_user->user_right = $request->email;
$update_ref_user->no_user_right = $right_count + 1;
$update_ref_user->user_listing_right = $request->email . ' , ' . $get_user_previous;
$update_ref_user->save();
$last_updated_id = $update_ref_user->ref;
///next
///
// echo $last_updated_id;
$ref_previous2 = $last_updated_id;
if($ref_previous2 ) {
$referal_email2 = DB::table('admins')->where('mobile', $last_updated_id)->first();
$get_user_previous2 = $referal_email2->user_listing_right;
$update_ref_user_id_2 = $referal_email2->id;
$update_ref_user2 = Admin::find($update_ref_user_id_2);
$update_ref_user2->user_right = 'jhkkkj';
$update_ref_user2->no_user_right = $right_count + 1;
$update_ref_user2->user_listing_right = $request->email . ' , ' . $get_user_previous2;
$update_ref_user2->save();
$ref_previous3 = $update_ref_user2->ref;
if($ref_previous3 ) {
$last_updated_id3 = $update_ref_user2->ref;
$referal_email3 = DB::table('admins')->where('mobile', $last_updated_id3)->first();
$get_user_previous3 = $referal_email3->user_listing_right;
$update_ref_user_id_3 = $referal_email3->id;
$update_ref_user3 = Admin::find($update_ref_user_id_3);
$update_ref_user3->user_right = 'jhkkkj';
$update_ref_user3->no_user_right = $right_count + 1;
$update_ref_user3->user_listing_right = $request->email . ' , ' . $get_user_previous3;
$update_ref_user3->save();
$ref_previous4 = $update_ref_user3->ref;
if($ref_previous4 ) {
$last_updated_id4 = $update_ref_user3->ref;
$referal_email4 = DB::table('admins')->where('mobile', $last_updated_id4)->first();
$get_user_previous4 = $referal_email4->user_listing_right;
$update_ref_user_id_4 = $referal_email4->id;
$update_ref_user4 = Admin::find($update_ref_user_id_4);
$update_ref_user4->user_right = 'jhkkkj';
$update_ref_user4->no_user_right = $right_count + 1;
$update_ref_user4->user_listing_right = $request->email . ' , ' . $get_user_previous4;
$update_ref_user4->save();
$ref_previous5 = $update_ref_user4->ref;
if($ref_previous5 ) {
$last_updated_id5 = $update_ref_user4->ref;
$referal_email5 = DB::table('admins')->where('mobile', $last_updated_id5)->first();
$get_user_previous5 = $referal_email5->user_listing_right;
$update_ref_user_id_5 = $referal_email4->id;
$update_ref_user5 = Admin::find($update_ref_user_id_5);
$update_ref_user5->user_right = 'jhkkkj';
$update_ref_user5->no_user_right = $right_count + 1;
$update_ref_user5->user_listing_right = $request->email . ' , ' . $get_user_previous5;
$update_ref_user5->save();
}
}
}
}
//next
//4th update
///five
///
///
return redirect('/admin/register2');
}
#############here is the solution
$referal_user = $request->ref;
$referal_email = DB::table('admins')->where('mobile', $referal_user)->first();
$referal_id = $referal_email->id;
$right_count = $referal_email->no_user_right;
$list_all_right_user = $referal_email->user_listing_right;
$ref = $request->ref;
$mobile = $request->mobile;
$user_listing_left = $referal_email->user_listing_left;
while( $refUser = Admin::where('mobile', $ref)->first() )
{
$refUser->user_left = $request->email;
$refUser->user_listing_left = $refUser->user_listing_left . "," .$request->email;
$refUser->save();
// Update $ref to find the next guy
$ref = $refUser->ref;
}
I don't understand the question fully, but I'll give it a shot.
Recursive is the key word here. You seem to want to go up the tree of reference, and depending on what level you are, add a certain amount of $ to that person. I do however not understand what you mean by add previous user's name in a database field name="user_under" the field is not visible as well...
$percentages = [50, 30, 10, 5, 2, 1, 0.5];
$iteration = 0;
$ref = $request->ref;
while( $refUser = Admin::where('ref', $ref)->first() && $percentages[$iteration] )
{
$refUser->income += floor( 200 * $percentages[$iteration++] );
$refUser->save();
// Update $ref to find the next guy
$ref = $refUser->ref;
}
The second condition for the while loop, is to make sure that if the $percentages array is shorted than the tree in the database, it won't break and quits giving money. You may of course extend the array.
I hope this is what you asked, else leave a comment.

Substract x% fee when adding fund to the account in PHP supersite resellerclub

I have a small query. When ever my customer enters amount to add funds to his account, the entire amount is added to his balance. I actually want to subtract "x%" as processing/payment gateway fee and add the remaining balance to his account.
Two options are mentioned in the below code. i.e selling currency amount and accounting currency amount.
Selling will be the amount he is entering and the accounting currency amount is the amount which will be added to his account balance after subtraction of "x%".
I have tried $_SESSION['accountingcurencyamount']=$sellingCurrencyAmount - ($sellingCurrencyAmount * (3/100));.
Following is the code :
<?php session_start();
#session_save_path("./"); ?>
<?php
include('config.php');
require('functions.php');
include('payment.php')?>
<?php
error_reporting(0);
/*Reseller Club Fields starts*/
$paymentTypeId = $_GET["paymenttypeid"]; //payment type id
$transId = $_GET["transid"]; //This refers to a unique transaction ID which we generate for each transaction
$userId = $_GET["userid"]; //userid of the user who is trying to make the payment
$userType = $_GET["usertype"]; //This refers to the type of user perofrming this transaction. The possible values are "Customer" or "Reseller"
$transactionType = $_GET["transactiontype"]; //Type of transaction (ResellerAddFund/CustomerAddFund/ResellerPayment/CustomerPayment)
$invoiceIds = $_GET["invoiceids"]; //comma separated Invoice Ids, This will have a value only if the transactiontype is "ResellerPayment" or "CustomerPayment"
$debitNoteIds = $_GET["debitnoteids"]; //comma separated DebitNotes Ids, This will have a value only if the transactiontype is "ResellerPayment" or "CustomerPayment"
$description = $_GET["description"];
$sellingCurrencyAmount = $_GET["sellingcurrencyamount"]; //This refers to the amount of transaction in your Selling Currency
// echo "Amount: " .$sellingCurrencyAmount;
$accountingCurrencyAmount = $_GET["accountingcurrencyamount"]; //This refers to the amount of transaction in your Accounting Currency
$redirectUrl = $_GET["redirecturl"]; //This is the URL on our server, to which you need to send the user once you have finished charging him
$checksuma = $_GET["checksum"]; //checksum for validation
/*Reseller Club Fields ends*/
$order_id=$_GET["transid"];
$amount= $_GET["sellingcurrencyamount"];
$currency=$currency;
$cancel_url=$redirect_url;
$language="EN";
$billing_name=$_GET["name"];
$billing_address=$_GET["address1"] ;
$billing_city=$_GET["city"];
$billing_state=$_GET["state"];
$billing_zip=$_GET["zip"];
$billing_country=$_GET["country"];
$billing_tel=$_POST["telNoCc"] . $_GET["telNo"];
$billing_email=$_GET["emailAddr"];
$delivery_name=$billing_name;
$delivery_address=$billing_address;
$delivery_city=$billing_city;
$delivery_state=$billing_state;
$delivery_zip=$billing_zip;
$delivery_country= $billing_country;
$delivery_tel=$billing_tel;
$merchant_param1="";
$merchant_param2="";
$merchant_param3="";
$merchant_param4="";
$merchant_param5="";
$promo_code="";
$customer_Id="";
/*Reseller Club code starts*/
if(verifyChecksum1($paymentTypeId, $transId, $userId, $userType, $transactionType, $invoiceIds, $debitNoteIds, $description, $sellingCurrencyAmount, $accountingCurrencyAmount, $key, $checksuma))
{
$_SESSION['redirecturl']=$redirectUrl;
$_SESSION['transid']=$transId;
$_SESSION['sellingcurrencyamount']=$sellingCurrencyAmount;
$_SESSION['accountingcurencyamount']=$accountingCurrencyAmount;
// $_SESSION['accountingcurencyamount']=$sellingCurrencyAmount - ($sellingCurrencyAmount * (3/100));
$checksumStatus=1;
}
else
{
$checksumStatus=0;
$base_url="";
}
//echo "Check: ".$checksumStatus;
//
// echo "<br/>Pay Id: ". $paymentTypeId;
// echo "<br/>Tran Id: ". $transId;
// echo "<br/>User Id: ". $userId;
// echo "<br/>User Type: ". $userType;
// echo "<br/>Tramscation Type: ". $transactionType;
// echo "<br/>Invoice ID: ". $invoiceIds;
// echo "<br/>debit note: ". $debitNoteIds;
// echo "<br/>Description: ". $description;
// echo "<br/>Selling Currency: ". $sellingCurrencyAmount;
// echo "<br/>Account currency: ". $accountingCurrencyAmount;
// echo "<br/>Key: ". $key;
// echo "<br/>Checksum: ". $checksuma;
/*Reseller Club code ends*/
class ProcessPayment {
function __construct(){
$this->paymentConfig = new payment_config();
}
function requestMerchant(){
$payment = new payment();
$datenow = date("d/m/Y h:m:s");
$modifiedDate = str_replace(" ", "%20", $datenow);
$payment->url = $this->paymentConfig->base_url;//$this->paymentConfig->Url;
$postFields = "";
$postFields .= "&login=".$this->paymentConfig->login_id;//$this->paymentConfig->Login;
$postFields .= "&pass=".$this->paymentConfig->password;//$this->paymentConfig->Password;
$postFields .= "&ttype=NBFundTransfer";//.$_POST['TType'];
$postFields .= "&prodid=HILL";//.$_POST['product'];
$postFields .= "&amt=".$GLOBALS['sellingCurrencyAmount'];
$postFields .= "&txncurr=".$this->paymentConfig->currency;//.$this->paymentConfig->TxnCurr;
$postFields .= "&txnscamt=".$this->paymentConfig->trn_service;//$this->paymentConfig->TxnScAmt;
$postFields .= "&clientcode=".urlencode(base64_encode($GLOBALS['billing_name']));
$postFields .= "&txnid=".rand(0,999999);
$postFields .= "&date=".$modifiedDate;
$postFields .= "&ru=".$this->paymentConfig->redirect_url;
$postFields .= "&custacc=".$GLOBALS['billing_tel'];
// Not required for merchant
//$postFields .= "&bankid=".$_POST['bankid'];
$sendUrl = $payment->url."?".substr($postFields,1)."\n";
$this->writeLog($sendUrl);
$returnData = $payment->sendInfo($postFields);
$this->writeLog($returnData."\n");
$xmlObjArray = $this->xmltoarray($returnData);
$url = $xmlObjArray['url'];
$postFields = "";
$postFields .= "&ttype=NBFundTransfer";//.$_POST['TType'];
$postFields .= "&tempTxnId=".$xmlObjArray['tempTxnId'];
$postFields .= "&token=".$xmlObjArray['token'];
$postFields .= "&txnStage=1";
$url = $payment->url."?".$postFields;
$this->writeLog($url."\n");
//echo "URL ". $url;
//echo "amount: " . $GLOBALS['sellingCurrencyAmount'];
//echo "<br/>Base URL ". $this->paymentConfig->base_url;
header("Location: ".$url);
}
function writeLog($data){
$fileName = date("Y-m-d").".txt";
$fp = fopen("log/".$fileName, 'a+');
$data = date("Y-m-d H:i:s")." - ".$data;
fwrite($fp,$data);
fclose($fp);
}
function xmltoarray($data){
$parser = xml_parser_create('');
xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, trim($data), $xml_values);
xml_parser_free($parser);
$returnArray = array();
$returnArray['url'] = $xml_values[3]['value'];
$returnArray['tempTxnId'] = $xml_values[5]['value'];
$returnArray['token'] = $xml_values[6]['value'];
return $returnArray;
}
}
$processPayment = new ProcessPayment();
$processPayment->requestMerchant();
?>
Substracting the amount multiplied by .3 (which would substract 30 percent of the value) should work:
$sellingCurrencyAmount - ($sellingCurrencyAmount * .3);
Ive tested the following:
$value = 100;
$calculated = $value - ($value * .3);
var_dump($calculated); // float 70
Maybe you are having problems due to the type of the value (float, int), in which case you could take a look at round
After taking a closer look, you are using $GLOBALS['sellingCurrencyAmount'] after in your post request, shouldn't you be using $_SESSION['sellingCurrencyAmount'] ?

OPENCART APP -> Customer Orders not being bound to Customer

Customer Orders not being bound to Customer
Postby DrFeeling » Mon Jun 01, 2015 4:05 pm
Good Afternoon peeps, I'm currently developping a mobile app for opencart that will bridge both tecnologies.
Most of the stuff is already active but I have a problem regarding order histories.
So, when you purchase something, through the main site, the default template of opencart, it generates a order history, that you can see through the website (my orders) or through the admin page.
My problem is that, whenever someone purchases something from the app, the orders of that costumer arent uptaded.
Though they appear in the main admin window (the dashboard) , once you go to customer (sales -> customers -> customers) the order made by the app isnt listed in the myOrders part of that customer, making both the "my previous orders" and the order of that customer inexistent in that place, but they appear in the dashboard and the notification email is foward to the customer
Please help me, and thanks for the support :D
Only order 261 (which was made in the website) is bounded to its customer, the others arent, as you can see in the pic below
AM I missing a parameter or a validation when the checkout process happens?
http://s16.postimg.org/y2h9rg5fp/image.jpg
EDIT: My code to create a order:
public function end_order() {
if ($this->customer->isLogged() == true){
$data= array();
$datap = array();
$this->load->model('account/customer');
$this->load->model('quickcheckout/order');
$this->load->model('checkout/order');
$myArray = $_POST["formData"];
$treatedArray = array();
foreach($myArray as $value) {
$treatedArray[$value['name']] = $value['value'];
}
$email = $_POST["email"];
$delivery = $_POST["deladdress"];
$delivery = array_shift($delivery); // sobe um nivel as posiçoes do array, em vez de usar $array[0]['bla'] , usasse so $array['bla']
$data2 = array();
$data2 = $this->model_account_customer->getCustomerByEmail($email);
$Method = $_POST["PayMethod"];
$TotalCheckout = $_POST["TotalCheck"];
$IP = $_POST["IP"];
$Agent = $_POST["User"];
$Products = $_POST["Prod"];
$length = count($Products);
for ($i = 0; $i < $length; $i++) {
(int)$datap[$i]['product_id'] = $Products[$i]['Id'];
$datap[$i]['name'] = $Products[$i]['Name'];
$datap[$i]['model'] = $Products[$i]['modelo'];
(int)$datap[$i]['quantity'] = $Products[$i]['NItems'];
$datap[$i]['price'] = $Products[$i]['Preco'];
$datap[$i]['total'] = $Products[$i]['Total'];
$datap[$i]['tax'] = 0; //$Products[$i]['Tax'];
(int)$datap[$i]['reward'] = 0; //$Products[$i]['Reward'];
}
$url = $myurl;
$data['invoice_prefix'] = $this->config->get('config_invoice_prefix');
$data['store_id'] = $this->config->get('config_store_id');
$data['store_name'] = "Loja Teste";
$data['store_url'] = $url;
$data['firstname'] = $data2['firstname'] ;
$data['lastname'] = $data2['lastname'];
$data['email'] = $data2['email'];
$data['telephone'] = $data2['telephone'];
$data['fax'] = $data2['fax'];
$data['payment_firstname'] = $delivery['firstname'];
$data['payment_lastname'] = $delivery['lastname'];
$data['payment_company'] = $delivery['company'];
$data['payment_company_id'] = $delivery['company_id'];;
$data['tax_id'] = $delivery['tax_id'];
$data['payment_address_1'] = $delivery['address_1'];
$data['payment_address_2'] = $delivery['address_2'];
$data['payment_city'] = $delivery['city'];
$data['payment_postcode'] = $delivery['postcode'];
$data['payment_country'] = $delivery['country'];
$data['payment_country_id'] = $delivery['country_id'];
$data['payment_zone'] = $delivery['zone'];
$data['payment_zone_id'] = $delivery['zone_id'];
$data['payment_method'] = "Cash On Delivery";
$data['payment_code'] = 1;
$data['total'] = $TotalCheckout;
//NOTA: esta duas variaveis abaixo servem para tratar dos preços, alterar depois para quando a loja tiver opçoes de escolher preços
$data['language_id'] = (int)$this->config->get('config_language_id');
$data['accept_language'] = $this->request->server['HTTP_ACCEPT_LANGUAGE'];
$data['currency_id'] = (int)2;
$data['currency_code'] = "USD";
$data['currency_value'] = (float)1.00000000;
$data['ip'] = $IP;
$data['forwarded_ip'] = $IP;
$data['user_agent'] = $Agent;
$data['products'] = $datap;
(int)$order = $this->model_checkout_order->addOrder($data);
$this->model_checkout_order->confirm($order, 1 , $comment = '', $notify = false);
echo ("teste");
}
}

Shipping Address not displayed in the Paypal Transaction Details page

I am unable to get the shipping Addresses of my customers in the 'Transacton Details' page.
It's displaying the following message.
'We have no shipping address on file'
The issue mainly happens when users use PaypalPro (Direct Payment) option.
Can anyone help me in this issue.
Note:
This is my code corresponding to the DoDirectPayment Request.
class ProAuthorizeRequest extends AbstractRequest
{
protected $action = 'Authorization';
public function getData()
{
$data = $this->getBaseData('DoDirectPayment');
$this->validate('amount', 'card');
$this->getCard()->validate();
$data['PAYMENTACTION'] = $this->action;
$data['AMT'] = $this->getAmount();
$data['CURRENCYCODE'] = $this->getCurrency();
$data['INVNUM'] = $this->getTransactionId();
$data['DESC'] = $this->getDescription();
// add credit card details
$data['ACCT'] = $this->getCard()->getNumber();
$data['CREDITCARDTYPE'] = $this->getCard()->getBrand();
$data['EXPDATE'] = $this->getCard()->getExpiryMonth().$this->getCard()->getExpiryYear();
$data['STARTDATE'] = $this->getCard()->getStartMonth().$this->getCard()->getStartYear();
$data['CVV2'] = $this->getCard()->getCvv();
$data['ISSUENUMBER'] = $this->getCard()->getIssueNumber();
$data['IPADDRESS'] = $this->getClientIp();
$data['FIRSTNAME'] = $this->getCard()->getFirstName();
$data['LASTNAME'] = $this->getCard()->getLastName();
$data['EMAIL'] = $this->getCard()->getEmail();
$data['STREET'] = $this->getCard()->getAddress1();
$data['STREET2'] = $this->getCard()->getAddress2();
$data['CITY'] = $this->getCard()->getCity();
$data['STATE'] = $this->getCard()->getState();
$data['ZIP'] = $this->getCard()->getPostcode();
$data['COUNTRYCODE'] = strtoupper($this->getCard()->getCountry());
return $data;
}
}
For DoDirectPayment you need to also include the SHIPTO variables:
public function getData()
{
$data = $this->getBaseData('DoDirectPayment');
$this->validate('amount', 'card');
$this->getCard()->validate();
$data['PAYMENTACTION'] = $this->action;
$data['AMT'] = $this->getAmount();
$data['CURRENCYCODE'] = $this->getCurrency();
$data['INVNUM'] = $this->getTransactionId();
$data['DESC'] = $this->getDescription();
// add credit card details
$data['ACCT'] = $this->getCard()->getNumber();
$data['CREDITCARDTYPE'] = $this->getCard()->getBrand();
$data['EXPDATE'] = $this->getCard()->getExpiryMonth().$this->getCard()->getExpiryYear();
$data['STARTDATE'] = $this->getCard()->getStartMonth().$this->getCard()->getStartYear();
$data['CVV2'] = $this->getCard()->getCvv();
$data['ISSUENUMBER'] = $this->getCard()->getIssueNumber();
$data['IPADDRESS'] = $this->getClientIp();
$data['FIRSTNAME'] = $this->getCard()->getFirstName();
$data['LASTNAME'] = $this->getCard()->getLastName();
$data['EMAIL'] = $this->getCard()->getEmail();
$data['STREET'] = $this->getCard()->getAddress1();
$data['STREET2'] = $this->getCard()->getAddress2();
$data['CITY'] = $this->getCard()->getCity();
$data['STATE'] = $this->getCard()->getState();
$data['ZIP'] = $this->getCard()->getPostcode();
$data['COUNTRYCODE'] = strtoupper($this->getCard()->getCountry());
//shipping information as you want displayed on transaction details. name is a single field.
$data['SHIPTONAME'] = $this->getCard()->getFirstName() . " " . $this->getCard()->getLastName();
$data['SHIPTOSTREET'] = $this->getCard()->getAddress1();
$data['SHIPTOSTREET2'] = $this->getCard()->getAddress2();
$data['SHIPTOCITY'] = $this->getCard()->getCity();
$data['SHIPTOSTATE'] = $this->getCard()->getState();
$data['SHIPTOZIP'] = $this->getCard()->getPostcode();
$data['SHIPTOCOUNTRYCODE'] = strtoupper($this->getCard()->getCountry());
return $data;
}

Currency Conversion using PHP [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
I'm looking for a way to convert any amount from one currency to another on a website. The user would enter something like '100' and select USD as the currency, and then chooses Australian or Canadian dollars as the currency to convert to. When he clicks the 'Convert' button, I'd like to convert that amount automatically, through some API, and show him the amount in the currency he chose to convert to.
Any ideas?
After searching a lot, found this.
// Fetching JSON
$req_url = 'https://api.exchangerate-api.com/v4/latest/USD';
$response_json = file_get_contents($req_url);
// Continuing if we got a result
if(false !== $response_json) {
// Try/catch for json_decode operation
try {
// Decoding
$response_object = json_decode($response_json);
// YOUR APPLICATION CODE HERE, e.g.
$base_price = 12; // Your price in USD
$EUR_price = round(($base_price * $response_object->rates->EUR), 2);
}
catch(Exception $e) {
// Handle JSON parse error...
}
}
This is working fine.
The snippet is from: https://www.exchangerate-api.com/docs/php-currency-api
This method is using Yahoo currency API
Full tutorial : Currency Converter in PHP, Python, Javascript and jQuery
function currencyConverter($currency_from, $currency_to, $currency_input) {
$yql_base_url = "http://query.yahooapis.com/v1/public/yql";
$yql_query = 'select * from yahoo.finance.xchange where pair in ("' . $currency_from . $currency_to . '")';
$yql_query_url = $yql_base_url . "?q=" . urlencode($yql_query);
$yql_query_url .= "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
$yql_session = curl_init($yql_query_url);
curl_setopt($yql_session, CURLOPT_RETURNTRANSFER, true);
$yqlexec = curl_exec($yql_session);
$yql_json = json_decode($yqlexec, true);
$currency_output = (float) $currency_input * $yql_json['query']['results']['rate']['Rate'];
return $currency_output;
}
$currency_input = 2;
//currency codes : http://en.wikipedia.org/wiki/ISO_4217
$currency_from = "USD";
$currency_to = "INR";
$currency = currencyConverter($currency_from, $currency_to, $currency_input);
echo $currency_input . ' ' . $currency_from . ' = ' . $currency . ' ' . $currency_to;
An example of converting EUR to USD
$url = 'http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=EUR&ToCurrency=USD';
$xml = simpleXML_load_file($url,"SimpleXMLElement",LIBXML_NOCDATA);
if($xml === FALSE)
{
//deal with error
}
else {
$rate = $xml;
}
My 2017 solution is a very lightweight function that gets the current exchange informations from the fixer.io API. It also stores the exchange rate in a daily cookie to prevent further heavy web loading time. You can also choose Sessions for that or remove it:
function convertCurrency($amount, $from = 'EUR', $to = 'USD'){
if (empty($_COOKIE['exchange_rate'])) {
$Cookie = new Cookie($_COOKIE);
$curl = file_get_contents_curl('http://api.fixer.io/latest?symbols='.$from.','.$to.'');
$rate = $curl['rates'][$to];
$Cookie->exchange_rate = $rate;
} else {
$rate = $_COOKIE['exchange_rate'];
}
$output = round($amount * $rate);
return $output;
}
Example usage to convert 100 euro to pounds:
echo convertCurrency(100, 'EUR', 'GBP');
Use Given code for currency Converter PHP
public function convertCurrency($from, $to, $amount)
{
$url = file_get_contents('https://free.currencyconverterapi.com/api/v5/convert?q=' . $from . '_' . $to . '&compact=ultra');
$json = json_decode($url, true);
$rate = implode(" ",$json);
$total = $rate * $amount;
$rounded = round($total);
return $total;
}
I like the first solution but there seems to be on BIG problem with it.
I tried to implement it into a payment gateway but I kept on getting a result of 1.
This perplexed me and I eventually found that it is because there is a space used by google for the thousands sparator. Thus the amount of 1 500.00 was returned as one since the rest was exploded. I have created a quick and dirty fix for it.
Let me know if anyone else has experienced this problem.
Here is my solution:
function currency($from_Currency,$to_Currency,$amount) {
$amount = urlencode($amount);
$from_Currency = urlencode($from_Currency);
$to_Currency = urlencode($to_Currency);
$url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency";
$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$rawdata = curl_exec($ch);
curl_close($ch);
$data = explode('"', $rawdata);
$data = explode('.', $data['3']);
$data[0] = str_replace(" ", "",preg_replace('/\D/', '', $data[0]));
if(isset($data[1])){
$data[1] = str_replace(" ", "",preg_replace('/\D/', '', $data[1]));
$var = $data[0].".".$data[1];
} else{
$var = $data[0];
}
return round($var,2); }
This is what I'm using:
function exchangeRate( $amount, $from, $to)
{
switch ($from) {
case "euro":
$from_Currency = "EUR";
break;
case "dollar":
$from_Currency = "USD";
break;
case "pounds":
$from_Currency = "GBP";
break;
}
switch ($to) {
case "euro":
$to_Currency = "EUR";
break;
case "dollar":
$to_Currency = "USD";
break;
case "pound":
$to_Currency = "GBP";
break;
}
$amount = urlencode($amount);
$from_Currency = urlencode($from_Currency);
$to_Currency = urlencode($to_Currency);
$get = file_get_contents("https://www.google.com/finance/converter?a=$amount&from=" . $from_Currency . "&to=" . $to_Currency);
$get = explode("<span class=bld>",$get);
$get = explode("</span>",$get[1]);
$converted_amount = preg_replace("/[^0-9\.]/", null, $get[0]);
return round($converted_amount, 2);
}
I used the following PHP to pull data from the ECB as Stefan Gehrig suggested.
<?php
try {
$xml_string = file_get_contents("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
$xml = new SimpleXMLElement($xml_string);
$cxml = $xml->xpath('//*[#currency]');
//anchored to USD in this case
$usx = $xml->xpath('//*[#currency="USD"]');
$base = floatval(strval($usx[0]['rate']));
//create a simple associative array with the 3-letter code
//as the key and the rate as the value
$c_arr = array();
foreach ($cxml as $c) {
$cur = strval($c['currency']);
$rate = floatval(strval($c['rate']))/$base;
$c_arr[$cur] = $rate;
}
//add the euro since it's assumed as the base rate for the ECB
$c_arr['EUR'] = 1/$base;
$currency_json = json_encode($c_arr);
//write to file
$file = "currency.json";
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, $currency_json);
fclose($fh);
echo $currency_json;
} catch (Exception $e) { echo $e; }
?>
It writes a JSON file that I include as a JavaScript variable:
<script type="text/javascript">
var data = <?php include('currency.json'); ?>;
</script>
I can then easy grab the data using the 3-letter currency code (e.g., data['GBP']) with JavaScript when a currency change is requested.
I use a Cron Job to update the JSON once a day, so it's not making a call each time the page is visited.
/**
* Rechnet den gegebenen Betrag von einer Währung in eine andere um
* #param FLOAT $value
* #param STRING $fromCurrency=USD Ursprungswärung des Betrags
* #param STRING $toCurrency=EUR Zielwärhung, in die umgerechnet wird
* #param BOOL $round=true Wenn aktiviert, wird der errechnete Wert auf 2 Nachkommastellen kaufmännisch gerundet
* #return ARRAY [timestamp][datetime_iso][datetime_de][value][from][to][result]
*/
function calcCurrency($value=0, $fromCurrency='USD', $toCurrency='EUR', $round=true) {
$timestamp = time();
$fromCurrency = preg_replace('[^A-Z]', '', strtoupper(trim($fromCurrency)));
$toCurrency = preg_replace('[^A-Z]', '', strtoupper(trim($toCurrency)));
$round = (bool) $round;
$wrongJSON = file_get_contents("http://www.google.com/ig/calculator?hl=en&q=1$fromCurrency=?$toCurrency");
$search = array('lhs', 'rhs', 'error', 'icc');
$replace = array('"lhs"', '"rhs"', '"error"', '"icc"');
$json = str_replace($search, $replace, $wrongJSON);
$jsonData = json_decode($json, true);
if ('' !== $jsonData['error']) throw new Exception('FEHLER: '.$jsonData['error']);
$rhs = explode(' ', $jsonData['rhs'], 2);
$calcValue = floatval(0.00);
$value = floatval($value);
$ratio = floatval($rhs[0]);
// Gültigkeitsprüfungen
if ($value < 0) throw new Exception('Umzurechnender Wert darf nicht negativ sein.');
// Plausibilitätsprüfung der eingestellten Währung und Festlegung
if ($toCurrency == $fromCurrency) {
// Ursprungswährung = Zielwährung | Es erfolgt keine Berechnung
$calcValue = $value;
$ratio = 1;
} else {
$calcValue = floatval($value * $ratio);
}
// Array mit Rückgabewerten erzeugen und zurück geben
return array(
'timestamp' => $timestamp,
'datetime_iso' => date('Y-m-d H:i:s', $timestamp),
'datetime_de' => date('d.m.Y H:i:s', $timestamp),
'value' => $value,
'from' => $fromCurrency,
'to' => $toCurrency,
'ratio' => round($ratio, 6),
'result' => (true===$round)
? round($calcValue, 2)
: $calcValue
);
}
use this simple function :
function convertCurrency($amount, $from, $to){
$url = "https://www.google.com/finance/converter?a=$amount&from=$from&to=$to";
$data = file_get_contents($url);
preg_match("/<span class=bld>(.*)<\/span>/",$data, $converted);
$converted = preg_replace("/[^0-9.]/", "", $converted[1]);
return round($converted, 3);
}
This is so simple if you use a local server like wamp or xampp or other server then you should have to enable extension of openssl first in php.ini
extension=php_openssl.dll `allow_url_fopen = On`
then you will be able to run my code
else you are runing your website with online hosting then you dont need to do this so you have to add this php function in your php script
<?php
function currencyCnv( $amount, $from, $to){
$get = file_get_contents("https://www.google.com/finance/converter?a=$amount&from=" . $from. "&to=" . $to);
$get = explode("<span class=bld>",$get);
$get = explode("</span>",$get[1]);
$converted_amount = $get[0];
echo round($converted_amount,2);
}
currencyCnv(100,'GBP','PKR');
//currencyCnv(you amount from form input filed ,currency from select box,currency to select box)
//any currency convert with this code
Please check below currency change example.
function oneUSDTo($amount, $toCurrency)
{
$currencyUrl = $amount."usd+to+$toCurrency";
$url = "https://www.google.com/search?q=".$currencyUrl;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$data = explode("$amount US Dollar = ",$result);
return (float) substr($data[1],0,10);
}
//Usage: oneUSDTo("type currency code here");
echo oneUSDTo("5","EUR");
https://fincharts.info/charts/exchange/?key=api_key&&from=USD&to=GBP,BWP,ZAR&amount=45854&date=2018-03-03&base=USD
seems you have to signup for an api key, I think
You can also check: https://free.currencyconverterapi.com
Disclaimer, I'm the author of this website.
A sample conversion URL is: http://free.currencyconverterapi.com/api/v6/convert?q=PHP_EUR,EUR_PHP&compact=ultra&apiKey=sample-api-key which will return a value in json format, e.g. {"PHP_EUR":0.016434,"EUR_PHP":60.849184}
You should note about the limitations though like maximum requests and queries (details found the website). I've implemented limits because there have been abusers of the service.
I've started this since 2014 and has been up ever since (aside from the link change and maintenance down times along the way). I personally use it for my other websites, and provided the service publicly so it can help other devs as well.
Anyway hope this helps, and here's a sample PHP code:
<?php
function convertCurrency($amount, $from, $to){
$conv_id = "{$from}_{$to}";
$string = file_get_contents("https://free.currencyconverterapi.com/api/v6/convert?q=$conv_id&compact=ultra&apiKey=sample-api-key");
$json_a = json_decode($string, true);
return $amount * round($json_a[$conv_id], 4);
}
echo(convertCurrency(5, "USD", "PHP"));
?>
<?php
// replace this key from fixer.io after getting a free API access key:
$API = '314259bbe6de76b961c84a5244ac0fc0';
function convertCurrency($API, $amount, $from = 'EUR', $to = 'USD'){
$curl = file_get_contents("http://data.fixer.io/api/latest?access_key=$API&symbols=$from,$to");
if($curl)
{
$arr = json_decode($curl,true);
if($arr['success'])
{
$from = $arr['rates'][$from];
$to = $arr['rates'][$to];
$rate = $to / $from;
$result = round($amount * $rate, 6);
return $result;
}else{
echo $arr['error']['info'];
}
}else{
echo "Error reaching api";
}
}
echo convertCurrency($API, 1, 'USD', 'EGP');

Categories