How to Build a Smart Online Store in Less Than 21 Days!

Tigran Bagdasaryan, Frontend Developer @ BuiltOn.dev on .

Share with Facebook
Share with Twitter
Share with LinkedIn

Why 21 days, you might ask. It’s a bit of an inside joke here at BuiltOn. Anyone working at a dev agency or consulting firm knows how often the question, "How long will it take!?", comes up.

Tools

Before we launched the full BuiltOn product earlier this year, we used our API tools to help us do consulting work faster and, to be blunt, cheaper than other dev agencies.  One day, one of our sales guys asked one of the dev team if they could build an app in a month, and the dev, translating that into development days, responded ‘You mean 21 days?’  Because there are about 21 working days in any given month.  And that was funny for some reason in the moment.

Right. Explaining inside jokes about project estimation. Cool story, bro, can you tell me about the store now?  Yes.

In this article, I will show you how to use BuiltOn's APIs to create an online store with recommenders and similarity models really, really fast, using our Instant ML tools and without blowing your budget. It’s pretty cool if like us you like to build smarter not harder.

NOTE: Layouts and styling are very specific to every project, so I’m going to leave those out of the scope of this article. I’ll be focusing on BuiltOn’s APIs and how to use them.

Prerequisites

  1. BuiltOn Account

  2. BuiltOn Javascript SDK

  3. Authorization Provider (Firebase)

  4. Payment Provider (Stripe)

  5. Products

(Don’t worry. They’re all free.)

1. BuiltOn Account

This is arguably the easiest step.  Just go sign up with us. :)

2. BuiltOn Javascript SDK

BuiltOn’s APIs are easily accessible through our SDK’s. You can check the docs for more details, but just set up your BuiltOn javascript sdk by running:

npm i --save @builton/core-sdk

3. Authorization Provider

BuiltOn offers support for various authentication providers (Firebase, Auth0, Cognito and your own custom solution). To keep it simple, I’ll use Firebase. More info is available in our docs, but basically, you just:

  • Register/login to your Firebase Console and enable authentication through email/password.

Authentication
  • You need the Project ID in Firebase, located in your project settings.  Then go to your BuiltOn dashboard and navigate to Settings, then Link Firebase and paste in the Project ID.

Auth provider

4. Payment Provider

You’ll no doubt want to be able to charge your customers. Our default payment provider is Stripe.  You can see our docs for more details, but to get set up:

  • Register/Login to Stripe and create your test account.

  • Login to your BuiltOn dashboard, go to Settings and Link Stripe as your payment provider. Be sure to choose QA, since it’s a test environment. You can also skip Stripe’s activation form by clicking on the link at the top.

Select environment

5. Products

And of course, you want to sell something. To set up your products, go back to your BuiltOn Dashboard and navigate to Products. There is a ‘Create Product’ button, just click the ‘+’ and start creating. Products are very flexible, so depending on how much information you provide, your online shop may look more complete.

Products

That’s it! Now, you can focus on creating your online store and finally do some programming.

Let’s code this thing out!

As I mentioned before, there is a lot that goes into creating an application.  I’m leaving out all the other technology choices, project structure, design meetings and all the rest to just focus on working with BuiltOn’s APIs. 

To begin with, you instantiate your BuiltOn singleton, which will give you everything you need to work with it. You also need to initialize Firebase for authentication.

// builton.js
import Builton from '@builton/core-sdk/src/main';
import firebase from "firebase/app";
import 'firebase/auth';

firebase.initializeApp({
 apiKey: "<YOUR_FIREBASE_API_KEY>", // From Firebase Dashboard
 authDomain: "<YOUR_FIREBASE_AUTH_DOMAIN>", // From Firebase Dashboard
});

const builton = new Builton({
 endpoint: "https://api.builton.dev/",
 apiKey: "<YOUR_BUILTON_API_KEY>", // From Builton Dashboard
});

export { firebase, builton };

Now that you have initialized Firebase and BuiltOn, you can start using the SDK freely. That is, you can make some API calls to list your products for your users. You will authenticate users, make some orders and train an ML model to give product recommendations.

1. Begin by authenticating users. Firebase should be set up already, and now you just need a few lines of code to create users.


// register.js
import {firebase, builton} from 'builton.js';
// Submit the authentication form with username and password
const onSubmit = async values => {
// We get the user from firebase
 const fbUserPromise =  new Promise((resolve, reject) => {
   const user = firebase.auth().currentUser;
   if (user) {
     resolve(user);
   } else {
     const unsubscribe = firebase.auth().onAuthStateChanged(user => {
       unsubscribe();
       if (user) {
         resolve(user);
       } else {
         const error = new Error('User is not authenticated');
         reject(error);
       }
     });
  }
});

 try {
   // We register with username and password
   await firebase
     .auth()
     .createUserWithEmailAndPassword(values.email, values.password);

   const fbPromise = await fbUserPromise;
   const idToken = await fbPromise.getIdToken();

   // we set up the bearer token
   await builton.refreshBearerToken(idToken);

   // We register the user with builton api's
   const apiUser = await builton.users.authenticate({
       email: values.email
   });
 } catch (err) {
   console.log(err)
 }
};

2. List some products to show to the user. In the prerequisites section, you added some products through the BuiltOn Dashboard. Now, all you have to do is fetch them.

// productList.js
const fetchProducts = async () => {
 try {
     const apiProducts = await builton.products.get({
       size: 6,
       page: 0,
       urlParams: {
         expand: "image", // so we get details/and use the images
       }
     });
   }
 } catch (err) {
   console.log(err)
 }
};

Simple as that. Same logic applies to fetching Orders, Users, Payments, etc. By passing “size,” you specify how many results you want the API to return. More products can be accessed by paginating.

// productList.js
const getNextProductsPage = async () => {
 try {
   const nextPage = await apiProducts.next();
 } catch(err) {
   console.log(err);
 }
};

3. Before you create some orders, you need to setup payment methods. Depending on where you live, there may be different requirements.  But, according to EU regulations active from the 14th of September 2019, online payments should comply with Strong Customer Authentication regulations. To set up a payment method, you do a couple things:

  • Create an empty payment method with BuiltOn’s APIs to get a Stripe setup intent.

// paymentMethod.js
const getStripeIntent = async () => {
 Try {
    const stripeIntent = await builton.paymentMethods.create({
     Payment_method: 'stripe',
    })
  } catch(err) {
    console.log(err)
  }
}

  • Use the Stripe.js SDK to setup the card with the intent. Follow the instructions in their documentation and use the Stripe Publishable Key from your BuiltOn Dashboard to set it up.

// paymentMethod.js
// https://stripe.com/docs/stripe-js/reference#stripe-handle-card-action
const stripe = Stripe('<STRIPE_PUBLISHABLE_KEY'); // From Builton Dashboard

// Create an instance of Elements.
const elements = stripe.elements();

const setupStripeCard = async (stripeIntent) => {
 try {
   const stripeCard = stripe.handleCardSetup(stripeIntent.setup_intent.client_secret, elements);
  } catch(err) {
    console.log(err)
  }
}

  • Update the payment method with BuiltOn’s APIs.

// paymentMethod.js
const updatePaymentMethod = async (stripeCard) => {
 Try {
    const paymentMethod = await builton.paymentMethods.update(stripeIntent._id.$oid, {
     payment_method_id: stripeCard.setupIntent.payment_method
    })
  } catch(err) {
    console.log(err)
  }
}

4. And now the user has a payment method to pay for orders.

  • Assuming that the products are listed and the user adds products to their order, you just need to create the order.

import {builton} from 'builton.js';

const placeOrder = async () => {
 try {
   const createdOrder = await builton.orders.create({
     "items": [
       {
         "product": "<PRODUCT_ID>",
         "quantity": 1,
         "sub_products": []
       }
     ],
     "delivery_address": {
       "street_name": "3 Tordenskiolds gate",
       "state": "Oslo",
       "city": "Oslo",
       "country": "Norway",
       "geo": [
         59.91316399999999,
         10.736260799999968
       ]
     },
     "payment_method": "<PAYMENT_METHOD_ID>"
   });
    
    // pay for the order
    await builton.payments.pay(createdOrder.payments[0].$oid);
    
 } catch (err) {
   console.log(err)
 }
};

And that’s it. You have created your order.  Order details are available on the BuiltOn Dashboard. So far you have created everything related to a normal e-commerce online store. Let’s add a little magic with BuiltOn’s integrated ML tools.

Let’s recommend a little magic

Using the BuiltOn ML tools is simple. You just need to log in to your Dashboard and navigate to ML, where you will find various models that can be trained. One important point is that you need to have valid data to train those models and output useable information. I.e., you need to have some Users, Orders and Products in the system. More detailed information is available in BuiltOn’s Docs.

Similar users

To train the “simple_product_similarity” model, which will give you similar products to the one selected, just press “Train” and wait until it’s completed.

Once the model is trained, you can use its ID to invoke the model and get the results. Note: You can train up to 5 versions of a particular model, and when invoked without a version ID, the last trained model is returned by default.

You have to invoke the model to get the similar product recommendations back.

// product.js
const fetchRecommendations = async () => {
 try {
   const recommendations = await builton.aiModels.getRecommendations("<MODEL_ID>",
   {
       data: "<PRODUCT_ID>",
       options: {
         size: 3, // Amount of recommendations to be returned
       },
     },
     {
       urlParams: {
         expand: 'product'
       }
     }
   );
 } catch(err) {
   console.log(err)
 }
};

And that’s it! 

The invoke will return recommendations, in this case products similar to the one passed in the “data” property. Expanding the product allows you to use the product right away. You can read more about expanding objects here.

Many more models are ready to go in BuiltOn’s InstantML Tools. They improve the customer’s experience while increasing sales revenue. And you don’t have to blow your budget on a data scientist toiling away to build a pipeline for 6 months.

BuiltOn’s APIs are powerful, reliable and scalable, all while being simple to use, which saves time. The ML tools will give you an edge that makes a real difference in today’s congested marketplace. 

I showed you some of the main points of an e-commerce system; users, product management and order creation. You can do a lot more than that with our APIs.  A full example of how to use BuiltOn’s APIs can be found on our Github, in the Demo Store repository and complete documentation can be found here, so check them out. 

Let us know how much you got done in 21 days.

loading...