How to save Payment Methods on Stripe — NodeJS

Daniel Kioko
TheCodr
Published in
2 min readSep 11, 2021

--

Stripe is capable of storing payment methods for you. This is more secure than storing this kind of information on your own database.

Photo by CardMapr on Unsplash

This is a brief tutorial to help you save a payment method and link it to a registered customer.

Installing Stripe

We’ll start by creating a js file, name it index.js. Install Stripe by running:

npm i stripe

Instantiate Stripe

Inside index.js, we’ll instantiate Stripe with our test secret keys

const stripe = require('stripe')('sk_test_key_here');

Save A Payment Method

We’ll next code to send a request with the card details as an object.

const paymentMethod = await stripe.paymentMethods.create({
type: 'card',
card: {
number: '4242424242424242',
exp_month: 9,
exp_year: 2022,
cvc: '314',
},
});
console.log(paymentMethod)

Test the app by running it:

node index.js

You should the see a response with an “ID” property. The value of this ID is a unique identifier for this payment method.

Please note that the card is saved on your Stripe account but it is not associated with any customer — we’ll need to attach it.

Attach A Saved Payment Method to a User

You might prefer to allow users to re-use their payment methods for future transactions. Here’s how to link a payment method to a customer.

For this function, you’ll need to provide a Payment Method ID and a Customer ID.

const paymentMethod = await stripe.paymentMethods.attach(
paymentId,
{customer: customerId}
);

You’ll need to re-write your code to pass these IDs as parameters. Here’s how I would do it:

attachPaymentMethod = (customerID, paymentMethodID) => {
return stripe.paymentMethods.attach(
customerID,
{customer: paymentMethodID}
);

You can finally call this function right after the payment method is added.

attachPaymentMethod('customer-id-goes-here', 'pm-id-goes-here')

--

--

Daniel Kioko
TheCodr
Editor for

Innovating, Creating & Learning with Software