You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Stripe集成报错求助:POST 500内部服务器错误排查

Stripe集成500内部服务器错误排查求助

我正在为学校项目集成Stripe,严格遵循官方文档操作,但出现**POST 500(INTERNAL SERVER ERROR)**错误,同时App.js第70行报错:Error fetching payment intent: Error: Failed to fetch payment intent。我已经反复查阅Stripe文档、咨询导师、使用ChatGPT,还联系了Stripe客服(尚未收到回复,但项目有截止日期,不确定能否及时得到反馈),请帮忙排查问题。以下是我的代码:

后端create-payment-intent代码

load_dotenv()
stripe_keys = {
    "secret_key": os.environ["STRIPE_SECRET_KEY"],
    "publishable_key": os.environ["STRIPE_PUBLISHABLE_KEY"],
}

stripe.api_key = stripe_keys["secret_key"]

class OrderItems(Resource):
    def get(self):
        order_items = [order_item.to_dict() for order_item in OrderItem.query.all()]
        return make_response(order_items, 200)

    def post(self):
        req_json = request.get_json()
        print(req_json)

        try:
            sku_id = req_json['sku_id']
            order_id = req_json['order_id']
            quantity = req_json['quantity']

            new_order_item = OrderItem(
                sku_id = sku_id,
                order_id = order_id,
                quantity=quantity,
            )

            db.session.add(new_order_item)
            db.session.commit()

            return make_response(new_order_item.to_dict(), 201)
        
        except KeyError as e:
            missing_field = str(e)
            print(f"keyError: {missing_field}")
            return {'error': f'Missing required field: {missing_field}'}, 400
        except IntegrityError:
            return {'error': 'Database integrity violation'}, 500

        
@app.route('/create-payment-intent', methods=['POST'])
def create_payment():
        try:
            # Setup env vars beforehand 
            stripe_keys = {
                "secret_key": os.environ["STRIPE_SECRET_KEY"],
                "publishable_key": os.environ["STRIPE_PUBLISHABLE_KEY"],
            }

            stripe.api_key = stripe_keys["secret_key"]
            data = request.get_json()

            if 'customer' not in data:
                return jsonify(error='Invalid request: Missing "customer" key'), 400
            
            print(f"Request Data: {request.data}")

            intent = stripe.PaymentIntent.create(
                amount=2000,
                currency='usd',
                automatic_payment_methods=['card'],
                metadata={
                    'customer': data['customer']
                },
            )

            # return jsonify({'clientSecret': intent['client_secret']}), 200
            return make_response(jsonify({'clientSecret': intent['client_secret']}), 200)

        except stripe.error.StripeError as e:
            error_message = str(e)
            print(f"Stripe Error creating payment intent: {error_message}")
            return jsonify(error=f'Stripe Error: {error_message}'), 500

        except Exception as e:
            error_message = str(e)
            print(f"Error creating payment intent: {error_message}")
            return jsonify(error=f'Failed to create payment intent: {error_message}'), 500

前端App.js代码

import React, { useEffect, useContext, useState } from "react";
import { Switch, Route } from "react-router-dom";
import { CustomerAuthContext } from "../context/CustomerAuthProvider";
import Home from './Home';
import Profile from './Profile';
import Shop from './Shop';
import Leather from './Leather';
import Story from "./Story";
import Donation from "./Donation";
import FAQs from "./FAQs";
import ProductDetail from "./ProductDetail"
import Cart from "./Cart";
import About from "./About"
import Header from "./Header"; 
import Footer from "./Footer";
import { Elements } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
import CheckoutForm from './CheckoutForm';

const stripePromise = loadStripe(
  // 这里填写了我的publishable key
);

function App() {
  const { checkAuthorized, customer } = useContext(CustomerAuthContext);
  const [clientSecret, setClientSecret] = useState("")
  const [order_items, setOrder_items] = useState(null);

  useEffect(() => {
    checkAuthorized();

    fetchOrderItems();
  }, [])

  function fetchOrderItems() {

    fetch('/order_items')
      .then((res) => {
        if (!res.ok) {
          throw new Error("Failed to fetch order items");
        }
        return res.json();
      })
      .then((data) => {
        setOrder_items(data);
      })
      .catch((error) => {
        console.error("Error fetching order items:", error);
      });
  }

  function loadIntent() {

    if (!order_items) {
      console.error("Order is not defined.");
      return;
    }

    const order_itemIds = order_items.map((order_item) => order_item.sku_id);
    console.log(order_itemIds)

        fetch("/create-payment-intent", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ items: order_itemIds, customer: customer.id }),
        })
          .then((res) => {
            console.log(res);
            if (!res.ok) {
              throw new Error("Failed to fetch payment intent");
            }
            return res.json();
          })
          .then((data) => {
            console.log("Stripe API: response:", data);
            setClientSecret(data.clientSecret);
          })
          .catch((error) => {
            console.error("Error fetching payment intent:", error);

          if (error.response) {
            console.error("Response Status:", error.response.status);
            error.response.text().then((text) => {
              console.error("Response Body:", text);
            });
            console.error("Stripe API response:", error.response);
          }
          });
        }


  useEffect(() => {
    if (customer) {
      loadIntent()}
  }, [customer, order_items])

  const appearance = {
    theme: 'stripe',
  };
  
  const options = {
    clientSecret,
    appearance,
  };


  return (
  <div>
    <Header />
      <Switch>
        <Route path="/customer/:id" ><Profile /></Route>
        <Route path="/about"><About /></Route>
        <Route path="/shop" ><Shop /></Route>         
        <Route path="/leather" ><Leather /></Route>        
        <Route path="/story" ><Story /></Route>
        <Route path="/donation"><Donation /></Route>
        <Route path="/faqs"><FAQs /></Route>
        <Route path="/products/:id"><ProductDetail /></Route>
        <Route path="/products"></Route>
        <Route path="/cart"><Cart /></Route>
        <Route path="/checkout">
          {clientSecret && (
            <Elements stripe={stripePromise} options={options}>
              <CheckoutForm />
            </Elements>
          )}
        </Route>
        <Route path="/"><Home /></Route>
      </Switch>
    <Footer />
      </div>
  )
}

export default App;

排查关键点

  1. Stripe API参数错误:automatic_payment_methods参数需为对象格式,当前写成数组['card']不符合要求,正确写法是automatic_payment_methods: {enabled: true},这大概率是触发500错误的核心原因。
  2. 环境变量验证:在create_payment函数开头添加print(os.environ.get("STRIPE_SECRET_KEY")),确认密钥是否正确加载(注意不要泄露完整密钥,仅验证存在性和格式)。
  3. 前端错误处理优化:fetch的catch块无法直接获取HTTP错误响应,需在res.ok为false时解析后端返回的错误信息,修改逻辑如下:
    .then((res) => {
      console.log(res);
      if (!res.ok) {
        return res.json().then(errData => { throw new Error(errData.error) });
      }
      return res.json();
    })
    
  4. 请求数据检查:查看服务器日志中request.data的输出,确认前端发送的customer字段是否正确传递。
  5. 冗余代码清理:后端全局已设置stripe.api_key,create_payment函数内重复设置属于冗余操作,可移除避免潜在问题。

内容的提问来源于stack exchange,提问作者Alyssa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 22:35:55