Skip to main

How to stripe up your e-business with a Node.js API

by Matteo Crippa

How to stripe up your e-business with a Node.js API

As a developer, you may face the need to introduce a payment method in the application logic at some point. Business is business, after all, and even a few cents at the end make a difference, regardless of you being a startup, scaleup or a corporation.

When you work with a backend infrastructure there are plenty of different players in the payment and credit card processing as a service to work with, and today we will focus on one of the most interesting and flexible solutions we have had to deal with recently.

Sorry, we’ve already spoiled it in the title, but it’s obviously Stripe we’ll be tackling here.


Copy link
Libraries

One of the first checks that I like to do on an as-a-service solution is to figure out what is the language supported natively (and also if any third-party developer might have enhanced any of those already).

Support for Stripe is pretty wide. In the case I am going through in this article, I focused on Node.js to dig down a bit more and noticed that apart from the original library done by the original team, we have more than 640 other packages on NPM.

For sure it is something to think about, but mostly I see integration with the third-party framework, so nothing that makes me scared like “Oh, it’s so over-engineered that someone had to create a wrapper to make it more humane”.

Also, as you can see below, the library is being kept up to date. Since Stripe makes releases very often and timely, we can say that their average sprint time is around 1 week. Conclusively, the frequency of Stripe’s bug updates and fixes can be associated with the security of their library.

Having this in mind, all I need to do is to keep my package.json a bit more updated than usual, but I’d rather bother myself with periodic updates than regret and waste time for avoidable issues.

Last, but not least, even the attention with which Stripe treats PR seems quite tailor-made:

On top of that, Stripe’s willingness to accept PR and fixes even from externals is also worthwhile :+1:.

By the way, Stripe’s library supports typescript bindings too, so if you love force types - it’s a good one!

Copy link
Documentation

As an old school developer I love to have clear documentation. I’m from the pre-internet era when books were the source of truth and you had to rely on them and trust them in order to accomplish anything. In this respect, I pay a lot of attention to having a well-documented API.

And this is where I think Stripe is able to provide a very detailed API reference to dig and play with before any implementation, which is very helpful.

Digging around is quite easy to get familiar with their unique naming conventions and to prepare a high-level flow of the steps we will need to achieve our project’s business goals.

A dedicated section is linked to errors, usually pretty verbose and detailed.

Worth mentioning, the package for Node.js supports automatic pagination, so again something less to be worried about.

TLDR; if you, unlike me, hate documentation and want to jump into the center of it as fast as possible, there’s a very detailed quick start documentation too with some examples of basic payment flows. Worth taking a look into it!


As mentioned before, Stripe's huge advantage is a micro-feature API structure that allows you to manipulate flows in the most profitable way for your company.

Keep in mind the first rule of business that rightfully claims not all the businesses work in the same way, hence both customization and flexibility Stripe provides are the two most essential features.

I know that first hand. Recently I had to take care of implementing Stripe’s API in two different projects. One of them was more of a common eCommerce approach with payment as the last step of the user flow to finalize the whole order. Pretty standard, no?

The second one involved more custom approach with steps that included credit card verification or payment holding during the pre-transaction and background check.

To be honest, I was very worried about the second one at first. According to my previous experience with other suppliers, namely the nightmare of having to debug the outdated documentation and figuring out how to deal with the related bugs.

In comparison Stripe seemed like a salvation right off the bat! I managed to achieve the goal quite fast and the documentation was well-prepared. and supportive, using the verbose response and snippet examples for your language. Time saver!


Copy link
Deployment of Stripe

As a developer myself, I suggest having at least a bit of development training first (this is not entirely a no-code solution after all). Apple did it very well with Playground tool which is a powerful instrument as a sandbox for Swift code, where you can experiment quickly and easily without having to create the whole project. It is a way to test some algorithms or functions in a lean and fast way without wasting time on creating the whole project. For Node.js you can still find similar options like JSFiddle. Make sure you use them before taking your VSCode and creating a dummy project to save yourself some time.

Don’t forget to register to Stripe website before you dive deeper into integrating its API with your website or app.

One thing I’m pretty sure of is two keys that will become your best friends at the beginning of your journey through the Stripe’s sandbox:

  • Publishable key

  • Secret key

They can be found in Stripe Dashboard under the API keys section. Below you can see how they should look like.

Before you start any action, remember to switch to “Viewing test data”.

The orange colour of UI will confirm that you are sandboxed. By using this feature you will avoid a real financial transactions using any dummy card.

Okay, so we'll start our simulation with the most common flow for the eCommerce market, where we'll keep the user's payment details for future transactions. By the way, if you are interested in the eCommerce market, we recommend you to check out our article regarding the worst aspects of online shopping.

One additional aspect, assume we do not use any official or external credit card helper to collect the data. We will simulate that the data comes from a custom field.

But before you start writing your first line of code remember to check the logic of the whole process - always.

Once you have familiarized yourself with the above flow, you can go to the appropriate reference in the Stripe documentation. Now let’s get down to business.

Copy link
Step 1

We have already gone through Libraries and Documentation - it's time to create a project:

Once we do this we should run our favorite editor and take a deep dive into the project.

Create a file called index.js and integrate Stripe API. In order to do this you just have to run following the command in the directory of our project:

Copy link
Step 2

Let's create a boilerplate in the index.js to be able to use async/await approach:

js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 const stripe = require('stripe')('REPLACE_WITH_YOUR_SECRET_KEY'); // helpers const createUser = async () => {}; const addCreditCard = async (user, card) => {}; const processPayment = async (user, card) => {}; (async () => { try { console.log('Stripe demo'); // TODO: create user const user = await createUser(); // TODO: add credit card to user const creditCard = await addCreditCard(user, { number: '4242424242424242', exp_month: 9, exp_year: 2021, cvc: '314', }); // TODO: create payment intent for user await processPayment(user, creditCard); } catch (e) { console.error(e); } })();

I added a few comments in the code and intentionally left some console.logs to speed up the debugging, but the point is to mimic the flow that we defined above: create a user, add a credit card and finally process the payment.

In case you wonder: 4242 4242 4242 4242 is a dummy credit card that is supported by Stripe.

Remember to replace the secret code with one of your accounts. Otherwise, it will not work and you may be disappointed.

Ok, at this point we should focus on creating a client by adapting the code like this one below.

js
1 2 3 4 5 6 7 8 9 10 11 const createUser = async () => { try { const customer = await stripe.customers.create({ email: 'jdoe@example.com', }); console.log(customer); return customer; } catch (error) { console.error(error); } };


As you can see, we are using the customers.create API, in particular, we are going very lean in this case using just the email, but we can provide additional data for the user, if needed.

Copy link
Step 3

Next step is to add the credit card. Below you can find how the snippet will look like.

js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 const addCreditCard = async (user, card) => { try { const paymentMethod = await stripe.paymentMethods.create({ type: 'card', card, }); console.log(paymentMethod); const attached = await stripe.paymentMethods.attach(paymentMethod.id, { customer: user.id, }); console.log(attached); return paymentMethod; } catch (error) { console.error(error); } };​

Now, here we have to combine two APIs under the same roof: paymentMethods.create and paymentMethods.attach.

We need to create a payment method with our credit card data (code, expiry, CVV, etc.) and associate it with the user we have created a moment ago.

Copy link
Step 4

Our last step is to put everything we’ve done so far together and process the payment:

js
1 2 3 4 5 6 7 8 9 10 11 12 13 const processPayment = async (user, card) => { try { const paymentIntent = await stripe.paymentIntents.create({ amount: 1250, customer: user.id, currency: 'usd', payment_method: card.id, }); console.log(paymentIntent); } catch (error) { console.error(error); } };

Our wingman here is the paymentIntents.create function, it requires just a few parameters passed as an object:

  • Amount

  • Customer

  • Currency

  • Payment method

It shall be pretty straightforward from now on. You might, however, be wary of just one potentially tricky element…the amount.

Remember that Stripe API is expecting the amount as an integer number, so you will need to add a little helper to convert it, according to this logic:

$10,00 → 1000

$10,50 → 1050

$0,50 → 50

OK. so now it’s turn to run the code.

Let’s use:

And a little of JSON will start kicking in into our terminal.

You can also open Stripe Dashboard (remember to set the test mode!) and double check the payment and the user just created.

And we're done. It's time for you to start counting the incoming influx of cash from your eCommerce. Happy hunting!

If you want to see the whole code and play a bit with it - feel free! You can find it here.

P.S. Once you’re a millionaire, thanks to this, don’t forget to say thanks by letting us do some development work for you, will you?


IntroductionArticle

Related Articles