首页 > 解决方案 > 使用 Next JS + Stripe 解决我未处理的运行时错误

问题描述

回购:https ://github.com/DoctorSte/aiAdvisor.git

我正在尝试让 Ne​​xt 应用程序与 Stripe 一起使用,但我不断收到未处理的运行时错误错误:执行此请求时发生错误。当我尝试在 paymentPage.ts 上启动 Stripe Checkout 会话时。

import Link from "next/link";
import "tailwindcss/tailwind.css"; 
import { GetServerSideProps } from "next";
import { loadStripe } from "@stripe/stripe-js";
import Stripe from "stripe";
import { createCheckoutSession } from "next-stripe/client";

interface IPrice extends Stripe.Price {
  product: Stripe.Product;
}

interface IProps {
  prices: IPrice[];
}

export default function Home({ prices }: IProps) {
  const onClick = async (priceId: string) => {
    const session = await createCheckoutSession({
      success_url: window.location.href,
      cancel_url: window.location.href,
      line_items: [{ price: priceId, quantity: 1 }],
      payment_method_types: ["card"],
      mode: "payment",
    });
    const stripe = await loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY);
    if (stripe) {
      stripe.redirectToCheckout({ sessionId: session.id });
    }
  };

  return (
    <div className="p-24">
      <h1>Buy Stuff</h1>

      <ul>
        {prices.map((price) => (
          <li key={price.id}>
            <h2>{price.product.name}</h2>
            <img className=" rounded-md" src={price.product.images[0]} />
            <p>Cost: ${((price.unit_amount as number) / 100).toFixed(2)}</p>
            <button onClick={() => onClick(price.id)}>Buy</button>
          </li>
        ))}
      </ul> <br />
 <Link href="/"><a>Back home</a></Link>
    </div>
  );
}


export const getServerSideProps: GetServerSideProps = async () => {
  const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
    apiVersion: "2020-08-27",
  });

  const prices = await stripe.prices.list({
    active: true,
    limit: 0,
    expand: ["data.product"],
  });

  return { props: { prices: prices.data } };
};

知道这里可能会发生什么吗?这是错误:

Unhandled Runtime Error
Error: An error occurred while performing this request.

Call Stack
_callee$
node_modules/next-stripe/dist/lib/fetcher.js (51:0)
tryCatch
node_modules/regenerator-runtime/runtime.js (63:14)
Generator.invoke [as _invoke]
node_modules/regenerator-runtime/runtime.js (293:0)
Generator.eval [as next]
node_modules/regenerator-runtime/runtime.js (118:0)
asyncGeneratorStep
node_modules/@babel/runtime/helpers/asyncToGenerator.js (3:0)
_next
node_modules/@babel/runtime/helpers/asyncToGenerator.js (25:0)

我正在使用 Next JS Stripe 包。

标签: next.jsstripe-payments

解决方案


推荐阅读