LibreChat 集成 Stripe 支付的奶妈级教程
我们假设你已经熟悉基本的 React 和 Node.js 开发,并且正在使用 LibreChat 的默认技术栈(React 前端、Node.js 后端、Vite 构建工具,可能还有 Electron 桌面应用)。教程会特别考虑 Electron 环境下的适配问题(例如 macOS 中文路径或路由错误)。“奶妈级”带你从零开始实现支付功能(包括一次性支付和添加高级会员订阅)
教程目标
- 在 LibreChat 中添加支付页面,支持用户通过信用卡付款。
- 实现 Stripe 的一次性支付功能。
- (可选)扩展到订阅功能,管理高级会员状态。
- 解决 Electron 环境下的常见问题(如路由和路径解析)。
- 生成可公开推送的 Markdown 教程,方便社区参考。
前提条件
在开始之前,请确保你已准备好以下内容:
- Stripe 账户:
- 注册 Stripe 账户(stripe.com)。
- 在 Stripe 仪表板获取测试模式的 Publishable Key(
pk_test_xxx
)和 Secret Key(sk_test_xxx
)。 - 启用测试模式,避免真实扣款。
- LibreChat 项目:
- 克隆并运行 LibreChat(GitHub 仓库)。
- 熟悉项目结构:
- 前端:
client
目录(React 代码)。 - 后端:
api
目录(Node.js 代码)。
- 前端:
- 确保项目能正常运行(
npm run dev
或yarn dev
)。
- 开发环境:
- Node.js:v18 或以上。
- 包管理器:npm 或 Yarn。
- Vite:用于构建前端(你的项目已配置)。
- Electron:如果需要桌面应用支持。
- 安装代码编辑器(如 VS Code)。
- 依赖安装:
- 基础知识:
- 了解 React 组件和 React Router。
- 熟悉 Node.js 的 Express 路由。
- (可选)了解 Electron 的主进程和渲染进程。
前端:安装 Stripe 的 React 库。
cd client
npm install @stripe/stripe-js @stripe/react-stripe-js
后端:安装 Stripe 的 Node.js SDK。
cd api
npm install stripe
集成步骤
步骤 1:配置 Stripe API 密钥
Stripe 的密钥分为 Publishable Key(前端使用)和 Secret Key(后端使用)。我们需要安全地存储这些密钥。
1.1 后端配置
创建 api/lib/stripe.js
,初始化 Stripe:
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
module.exports = stripe;
在 api
目录下,创建或编辑 .env
文件,添加 Stripe Secret Key:
STRIPE_SECRET_KEY=sk_test_你的密钥
1.2 前端配置
在前端入口文件(例如 client/src/App.jsx
)中加载 Stripe:
import { loadStripe } from '@stripe/stripe-js';
const stripePromise = loadStripe(import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY);
在 client
目录下,创建或编辑 .env
文件,添加 Publishable Key:
VITE_STRIPE_PUBLISHABLE_KEY=pk_test_你的密钥
注意:
- 永远不要在前端暴露
Secret Key
,否则会有安全风险。 - 确保
.env
文件已加入.gitignore
,避免密钥泄露。
步骤 2:创建支付页面(前端)
我们将在 LibreChat 的前端添加一个支付页面,让用户可以输入信用卡信息并完成支付。
2.1 修改路由
在你的路由配置文件(例如 client/src/router.js
)中,添加支付页面路由:
import PaymentPage from './components/PaymentPage';
import { createBrowserRouter } from 'react-router-dom';
export const router = createBrowserRouter([
// 现有路由
{
path: '/payment',
element: <PaymentPage />,
errorElement: <RouteErrorBoundary />,
},
// ... 其他路由
]);
Electron 适配:
如果你在 Electron 环境下遇到路由问题(例如“No route matches URL”),建议切换到 HashRouter
,因为它更适合 file://
协议:
import { createHashRouter } from 'react-router-dom';
export const router = createHashRouter([...]);
2.2 创建支付组件
在 client/src/components
目录下,创建 PaymentPage.jsx
:
import React, { useState, useEffect } from 'react';
import { Elements, CardElement, useStripe, useElements } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
const stripePromise = loadStripe(import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY);
const CheckoutForm = () => {
const stripe = useStripe();
const elements = useElements();
const [error, setError] = useState(null);
const [processing, setProcessing] = useState(false);
const [clientSecret, setClientSecret] = useState('');
// 从后端获取支付意图的 client_secret
useEffect(() => {
fetch('/api/stripe/create-payment-intent', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ amount: 1000, currency: 'usd' }), // 示例:10美元
})
.then((res) => res.json())
.then((data) => setClientSecret(data.clientSecret))
.catch((err) => setError(err.message));
}, []);
const handleSubmit = async (event) => {
event.preventDefault();
setProcessing(true);
const payload = await stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: elements.getElement(CardElement),
},
});
if (payload.error) {
setError(payload.error.message);
setProcessing(false);
} else {
setError(null);
setProcessing(false);
alert('Payment succeeded!'); // 替换为更好的 UI 提示
}
};
return (
<form onSubmit={handleSubmit} style={{ maxWidth: '400px', margin: '0 auto' }}>
<CardElement options={{ style: { base: { fontSize: '16px' } } }} />
{error && <div style={{ color: 'red', marginTop: '10px' }}>{error}</div>}
<button
disabled={processing || !stripe || !elements}
style={{
marginTop: '20px',
padding: '10px 20px',
background: '#009688',
color: 'white',
border: 'none',
borderRadius: '4px',
}}
>
{processing ? 'Processing...' : 'Pay Now'}
</button>
</form>
);
};
const PaymentPage = () => (
<Elements stripe={stripePromise}>
<h2 style={{ textAlign: 'center', margin: '20px 0' }}>
Subscribe to LibreChat Premium
</h2>
<CheckoutForm />
</Elements>
);
export default PaymentPage;
代码说明:
CardElement
:Stripe 提供的信用卡输入框,自动处理卡号、有效期和 CVV。fetch('/api/stripe/create-payment-intent')
:调用后端 API 获取支付意图的client_secret
。Elements
:Stripe 的 React 组件,确保 SDK 正确加载。- 添加了简单的样式(可根据 LibreChat 的 UI 调整)。
2.3 适配 Electron
如果在 Electron 环境下运行,确保支付页面能正常加载:
- 如果遇到 macOS 中文路径问题(例如
/Applications/极客ai.app
),尝试:- 将应用移动到非中文路径(例如
/Applications/LibreChat.app
)。
- 将应用移动到非中文路径(例如
使用 decodeURI
处理编码路径:
const decodedPath = decodeURI(path.join(__dirname, '../dist/chat/index.html'));
win.loadFile(decodedPath);
检查 Electron 主进程(main.js
)是否正确加载构建后的 dist/chat/index.html
:
const { app, BrowserWindow } = require('electron');
const path = require('path');
app.whenReady().then(() => {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: { contextIsolation: true, nodeIntegration: false },
});
win.loadFile(path.join(__dirname, '../dist/chat/index.html'));
});
步骤 3:创建后端支付 API
在 LibreChat 的后端(api
目录),添加 Stripe 支付相关的 API 端点,用于创建支付意图。
3.1 创建支付意图
在 api/routes
目录下,创建 stripe.js
:
const express = require('express');
const stripe = require('../lib/stripe');
const router = express.Router();
router.post('/create-payment-intent', async (req, res) => {
const { amount, currency } = req.body;
try {
const paymentIntent = await stripe.paymentIntents.create({
amount, // 以分为单位,例如 1000 = 10美元
currency,
payment_method_types: ['card'],
});
res.json({ clientSecret: paymentIntent.client_secret });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
module.exports = router;
3.2 挂载路由
在 api/index.js
或主服务器文件中,挂载 Stripe 路由:
const express = require('express');
const stripeRoutes = require('./routes/stripe');
const app = express();
app.use(express.json());
app.use('/api/stripe', stripeRoutes);
// ... 其他中间件和路由
3.3 配置 Vite 代理
为了在开发模式下让前端正确访问后端 API,检查 client/vite.config.js
,确保代理配置正确:
server: {
proxy: {
'/api': {
target: 'http://localhost:3080', // 你的后端端口
changeOrigin: true,
},
},
},
说明:
- 后端 API 创建一个支付意图(
PaymentIntent
),返回client_secret
给前端。 - 前端使用
client_secret
完成支付确认。
步骤 4:(可选)集成订阅功能
如果想支持订阅(例如 Premium 会员每月收费),可以扩展 Stripe 集成。
4.1 创建产品和价格
- 在 Stripe 仪表板手动创建:
- 进入“产品”页面,添加产品(例如“LibreChat Premium”)。
- 创建价格(例如每月 10 美元,价格 ID 为
price_xxx
)。
或者通过 API 创建:
const product = await stripe.products.create({
name: 'LibreChat Premium',
});
const price = await stripe.prices.create({
product: product.id,
unit_amount: 1000, // 10美元
currency: 'usd',
recurring: { interval: 'month' },
});
4.2 创建订阅 API
在 api/routes/stripe.js
中添加订阅端点:
router.post('/create-subscription', async (req, res) => {
const { priceId } = req.body;
try {
const customer = await stripe.customers.create();
const subscription = await stripe.subscriptions.create({
customer: customer.id,
items: [{ price: priceId }],
payment_behavior: 'default_incomplete',
expand: ['latest_invoice.payment_intent'],
});
res.json({
clientSecret: subscription.latest_invoice.payment_intent.client_secret,
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
4.3 修改前端
在 PaymentPage.jsx
的 CheckoutForm
中,调用订阅 API:
useEffect(() => {
fetch('/api/stripe/create-subscription', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ priceId: 'price_你的价格ID' }),
})
.then((res) => res.json())
.then((data) => setClientSecret(data.clientSecret))
.catch((err) => setError(err.message));
}, []);
4.4 配置 Webhook
订阅需要处理异步事件(例如支付成功或失败)。在后端添加 Webhook:
- 在 Stripe 仪表板 > 开发者 > Webhook,添加端点(例如
https://你的域名/api/stripe/webhook
)。
在 api/.env
中添加 Webhook Secret:
STRIPE_WEBHOOK_SECRET=whsec_你的密钥
在 api/routes/stripe.js
中添加:
router.post('/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
const sig = req.headers['stripe-signature'];
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
try {
const event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
switch (event.type) {
case 'payment_intent.succeeded':
console.log('Payment succeeded:', event.data.object);
// 更新用户订阅状态(例如 MongoDB)
// await User.updateOne({ stripeCustomerId: event.data.object.customer }, { isPremium: true });
break;
case 'payment_intent.payment_failed':
console.log('Payment failed:', event.data.object);
break;
}
res.json({ received: true });
} catch (error) {
res.status(400).send(`Webhook Error: ${error.message}`);
}
});
步骤 5:测试支付功能
现在,让我们测试整个支付流程!
5.1 使用 Stripe 测试卡
- 访问支付页面(
/payment
)。 - 输入测试卡号:
- 卡号:
4242 4242 4242 4242
- 有效期:任意未来日期(例如 12/34)
- CVV:任意三位数(例如 123)
- 卡号:
- 点击“Pay Now”,确认支付成功提示。
- 更多测试卡:Stripe 测试卡.
5.2 验证 Electron 环境
- 运行
npm run build
,生成dist/chat
目录。
如果遇到路由错误,切换到 HashRouter
或使用自定义协议:
const { protocol } = require('electron');
protocol.registerFileProtocol('app', (request, callback) => {
const url = request.url.replace('app://', '');
callback({ path: path.join(__dirname, '../dist/chat', url || 'index.html') });
});
win.loadURL('app://index.html');
检查 Electron 主进程,确保加载正确:
win.loadFile(path.join(__dirname, '../dist/chat/index.html'));
5.3 测试 Webhook(如果使用)
- 在 Stripe 仪表板查看 Webhook 事件日志。
使用 Stripe CLI 模拟 Webhook:
stripe listen --forward-to http://localhost:3080/api/stripe/webhook
步骤 6:部署和上线
当测试通过后,可以准备上线!
6.1 切换到生产模式
- 在 Stripe 仪表板切换到 Live Mode,获取生产密钥:
更新 client/.env
:
VITE_STRIPE_PUBLISHABLE_KEY=pk_live_你的密钥
更新 api/.env
:
STRIPE_SECRET_KEY=sk_live_你的密钥
6.2 确保安全性
- 使用 HTTPS(Electron 可通过代理或证书支持)。
- 遵守 PCI DSS(Stripe 的
CardElement
已处理大部分合规性)。
检查 CORS 配置(如果前端后端域名不同):
const cors = require('cors');
app.use(cors({ origin: '你的前端域名' }));
6.3 部署后端
- 部署到云服务(例如 Heroku、Vercel、AWS)。
- 确保
/api/stripe/webhook
端点可公开访问。
6.4 测试生产环境
- 使用真实信用卡进行小额支付测试(例如 1 美元)。
- 验证 Webhook 事件和用户状态更新。
常见问题与解决方案
- 支付页面在 Electron 中无法加载:
- 确认
dist/chat/index.html
路径正确。 - 使用
HashRouter
或自定义协议(app://
)。 - 检查 Vite 构建输出(
npm run build
)。
- 确认
- Stripe API 请求失败:
- 验证
.env
文件中的密钥。 - 确保后端服务器运行(端口 3080)。
- 查看 Stripe 仪表板的 API 错误日志。
- 验证
- Webhook 未触发:
- 确认 Webhook URL 正确。
- 使用 Stripe CLI 进行本地测试。
- 检查服务器防火墙或网络设置。
- macOS 中文路径问题:
- 将应用移动到非中文路径(例如
/Applications/LibreChat.app
)。
- 将应用移动到非中文路径(例如
在 Electron 中使用 decodeURI
:
const decodedPath = decodeURI(path.join(__dirname, '../dist/chat/index.html'));
win.loadFile(decodedPath);
参考资源
- Stripe 官方文档:
- LibreChat 文档:docs.librechat.ai
- React Stripe 库:github.com/stripe/react-stripe-js
- Electron 文档:electronjs.org/docs