Description: This tutorial demonstrates how to integrate FraudLabs Pro fraud detection service into PayPal payment process. Below we show you the step-by-step instructions using the PHP language.
Using PHP
Create a new table to store the transaction value of FraudLabs Pro and PayPal 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, `paypal_transaction_id` VARCHAR(30) NOT NULL, `paypal_amount` DECIMAL(12,2) NOT NULL, `paypal_captured_id` VARCHAR(30), 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 PayPal 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 PayPal library
require __DIR__ . '/../bootstrap.php';
use PayPal\Api\Amount;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'your_client_id', // ClientID
'your_client_secret' // ClientSecret
)
);
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'],
],
'billing' => [
'country' => $_POST['country'],
],
];
// Sends the order details to FraudLabs Pro
$fraudResult = FraudLabsPro\Order::validate($orderDetails);
// This transaction is legitimate, let's submit to PayPal
if ($fraudResult->fraudlabspro_status == 'APPROVE') {
// Set Payer that funds a payment
$payer = new Payer();
$payer->setPaymentMethod("paypal");
// Set payment amount
$amount = new Amount();
$amount->setCurrency("USD");
$amount->setTotal($_POST['amount']);
// Set transaction that defines the details of payment
$transaction = new Transaction();
$transaction->setAmount($amount);
$transaction->setInvoiceNumber(uniqid());
// Set the URLs that the buyer must be redirected to after payment approval/cancellation
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl("https://example.com/your_redirect_url.html");
$redirectUrls->setCancelUrl("https://example.com/your_cancel_url.html");
// Set payment resource
$payment = new Payment();
$payment->setIntent("sale");
$payment->setPayer($payer);
$payment->setRedirectUrls($redirectUrls);
$payment->setTransactions(array($transaction));
// Create payment
try {
$payment->create($apiContext);
// echo $payment;
echo "\n\nRedirect user to approval_url: " . $payment->getApprovalLink() . "\n";
}
catch (\PayPal\Exception\PayPalConnectionException $ex) {
// This will print the detailed information on the exception.
echo $ex->getData();
}
}
// 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') {
// Set Payer that funds a payment
$payer = new Payer();
$payer->setPaymentMethod("paypal");
// Set payment amount
$amount = new Amount();
$amount->setCurrency("USD");
$amount->setTotal($_POST['amount']);
// Set transaction that defines the details of payment
$transaction = new Transaction();
$transaction->setAmount($amount);
$transaction->setInvoiceNumber(uniqid());
// Set the URLs that the buyer must be redirected to after payment approval/cancellation
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl("https://example.com/your_redirect_url.html");
$redirectUrls->setCancelUrl("https://example.com/your_cancel_url.html");
// Set payment resource
$payment = new Payment();
$payment->setIntent("authorize");
$payment->setPayer($payer);
$payment->setRedirectUrls($redirectUrls);
$payment->setTransactions(array($transaction));
// Create payment
try {
$payment->create($apiContext);
echo "\n\nRedirect user to approval_url: " . $payment->getApprovalLink() . "\n";
$transactions = $payment->getTransactions();
$related_resources = $transactions[0]->getRelatedResources();
$txn_authorize = $related_resources[0]->getAuthorization();
$txn_authorize_id = $txn_authorize->getId();
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` (flp_transaction_id, flp_status, paypal_transaction_id, paypal_amount) VALUES (:flpId, :flpStatus, :paypalId, :paypalAmount)');
$st->execute(array(
':flpId'=>$fraudResult->fraudlabspro_id,
':flpStatus'=>$fraudResult->fraudlabspro_status,
':paypalId'=>$txn_authorize_id,
':paypalAmount'=>$_POST['amount']
));
}
catch(PDOException $e){
// MySQL error
die($e->getFile() . ':' . $e->getLine() . ' ' . $e->getMessage());
}
}
catch (\PayPal\Exception\PayPalConnectionException $ex) {
// This will print the detailed information on the exception.
echo $ex->getData();
}
}
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 PayPal library
require __DIR__ . '/../bootstrap.php';
use PayPal\Api\Amount;
use PayPal\Api\Authorization;
use PayPal\Api\Capture;
$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 PayPal 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);
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'your_client_id', // ClientID
'your_client_secret' // ClientSecret
)
);
$authorizationId = $row['paypal_transaction_id'];
if($action == 'REJECT'){
// Merchant rejected the order. Void the transaction in PayPal
try {
// Lookup the authorization
$authorization = Authorization::get($authorizationId, $apiContext);
// Void the authorization
$voidedAuth = $authorization->void($apiContext);
// 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 (\PayPal\Exception\PayPalConnectionException $ex) {
// This will print the detailed information on the exception.
echo $ex->getData();
}
}
else{
// Merchant approved the order. Submit for settlement
try {
// Retrieve the authorization
$authorization = Authorization::get($authorizationId, $apiContext);
// Set payment amount
$amount = new Amount();
$amount->setCurrency("USD");
$amount->setTotal($row['paypal_amount']);
// Create a capture
$capture = new Capture();
$capture->setAmount($amount);
// Perform a capture
$getCapture = $authorization->capture($capture, $apiContext);
$captureID = $getCapture->getId();
// Update database
$st = $db->prepare('UPDATE `fraudlabs_pro` SET `flp_status`=:action, `paypal_captured_id`=:captureId WHERE `flp_transaction_id`=:flpId');
$st->execute(array(
':flpId'=>$id,
':captureid'=>$captureID,
':action'=>$action
));
} catch (\PayPal\Exception\PayPalConnectionException $ex) {
// This will print the detailed information on the exception.
echo $ex->getData();
}
}
}
}
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 that.
// Include PayPal library
require __DIR__ . '/../bootstrap.php';
use PayPal\Api\Capture;
use PayPal\Api\Refund;
use PayPal\Api\RefundRequest;
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 PayPal 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);
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'your_client_id', // ClientID
'your_client_secret' // ClientSecret
)
);
$captureId = $row['paypal_captured_id'];
// Set payment amount
$amount = new Amount();
$amount->setCurrency("USD");
$amount->setTotal(20);
// Set refund request
$refundRequest = new RefundRequest();
$refundRequest->setAmount($amount);
try {
// Retrieve Capture details
$capture = Capture::get($captureId, $apiContext);
// Refund the Capture
$captureRefund = $capture->refundCapturedPayment($refundRequest, $apiContext);
// Update database
$st = $db->prepare('UPDATE `fraudlabs_pro` SET `flp_status`=\'REFUNDED\' WHERE `flp_transaction_id`=:flpId');
$st->execute(array(
':flpId'=>$_POST['flpId']
));
} catch (\PayPal\Exception\PayPalConnectionException $ex) {
// This will print the detailed information on the exception.
echo $ex->getData();
}
}
}
catch(PDOException $e){
// MySQL error
die($e->getFile() . ':' . $e->getLine() . ' ' . $e->getMessage());
}