bt.tn mash

Matt Foyle profile picture Written by: Matt Foyle - Published on: 15 Nov 2016
Create your own one-press IoT checkout for your customers, powered by Moltin &bttn.

Introduction

When the Amazon Dash was introduced, it was awesome. However, upon having to choose a single Amazon product to link it to, it became less awesome - IoT should be flexible, and extendable.

It made me wonder, shouldn’t every retailer be able to create their own IoT experience, with the ability to link it to any product they sell?

Luckily, the good folks at Bttn feel the same way. I grabbed one of their IoT devices, capable of HTTP requests and started building. The result became a button attached to my own defined product and customer on a Moltin store.

When pressed, it automatically adds a product to cart, runs through checkout with saved bill_to & ship_to details, completing the purchase!

In this example, all the Moltin customer info is predefined, but we can dynamically pull that in, as well as make some optimizations and ensure that all sensitive details are handled securely - This will be covered in the next post.

OK, let’s jump in and see how it works! You can find the code in full here, and I recommend you have it up while reading through this guide. The repo also has a video of the bttn completing! We want your customers to be able to buy items as they come down the catwalk, making them instantly purchasable.

Moltin setup

Preface - apart from store creation, you can do each of the following steps programmatically. I will describe the manual method - if you prefer to do it programmatically, visit the docs.

We’re going to need to have a Moltin store with an active product and shipping method.

  1. Hop onto moltin.com and hit register in top right hand corner. Throw in your details and you’re good to go.
  2. Once you have created your store, you can go to the account management page, click on that store and find your API keys - make a note of those.
  3. Next, login to the store dashboard. On the left-hand menu, hit “Inventory” and in the dropdown, choose “Products”.
  4. On the top right of the Products page, hit the ‘Create Product” button.

  1. Fill out the required information (make sure to set the status to “live”), and then hit Submit at the bottom. Once back on the main products page, you can make a note of the new products ID (#) field.
  2. Next, back at the left-hand menu of the dashboard, choose “Advanced”, and in the dropdown, choose “Shipping”. On the top right of the next page, hit “Create a Shipping Method”

  1. Fill in the details (again, setting the status to “live”), and make a note of the Slug. When you’re done, hit submit at the bottom.

Great work. By now you should have a note of:

  1. Your store API credentials - Use in App Config
  2. ID of a live Product - Use in App Config
  3. Slug of an active Shipping Method - Use in Moltin part of Server App

Let’s move on to building our app, and keep an eye out for instructions to plug in the above!

Quick note at this point. We’re going to use the ‘dummy payment gateway’ to make things easier, but if you want to do live payments, I recommend this guide for Stripe.

App Config

We need to set all our variables for later, and we store them here. You won’t have the bttn API key yet, but don’t worry, we can come back and fill that in after we do the bttn admin.

  // Variables
var config = {
  port:      3000,

  // Moltin Product ID you noted earlier
  product:   'XXXX',

  // Your moltin API credentials you noted earlier
  publicId: 'XXXX',
  secretKey: 'XXXX',

  //  Your bttn API key
  bttnKey:   'XXXX',

  callback:  undefined,

  // Predefined customer
  customer: {
    first_name: 'Jon',
    last_name:  'Doe',
    email:      'jon.doe@gmail.com'
  },
  address: {
    first_name: 'Jon',
    last_name:  'Doe',
    address_1:  '123 Sunny Street',
    address_2:  'Sunnycreek',
    city:       'Sunnyvale',
    county:     'California',
    country:    'US',
    postcode:   'CA94040',
    phone:      '6507123124'
  },
  card: {
    number:       '4242424242424242',
    expiry_month: '02',
    expiry_year:  '2017',
    cvv:          '123'
  }
};

Server app

On the bttn admin interface side, we need to do a couple of things to configure the request it makes correctly, and we’ll cover that in the third section.

First though, we’ll cover the build of our own server that takes the bttn’s request, handles Moltin, and responds to the bttn.

We’ll build a NodeJS Express app (I’ve called mine “bttn”) which, when it gets a request from the bttn, processes the bits that we need, calls the Moltin operation, sends a callback request to the bttn and closes the connection as a response.

  // Start Express
var bttn = express();

// Configure JSON and Form handlers
bttn.use(bodyParser.json());
bttn.use(bodyParser.urlencoded({extended: true}));

// Start the server
bttn.listen(config.port, function () {
  console.log('app listening on port ' + config.port);
})

// Listen for a post request
bttn.post('/', function (req, res) {

  // Debug
  console.log('Request Received');

  // No callback provided
  if ( req.body.callback === undefined ) {
    return console.log('Error: No callback URL provided.');
  }

  // Add the bttn callback URL to config, more on this later
  config.callback = req.body.callback;

  // Run the purchase operation
  return purchase('test', function(data) {

    // Debug
    console.log('Purchase Success');

    // Setup the response to bt.tn
    var options = {
url: config.callback,
method: 'POST',
json: true,
headers: {'X-Api-Key': config.bttnKey},
body: {result: 'success'}
    };

    // Make the callback request
    request(options, function(error, response, body) {
if ( ! error && response.statusCode == 200 ) {
  console.log('Callback Success');
}
    });

    // Close this request
    res.setHeader("Connection", "close");
    res.end();

  // Error handler
  }, function(status, err) {
    return console.log(err);
  });

});

Let’s dip into the point of “// Setup the response to bt.tn” so we understand what’s happening.

Once the Moltin checkout has completed, we can tell the bttn that the event has been a success, and we do this by using a callback.

When the bttn is pressed, the request sent to our server includes a unique, dynamically generated callback URL, and we use the URL to send a success message back. That’s saved in config.callback automatically when we receive the request.

We’re also passing our bttn API key (generated later via the bttn interface and stored within config)

Finally, we pass a success message in the body - we’ll go into this more in the bttn admin section.

Next, comes the code for our Moltin requests, which we just triggered, executing the one-press checkout.

This code authenticates, pushes a product to cart, pushes from cart to checkout, then checkout to payment, and payment to order completion. Remember, we’re using the Dummy gateway, normally no credit card info would be processed here.

  // Moltin handler
var purchase = function(slug, success, error) {


  // Get a Moltin instance
  var moltin = require('moltin')({publicId: config.publicId, secretKey: config.secretKey});


  // Authenticate
  moltin.Authenticate(function() {


    // Add the item to a cart
    moltin.Cart.Insert(config.product, 1, null, function(item) {


// Create the checkout
moltin.Cart.Complete({
  gateway: 'dummy',
  customer: config.customer,
  bill_to: config.address,
  ship_to: 'bill_to',
  // Enter the shipping method slug here
  shipping: 'XXXX'
}, function(order) {


  // Run the purchase
  moltin.Checkout.Payment('purchase', order.id, {data: config.card}, success, error);


}, error);
    }, error);
  }, error);


};

That’s it! The final step is to expose a tunnel to your local server app so that we can test this thing.

You can do so by installing Ngrok and running Ngrok HTTP 3000, which will give you a URL to use when setting up the bttn admin. Once ngrok is running, you’ll see something like this.

The URL you need to give our bttn in the next section is the first one in “Forwarding” before the “-> localhost:3000”

Bttn setup

We’re going to assume that at this stage, you have registered and done the initial setup of your bttn. If you haven’t, this guideshows you how.

The first thing we’re going to do is to create our bttn API key, so we can fill in the XXXX in config. We do so via our bttn account settings. At the bottom of the page, hit Generate.

This process will also create a callback application, as the next step will ask you for an application name, once that’s done, you’ll have an API key. Let’s now use that key to replace the “XXX” part in the config section for bttnkey.

Now, we’re going to set the action for the bttn so that it interacts with our Express app via the ngrok URL once you press it. Go to your bttn homepage, scroll down to your own button, and hit action in the top right-hand corner.

This will bring you to the action page, and you’ll want to hit “New action”

For “Execute action if BTTN is”, leave it as “Pressed”, and hit next.

For “What kind of message would you like to send”, choose HTTP.

The first thing we need to give it the URL to call. For testing, I’ve exposed the localhost that the Express app server is running on via Ngrok, so just paste in the Ngrok URL here.

Then we need to instruct the bttn to pass us the callback URL, so we can store it while processing the request in our server app. We do this by specifying argument format of “application/x-www-form-urlencoded” and referencing bttn’s’ predefined, like so.

Then we need to enter the method, which I’ve set to POST because, within my express app, I’ve asked it to listen and respond to POST requests at the root.

You can leave all the other fields up to “wait for HTTP callback” as No, like shown.

We then check the box for “wait for HTTP callback” and it gives us some extra info.

In the “Select callback application” field, you’ll have a dropdown, and you can select the application you created earlier while generating an API key.

Lastly, we set what to look for within the callback to define success. In our Node app, you’ll remember that we passed a body of { result: ‘success’ } within the callback. Thus, we’ll ask the bttn to show green if the response we send contains the word success.

Hit next at the bottom right of the page and review the summary to make sure everything is correct. You can check “Store this as a template under your stored actions” and save it.

Finally, hit “Save” at the bottom right of the page, and you’re done!

Testing

Assuming you have Ngrok running away, and assuming you’re in the working directory with Terminal, run the Node app with “node bttn.js”. You should see the Terminal log ‘app listening on port 3000!’.

Now, PRESS THE BTTN!

The Terminal should start to log out requests.

The first thing you’ll see is “request received”, showing that the server has detected a bttn press.

Once we see “purchase success”, we know that the Moltin bit is finished and we have a completed purchase!

Finally, you’ll see “callback success” showing that we completed the callback to the URL passed to us.

It’s around this time that you should see your bttn flash green. Seeing this confirms that we made the callback successfully, and we’re done!

Deployment

In order to run this without your local machine and Ngrok, you’ll need to host it.

Grab the Github code, edit the config with your own API keys and then edit the Moltin code section with info shipping method, and host it wherever you prefer.

Copy the new URL, and paste it into the URL section of the bttn action interface, where we previously had the Ngrok URL.

Resources

Bttn:

moltin:

NodeJS and other:

Let's build something amazing with Moltin