Let’s Talk

How to integrate Braintree in PHP/Javascript

Integrating a new payment provider can be daunting, and the official documentation unneccesarily complex. Here are four easy steps to a complete Braintree integration.

Note that you don’t technically need an SSL certificate to be compliant, as the form itself is secured by Braintree, but we would highly recommend the purchase of at least the basic certificate, if only for customer confidence.

Step 1

Download the SDK from here https://developers.braintreepayments.com/start/hello-server/php. You can deleted the “tests” folder as it’s not required.

Step 2

Create a config file to include Braintree, plus your API credentials (you’ll need to sign up to get these https://www.braintreepayments.com/get-started).

$urlPrefix = '/braintree/';

// Include the Braintree.php library
define('THIS_PATH_FILE', realpath(dirname(__FILE__)));
define('PATH_TO_BRAINTREE', THIS_PATH_FILE . '/../braintree-php-2.35.2');
define('PATH_TO_BRAINTREE_LIBRARY', PATH_TO_BRAINTREE . '/lib/Braintree.php');
include(PATH_TO_BRAINTREE_LIBRARY);

Braintree_Configuration::environment('sandbox'); // 'production' when live
Braintree_Configuration::merchantId('');
Braintree_Configuration::publicKey('');
Braintree_Configuration::privateKey('');

Step 3

Generate your Client Token then create a payment form along with the required Javascript.

All you need to do is make sure you have a div within the form with the same ID as the “container” in the Javascript. The Javascript will then generate the required form inputs for credit card information (plus a PayPal button if set up to do so within your Braintree account).

$clientToken = Braintree_ClientToken::generate();

<form action="/payment/take-payment.html" method="post">
    <div id="payment-form"></div>
    <input type="submit" value="Pay"/>
</form>
<script src="https://js.braintreegateway.com/v2/braintree.js"></script>
<script>
	var clientToken = "<?=$clientToken?>";

	braintree.setup(clientToken, "dropin", {
		container: "payment-form"
	});
</script>

Step 4

The take-payment.php page (to which the form above posts) then needs to charge the card.

if($nonce = $_POST['payment_method_nonce']){
    // Customer submitted payment information

    // Take payment, get $result of transaction
    $result = Braintree_Transaction::sale([
        "amount" => 1,
        "paymentMethodNonce" => $nonce,
        "options" => [
            "submitForSettlement" => true
        ]
    ]);

    if($result->success){
        // Payment has been authorised
    }else{
       // Payment hasn't been authorised
    }
}

The above will charge £1 to the card. In a production environment you’d want to retrieve the customer’s order details here to get the correct amount.

This code is free to use at your own discretion. It comes without warranty. Please feel free to feedback any edits.