Rating: 1 Star2 Stars3 Stars4 Stars5 Stars

Integrating BrainTree Payment Gateway With PHP

BrainTree Payment Gateway API is cool enough for you to understand, but you need to setup the prerequisites first. This article assumes that you have installed the dependencies on your server. BrainTree API expect the followings:

  1. A Developer Sandbox Account – Create one here
  2. BrainTree Client Framework within your application – Download from here

Now, lets create a php file called _environment.php and place the following code in it

BrainTree Control Panel API Key

Now, login to your Sandbox account. You will see your merchant Id, Public Key and Private Key. Replace those values in this code.

BrainTree Transparent Redirect

We will use BrainTree Transparent Redirect to accept one time transactions. Create a file called single_transactions.php and place the following code in it.

Code Explanation

Above code is simple to understand. First we are showing a form to customers, taking their information and passing to BrainTree without actually redirecting our customers to BrainTree Payment Gateway. You can use these test credit card information:
Credit Card #: 5105105105105100
Expiry: 05/2015
CVV: 123

This is the most important piece of code, notice the transaction array in which we are passing amount and type to BrainTree PG.

$result holds the processor responses from BrainTree.

Now, we have the full information in $transaction and you can display the transaction information like

This is how you can use BrainTree Payment Gateway’s Transparent Redirect Method to make one time transactions. In the next part we are going to explain how to subscribe customers for recurring payments.

Creating Transactions from the Vault

BrainTree Payment Gateway expects Secure Credit Card Storage before actually initiating recurring billing to any customers. This is how it is expected.

  1. Secure Credit Card Storage
  2. Creating Transactions from the Vault

To develop recurring billing option first we will setup Secure Credit Cart Storage. This is fairly easy just use the following code.

Above code is straightforward, all commented code is optional but you can specify additional information you want to attach to a customer. First we can taking customers information on a form and then passing all the information to this function via AJAX or POST. The function calls BrainTree Payment Gateway and creates a record in BrainTree vault.

While creating a transaction we will need this token to tell BrainTree which credit card is going to be used for recurring billing. Finally, you will see your customer record in your sandbox like this

BrainTree Customer Record in Vault

If you can see your newly created customer in BrainTree Sandbox Vault, you are good to create Transactions (recurring in our case).

Creating BrainTree Recurring Billing Using PHP

To create a recurring billing option first, you need to create recurring billing plan under your sandbox account. Login to your sandbox account => Recurring Billing => Plans => Add New Fill the form and create a valid billing plan. Once you plan is created note the Plan ID as this is what we are going to associate our customers to. Following is the function to subscribe customers already in BrainTree vault to recurring billing plan we have just created.

Congratulations, you have just created your first recurring billing transaction. Should you need to cancel a subscription, you will need the $subscriptionID, simply use the following code

BrainTree on CVV

BrainTree’s stand on storing CVV

We can’t store the CVV according to PCI guidelines, but you can send it in with the Vault tokens. CVV rules will be applied to these transactions if the CVV is sent in with the tokens. However, CVV is not required when creating a transaction from Vault tokens. If the CVV is not passed CVV rules will not be applied.

I hope these methods will help you create BrainTree Payment Gateway one time or recurring billing transactions. I would love to hear your own experiences of using BrainTree Payment Gateway with PHP.

  • Richard Simmons

    This is exactly i was looking for, i tried the API manual from Braintree but that was taking time. Could you explain $tr_data array before sending request to Braintree?

  • In simpler terms

    relies on $tr_data which contains your request, an array containing your URL and transaction data i.e. amount, type, customer detail etc.

  • om

    Thanks a lot ……………………………

  • Rajen

    This helps very much to me…..

  • Mindy

    Thank you this code is really useful.

    I want some help on setting the credit info to vault.
    I had added the “function create_customer” codes under “function braintree_text_field” codes. I am not selling anything but just storing the credit card information to vault. When I did couple test, the card info didn’t go to the vault. The card info showed up as buying a product. I tried removing the codes that have to do with purchasing (i.e $tr_data …..) it gave me an error saying that the payment is not charged.

    If there’s anything you can help me, please email me or reply my comment! Thanks!

  • Inspired

    I’m using Webhooks which returns a subscription_id. I’ve been trying to find a code sample that will return transaction values (e.g. email) given a subscription_id. Can you advise? Thank you.

  • gurcharansinghgill6

    this tutorial is great!! and payment is executed excellently but I do no know how to
    get the Transaction id value to my database? trasaction id means the successfull transation code which comes after the successfull payment.

    and moreover the price value is right now have to change manually but can we assign any variable to it.

  • gre

    doesn’t even work…. don’t waste your time

  • Rick

    Hello, I am using one time payment on braintree. But I can not see the transaction details after payment in braintree sandbox account.. Anyone please help me?

  • Randy

    Isn’t it a tremendous security breach to put your public and private key in the same file?

  • Randy

    I am so grateful for this post. Braintree’s documentation is terrible, and I couldn’t find anything else out there to explain this for me. This is a life saver.

    One minor point: in your create_transaction function you have a couple of echo lines commented out. If you uncomment them for testing (like I did), you need to change $result to $result1.

  • Craig Arnold

    Important: The first file shown above (_environment.php) *must* have the PHP start/end symbols ( <? php goes here ?> ) on it, or you will get an error (Class ‘Braintree_TransparentRedirect’ not found). I’m not sure why that file doesn’t have the symbols, but the next example file does. I wasted about an hour on this. What makes this tricky is that the error message shows in the middle of the example, well after the environment is supposedly set correctly, so it is not obvious that this is a problem. (In any case, thanks to the author for an example that is far more readable that the BrainTree docs.)

  • Reginald

    I put the Braintree Client Framework in my /root/braintree folder. Where do I put the environment.php file?

  • Pingback: Braintree Credit Card Types | Why Money Matters 4U()

  • Whoru12C

    I want to second Randy’s comment that Braintree’s documentation was difficult to understand. This post made it so easy. I’m glad I found it! Thanks! I did have to make a few modification, but I have everything I need now to create a transaction and reocurring transactions for my client.

  • Tonitech

    Whoever you are, thank you! I am a brand new merchant to Braintree, also a fairly decent PHP coder. This is undoubtedly the best of very few resources on Braintree integration I’ve come across – that wasn’t written by Braintree! They certainly know their stuff; however, explaining it is definitely not their strong suit. So thank you again for taking the time to help us spend less time banging our heads against the wall. πŸ™‚

    I’m using the Transparent Redirect for single/one-time transactions with PHP. Here are some additional tips I’d like to share that I didn’t see mentioned below:

    1. Everyone’s payment form will differ slightly from the above sample depending upon your business and the information you want/need to collect. At minimum, the code above is missing the field for the card holder’s name. Your “Customer” and your “Card holder” might not be the same person; they definitely aren’t in Braintree coding land. So, if you want your transaction to pass the card holder’s name to the issuing bank when seeking authorization (yes, you definitely want that!), add it to the payment form like this:

    You can change the part that says “Cardholder Name” to read differently if you prefer.

    2. Here’s another big caveat to the above code: transactions aren’t automatically settled, they are only authorized. That means you’ll have to log into the Braintree Control panel and manually settle them (within 7 days, I think it is) or you’ll lose the authorization, unless you add the following option to automatically settle them for you, like this:

    “http://” . $_SERVER[“SERVER_NAME”] . “:” . $_SERVER[“SERVER_PORT”] . parse_url($_SERVER[“REQUEST_URI”], PHP_URL_PATH),
    ‘transaction’ => array(‘amount’ => $order_amount, ‘type’ => ‘sale’, ‘options’ => array(‘submitForSettlement’ => True
    )))) ? >

    3. This one is sort of a tip-within-a-tip related to the last one. Other coders might notice that array is written in “old” PHP. Braintree stipulates PHP 5.4 or higher; they will check and throw a fatal exception error if you’re using an older version like me, but you can easily get around that. Not using newer programming shortcuts is one way; you can also simply remove the version checker. Find it in braintree-php/lib/Braintree.php on line 137 and comment it out, like this:

    /* if (version_compare(PHP_VERSION, ‘5.4.0’, ‘= 5.4.0 required’);

    You might have to “antique” some additional arrays and/or other things along the way, but PHP is great in that it always provides a file name and a line number when you have an error.

    4. Okay, so the hard-coded sale amount wasn’t so much helpful as it was illustrative to the example. Most of us using the Transparent Redirect method probably won’t know what the order total is until the customer checks out, and it isn’t like we’re going to be holding their hand when they do, right? That has to be replaced with a variable (if the customer shouldn’t be able alter the sale amount) or an HTML form field (if the customer decides the amount, like when making a donation). I’m using $order_amount for my variable. If you need a form field instead, it would look something like this:

    5. Lastly, I found it very helpful to add both my sandbox codes and my live production codes to the _environment.php file and just comment out whichever one I wasn’t using. It’s annoying to have to look them up then copy/paste all of those codes each time you switch environments, especially as often as you might go back and forth in the beginning. To answer a related question from below as well, _environment.php and single_transaction.php belong in the same location as your checkout/payment page, unless you’re sure to specify a different file path in the require function.

    In all of the above coding examples, be sure to remove the spaces between the opening and closing PHP symbols. I had to put them in in order to get the code to display in the post.

    Hope this helps. Happy coding and credit-carding with Braintree! πŸ™‚

  • Sam

    When I am running this code, i can see only a blank page..Please suggest..

  • Amy

    Thank you SO much for this!!! I was VERY stuck before this, but now I have most of my store up and running!! My question is, how do I pass a ‘variable’ amount to braintree? Since I have multiple items in my catalog, after processing the total sale, adding tax and shipping, it is going to change each time but every example I see is sending a hard coded amount to Braintree.

  • Sero

    Hi there,
    thanks for the sample and clear explanation! However I found out that this method of transaction is labeled as deprecated by braintree. I couldn’t find any information why is that so. Do you know if it’s still safe to use transparent redirects?

  • kiran

    hi this is very help full. but my sandbox account accepts payment of Expired cards also

  • Dan

    is this possible to integrate account to account transfer using Brain tree ?

  • Nick

    Is there a way to set an option to make make the status automatically start the process for becoming “settled”

  • Shivangi

    Subscription is created but status is pending. So what do I need to do to change the status?

    This helped me alot.. Thanks Buddy..

  • Dushyant Sharma

    I am using braintree transparent redirect. I have setup all these things. I have setup merchant sandbox id. But I am getting same 0 error again and again. Please help me.


  • ricardo

    what if i want to put a default value from the code for example in card number where im suppose to put it

  • ricardo

    what if want to put a default value from the code for example in the card number where im suppose to put it

  • karl

    Thank you for this information it was most helpful.