Time
25mins
Platforms
Windows & Mac
Difficulty
Easy
Technologies
JavaScript, Node.js, Express

Thanks for trying out the preview of our new tutorial! It’s intended to get you from a blank slate to a test transaction as quickly as possible.

For a more detailed walkthrough of a complete Braintree integration, see our Get Started guide.

Before you begin

First, make sure you have the latest versions of Node.js and npm installed. You’ll also need a console (e.g. Terminal on Mac, Command Line on Windows) and a text editor of your choice.

To get you up and running quickly, we’ll use Express to generate a Node app with basic routing.

Install the Express app generator

console
Click to copy
Copied
npm install --global express-generator@4

If you’re interested in how the Express generator works or its options, see the Express generator docs.

Get a Braintree sandbox

To successfully run a test transaction, you’ll need a Braintree sandbox account. Log in or sign up for one now.

Rate this section

1. Set up a basic app

Now that you have all the necessary tools installed, we can use the Express app generator to quickly create the basic application structure we’ll use for the tutorial.

Generate the app

Run this command in your console where you want to store the tutorial code. Use --view=hbs to set the template engine to Handlebars – this is what we will use throughout the tutorial.

console
Click to copy
Copied
express braintreeTutorial --view=hbs

Open your newly created app

The command above will have created a new folder with your app structure inside. Open that folder now.

console
Click to copy
Copied
cd braintreeTutorial

Install dependencies

console
Click to copy
Copied
npm install

Install Braintree

The Braintree Node.js library is the server-side Braintree SDK that will communicate with Braintree’s servers. Install it now so that when we’re ready, we can wire up the payment form.

console
Click to copy
Copied
npm install braintree --save

Rate this section

2. Add the Drop-in UI

Our basic app will have one page on the client and one route on the server.

Express already generated an index view that we’ll use for the payment form markup on the client. From here, we'll use Braintree's Drop-in UI to quickly create the form.

To load the Drop-in UI on the page, we’ll need 3 things:

  1. The Braintree JavaScript client SDK (learn more in our Client SDK Setup guide)
  2. A tokenization key
  3. Drop-in UI markup

Include the Braintree client SDK

Add the following code just above the closing </head> tag in views/layout.hbs.

HTML
Click to copy
Copied
<!-- includes the Braintree JS client SDK -->
<script src="https://js.braintreegateway.com/web/dropin/1.4.0/js/dropin.min.js"></script>

<!-- includes jQuery -->
<script src="http://code.jquery.com/jquery-3.2.1.min.js" crossorigin="anonymous"></script>
note

We only include jQuery here to reduce the complexity of our tutorial code. It’s not a requirement in order to use Braintree.

Get a tokenization key

There are 2 ways to authorize the client to tokenize payment methods:

  • A client token, which requires a round trip to your server and enables you to use all of Braintree’s client API capabilities
  • A tokenization key, which is a static key with reduced privileges that authorizes a subset of Braintree’s client API capabilities

For this tutorial, we’ll use a tokenization key, which is stored in your Braintree Control Panel. To find it:

  1. In your sandbox Control Panel, go to Account > My User
  2. Under API Keys, Tokenization Keys, Encryption Keys, click View Authorizations
  3. You should see your key under the Tokenization Key section; if no key appears, click Generate New Tokenization Key
  4. Keep this page open so you can add your key in the code below

For more information or help with this step, see our API Credentials support article.

Add the Drop-in UI markup

Our Drop-in UI consists of a small amount of HTML markup, which will be initialized using the Braintree JavaScript SDK we included above.

Replace the contents of views/index.hbs with this code:

HTML
Click to copy
Copied
<div id="dropin-wrapper">
  <div id="checkout-message"></div>
  <div id="dropin-container"></div>
  <button id="submit-button">Submit payment method</button>
</div>
<script>
  var button = document.querySelector('#submit-button');

  braintree.dropin.create({
    // Insert your tokenization key here
    authorization: '<use_your_tokenization_key>',
    container: '#dropin-container'
  }, function (createErr, instance) {
    button.addEventListener('click', function () {
      instance.requestPaymentMethod(function (requestPaymentMethodErr, payload) {
        // When the user clicks on the 'Pay' button this code will send the encrypted
        // payment information in a variable called a payment method nonce
        $.ajax({
          type: 'POST',
          url: '/checkout',
          data: {'paymentMethodNonce': payload.nonce}
        }).done(function(result) {
          // Tear down the Drop-in UI
          instance.teardown(function (teardownErr) {
            if (teardownErr) {
              console.error('Could not tear down Drop-in UI!');
            } else {
              console.info('Drop-in UI has been torn down!');
              // Remove the submit payment method button
              $('#submit-button').remove();
            }
          });

          if (result.success) {
            $('#checkout-message').html('<h1>Success</h1><p>Your Drop-in UI is working! Check your <a href="https://sandbox.braintreegateway.com/login">sandbox Control Panel</a> for your test transactions.</p><p>Refresh to try another transaction.</p>');
          } else {
            console.log(result);
            $('#checkout-message').html('<h1>Error</h1><p>Check your console.</p>');
          }
        });
      });
    });
  });
</script>
note

Be sure to add your own tokenization key in the authorization parameter above.

The paymentMethodNonce is a string returned by the client SDK to represent a payment method. It’s a one-time-use reference to the payment method details that your customer provided in your payment form. In the next step, we’ll set up your server to receive this string so it can be used to create a transaction request.

Rate this section

3. Handle checkout

Now that the client is set up to securely collect payment information, we’ll create a route on your server that accepts the payment method nonce from the Drop-in UI and then uses that nonce to create a sale transaction request for $10.

Create a file called routes/checkout.js

Create this file in your text editor, IDE, or console.

On Mac

console
Click to copy
Copied
touch routes/checkout.js

On Windows

console
Click to copy
Copied
echo.>routes\checkout.js

Add the payment logic

Get your sandbox API credentials

Next, get your sandbox API credentials from the sandbox Control Panel. You'll need your:

  • Sandbox merchant ID
  • Public key
  • Private key

You can get all 3 values on the same Authorizations page where you found your tokenization key. For full instructions, follow this quick guide.

Add the route code to routes/checkout.js

In routes/checkout.js, add the following code inside of the route function.

JavaScript
Click to copy
Copied
var express = require('express');
var router = express.Router();
var braintree = require('braintree');

router.post('/', function(req, res, next) {
  var gateway = braintree.connect({
    environment: braintree.Environment.Sandbox,
    // Use your own credentials from the sandbox Control Panel here
    merchantId: '<use_your_merchant_id>',
    publicKey: '<use_your_public_key>',
    privateKey: '<use_your_private_key>'
  });

  // Use the payment method nonce here
  var nonceFromTheClient = req.body.paymentMethodNonce;
  // Create a new transaction for $10
  var newTransaction = gateway.transaction.sale({
    amount: '10.00',
    paymentMethodNonce: nonceFromTheClient,
    options: {
      // This option requests the funds from the transaction
      // once it has been authorized successfully
      submitForSettlement: true
    }
  }, function(error, result) {
      if (result) {
        res.send(result);
      } else {
        res.status(500).send(error);
      }
  });
});

module.exports = router;
note

Be sure to add your own merchantId, publicKey and privateKey into their correct variables above.

To learn more about how the transaction.sale method works and which options you can specify, see the reference.

Connect the route to app.js

In simple terms: Node and Express apps are driven through a file called app.js. All routes, as well as other critical information that define how your app will work, are stored here. We’ll use the app.js file to link up the route we created in the previous step.

Add a /checkout route to app.js

After app.use('/users', users); in app.js, add your checkout route:

JavaScript
Click to copy
Copied
// The checkout route
var checkout = require('./routes/checkout');
app.use('/checkout', checkout);

Rate this section

4. Create a test transaction

At this point, you should have a properly-initialized payment form when you run your app.

To see your payment UI in action, we’ll run a few test transactions and then view them in the sandbox Control Panel.

Run the app

Run the following command in your console.

console
Click to copy
Copied
npm start

Then open http://localhost:3000/ in your browser.

Enter a test card in the payment form

The Braintree sandbox only accepts specific test values. To create a successful transaction in your app, be sure to use the card information below for this test.

  • Card number: 4111 1111 1111 1111
  • Expiry: 09/20
  • CVV: 400
  • Postal Code: 40000

Once you create a successful transaction, feel free to try out other test cards listed on our Testing reference page.

See your transaction in the sandbox

You can view test transactions by logging back into the sandbox Control Panel. At a high level, you'll see your new sale transaction reflected in the graph on your dashboard, but to see its details:

  • Search for 1111 (the last 4 digits of the test card number above) in the search box, or
  • Click Transactions under Advanced Search in the side navigation to search with full control over your parameters

To learn more about searching in the Control Panel, see our Search support article.

Rate this section

Next steps

Give yourself a high five! Now that you have a basic working integration, choose what you'd like to do next:

\(^O^)/

Rate this section

Still have questions?

If you can’t find an answer, contact our Support team.