Stripe Checkout 不起作用 - 使用 Next.js App Router 时出现 404 错误

问题描述 投票:0回答:1

我正在尝试向 Next.js App 路由器应用程序添加一个简单的 Stripe 结账。如果我在 next.js 中使用页面路由器,则代码可以工作,但由于某种原因,当我单击结帐按钮时,我收到 404 - 此页面无法找到错误。有人知道为什么会这样吗?

在这里获取代码:

应用程序/page.js:

'use client'

import React from 'react';
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>
  );
}

应用程序/api/checkout_sessions/route.js:

const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

export default async function handler(req, res) {
  if (req.method === 'POST') {
    try {
      // Create Checkout Sessions from body params.
      const session = await stripe.checkout.sessions.create({
        line_items: [
          {
            price: 'price_id',
            quantity: 1,
          },
        ],
        mode: 'subscription',
        success_url: `${req.headers.origin}/?success=true`,
        cancel_url: `${req.headers.origin}/?canceled=true`,
      });
      res.redirect(303, session.url);
    } catch (err) {
      res.status(err.statusCode || 500).json(err.message);
    }
  } else {
    res.setHeader('Allow', 'POST');
    res.status(405).end('Method Not Allowed');
  }
}
next.js stripe-payments
1个回答
0
投票

听起来您正面临 Next.js 及其路由的常见问题,尤其是在集成 Stripe 之类的东西时。鉴于详细信息,问题似乎可能与您在 Next.js 应用程序中构造 API 路由的方式有关。

在 Next.js 中,API 路由应放置在

pages/api
目录下。此设置对于 Next.js 正确识别和处理 API 请求至关重要。从您的代码片段来看,您似乎已将
checkout_sessions
路线放置在
app/api/checkout_sessions/route.js
路径中。

这里有一个可能修复 404 错误的快速建议:

  1. 移动您的 API 路由:确保您的 API 路由 (

    checkout_sessions
    ) 直接位于
    pages/api
    目录下。正确的路径是
    pages/api/checkout_sessions.js
    。此调整应该有助于 Next.js 正确识别您的 API 路由。

  2. 调整表单操作:移动 API 路由文件后,确保

    PreviewPage
    组件中的表单操作指向正确的端点。由于您的 API 路线现在位于
    pages/api/checkout_sessions.js
    ,因此您的表单操作应设置为
    /api/checkout_sessions
    ,看起来已经如此,所以您在这里很好。

通过将 API 路由移至正确的目录,Next.js 应该能够正确处理对

/api/checkout_sessions
的请求,而不会返回 404 错误。尝试一下,它应该有助于解决结账按钮问题。如果一路上还有什么坎坷或者有什么想聊的,请告诉我!

© www.soinside.com 2019 - 2024. All rights reserved.