how to store stripe session in nextjs 13 in javascript

To store Stripe session in Next.js 13, you can use the stripe-checkout package to initiate a payment on the client-side and then fetch the payment intent object on the server-side using Stripe API.

Here's an example code on how you can implement this:

index.tsx
import { loadStripe } from '@stripe/stripe-js';
import { Elements } from '@stripe/react-stripe-js';
import { useSession, signIn } from 'next-auth/client';
import { createCheckoutSession } from '../lib/stripe';

const stripePromise = loadStripe(process.env.STRIPE_PUBLIC_KEY);

export default function Checkout() {
  const [session] = useSession();

  const handleCheckout = async (event) => {
    event.preventDefault();
    if (!session) {
      signIn('github');
      return;
    }

    try {
      const { sessionId } = await createCheckoutSession(session.user.email);
      const stripe = await stripePromise;
      stripe.redirectToCheckout({ sessionId });
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <Elements stripe={stripePromise}>
      <button onClick={handleCheckout}>Checkout</button>
    </Elements>
  );
}
852 chars
33 lines

In the code above, we are fetching the checkout session object from the createCheckoutSession function and then redirecting the user to the Stripe checkout page by calling stripe.redirectToCheckout.

On the server-side, you can use Stripe API to retrieve the payment intent object like this:

index.tsx
import Stripe from 'stripe';

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

export async function createCheckoutSession(customerEmail) {
  const session = await stripe.checkout.sessions.create({
    payment_method_types: ['card'],
    line_items: [
      {
        price_data: {
          currency: 'usd',
          product_data: {
            name: 'T-shirt',
          },
          unit_amount: 2000,
        },
        quantity: 1,
      },
    ],
    mode: 'payment',
    success_url: `${process.env.BASE_URL}/success?session_id={CHECKOUT_SESSION_ID}`,
    cancel_url: `${process.env.BASE_URL}/cancel`,
    customer_email: customerEmail,
  });

  return { sessionId: session.id };
}
733 chars
30 lines

In the code above, we are creating a new checkout session object with the stripe.checkout.sessions.create method and returning the session ID.

You can then use this session ID to capture the payment or retrieve the payment intent object using Stripe API.

related categories

gistlibby LogSnag