How to integrate FraudLabs Pro fraud detection with Authorize.Net payment

Description: This tutorial demonstrates how to integrate FraudLabs Pro fraud detection into Authorize.Net payment.

PHP
Create a new table to store the transaction value of FraudLabs Pro and Authorize.Net payment processing. This table will be used during the settlement, void or refund process.

CREATE TABLE `fraudlabs_pro` (
	`flp_transaction_id` CHAR(15) NOT NULL,
	`flp_status` VARCHAR(10) NOT NULL,
	`authorizenet_transaction_id` VARCHAR(30) NOT NULL,
	PRIMARY KEY (`flp_transaction_id`)
)
COLLATE='utf8_general_ci'
ENGINE=MyISAM;

Download FraudLabs Pro PHP class from https://github.com/fraudlabspro/fraudlabspro-php/releases

Integrate FraudLabs Pro fraud detection logic with your Authorize.Net code. This code will perform a simple validation check of one credit card purchase and perform the appropriate action based on the fraud validation result.

// Include FraudLabs Pro library
require_once 'PATH_TO_FRAUDLABSPRO/lib/FraudLabsPro.php';

// Include Authorize.Net library
require 'vendor/autoload.php';
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;

$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
$merchantAuthentication->setName("your_api_login_id");
$merchantAuthentication->setTransactionKey("your_transaction_key");
$refId = 'ref' . time();

FraudLabsPro\Configuration::apiKey('your_fraudlabspro_api_key');

// Check this transaction for possible fraud. FraudLabs Pro support comprehensive validation check,
// and for this example, we only perform the IP address, BIN and billing country validation.
// For complete validation, please check our developer page at http://www.fraudlabspro.com/developer
$orderDetails = [
	'order'		=> [
		'amount'	=> $_POST['amount'], 
		'paymentMethod'	=> FraudLabsPro\Order::CREDIT_CARD,
	],
	'card'		=> [
		'number'	=> $_POST['number'],
	],
	'billing'	=> [
		'country'	=> $_POST['country'],
	],
];

// Sends the order details to FraudLabs Pro
$fraudResult = FraudLabsPro\Order::validate($orderDetails);

// This transaction is legitimate, let's submit to Authorize.Net
if ($fraudResult->fraudlabspro_status == 'APPROVE') {
	// Create payment data for a credit card
	$creditCard = new AnetAPI\CreditCardType();
	$creditCard->setCardNumber($_POST['number']);
	$creditCard->setExpirationDate($_POST['year'] . "-" . $_POST['month']);
	$creditCard->setCardCode($_POST['cvv']);

	// Add payment data to a paymentType object
	$paymentOne = new AnetAPI\PaymentType();
	$paymentOne->setCreditCard($creditCard);

	$transactionRequestType = new AnetAPI\TransactionRequestType();
	$transactionRequestType->setTransactionType("authCaptureTransaction");
	$transactionRequestType->setAmount($_POST['amount']);
	$transactionRequestType->setPayment($paymentOne);

	$request = new AnetAPI\CreateTransactionRequest();
	$request->setMerchantAuthentication($merchantAuthentication);
	$request->setRefId($refId);
	$request->setTransactionRequest($transactionRequestType);

	$controller = new AnetController\CreateTransactionController($request);
	$result = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);

	if ($result != null) {
		if ($result->getMessages()->getResultCode() == 'Ok') {
			$tresult = $result->getTransactionResponse();
			if (($tresult != null) && ($tresult->getMessages() != null)) {
				echo " Successfully created transaction with Transaction ID: " . $tresult->getTransId() . "\n";
				echo " Transaction Response Code: " . $tresult->getResponseCode() . "\n";
				echo " Message Code: " . $tresult->getMessages()[0]->getCode() . "\n";
				echo " Auth Code: " . $tresult->getAuthCode() . "\n";
				echo " Description: " . $tresult->getMessages()[0]->getDescription() . "\n";
			} else {
				echo "Transaction Failed \n";
				if ($tresult->getErrors() != null) {
					echo " Error Code : " . $tresult->getErrors()[0]->getErrorCode() . "\n";
					echo " Error Message : " . $tresult->getErrors()[0]->getErrorText() . "\n";
				}
			}
		} else {
			echo "Transaction Failed \n";
			$tresult = $result->getTransactionResponse();

			if ($tresult != null && $tresult->getErrors() != null) {
				echo " Error Code : " . $tresult->getErrors()[0]->getErrorCode() . "\n";
				echo " Error Message : " . $tresult->getErrors()[0]->getErrorText() . "\n";
			} else {
				echo " Error Code : " . $result->getMessages()->getMessage()[0]->getCode() . "\n";
				echo " Error Message : " . $result->getMessages()->getMessage()[0]->getText() . "\n";
			}
		}
	} else {
		echo "No response returned \n";
	}
}

// Transaction has been rejected by FraudLabs Pro based on your custom validation rules.
elseif ($fraudResult->fraudlabspro_status == 'REJECT') {
	/*
	Do something here, try contact the customer for verification
	*/
}

// Transaction is marked for a manual review by FraudLabs Pro based on your custom validation rules.
elseif ($fraudResult->fraudlabspro_status == 'REVIEW') {
	// Create payment data for a credit card
	$creditCard = new AnetAPI\CreditCardType();
	$creditCard->setCardNumber($_POST['number']);
	$creditCard->setExpirationDate($_POST['year'] . "-" . $_POST['month']);
	$creditCard->setCardCode($_POST['cvv']);

	// Add payment data to a paymentType object
	$paymentOne = new AnetAPI\PaymentType();
	$paymentOne->setCreditCard($creditCard);

	$transactionRequestType = new AnetAPI\TransactionRequestType();
	$transactionRequestType->setTransactionType("authOnlyTransaction");
	$transactionRequestType->setAmount($_POST['amount']);
	$transactionRequestType->setPayment($paymentOne);

	$request = new AnetAPI\CreateTransactionRequest();
	$request->setMerchantAuthentication($merchantAuthentication);
	$request->setRefId($refId);
	$request->setTransactionRequest($transactionRequestType);

	$controller = new AnetController\CreateTransactionController($request);
	$result = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);

	if ($result != null) {
		if ($result->getMessages()->getResultCode() == 'Ok') {
			$tresult = $result->getTransactionResponse();
			if (($tresult != null) && ($tresult->getMessages() != null)) {
				echo " Successfully created transaction with Transaction ID: " . $tresult->getTransId() . "\n";
				echo " Transaction Response Code: " . $tresult->getResponseCode() . "\n";
				echo " Message Code: " . $tresult->getMessages()[0]->getCode() . "\n";
				echo " Auth Code: " . $tresult->getAuthCode() . "\n";
				echo " Description: " . $tresult->getMessages()[0]->getDescription() . "\n";

				try{
					// Initial MySQL connection
					$db = new PDO('mysql:host=your_database_host;dbname=your_database_name;charset=utf8', 'your_database_user', 'your_database_password');
					$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

					// Store the transaction information for decision making
					$st = $db->prepare('INSERT INTO `fraudlabs_pro` VALUES (:flpId, :flpStatus, :authorizeNetId)');
					$st->execute(array(
						':flpId'=>$fraudResult->fraudlabspro_id,
						':flpStatus'=>$fraudResult->fraudlabspro_status,
						':authorizeNetId'=>$tresult->getTransId()
					));
				}
				catch(PDOException $e){
					// MySQL error
					die($e->getFile() . ':' . $e->getLine() . ' ' . $e->getMessage());
				}
			} else {
				echo "Transaction Failed \n";
				if ($tresult->getErrors() != null) {
					echo " Error Code : " . $tresult->getErrors()[0]->getErrorCode() . "\n";
					echo " Error Message : " . $tresult->getErrors()[0]->getErrorText() . "\n";
				}
			}
		} else {
			echo "Transaction Failed \n";
			$tresult = $result->getTransactionResponse();

			if ($tresult != null && $tresult->getErrors() != null) {
				echo " Error Code : " . $tresult->getErrors()[0]->getErrorCode() . "\n";
				echo " Error Message : " . $tresult->getErrors()[0]->getErrorText() . "\n";
			} else {
				echo " Error Code : " . $result->getMessages()->getMessage()[0]->getCode() . "\n";
				echo " Error Message : " . $result->getMessages()->getMessage()[0]->getText() . "\n";
			}
		}
	} else {
		echo "No response returned \n";
	}
}

Now, we are going to create a callback page to receive the review action, APPROVE or REJECT, performed by the merchant.

Note: You need to configure the callback URL at the FraudLabs Pro merchant area->settings page. It has to be pointed to the location where you hosted this “fraudlabspro-callback.php” file. Below is the sample code for fraudlabspro-callback.php

// Include Authorize.Net library
require 'vendor/autoload.php';
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;

$id = (isset($_POST['id'])) ? $_POST['id'] : '';
$action = (isset($_POST['action'])) ? $_POST['action'] : '';

if($id && in_array($action, array('APPROVE', 'REJECT'))){
	try{
		// Initial MySQL connection
		$db = new PDO('mysql:host=your_database_host;dbname=your_database_name;charset=utf8', 'your_database_user', 'your_database_password');
		$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

		// Get the Authorize.Net Transaction ID
		$st = $db->prepare('SELECT * FROM `fraudlabs_pro` WHERE `flp_transaction_id`=:flpId AND `flp_status`=\'REVIEW\'');
		$st->execute(array(
			':flpId'=>$id
		));

		if($st->rowCount() == 1){
			$row = $st->fetch(PDO::FETCH_ASSOC);

			$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
			$merchantAuthentication->setName("your_api_login_id");
			$merchantAuthentication->setTransactionKey("your_transaction_key");
			$refId = 'ref' . time();

			if($action == 'REJECT'){
				// Merchant rejected the order. Void the transaction in Authorize.Net
				$transactionRequestType = new AnetAPI\TransactionRequestType();
				$transactionRequestType->setTransactionType("voidTransaction"); 
				$transactionRequestType->setRefTransId($row['authorizenet_transaction_id']);

				$request = new AnetAPI\CreateTransactionRequest();
				$request->setMerchantAuthentication($merchantAuthentication);
				$request->setRefId($refId);
				$request->setTransactionRequest($transactionRequestType);

				$controller = new AnetController\CreateTransactionController($request);
				$controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);
			}
			else{
				// Merchant approved the order. Submit for settlement
				$transactionRequestType = new AnetAPI\TransactionRequestType();
				$transactionRequestType->setTransactionType("priorAuthCaptureTransaction");
				$transactionRequestType->setRefTransId($row['authorizenet_transaction_id']);

				$request = new AnetAPI\CreateTransactionRequest();
				$request->setMerchantAuthentication($merchantAuthentication);
				$request->setTransactionRequest($transactionRequestType);

				$controller = new AnetController\CreateTransactionController($request);
				$controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);
			}

			// Update database
			$st = $db->prepare('UPDATE `fraudlabs_pro` SET `flp_status`=:action WHERE `flp_transaction_id`=:flpId');
			$st->execute(array(
				':flpId'=>$id,
				':action'=>$action
			));
		}
	}
	catch(PDOException $e){
		// MySQL error
		die($e->getFile() . ':' . $e->getLine() . ' ' . $e->getMessage());
	}
}

If there is a need to issue a refund of a settled transaction, below is the sample code of how to accomplish it.

// Include Authorize.Net library
require 'vendor/autoload.php';
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;

try{
	// Initial MySQL connection
	$db = new PDO('mysql:host=your_database_host;dbname=your_database_name;charset=utf8', 'your_database_user', 'your_database_password');
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

	// Get the Authorize.Net transaction ID based on the FraudLabs Pro ID
	$st = $db->prepare('SELECT * FROM `fraudlabs_pro` WHERE `flp_transaction_id`=:flpId');
	$st->execute(array(
		':flpId'=>$_POST['flpId']
	));

	if($st->rowCount() == 1){
		$row = $st->fetch(PDO::FETCH_ASSOC);

		$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
		$merchantAuthentication->setName("your_api_login_id");
		$merchantAuthentication->setTransactionKey("your_transaction_key");
		$refId = 'ref' . time();

		$creditCard = new AnetAPI\CreditCardType();
		// Only the last four digits of customer's credit card number are required for credit card refunds.
		$creditCard->setCardNumber("NNNN");
		// For refunds, use XXXX instead of the customer's credit card expiration date.
		$creditCard->setExpirationDate("XXXX");
		$paymentOne = new AnetAPI\PaymentType();
		$paymentOne->setCreditCard($creditCard);

		$transactionRequestType = new AnetAPI\TransactionRequestType();
		$transactionRequestType->setTransactionType("refundTransaction");
		$transactionRequestType->setAmount($amount);
		$transactionRequestType->setPayment($paymentOne);
		$transactionRequestType->setRefTransId($row['authorizenet_transaction_id']);

		$request = new AnetAPI\CreateTransactionRequest();
		$request->setMerchantAuthentication($merchantAuthentication);
		$request->setRefId($refId);
		$request->setTransactionRequest($transactionRequestType);

		$controller = new AnetController\CreateTransactionController($request);
		$controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);

		// Update database
		$st = $db->prepare('UPDATE `fraudlabs_pro` SET `flp_status`=\'REFUNDED\' WHERE `flp_transaction_id`=:flpId');
		$st->execute(array(
			':flpId'=>$_POST['flpId']
		));
	}
}
catch(PDOException $e){
	// MySQL error
	die($e->getFile() . ':' . $e->getLine() . ' ' . $e->getMessage());
}

Was this article helpful?

Related Articles