PHP HOSTED PAYMENTS WITH SECURECARD STORAGE

Settings file (nuvei_account.inc):

(nuvei_account.inc
<?php
 
# These values are used to identify and validate the account that you are using. They are mandatory.
$gateway = '';			# This is the Nuvei payments gateway that you should use, assigned to the site by Nuvei.
$terminalId = '';		# This is the Terminal ID assigned to the site by Nuvei.
$currency = '';			# This is the 3 digit ISO currency code for the above Terminal ID.
$secret = '';			# This shared secret is used when generating the hash validation strings. 
				        # It must be set exactly as it is in the Nuvei SelfCare  system.
$testAccount = true;
$host = '';				#This should be your host eg. http://localhost:8000

# This should contain the URL of the receipt page and validation page
$receiptPageURL = $host.'';		
$validationURL = $host.'';		
 
# These are used only in the case where the response hash is incorrect, which should
# never happen in the live environment unless someone is attempting fraud.
$adminEmail = '';
$adminPhone = '';
 
?>


Payment page (nuvei_payment.php):

nuvei_payment.php
<?php
# This is the file that contains the account settings for Nuvei.
require('nuvei_account.inc');
 
# This is a helper file for integrating to the Nuvei HPP in PHP.
require('nuvei_hpp_functions.inc');
 
# These values are specific to the transaction.
$orderId = '';			# This should be unique per transaction.
$amount = '';			# This should include the decimal point.
$secureCardMerchantRef = '';    # (mandatory in order to store card details) This should be a unique identifier for the card such as a DB id.

$email = '';			# (optional) If this is sent then Nuvei will send a receipt to this e-mail address.
$description = '';		# (optional) This can is a description for the transaction that will be available in the merchant notification e-mail and in the SelfCare  system.
$autoReady = '';		# (optional) Y or N. Automatically set the transaction to a status of Ready in the batch. If not present the terminal default will be used.

$cardholderName = '';	# (optional) If the cardholders name is available it should be populated here. If so it will be pre-populated on the payment page.
$address1 = '';			# (optional) This is the first line of the cardholders billing address.
$address2 = '';			# (optional) This is the second line of the cardholders billing address.
$postcode = '';			# (optional) This is the postcode of the cardholders billing address.
$host	  = '';			# This should be your host eg. http://localhost:8000
$dateTime = requestDateTime();
 
$requestURL = $host.'/merchant/paymentpage';
# If there's no orderId set then generate a unique time-based order ID.
if(!isset($orderId) || $orderId == '') $orderId = generateUniqueOrderId();
 
# ------ Add order to the local database here if using one ------

# Verification string
$requestHash = authRequestHash($orderId, $amount, $dateTime);
 
# Write the HTML of the submission form
echo "<html><body><form id='nuveiform' action='" . $requestURL . "' method='post'>\n";
writeHiddenField("TERMINALID", $terminalId);
writeHiddenField("CURRENCY", $currency);
writeHiddenField("ORDERID", $orderId);
writeHiddenField("SECURECARDMERCHANTREF", $secureCardMerchantRef);
writeHiddenField("AMOUNT", $amount);
writeHiddenField("DATETIME", $dateTime);
if(isset($cardholderName) && $cardholderName != '') writeHiddenField("CARDHOLDERNAME", $cardholderName);
if(isset($postcode) && $postcode != '') {
	writeHiddenField("ADDRESS1", $address1);
	writeHiddenField("ADDERSS2", $address2);
	writeHiddenField("POSTCODE", $postcode);
}
if(isset($email) && $email != '') writeHiddenField("EMAIL", $email);
if(isset($description) && $description != '') writeHiddenField("DESCRIPTION", $description);
if(isset($autoReady) && $autoReady != '') writeHiddenField("AUTOREADY", $autoReady);
writeHiddenField("RECEIPTPAGEURL", $receiptPageURL);
if($validationURL != '') writeHiddenField("VALIDATIONURL", $validationURL);
writeHiddenField("HASH", $requestHash);
 
 
# You can also include any other custom fields here. Their contents will for included in the response POST to the receipt page.
# writeHiddenField("Customer ID", '32856951');

# Write the JavaScript that will submit the form to Nuvei.
echo '</form>Submitting order to Nuvei for Payment...<script language="JavaScript">document.getElementById("nuveiform").submit();</script></body></html>';
//var_dump(get_defined_vars());
 
?>


Receipt page (nuvei_receipt_page.php):

nuvei_receipt_page.php
<?php
 
# This is the file that contains the account settings for Nuvei.
require('nuvei_account.inc');
 
# This is a helper file for integrating to the Nuvei HPP in PHP.
require('nuvei_hpp_functions.inc');
 
if(authResponseHashIsValid($_REQUEST["ORDERID"], $_REQUEST["AMOUNT"], $_REQUEST["DATETIME"], $_REQUEST["RESPONSECODE"], $_REQUEST["RESPONSETEXT"], $_REQUEST["MERCHANTREF"], $_REQUEST["CARDREFERENCE"], $_REQUEST["CARDTYPE"], $_REQUEST["MASKEDCARDNUMBER"], $_REQUEST["CARDEXPIRY"], $_REQUEST["HASH"])) {
	switch($_REQUEST["RESPONSECODE"]) {
		case "A" :	# -- If using local database, update order as Paid/Successful
				if($_REQUEST["ISSTORED"]="true") {
					# Also Store SecureCard token details: 
					$_REQUEST["MERCHANTREF"];	# The Merchant Reference of the card stored (same as sent to us above)
					$_REQUEST["CARDREFERENCE"];	# The 16 digit SecureCard Card Reference used for processing payments
					$_REQUEST["CARDTYPE"];
					$_REQUEST["MASKEDCARDNUMBER"];
					$_REQUEST["CARDEXPIRY"];
					echo 'Card details have been securely stored with Nuvei for future use on this site only.';
				} else {
					echo 'Card details failed to be stored. Reason: $_REQUEST["SCERROR"].';
				}
				echo 'Payment Processed successfully. Thanks you for your order.';
				break;
		case "R" :
		case "D" :
		case "C" :
		case "S" :
		default  :	# -- If using local database, update order as declined/failed --
				echo 'PAYMENT DECLINED! Please try again with another card. Bank response: ' . $_REQUEST["RESPONSETEXT"];
	}
} else {
	echo 'PAYMENT FAILED: INVALID RESPONSE HASH. Please contact <a href="mailto:' . $adminEmail . '">' . $adminEmail . '</a> or call ' . $adminPhone . ' to clarify if you will get charged for this order.';
	if(isset($_REQUEST["ORDERID"])) echo 'Please quote Nuvei Terminal ID: ' . $terminalId . ', and Order ID: ' . $_REQUEST["ORDERID"] . ' when mailling or calling.';
}
 
?>


Helper file (nuvei_hpp_functions.inc):

nuvei_hpp_functions.inc)
<?php
 
# This function returns the URL that should be used as the "action" for the form posting the Nuvei's servers.
function requestURL() {
	global $gateway, $testAccount;
	$url = 'https://';
	if($testAccount) $url .= 'test';
	switch (strtolower($gateway)) {
		case 'cashflows' : $url .= 'cashflows.nuvei.com'; break;
		case 'payius' : $url .= 'payments.payius.com'; break;
		default :
		case 'nuvei'  : $url .= 'payments.nuvei.com'; break;
	}
	$url .= '/merchant/paymentpage';
	return $url;
}
 
# This simply reduces the PHP code required to build the form.
function writeHiddenField($fieldName, $fieldValue) {
	echo "<input type='hidden' name='" . $fieldName . "' value='" . $fieldValue . "' />\r";
}
 
# This generates a DATETIME value in the correct format expected in the request.
function requestDateTime() {
	return date('d-m-Y:H:i:s:000');
}
 
# If you are not using your own Order ID's and need to use unique random ones, this function will generate one for you.
function generateUniqueOrderId() {
	$seconds = date('H')*3600+date('i')*60+date('s');
	return date('zy') . $seconds;
}
 
# This is used to generate the Authorisation Request Hash.
function authRequestHash($orderId, $amount, $dateTime) {
	global $terminalId, $secret, $receiptPageURL, $validationURL;
	return md5($terminalId . $orderId . $amount . $dateTime . $receiptPageURL . $validationURL . $secret);
}
 
# This function is used to validate that the Authorisation Response Hash from the server is correct.
#     If authResponseHashIsValid(...) != $_REQUEST["HASH"] then an error should be shown and the transaction should not be approved.
function authResponseHashIsValid($orderId, $amount, $dateTime, $responseCode, $responseText, $merchantRef, $secureCardCardRef, $cardType, $maskedCardNumber, $cardExpiry, $responseHash) {
	global $terminalId, $secret;
	return (md5($terminalId . $orderId . $amount . $dateTime . $responseCode . $responseText . $merchantRef . $secureCardCardRef . $cardType . $maskedCardNumber . $cardExpiry . $secret)==$responseHash);
}
 
?>


Background Validation page (nuvei_validate.php):

nuvei_validate.php
<?php
 
# This is the file that contains the account settings for Nuvei.
require('nuvei_account.inc');
 
# This is a helper file for intgerating to the Nuvei HPP in PHP.
require('nuvei_hpp_functions.inc');
 
if(authResponseHashIsValid($_REQUEST["ORDERID"], $_REQUEST["AMOUNT"], $_REQUEST["DATETIME"], $_REQUEST["RESPONSECODE"], $_REQUEST["RESPONSETEXT"], $_REQUEST["MERCHANTREF"], $_REQUEST["CARDREFERENCE"], $_REQUEST["CARDTYPE"], $_REQUEST["MASKEDCARDNUMBER"], $_REQUEST["CARDEXPIRY"], $_REQUEST["HASH"])){
	if() {
		switch($_REQUEST["RESPONSECODE"]) {
			case "A" :	# -- Update order in database as paid/sucessful
					if($_REQUEST["ISSTORED"]="true") {
						# Also Store SecureCard token details: 
						$_REQUEST["MERCHANTREF"];	# The Merchant Reference of the card stored (same as sent to us above)
						$_REQUEST["CARDREFERENCE"];	# The 16 digit SecureCard Card Reference used for processing payments
						$_REQUEST["CARDTYPE"];
						$_REQUEST["MASKEDCARDNUMBER"];
						$_REQUEST["CARDEXPIRY"];
					}
					echo 'OK';
					break;
			case "R" :
			case "D" :
			case "C" :
			default  :	# -- Update order in database as declined/failed --
					echo 'OK';
		}
	} else {
		echo 'Order ID: ' . $_REQUEST["ORDERID"] . ' not found in database.';
	}
} else {
	echo 'Background validation hash incorrect.';
}
 
?>
Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Share Alike 4.0 International