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

React项目中正确引入Stripe库及调用全量API功能的最优方式

嘿,我来帮你梳理下在React应用里使用Stripe全量功能的最佳姿势!

首先得明确一个核心原则:永远不要在前端代码里暴露你的Stripe Secret Key。像创建客户、编辑客户、管理/取消订阅这类涉及敏感数据或资金操作的功能,必须放在后端服务中实现;前端只负责处理需要用户交互的部分(比如收集支付方式、展示订阅状态)。

1. 后端实现(以Node.js/Express为例)

Stripe提供了官方SDK支持几乎所有主流后端语言(Node.js、Python、Java等),这里用Node.js举例:

第一步:安装Stripe SDK

npm install stripe

第二步:编写后端接口

创建客户接口

const stripe = require('stripe')('你的Stripe Secret Key');
const express = require('express');
const app = express();
app.use(express.json());

// 创建客户
app.post('/api/stripe/customers', async (req, res) => {
  try {
    const { email, paymentMethodId } = req.body;
    // 调用Stripe API创建客户,关联支付方式
    const customer = await stripe.customers.create({
      email: email,
      payment_method: paymentMethodId,
      invoice_settings: {
        default_payment_method: paymentMethodId,
      },
    });
    res.status(200).json(customer);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

编辑客户接口

// 更新客户信息
app.patch('/api/stripe/customers/:customerId', async (req, res) => {
  try {
    const { customerId } = req.params;
    const { name, email } = req.body;
    const updatedCustomer = await stripe.customers.update(customerId, {
      name: name,
      email: email,
      // 你还可以更新其他字段,比如账单地址
    });
    res.status(200).json(updatedCustomer);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

管理订阅接口

// 创建订阅
app.post('/api/stripe/subscriptions', async (req, res) => {
  try {
    const { customerId, priceId } = req.body;
    const subscription = await stripe.subscriptions.create({
      customer: customerId,
      items: [{ price: priceId }], // priceId来自你Stripe后台创建的产品价格
      payment_behavior: 'default_incomplete',
      expand: ['latest_invoice.payment_intent'],
    });
    res.status(200).json(subscription);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 取消订阅
app.delete('/api/stripe/subscriptions/:subscriptionId', async (req, res) => {
  try {
    const { subscriptionId } = req.params;
    const canceledSubscription = await stripe.subscriptions.cancel(subscriptionId);
    res.status(200).json(canceledSubscription);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

2. 前端React实现

前端使用Stripe官方提供的@stripe/react-stripe-js和@stripe/stripe-js包,这两个包是react-stripe-checkout的替代方案,支持更完整的交互能力。

第一步:安装依赖

npm install @stripe/react-stripe-js @stripe/stripe-js

第二步:初始化Stripe并包裹组件

import { loadStripe } from '@stripe/stripe-js';
import { Elements } from '@stripe/react-stripe-js';
import CustomerAndSubscriptionManager from './CustomerAndSubscriptionManager';

// 这里用你的Stripe Publishable Key
const stripePromise = loadStripe('pk_test_xxxxxx');

function App() {
  return (
    <Elements stripe={stripePromise}>
      <CustomerAndSubscriptionManager />
    </Elements>
  );
}

export default App;

第三步:编写交互组件(收集支付方式+调用后端接口)

import { useStripe, useElements, CardElement } from '@stripe/react-stripe-js';
import { useState } from 'react';

function CustomerAndSubscriptionManager() {
  const stripe = useStripe();
  const elements = useElements();
  const [email, setEmail] = useState('');
  const [error, setError] = useState(null);
  const [customerId, setCustomerId] = useState('');

  // 创建客户+关联支付方式
  const handleCreateCustomer = async (e) => {
    e.preventDefault();
    if (!stripe || !elements) return;

    // 创建支付方式(从用户输入的卡片信息生成)
    const { error: paymentError, paymentMethod } = await stripe.createPaymentMethod({
      type: 'card',
      card: elements.getElement(CardElement),
      billing_details: { email: email },
    });

    if (paymentError) {
      setError(paymentError.message);
      return;
    }

    // 调用后端接口创建客户
    try {
      const response = await fetch('/api/stripe/customers', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email, paymentMethodId: paymentMethod.id }),
      });
      const customer = await response.json();
      setCustomerId(customer.id);
      setError(null);
      alert('客户创建成功!');
    } catch (fetchError) {
      setError(fetchError.message);
    }
  };

  // 取消订阅示例
  const handleCancelSubscription = async (subscriptionId) => {
    try {
      const response = await fetch(`/api/stripe/subscriptions/${subscriptionId}`, {
        method: 'DELETE',
      });
      const result = await response.json();
      alert('订阅已取消!');
    } catch (fetchError) {
      setError(fetchError.message);
    }
  };

  return (
    <div>
      <h3>创建客户</h3>
      <form onSubmit={handleCreateCustomer}>
        <input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder="输入邮箱"
          required
        />
        <CardElement />
        {error && <div style={{ color: 'red', marginTop: '10px' }}>{error}</div>}
        <button type="submit" disabled={!stripe} style={{ marginTop: '10px' }}>
          创建客户
        </button>
      </form>

      {customerId && (
        <div style={{ marginTop: '20px' }}>
          <h3>管理订阅</h3>
          <button onClick={() => handleCancelSubscription('你的订阅ID')}>
            取消订阅
          </button>
        </div>
      )}
    </div>
  );
}

export default CustomerAndSubscriptionManager;

3. 额外最佳实践

  • 用Webhooks监听事件:比如订阅到期、付款失败、客户信息更新等事件,Stripe会主动发送请求到你的后端,你可以在Webhook里更新自己数据库的状态,保证数据一致性。
  • 前端仅获取非敏感数据:如果需要在前端展示客户的支付方式列表,可以用Stripe Publishable Key调用stripe.paymentMethods.list({ customer: customerId }),但前提是你已经获得了客户的授权。
  • 处理异常场景:比如支付失败、订阅取消失败等,要给用户清晰的提示,并在后端记录错误日志。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:26:43