How to Integrate Stripe Payment APIs Using Node.JS
Types of payment method APIs
Stripe offers three different types of payment method APIs. And those are,
- Stripe Checkout
- Charges API
- Payment Intents API
Prerequisites
- Install Node
- Get Stripe API keys
- Postman for API calling
- Install stripe dependencies
Getting started with stripe payment APIs
1. Stripe Checkout
- Here we’re going to see, An overview of stripe checkout, and how to build a simple checkout integration to accept one-time payments.
- Stripe Checkout is a payment page that has already been constructed.
- Accepting payments with stripe checkout consist of two steps.
- Create a checkout session for what your customer intends to purchase.
- Redirect your customer to a stripe-hosted payment form to complete their purchase.
- ( Later you can optionally add a webhook handler to automate fulfillment of the purchase by sending an email.)
- This is an example of creating the checkout session on the server. Here we are using the stripe node client library. First, we configure the library with our stripe secret key then make an API call to create the checkout session object. Once the response is returned from the API that session variable will contain the data including an id that’s used to redirect from the front end.
app.js
- Define your route for API in the app.js file.
var indexRouter = require('./routes/index'); app.use('/', indexRouter);
routes / index.js
- Create a checkout session for what your customer intends to purchase.
var express = require('express'); var router = express.Router(); const stripe = require("stripe")('sk_test_51JINs1SHKFpjeywqugn3nyuLK1inUNc6uN5GJsN0ESwCahDK8uOSLhXgS0ezrTqPRp5TxaW2jynxhFWno7fPfOeV00Y5a48XSG'); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Stripe Checkout Example' }); }); router.post('/create-checkout-session', async function(req, res, next) { try { const session = await stripe.checkout.sessions.create({ customer: 'cus_KudUxj75qTue5P', payment_method_types: ["card"], mode: "payment", line_items: [{ price: 'price_1KEoG2SHKFpjeywqDvm3EbiI', // One time pricing quantity: req.body.quantity }], success_url: 'http://localhost:4900/success.html?id={CHECKOUT_SESSION_ID}', cancel_url: 'http://localhost:4900/cancel.html', }) res.send({ id: session.id }); } catch (e) { throw new Error(e); } }); module.exports = router;
views / index.ejs
- Redirect your customer to a stripe-hosted payment form to complete their purchase.
var express = require('express'); var router = express.Router(); const stripe = require("stripe")('sk_test_51JINs1SHKFpjeywqugn3nyuLK1inUNc6uN5GJsN0ESwCahDK8uOSLhXgS0ezrTqPRp5TxaW2jynxhFWno7fPfOeV00Y5a48XSG'); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Stripe Checkout Example' }); }); router.post('/create-checkout-session', async function(req, res, next) { try { const session = await stripe.checkout.sessions.create({ customer: 'cus_KudUxj75qTue5P', payment_method_types: ["card"], mode: "payment", line_items: [{ price: 'price_1KEoG2SHKFpjeywqDvm3EbiI', // One time pricing quantity: req.body.quantity }], success_url: 'http://localhost:4900/success.html?id={CHECKOUT_SESSION_ID}', cancel_url: 'http://localhost:4900/cancel.html', }) res.send({ id: session.id }); } catch (e) { throw new Error(e); } }); module.exports = router;
success.html
- If the payment is successful, the customer will be redirected to the success page.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <b>Success Page</b> </body> </html>
cancel.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <b>cancel Page</b> </body> </html>
Output
- After clicking on the Checkout button.
success page:
2. Charges API
- Using Charges and payment Intent APIs you can create your payment flow.
- The Charges API is used to build basic payment flow without handling SCA or Strong customer authentication.
Steps to create stripe charges
- app.js
var indexRouter = require('./routes/index'); app.use('/', indexRouter);
routes / index.js
- Define routes for creating customers, add a new card and create charges for customers.
var express = require('express'); var router = express.Router(); const STRIPEHANDLER = require('../controllers/stripeHandler'); router.post('/create-Customer', STRIPEHANDLER.createNewCustomer); router.post('/add-Card', STRIPEHANDLER.addNewCard); router.post('/create-Charges', STRIPEHANDLER.createCharges); module.exports = router;
Create customer
const Stripe_Key = "sk_test_51JINs1SHKFpjeywqugn3nyuLK1inUNc6uN5GJsN0ESwCahDK8uOSLhXgS0ezrTqPRp5TxaW2jynxhFWno7fPfOeV00Y5a48XSG"; const stripe = require("stripe")(Stripe_Key); module.exports.createNewCustomer = async(req, res, next) =>{ try{ const customer = await stripe.customers.create({ name: req.body.name, email: req.body.email, }); res.status(200).send(customer); }catch(error){ throw new Error(error); } }
Create or add a new card
module.exports.addNewCard = async(req, res, next) =>{ const { customer_Id, card_Name, card_ExpYear, card_ExpMonth, card_Number, card_CVC, } = req.body; try { const card_Token = await stripe.tokens.create({ card: { name: card_Name, number: card_Number, exp_month: card_ExpMonth, exp_year: card_ExpYear, cvc: card_CVC, }, }); const card = await stripe.customers.createSource(customer_Id, { source: `${card_Token.id}`, }); return res.status(200).send({ card: card.id }); } catch (error) { throw new Error(error); } }
Create charges
- Using customer and card ID creates new charges.
module.exports.createCharges = async(req, res, next) =>{ try{ const createCharge = await stripe.charges.create({ receipt_email: '[email protected]', amount: 50*100, //USD*100 currency: "inr", card: req.body.card_ID, customer: req.body.customer_Id, }); res.send(createCharge); }catch(err){ throw new Error(error); } }
Output
3. Payment Intents API
- The Charges API has been replaced with the Payment Intent API.
- Payment intent API provides Strong customer authentication or SCA.
- The Payment Methods API has replaced tokens, which were previously used to securely transmit customer card information.
- In this example, we will learn how to accept a one-time payment using payment intent.
index.js
var express = require('express'); var router = express.Router(); const stripe = require('stripe')('sk_test_51JINs1SHKFpjeywqugn3nyuLK1inUNc6uN5GJsN0ESwCahDK8uOSLhXgS0ezrTqPRp5TxaW2jynxhFWno7fPfOeV00Y5a48XSG'); router.post('/', async function(req, res, next) { let paymentMethod = await stripe.paymentMethods.create({ type: 'card', card: { number: '4242424242424242', exp_month: 9, exp_year: 2022, cvc: '314', }, }); paymentIntent = await stripe.paymentIntents.create({ payment_method: paymentMethod.id, amount: 75*100, // USD*100 currency: 'inr', confirm: true, payment_method_types: ['card'], }); res.send(paymentIntent); }); module.exports = router;
Call API
Output
This is the fully functional code for handling payments and related data. It’ll work properly if you simply replace the sandbox key with your Stripe API key.
Stripe, on the other hand, makes it incredibly simple to develop payment sites without ever having to deal with sensitive data like credit card information, as you’ve seen.
Leave a Reply
Want to join the discussion?Feel free to contribute!