PX : code

Fraud Detection with BrainTree payment by Howynn
Download this code


<?php

Create a 
new table to store the transaction value of FraudLabs Pro and BrainTree payment processingThis table will be used during the settlementvoid or refund process.

<
sql>CREATE TABLE `fraudlabs_pro` (
    `
flp_transaction_idCHAR(15NOT NULL,
    `
flp_statusVARCHAR(10NOT NULL,
    `
braintree_transaction_idVARCHAR(10NOT NULL
    PRIMARY KEY 
(`flp_transaction_id`)
)
COLLATE='utf8_general_ci'
ENGINE=MyISAM;
</
sql>

Download FraudLabs Pro PHP class from http://www.fraudlabspro.com/downloads/FraudLabsPro.class.php.zip

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

<
php>
// Include FraudLabs Pro library
require_once 'PATH_TO_FRAUDLABSPRO/lib/FraudLabsPro.class.php';
 
// Include BrainTree library
require_once 'PATH_TO_BRAINTREE/lib/Braintree.php';
 
// We show the example code using the SandBox environment.              
Braintree_Configuration::environment('sandbox');
Braintree_Configuration::merchantId('use_your_merchant_id');
Braintree_Configuration::publicKey('use_your_public_key');
Braintree_Configuration::privateKey('use_your_private_key');
 
// Create a free user account at http://www.fraudlabspro.com, if you do not have one
$fraud = new FraudLabsPro('use_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
$fraudResult $fraud->check(array(
    
'ipAddress' => $_SERVER['REMOTE_ADDR'],
    
'creditCardNumber' => $_POST['number'],
    
'billingCountry' => $_POST['country'],
    
'amount' => $_POST['amount']
));
 
// This transaction is legitimate, let's submit to Braintree
if($fraudResult->fraudlabspro_status == 'APPROVE'){
    
// Submit for settlement
    
$result Braintree_Transaction::sale(array(
        
'amount' => $_POST['amount'],
        
'creditCard' => array(
            
'number' => $_POST['number'],
            
'cvv' => $_POST['cvv'],
            
'expirationMonth' => $_POST['month'],
            
'expirationYear' => $_POST['year']
        ),
        
'options' => array(
            
'submitForSettlement' => true
        
)
    ));
 
    if (
$result->success) {
        echo(
"Success! Transaction ID: " $result->transaction->id);
    } else if (
$result->transaction) {
        echo(
"Error: " $result->message);
        echo(
"<br>");
        echo(
"Code: " $result->transaction->processorResponseCode);
    } else {
        echo(
"Validation errors:<br>");
        foreach ((
$result->errors->deepAll()) as $error) {
            echo(
"- " $error->message "<br>");
        }
    }
}
 
// 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'){
    
// Authorize this order with BrainTree, but no settlement
    
$result Braintree_Transaction::sale(array(
        
'amount' => $_POST['amount'],
        
'creditCard' => array(
            
'number' => $_POST['number'],
            
'cvv' => $_POST['cvv'],
            
'expirationMonth' => $_POST['month'],
            
'expirationYear' => $_POST['year']
        ),
        
'options' => array(
            
'submitForSettlement' => false
        
)
    ));
 
    if (
$result->success) {
        echo(
"Success! Transaction ID: " $result->transaction->id);
 
        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_ERRMODEPDO::ERRMODE_EXCEPTION);
 
            
// Store the transaction information for decision making
            
$st $db->prepare('INSERT INTO `fraudlabs_pro` VALUES (:flpId, :flpStatus, :braintreeId)');
            
$st->execute(array(
                
':flpId'=>$fraudResult->fraudlabspro_id,
                
':flpStatus'=>$fraudResult->fraudlabspro_status,
                
':braintreeId'=>$result->transaction->id
            
));
        }
        catch(
PDOException $e){
            
// MySQL error
            
die($e->getFile() . ':' $e->getLine() . ' ' $e->getMessage());
        }
    } else if (
$result->transaction) {
        echo(
"Error: " $result->message);
        echo(
"<br>");
        echo(
"Code: " $result->transaction->processorResponseCode);
    } else {
        echo(
"Validation errors:<br>");
        foreach ((
$result->errors->deepAll()) as $error) {
            echo(
"- " $error->message "<br>");
        }
    }
}
</
php>

Nowwe are going to create a callback page to receive the review actionAPPROVE or REJECTperformed by the merchant.

NoteYou need to configure the callback URL at the FraudLabs Pro merchant area->settings pageIt has to be pointed to the location where you hosted this "fraudlabspro-callback.php" fileBelow is the sample code for fraudlabspro-callback.php

<php>
$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_ERRMODEPDO::ERRMODE_EXCEPTION);
 
        
// Get the BrainTree 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);
 
            require_once 
'PATH_TO_BRAINTREE/lib/Braintree.php';
 
            
Braintree_Configuration::environment('sandbox');
            
Braintree_Configuration::merchantId('use_your_merchant_id');
            
Braintree_Configuration::publicKey('use_your_public_key');
            
Braintree_Configuration::privateKey('use_your_private_key');
 
            if(
$action == 'REJECT'){
                
// Merchant rejected the order. Void the transaction in Braintree
                
Braintree_Transaction::void($row['braintree_transaction_id']);
            }
            else{
                
// Merchant approved the order. Submit for settlement
                
Braintree_Transaction::submitForSettlement($row['braintree_transaction_id']);
            }
             
            
// 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());
    }
}
</
php>

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

<
php>
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_ERRMODEPDO::ERRMODE_EXCEPTION);
 
    
// Get the BrainTree 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);
 
        require_once 
'PATH_TO_BRAINTREE/lib/Braintree.php';
 
        
Braintree_Configuration::environment('sandbox');
        
Braintree_Configuration::merchantId('use_your_merchant_id');
        
Braintree_Configuration::publicKey('use_your_public_key');
        
Braintree_Configuration::privateKey('use_your_private_key');
 
        
// Issue the refund
        
$result Braintree_Transaction::refund($row['braintree_transaction_id']);
         
        
// 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());
}
</
php>

?>

Comments or questions?
PX is running PHP 5.2.17
Thanks to Miranda Productions for hosting and bandwidth.
Use of any code from PX is at your own risk.