Create Stripe Checkout In Next.js | Stripe Session | Stripe Webhook.

In this blog you will learn how to create a stripe session, redirect the user to the stripe checkout and also create stripe webhook that listens to when the payment is made.

Live Demo Example

Create Next.js app

npx create-next-app
cd my-app// Install packages
npm i @stripe/stripe-js next-stripe@beta micro

Create stripe keys and put them in next.js`.env` file
Create a stripe account if you don’t already have one and create your publishable key and secret key and place them in .env

NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_19HI412TBidBrJMDDsQ3HcDZ
STRIPE_SECRET_KEY=sk_test_wUdwAIjtgDq0oAa3rR0hJLU2h

Create a Next stripe api

Create a `[…nextstripe].js` catch-all route in your project’s `pages/api/stripe` directory.

import NextStripe from 'next-stripe'export default NextStripe({
    stripe_key: process.env.STRIPE_SECRET_KEY
})

Creating Checkout Page

Create two pages in Next.js pages folder my-checkout.js and thank-you.js

import { createCheckoutSession } from 'next-stripe/client'
import { loadStripe } from "@stripe/stripe-js";


export default function MyCheckout() {

    const handleCheckout = async () => {
        const priceOne = 18;
        const session = await createCheckoutSession({
            success_url: window.location.origin + '/thank-you?session_id={CHECKOUT_SESSION_ID}',
            cancel_url: window.location.href,
            line_items: [
                {
                    quantity: 1,
                    name : 'Beanie with Logo',
                    images: ['https://via.placeholder.com/150'],
                    amount: Math.round(priceOne * 100),
                    currency: 'usd',
                },
            ],
            payment_method_types: ['card'],
            mode: 'payment'
        })

        try {
            const stripe = await loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY);
            if (stripe) {
                stripe.redirectToCheckout({ sessionId: session.id });
            }
        } catch (error) {
            console.log( error );
        }
    }

    return <div>
        <button onClick={handleCheckout}>Checkout</button>
    </div>
}

Create Stripe API webhook endpoint

Endpoint Url : https://yournextjssiteurl/api/stripe-webhook
Events to sendcheckout.session.completed

Then copy your signing secret and place it in your .env file

STRIPE_WEBHOOK_ENDPOINT_SECRET=xxxx

Create stripe webhook endpoint file in next.js
Create a file calle `pages/api/stripe-web-hook.js`

import { buffer } from "micro";
const Stripe = require('stripe');

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
    apiVersion: '2020-08-27'
});
const webhookSecret = process.env.STRIPE_WEBHOOK_ENDPOINT_SECRET;

export const config = {
    api: {
        bodyParser: false,
    },
};


const handler = async (req, res) => {
    if (req.method === "POST") {
        const buf = await buffer(req);
        const sig = req.headers["stripe-signature"];

        let stripeEvent;

        try {
            stripeEvent = stripe.webhooks.constructEvent(buf, sig, webhookSecret);
            console.log( 'stripeEvent', stripeEvent );
        } catch (err) {
            res.status(400).send(`Webhook Error: ${err.message}`);
            return;
        }

        if ( 'checkout.session.completed' === stripeEvent.type ) {
            const session = stripeEvent.data.object;
            console.log( 'payment success', session );
// Do something here on payment success, like update order etc.        }

        res.json({ received: true });
    } else {
        res.setHeader("Allow", "POST");
        res.status(405).end("Method Not Allowed");
    }
};

export default handler;

Install srtipe cli and login to stripe account through cliStripe CLIAfter installing the Stripe CLI, you must pair it with your Stripe account. To do so, run stripe login in the terminal…stripe.com

brew install stripe/stripe-cli/stripestripe login

Listen to the webhook endpoint event.

stripe listen --forward-to localhost:3000/api/stripe-web-hook/

Make sure the value of `STRIPE_WEBHOOK_ENDPOINT_SECRET`while testing locally should be. the same as sigining secret received in terminal.

Now click on place order

Leave a Reply