Getting started overview

Integrating Braintree for payment processing involves a sequence of steps, beginning with account setup and culminating in a successful transaction. This guide focuses on the initial configuration, credential retrieval, and the execution of a basic API request in the Braintree sandbox environment. The sandbox provides a testing ground that mimics the production environment without processing actual funds, enabling developers to validate their integration logic before going live Braintree documentation for getting started.

The core process includes:

  1. Creating a Braintree sandbox account.
  2. Generating API keys and credentials.
  3. Installing a Braintree SDK in your preferred programming language.
  4. Making a client-side request to generate a client token.
  5. Making a server-side request to process a transaction.

This structured approach ensures that each component of the payment flow is tested and verified. Braintree provides client-side SDKs to collect payment information securely and server-side SDKs to interact with the Braintree Gateway for transaction processing Braintree developer documentation. Secure handling of payment data is critical, and Braintree's client-side SDKs assist in meeting PCI DSS compliance requirements by tokenizing sensitive information before it reaches your server PCI Security Standards Council.

Quick Reference Table

Step What to do Where
1. Sign Up Create a Braintree sandbox account. Braintree Sign Up Page
2. Get Credentials Locate your Merchant ID, Public Key, Private Key. Braintree Control Panel > Account > My User > API Keys
3. Install SDK Add the Braintree client and server SDKs to your project. Braintree Client SDK documentation and Braintree Server SDK documentation
4. Configure Server-Side Initialize the Braintree Gateway with your credentials. Your server-side application code
5. Generate Client Token Request a client token from your server and pass it to your client. Your server-side application (e.g., gateway.clientToken.generate())
6. Implement Client-Side UI Set up the Braintree Drop-in UI or custom UI to collect payment info. Your client-side application (e.g., JavaScript, iOS, Android)
7. Process Transaction Send the payment method nonce from the client to your server, then create a transaction. Your server-side application (e.g., gateway.transaction.sale())

Create an account and get keys

To begin, you need a Braintree account. For development and testing, Braintree recommends starting with a sandbox account, which allows you to simulate transactions without real money Braintree guide on going live. You can sign up for a sandbox account directly from the Braintree website Braintree Get Started page.

Sandbox Account Creation

  1. Navigate to the Braintree sign-up page.
  2. Select the option to create a sandbox account.
  3. Follow the prompts to enter your business information and create your login credentials.
  4. Once your sandbox account is active, you will gain access to the Braintree Control Panel.

Retrieving API Keys

Your API keys are essential for authenticating your application with the Braintree Gateway. These keys are unique to your account and environment (sandbox or production). You will need a Merchant ID, Public Key, and Private Key.

  1. Log in to your Braintree Control Panel for your sandbox account.
  2. From the navigation menu, go to Account > My User.
  3. Scroll down to the API Keys section.
  4. If you don't see any API keys, click Generate New API Key.
  5. Make note of your Merchant ID, Public Key, and Private Key. These credentials should be stored securely and never exposed in client-side code Braintree API keys documentation.

For production environments, the process for obtaining API keys is similar, but you will access them from your live Braintree account's control panel after it has been approved.

Your first request

A typical Braintree transaction flow involves both client-side and server-side interactions. The client-side collects payment information securely using a Braintree SDK and receives a payment method nonce. The server-side then uses this nonce to create a transaction via the Braintree Gateway.

Server-Side Setup (Node.js Example)

First, set up your server-side environment. This example uses Node.js, but Braintree provides SDKs for various languages Braintree server-side SDK documentation.

1. Install the Braintree Node.js SDK:

npm install braintree

2. Initialize the Braintree Gateway:

Create a file (e.g., server.js) and configure the gateway with your sandbox credentials:

const braintree = require('braintree');

const gateway = new braintree.BraintreeGateway({
  environment: braintree.Environment.Sandbox,
  merchantId: 'YOUR_MERCHANT_ID',
  publicKey: 'YOUR_PUBLIC_KEY',
  privateKey: 'YOUR_PRIVATE_KEY'
});

// Example endpoint to generate a client token
app.get('/client_token', (req, res) => {
  gateway.clientToken.generate({}, (err, response) => {
    if (err) {
      res.status(500).send(err);
    } else {
      res.send({ clientToken: response.clientToken });
    }
  });
});

// Example endpoint to create a transaction
app.post('/checkout', (req, res) => {
  const nonceFromTheClient = req.body.paymentMethodNonce;
  const amount = req.body.amount;

  gateway.transaction.sale({
    amount: amount,
    paymentMethodNonce: nonceFromTheClient,
    options: {
      submitForSettlement: true
    }
  }, (err, result) => {
    if (err) {
      res.status(500).send(err);
    } else if (result.success) {
      res.send({ success: true, transactionId: result.transaction.id });
    } else {
      res.status(400).send({ success: false, message: result.message });
    }
  });
});

Client-Side Setup (JavaScript Example with Drop-in UI)

The client side uses the Braintree JavaScript SDK to render a payment UI and obtain a payment method nonce.

1. Include the Braintree client-side SDK:

Add the following script tags to your HTML file's <head> or before the closing <body> tag:

<script src="https://js.braintreegateway.com/web/drop-in/1.33.0/js/dropin.min.js"></script>

2. Render the Drop-in UI and process payment:

Create a container for the UI and add JavaScript to initialize it.

<div id="dropin-container"></div>
<button id="submit-button">Purchase</button>

<script>
  const button = document.querySelector('#submit-button');

  fetch('/client_token') // Request client token from your server
    .then(response => response.json())
    .then(data => {
      braintree.dropin.create({
        authorization: data.clientToken,
        container: '#dropin-container'
      }, function (createErr, instance) {
        if (createErr) {
          console.error(createErr);
          return;
        }
        button.addEventListener('click', function () {
          instance.requestPaymentMethod(function (requestPaymentMethodErr, payload) {
            if (requestPaymentMethodErr) {
              console.error(requestPaymentMethodErr);
              return;
            }

            // Send payload.nonce to your server
            fetch('/checkout', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                paymentMethodNonce: payload.nonce,
                amount: '10.00' // Example amount
              })
            })
            .then(response => response.json())
            .then(result => {
              if (result.success) {
                alert('Transaction success! Transaction ID: ' + result.transactionId);
              } else {
                alert('Transaction failed: ' + result.message);
              }
            })
            .catch(error => {
              console.error('Error:', error);
            });
          });
        });
      });
    })
    .catch(error => {
      console.error('Error fetching client token:', error);
    });
</script>

This setup provides a functional payment form that collects card details, tokenizes them, and sends a nonce to your server for transaction processing. Ensure your server-side code is running and accessible from your client-side application.

Common next steps

After successfully processing your first sandbox transaction, consider these next steps to further your Braintree integration:

  • Explore Advanced Features: Braintree offers features like recurring billing for subscriptions, marketplace payments, and various payment methods beyond standard credit cards Braintree recurring billing guide. Review the Braintree documentation to understand how to implement these for your specific use cases.
  • Error Handling and Webhooks: Implement robust error handling on both client and server sides. Utilize Braintree webhooks to receive real-time notifications about transaction status changes, disputes, or other important events, which is crucial for maintaining accurate records and responding to customer issues Braintree webhooks overview.
  • Go Live: Once your integration is thoroughly tested in the sandbox, you can apply for a production Braintree account. This involves providing business details and undergoing an approval process. After approval, you will switch your API credentials and environment to production Braintree go-live checklist.
  • Security Best Practices: Continuously review and apply security best practices, such as PCI DSS compliance measures, secure storage of API keys, and validation of all incoming data. Never hardcode sensitive credentials directly into your application code; use environment variables or a secure configuration management system.
  • Reporting and Analytics: Familiarize yourself with Braintree's reporting and analytics tools available in the Control Panel. These tools provide insights into your transactions, customer behavior, and financial performance.

Troubleshooting the first call

Encountering issues during the initial integration is common. Here are some common problems and their solutions:

  • Invalid API Credentials: Double-check that your Merchant ID, Public Key, and Private Key are correct and that you are using sandbox credentials for the sandbox environment. Mismatched credentials or using production keys in sandbox will result in authentication failures Braintree API key troubleshooting.
  • Network Connection Issues: Ensure your server can reach the Braintree API endpoints. Firewall rules or network configurations might block outgoing requests.
  • Client Token Generation Failure: If your client token request fails, verify your server-side code for generating the token. Ensure the gateway is initialized correctly and that there are no errors in the gateway.clientToken.generate() call.
  • Payment Method Nonce Issues: If the client-side fails to generate a nonce or if the nonce is invalid when sent to the server, check the client-side SDK initialization and the requestPaymentMethod callback. Ensure test card numbers are being used correctly in the sandbox Braintree test card numbers.
  • Transaction Decline: In the sandbox, transactions can decline for various reasons, including using specific test card numbers designed to simulate declines or exceeding daily transaction limits for test accounts. Review the transaction response for specific error messages and consult Braintree's error code documentation Braintree general testing information.
  • CORS Errors: If you're developing on a local environment and encountering Cross-Origin Resource Sharing (CORS) errors, ensure your server is configured to allow requests from your client-side origin. While Braintree's client-side SDKs handle cross-origin requests to their domains, your server API endpoints might require CORS headers.
  • SDK Version Mismatch: Ensure that your client-side and server-side SDKs are compatible and up-to-date. Refer to the Braintree SDK documentation for version compatibility Braintree SDK documentation.