Search code examples
javascriptnode.jsexpressstripe-paymentsmern

Stripe Payment Method using node.js


I am implementing stripe payment method using node and express it runs successfully and returns success message but customer is not adding in stripe customers and also my node code crashed. I am new here so learning help will be appreciated.

Here is my code:

const express = require('express')
const app = express()
const { stripecard } = require('../../schemas')
var stripe = require("stripe")("sk_test_51LM4hdClyoITdq3ZfTfLdVZjmLKskcWAV17Yef5fGAjKFBReC82bstJOP7VyuauMiHFVGvHgyfQdSLsfcQHTzb9w00s65S9CT6")

const CreateCard = app.post('/payment', function(req, res) {
    const {
        id,
        duration,
        cardNumber,
        expMM,
        expYY,
        cvv,
        email,
        name
    } = req.body;

    const createdUser =  stripe.customers.create({
        email: email || '[email protected]',
        name: name || "123"
    })

    //console.log("createdUser", createdUser)
    if (createdUser) {
        try {
            const token =  stripe.tokens.create({
                card: {
                    number: cardNumber,
                    exp_month: expMM,
                    exp_year: expYY,
                    cvc: cvv
                }
            })
            //console.log("token : ", token)
            const AddingCardToUser =  stripe.customers.createSource(createdUser.id, {
                source: token.id
            })

            return res.status(201).json({
                success: true,
                AmountCharged: req.body.charge,
                message: "Payment Charged Successfully and also a mail has been sent to User as well as Admin."
            });
        } catch (error) {
            return res.status(501).json({
                success: false,
                message: `Error in ${error.type} and error is :  ${error.message}`
            });
        }
    }

})
module.exports = CreateCard

Here is the output in postman:

{
    "success": true,
    "AmountCharged": "1200",
    "message": "Payment Charged Successfully and also a mail has been sent to User as well as Admin."
}

Solution

  • You might want to add await keyword in front of each API call so that it returns the customer object instead of Promise.

    I'd also like to highlight a few more things.

    1. Your secret key in leaked in this post, you should roll it as soon as possible.
    2. You are passing credit card number and details to your application directly. Unless you plan to handle the PCI compliance by yourself, I'd highly recommend you to tokenize the card details at the frontend, and pass the token ID to backend.
    3. Sources and Tokens are Stripe's old APIs. If you are not maintaining a legacy project, you should use the new Payment Intents and Setup Intents APIs.