Stripe and Node.js: 4 Best Practices and Examples

Have you ever woken up in the middle of the night, worried that you are not using the Stripe npm module properly? Probably not, but this article will help put your troubled soul at ease anyway with some interactive Node.js examples that explain how to build an excellent Stripe integration.

1. Use auto-pagination to avoid bloated code

Pagination is a necessary evil that saves us from loading too much data, but dealing with it in code can be a pain. Before `v6.11.0`, your Stripe code would look something like this to deal with pagination:

This example shows the old way of handling pagination in Stripe

//require Stripe's Node bindings
const stripe = require("stripe")("rk_test_72wdhn7pifTOWbrtrSNFxhsQ00NrdzPvaC")

//get first 100 invoices
let invoices = await stripe.invoices.list({limit: 100});
let numberProcessed = 0;

//loop through these invoices
for(let invoice of invoices.data){
    numberProcessed++;
}

//has_more indicates if we need to deal with pagination
while(invoices.has_more){

    //starting_after will be the the id of the last result
    invoices = await stripe.invoices.list({limit: 100, starting_after: invoices.data[invoices.data.length -1].id});
    
    //loop through the next 100
    for(let invoice of invoices.data){
        numberProcessed++;
    }
    console.log("Number processed so far: " + numberProcessed);
}
console.log("Total Number Processed: " + numberProcessed);

With the introduction of Β auto-pagination in `v6.11.0`, we are now able to have a much more efficient way of paginating:

This example shows how to auto-paginate in Stripe

//require Stripe's Node bindings
const stripe = require("stripe")("rk_test_72wdhn7pifTOWbrtrSNFxhsQ00NrdzPvaC")

//get all invoices
const allInvoices = await stripe.invoices.list({limit: 100}).autoPagingToArray({limit: 10000});
console.log("Invoices - " + allInvoices.length);
Note: You need to be running Node.js v10 or above for this.

2. Use expand to reduce the number of API calls

In Stripe, there are a lot of different objects. A lot of times, when dealing with one type of object, say a subscription; you want to get the product that subscription belongs. To get the product, you need to make an extra call to Stripe as shown here:

This example shows how to get the product from a subscription in Stripe without using expand

//require Stripe's Node bindings
const stripe = require("stripe")("rk_test_3U9s3aPLquPOczvc4FVRQKdo00AhMZlMIE")

const subscription = await stripe.subscriptions.retrieve("sub_G0zK9485afDl6O");
const product = await stripe.products.retrieve(subscription.plan.product);
console.log(product.name);

We can effectively avoid this by using the "expand" attribute in Stripe's API:

This example shows getting the product by using expand

//require Stripe's Node bindings
const stripe = require("stripe")("rk_test_3U9s3aPLquPOczvc4FVRQKdo00AhMZlMIE")

//expand the product inside the plan
const subscription = await stripe.subscriptions.retrieve("sub_G0zK9485afDl6O", {expand: "plan.product"});
console.log(subscription.plan.product.name);

Cutting down on API calls will improve your app's performance and reduce the risk of hitting Stripe's API limits.

3. Configure your Stripe connection for a more stable experience

Most people with a simple Stripe integration will define a new Stripe connection on the fly without configuring it first like so:

const stripe = require("stripe")("STRIPE_SECRET_KEY");

When scaling your billing system, consider doing the following to improve your integration quality:

  • Lock your API version to avoid being affected by API changes
  • Set to Retry Automatically in case of network failure
  • Define your app information to help the Stripe team

Here's an example function that returns a configured Stripe connection

function createStripeConnection(stripe_api_key){
    const Stripe = require("stripe");
    const stripe = Stripe(stripe_api_key);
    stripe.setApiVersion('2019-03-14');//lock API version down to avoid code breaking
    stripe.setAppInfo({
        name: 'Servicebot',
        version: "1.1.3", //Optional
        url: 'https://servicebot.io' // Optional
    });
    stripe.setMaxNetworkRetries(3); //retry on network failure
    return stripe;
}

const stripe = createStripeConnection("rk_test_72wdhn7pifTOWbrtrSNFxhsQ00NrdzPvaC");
console.log(await stripe.invoices.list());

4. Use Webhooks to process events that occur in Stripe

Webhooks play an essential role in most Stripe integrations. There are a lot of different events that happen, so which ones should you care about?

The most important webhook as a SaaS app to pay attention to is the customer.subscription.deleted - when a subscription goes into state cancelled. You listen for this event in order to decide what to do with someone's account when they cancel, trial runs out, or their card fails.

Once you start listening to Stripe events, it is a good idea to secure your webhook receiver as not to be fed phony webhooks by a bad-actor. You do this by Β utilizing Stripe's webhook si gning functionality:

This example shows how to validate a webhook has come from Stripe

// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
const stripe = require('stripe')('sk_test_bkoS59kZFWBR3XZgkiHwozoX00lD4ttSs1');

// Find your endpoint's secret in your Dashboard's webhook settings
const endpointSecret = 'whsec_...';

// This example uses Express to receive webhooks
const app = require('express')();

// Use body-parser to retrieve the raw body as a buffer
const bodyParser = require('body-parser');

// Match the raw body to content type application/json
app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => {
  const sig = request.headers['stripe-signature'];

  let event;

  try {
    event = stripe.webhooks.constructEvent(request.body, sig, endpointSecret);
  }
  catch (err) {
    response.status(400).send(`Webhook Error: ${err.message}`);
  }

  // Handle the event
  switch (event.type) {
    case 'payment_intent.succeeded':
      const paymentIntent = event.data.object;
      handlePaymentIntentSucceeded(paymentIntent);
      break;
    case 'payment_method.attached':
      const paymentMethod = event.data.object;
      handlePaymentMethodAttached(paymentMethod);
      break;
    // ... handle other event types
    default:
      // Unexpected event type
      return response.status(400).end();
  }

  // Return a response to acknowledge receipt of the event
  response.json({received: true});
});

app.listen(8000, () => console.log('Running on port 8000'));


Avoid the effort of building and maintaining a complex Stripe Integration

Your billing code can get pretty complicated when it comes to having a fully-featured solution that includes coupons, free trials, metered billing, and more.

Building a user interface for your Stripe integration could take months to develop. Servicebot provides a drop-in UI for Stripe Billing. It takes less than an hour to set up and doesn’t require any development effort.

Stripe and Node.js: 4 Best Practices and Examples
What to know about SaaS billing in 2020?

Do you have a SaaS launch around the corner, and want to know how to bill your customers monthly? Do you already have hundreds of customers but manually update their credit cards when they expire? Or do you have a very complex pricing strategy and have no idea how to charge your customers? Well, you came to the right place. I've witnessed these scenarios and many more while designing billing architectures for various SaaS companies. My goal is to help you understand the main components of SaaS billing without ending up with an overly complicated, unscalable solution.

What is SaaS billing?

In short, SaaS billing software allows customers to pay for your Software-as-a-Service (SaaS) on a recurring basis. The goal of your SaaS billing software is to automate the billing processes so you can focus on your product and scale faster without worrying about billing your customers.

What are the building blocks of SaaS billing?

What to know about SaaS billing in 2020?

You might be overwhelmed with the sheer number of tools that you came across while searching for an ideal billing solution. The truth is, there are tons of tools out there, and many of them overlap in functionality. Understanding the building blocks of SaaS billing will help you identify the key features to look out for when selecting your tools. The components of SaaS billing are as follows:

Merchant Account

A merchant account is your business bank account. We won't get much into this component, assuming that at this point, you already have your business bank account in place.

Payment gateway

This component handles the heavy-lifting of transactions, processes credit cards, and fulfills PCI compliance regulations. In short, it is responsible for delivering the money from your customers’ credit card to your bank account safely.

Subscription billing system

I call it the brain of SaaS billing. It sits on top of the payment gateway, and it is responsible for automatically charging customers, generating invoices, collecting credit cards, and handling all other aspects of your customer's subscriptions. Subscription billing systems are also responsible for handling the pricing, so make sure to fully understand your pricing strategy and potential strategies that you'll want to test out. You will end up updating your pricing frequently, so your system should be able to handle pricing changes without consuming a lot of resources every time. Kyle Poyar has some amazing SaaS pricing guides you can check out.

Other features such as dunning, revenue recognition, referrals, and taxes are example features that connect to the subscription billing system, so it is always a good practice to define your use cases first.

Billing User Interface (UI) & User Experience (UX)

The least spoken about, the UI/UX, is the part of SaaS billing that your customers will interact with the most. For example, showing your pricing page, allowing customers to subscribe to your SaaS, updating credit card, downloading previous invoices, and practically any interface that your end customer views within your billing system is part of the UI. Billing User Experience (UX) is your end customer's experience with your billing system. To design the most intuitive user experience, you must define your onboarding flow. Onboarding flow is the process in which customers sign up, start using your software and eventually pay for it.

How do you choose a SaaS billing system?

Three factors to consider when choosing billing software are easy, fast, and extensible. You shouldn't have to go through a lengthy setup process or read a lot of docs to use billing software. Billing tools should be easy to learn. Depending on your use case, you might be able to build your entire billing system without writing a single line of code. The faster you can set up your billing, the quicker you'll launch and focus on your product. If a tool requires a lot of architecting and dev work, consider something faster. Maintaining a complex integration can cost you time in the future. Integration is critical for an extensible system. If it integrates well with other tools, it is extensible. Up-to-date API documentation, Zapier integration, or plugin directory are all indicators of well-integrated software.

Don't base your decision purely on the price of the software. It is helpful to pick solutions that are commonly used by other companies. You can ask founder communities like IndieHackers about what they use and their experience with those tools. Not choosing the right tools can leave you with a Frankenstein billing solution that'll cost you time and resources to maintain.

What to know about SaaS billing in 2020?

Choosing a payment gateway system

Luckily, it is 2020, there are some major players in this space, and picking the right payment gateway for your business is going to be one of the more straightforward decisions, mainly if your business is operating within these countries. The most crucial factors to consider when choosing a payment gateway system is if it supports your country and your required payment method, such as credit cards, ACH, ApplePay, etc.

What to know about SaaS billing in 2020?

Choosing a subscription billing system

There are hundreds of subscription billing solutions out there, but only a few are leading the pack when it comes to their technology. Many SaaS founders, CTOs, or technical leads make the mistake of stacking multiple subscription billing systems on top of each other due to not understanding the capacity of the tools. Don't follow an outdated online subscription billing review or article. If a guide is more than two years old, you should look for a more updated one. The SaaS market is constantly changing with new tools that could make your life a whole lot easier.

A lot of subscription billing solutions have a basic payment gateway built into their products. This often leads to reinventing common features and half-bakes implementation of more advanced requirements, such as dunning, viewing specific analytics, or a referral program. Oftentimes you’d be better off using specialized third-party SaaS tools that integrate with subscription billing systems.

What to know about SaaS billing in 2020?

Choosing a billing UI/UX tool

The billing UI connects to your subscription billing's API to view pricing and billing information to your end customers. Until recently, many SaaS companies developed in-house front-end billing pages for their website and SaaS. Depending on the pricing complexity and granularity of use cases, building an in-house billing UI could take anywhere from weeks to months. In 2020 there are no-code drag and drop-in tools available that hookup to your subscription billing system and provide billing pages in minutes.

What are the trending SaaS billing platforms in 2020?

It is easy to get lost in hundreds of tools that are aiming to be the "best" SaaS billing solution. In this section, I will give you the newest trend in SaaS billing I recommend for SaaS companies making anywhere from $0 to $20M annual recurring revenue (ARR). If your business is operating over $50M in ARR, you can ask questions from enterprise experts, such as Jack Lape from Wizeline. You can use this list as your baseline to compare solutions.

What to know about SaaS billing in 2020?

Trending payment gateway solution

If your business is operating in any of the countries listed on this page, then Stripe would be a great payment gateway solution. Stripe has a powerful API, documentation, and integration ecosystem that aims at make billing simpler and faster. Stripe’s API is known to be one of the best.

Trending subscription billing solution

This is a very competitive space, and the lineup changes almost every couple of years. Since mid-2018, Stripe released Stripe Billing, which has changed the subscription billing game by handling most pricing models while being deliberately simple. Stripe Billing provides fully automated subscription invoicing. If you are planning on using Stripe as your payment gateway, it is a no-brainer to use Stripe Billing as your subscription billing tool. If you're planning on using other tools like Chargebee or Recurly (there are many more), make sure to look at their comparison with Stripe Billing.

Stripe Billing integrates well with third-party tools that aim to handle edge cases. Tools like ChartMogul, Churn Buster, and Rewardful, connect to Stripe to manage revenue analytics, churn, and affiliates. You can browse through the Stripe Partner Program to view other tools that work well with Stripe.

Trending billing UI/UX solution

In 2019 Servicebot introduced a UI/UX toolkit for Stripe Billing. Using Servicebot, you can drag and drop-in billing pages into your website and SaaS so your customers can view your pricing, subscribe to plans, update credit cards, and download invoices without writing a single line of code. The goal is to save weeks or months of development by using a no-code tool that automatically stays up to date with new features and compliance.

Conclusion

In summary, understand the basics of SaaS billing, be up to date with the latest trends, and choose tools that are simple to use. We've scratched the surface with this article. You can continue your research by looking into some of the tools I introduced in this article. As the CEO and founder of Servicebot, I have dedicated my career to helping businesses launch faster without worrying about billing. If you need guidance or help with your SaaS billing, you can book a call with me here, and I'll do my best to answer your questions.

How to sell subscriptions with WordPress using Stripe Billing

It can be a pain to sell subscriptions on WordPress. You are pretty much at the mercy of the plugin you are using, which generally tend to be missing a lot of capabilities as well as being a huge pain to get configured to your liking, also many WordPress payments plugins focus on physical products while subscriptions are a sidenote (Woocommerce for example) . Stripe Billing is a subscription management system loved by developers for their great API and rich set of subscription billing features. Stripe is ideal for many use-cases you see on WordPress; the problem is if you are using WordPress you might not be a developer, and those great APIs may look like a foreign language to you. In this article, we are going to dive into how you can utilize the power of Stripe Billing and WordPress by using the Servicebot WordPress Plugin, a drop-in UI designed explicitly for Stripe Billing so you can have customers signup and manage their subscriptions.

How to sell subscriptions with WordPress using Stripe Billing

Getting Started With Stripe

Sign up for a Stripe Account

The first thing you will need to do if you haven't already is to sign up for Stripe. The process is pretty straightforward, but you will need to enter your bank account details if you want to receive funds.

Define your Products and Plans in Stripe

You will need to create some products and plans in your Stripe account. If you haven't registered for Stripe, you can do so here. For a more in-depth walkthrough of getting started with Stripe, check out this article.

For an example strategy, you can create a two-tiered pricing strategy, with a Basic $50/month tier and a Premium at $300/month tier defined as separate Products in Stripe.

How to sell subscriptions with WordPress using Stripe Billing

For the plugin to pick up what tier is which, you will need to add metadata to these Products. In Stripe you should add sb_tier and sb_service to each product you created, for example, the Basic product will have sb_tier equal to `Basic` and sb_service will be "MyService",

Similarly, the Premium product will have sb_tier = Premium and sb_service = "MyService". For a more detailed guide on how to setup your Stripe, see this article.

Now that your Stripe is set up for subscriptions, you can move onto the WordPress plugin.

Using the Plugin in WordPress

Install The Plugin

In your WordPress, go to the "Plugins" sections and click "Add New". Search for "Servicebot" and install the plugin on your WordPress.

Get your Servicebot ID and Secret

If you haven't already, sign up for Servicebot, it's free to get started. Once you connect your Stripe account, you created earlier. You can get your Servicebot ID and Secret that will be used to configure the WordPress Plugin.

Configure the Plugin

With the plugin installed, a new Servicebot link should show up on the sidebar of the admin panel in your WordPress. This is where you can configure the plugin.

Add your Test Mode Servicebot ID, your Service Name (in this example "MyService") and your Secret Key to the configuration, afterward you can start embedding and see the fruits of our labor.

How to sell subscriptions with WordPress using Stripe Billing

Embed The Pricing Page

Now that you have configured the plugin let's add your pricing and plans to a Wordpress page to display your plans and allow customers to pick and subscribe. The easiest way to do this is to use shortcodes. First, create a new Page in WordPress, in the body, type /, and pick "Shortcode" as the block to insert. The shortcode for Pricing is [servicebot_pricing_page_shortcode]
If you view the page you just created as an anonymous user, you will see your subscription tiers, and when you subscribe to one, a new WordPress user will be created (as part of the configuration in the previous step)

Embed a Subscription Portal

Next, let's create a customer billing portal for your customers. Just like in the previous step, we create a new page and add a shortcode. For Subscription Portal the shortcode will be [servicebot_subscription_portal_shortcode].

If you view the page as a logged-in user with a subscription, you will see your subscription information, and the user will have the ability to add a credit card, change their plan, or download their invoices.

How to sell subscriptions with WordPress using Stripe Billing

Customizations

Now that we have the plugin configured and our pages setup, you can add to the embeds various customizations to get your onboarding flow just right. For a complete list of properties, see this article for the pricing page configurations and this article for the subscription portal.

You can add these configurations to the shortcode directly, for example, the shortcode [servicebot_pricing_page_shortcode options="{forceCard: true}"] will force a credit card to be entered even on free trials.

Conclusion

Using Servicebot and Stripe Billing, you can turn your WordPress into a subscription powerhouse in a short amount of time, as we have just demonstrated. The power behind this combination is that Servicebot allows you to utilize all of the features of Stripe Billing, such as coupons, customizable invoices, proration, and more. Other Subscription software in WordPress is generally lacking in capability and those that do integrate with Stripe, don’t integrate with Stripe Billing.

How to sell subscriptions with WordPress using Stripe Billing

It can be a pain to sell subscriptions on WordPress. You are pretty much at the mercy of the plugin you are using, which generally tend to be missing a lot of capabilities as well as being a huge pain to get configured to your liking, also many WordPress payments plugins focus on physical products while subscriptions are a sidenote (Woocommerce for example) . Stripe Billing is a subscription management system loved by developers for their great API and rich set of subscription billing features. Stripe is ideal for many use-cases you see on WordPress; the problem is if you are using WordPress you might not be a developer, and those great APIs may look like a foreign language to you. In this article, we are going to dive into how you can utilize the power of Stripe Billing and WordPress by using the Servicebot WordPress Plugin, a drop-in UI designed explicitly for Stripe Billing so you can have customers signup and manage their subscriptions.

How to sell subscriptions with WordPress using Stripe Billing

Getting Started With Stripe

Sign up for a Stripe Account

The first thing you will need to do if you haven't already is to sign up for Stripe. The process is pretty straightforward, but you will need to enter your bank account details if you want to receive funds.

Define your Products and Plans in Stripe

You will need to create some products and plans in your Stripe account. If you haven't registered for Stripe, you can do so here. For a more in-depth walkthrough of getting started with Stripe, check out this article.

For an example strategy, you can create a two-tiered pricing strategy, with a Basic $50/month tier and a Premium at $300/month tier defined as separate Products in Stripe.

How to sell subscriptions with WordPress using Stripe Billing

For the plugin to pick up what tier is which, you will need to add metadata to these Products. In Stripe you should add sb_tier and sb_service to each product you created, for example, the Basic product will have sb_tier equal to `Basic` and sb_service will be "MyService",

Similarly, the Premium product will have sb_tier = Premium and sb_service = "MyService". For a more detailed guide on how to setup your Stripe, see this article.

Now that your Stripe is set up for subscriptions, you can move onto the WordPress plugin.

Using the Plugin in WordPress

Install The Plugin

In your WordPress, go to the "Plugins" sections and click "Add New". Search for "Servicebot" and install the plugin on your WordPress.

Get your Servicebot ID and Secret

If you haven't already, sign up for Servicebot, it's free to get started. Once you connect your Stripe account, you created earlier. You can get your Servicebot ID and Secret that will be used to configure the WordPress Plugin.

How to sell subscriptions with WordPress using Stripe Billing

Configure the Plugin

With the plugin installed, a new Servicebot link should show up on the sidebar of the admin panel in your WordPress. This is where you can configure the plugin.

Add your Test Mode Servicebot ID, your Service Name (in this example "MyService") and your Secret Key to the configuration, afterward you can start embedding and see the fruits of our labor.

How to sell subscriptions with WordPress using Stripe Billing

Embed The Pricing Page

Now that you have configured the plugin let's add your pricing and plans to a Wordpress page to display your plans and allow customers to pick and subscribe. The easiest way to do this is to use shortcodes. First, create a new Page in WordPress, in the body, type /, and pick "Shortcode" as the block to insert. The shortcode for Pricing is [servicebot_pricing_page_shortcode]
If you view the page you just created as an anonymous user, you will see your subscription tiers, and when you subscribe to one, a new WordPress user will be created (as part of the configuration in the previous step)

<IMAGE HERE>

Embed a Subscription Portal

Next, let's create a customer billing portal for your customers. Just like in the previous step, we create a new page and add a shortcode. For Subscription Portal the shortcode will be [servicebot_subscription_portal_shortcode].

If you view the page as a logged-in user with a subscription, you will see your subscription information, and the user will have the ability to add a credit card, change their plan, or download their invoices.

How to sell subscriptions with WordPress using Stripe Billing

Customizations

Now that we have the plugin configured and our pages setup, you can add to the embeds various customizations to get your onboarding flow just right. For a complete list of properties, see this article for the pricing page configurations and this article for the subscription portal.

How to sell subscriptions with WordPress using Stripe Billing

You can add these configurations to the shortcode directly, for example, the shortcode [servicebot_pricing_page_shortcode options="{forceCard: true}"] will force a credit card to be entered even on free trials.

Conclusion

Using Servicebot and Stripe Billing, you can turn your WordPress into a subscription powerhouse in a short amount of time, as we have just demonstrated. The power behind this combination is that Servicebot allows you to utilize all of the features of Stripe Billing, such as coupons, customizable invoices, proration, and more. Other Subscription software in WordPress is generally lacking in capability and those that do integrate with Stripe, don’t integrate with Stripe Billing.

Self-serve Subscriptions with Stripe in minutes


No-code embeddable billing pages that help online businesses monetize easier & faster.

Save Time & Development Effort


STEP 1
One-click connect to your Stripe account

STEP 2
Visually create & customize customer-facing billing pages

STEP 3
Embed billing pages in your website or SaaS

Let your customers self-serve subscriptions!

Simple integration with Stripe

A lightweight front-end layer on top of Stripe Billing, allowing you to continue using the power ofΒ  Stripe APIs & docs for advanced use.

GET STARTED w/ ServiceBot!