#tushark-checkout-nextjs

1 messages · Page 1 of 1 (latest)

cunning reefBOT
rain halo
#

Unfortunately I don't think we have any examples that use that yet

raven geyser
#
import { redirect } from "next/navigation"
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

export async function POST(request: Request, res: NextApiResponse) {
  try {
    const origin = request.headers.get("origin")
    const session = await stripe.checkout.sessions.create({
      line_items: [
        {
          price: "{{price_id}}",
          quantity: 1,
        },
      ],
      mode: "payment",
      success_url: `${origin}/plans?success=true`,
      cancel_url: `${origin}/plans?canceled=true`,
    })
    redirect(session.url as string)
  } catch (error: any) {
    console.log("==Error===", error)
    res.status(error.statusCode || 500).json(error.message)
  }
}

This is the route handler I have. It's throwing :
TypeError: webpack_require(...) is not a function

rain halo
cunning reefBOT
glacial sleet
#

tushark-checkout-nextjs

raven geyser
#

I somehow managed to make this work. But after redirecting to session.url, I am getting error as shown in the attached image.

glacial sleet
#

Can you share the exact code for your redirect?

raven geyser
#
import { RedirectType } from "next/dist/client/components/redirect"
import { redirect } from "next/navigation"
import { NextResponse } from "next/server"
import Stripe from "stripe"

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY as string, {
  apiVersion: "2022-11-15",
})


export async function POST(request: Request, res: NextApiResponse) {
  const origin = request.headers.get("origin")
  const session = await stripe.checkout.sessions.create({
    line_items: [
      {
        price: "price_1NGimxFW4sW3Sm0mBN4hpuec",
        quantity: 1,
      },
    ],
    mode: "payment",
    success_url: `${origin}/plans?success=true`,
    cancel_url: `${origin}/plans?canceled=true`,
  })
  redirect(session.url as string)
}```
#

redirect(session.url as string)

glacial sleet
#

Okay so what's the value of session.url? Does it match exactly what you see in the browser's URL?
How are you triggering that code from your client?

raven geyser
#

Yes, session.url and the browser url matches

#
import { loadStripe } from '@stripe/stripe-js';

// Make sure to call `loadStripe` outside of a component’s render to avoid
// recreating the `Stripe` object on every render.
const stripePromise = loadStripe(
  process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY
);
export default function PreviewPage() {
  React.useEffect(() => {
    // Check to see if this is a redirect back from Checkout
    const query = new URLSearchParams(window.location.search);
    if (query.get('success')) {
      console.log('Order placed! You will receive an email confirmation.');
    }

    if (query.get('canceled')) {
      console.log('Order canceled -- continue to shop around and checkout when you’re ready.');
    }
  }, []);

  return (
    <form action="/api/checkout_sessions" method="POST">
      <section>
        <button type="submit" role="link">
          Checkout
        </button>
      </section>
      <style jsx>
        {`
          section {
            background: #ffffff;
            display: flex;
            flex-direction: column;
            width: 400px;
            height: 112px;
            border-radius: 6px;
            justify-content: space-between;
          }
          button {
            height: 36px;
            background: #556cd6;
            border-radius: 4px;
            color: white;
            border: 0;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            box-shadow: 0px 4px 5.5px 0px rgba(0, 0, 0, 0.07);
          }
          button:hover {
            opacity: 0.8;
          }
        `}
      </style>
    </form>
  );
}```
#

It's exactly the same as in the stripe documentation

glacial sleet
#

Can you share the exact URL you're trying to load?

glacial sleet
#

okay so that URL loads fine if you click it right?

raven geyser
#

weird. If I directly access this url, the checkout page is showing

glacial sleet
#

So I'm thinking it's something Next.js specific where you do the redirect server-side and it's doing it as a POST request for some reason

#

I've never used Next.js so I'm googling around but maybe that rings a bell for you?

raven geyser
#

let me look into this too

glacial sleet
#

I think it's because you do the redirect inside your POST request already

#

If you look at the network request in Chrome, does it appear as a POST?

raven geyser
#

yes, with a status code: 307 Temporary Redirect

glacial sleet
#

yeah so you need to figure out how to configure Next.js to redirect to that URL directly as a GET

glacial cape
#

not a stripe employee - but im using a GET handler to create the session and redirect - works fine

glacial sleet
#

so you configured the form client-side to do a GET instead of a POST?

glacial cape
#

yeah

glacial sleet
#

Gotcha, that could work, but that's not always safe to do since it posts the params as GET params and could put them in logs and such

raven geyser
#

GET works. Thanks @glacial cape and @glacial sleet

#

this is the final code that's working.

import { RedirectType } from "next/dist/client/components/redirect"
import { redirect } from "next/navigation"
import { NextResponse } from "next/server"
import Stripe from "stripe"

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY as string, {
  apiVersion: "2022-11-15",
})

export async function GET(request: Request, res: NextApiResponse) {
  const origin = new URL(request.url).origin
  const session = await stripe.checkout.sessions.create({
    line_items: [
      {
        price: "price_id",
        quantity: 1,
      },
    ],
    mode: "payment",
    success_url: `${origin}/plans?success=true`,
    cancel_url: `${origin}/plans?canceled=true`,
  })
  redirect(session.url as string)
}