LibreChat 集成 Stripe 支付的奶妈级教程

LibreChat 集成 Stripe 支付的奶妈级教程
Photo by Jonas Leupe / Unsplash

我们假设你已经熟悉基本的 React 和 Node.js 开发,并且正在使用 LibreChat 的默认技术栈(React 前端、Node.js 后端、Vite 构建工具,可能还有 Electron 桌面应用)。教程会特别考虑 Electron 环境下的适配问题(例如 macOS 中文路径或路由错误)。“奶妈级”带你从零开始实现支付功能(包括一次性支付和添加高级会员订阅)


教程目标

  • 在 LibreChat 中添加支付页面,支持用户通过信用卡付款。
  • 实现 Stripe 的一次性支付功能。
  • (可选)扩展到订阅功能,管理高级会员状态。
  • 解决 Electron 环境下的常见问题(如路由和路径解析)。
  • 生成可公开推送的 Markdown 教程,方便社区参考。

前提条件

在开始之前,请确保你已准备好以下内容:

  1. Stripe 账户
    • 注册 Stripe 账户(stripe.com)。
    • 在 Stripe 仪表板获取测试模式的 Publishable Keypk_test_xxx)和 Secret Keysk_test_xxx)。
    • 启用测试模式,避免真实扣款。
  2. LibreChat 项目
    • 克隆并运行 LibreChat(GitHub 仓库)。
    • 熟悉项目结构:
      • 前端:client 目录(React 代码)。
      • 后端:api 目录(Node.js 代码)。
    • 确保项目能正常运行(npm run devyarn dev)。
  3. 开发环境
    • Node.js:v18 或以上。
    • 包管理器:npm 或 Yarn。
    • Vite:用于构建前端(你的项目已配置)。
    • Electron:如果需要桌面应用支持。
    • 安装代码编辑器(如 VS Code)。
  4. 依赖安装
  5. 基础知识
    • 了解 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 创建产品和价格

  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.jsxCheckoutForm 中,调用订阅 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:

  1. 在 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 测试卡

  1. 访问支付页面(/payment)。
  2. 输入测试卡号:
    • 卡号:4242 4242 4242 4242
    • 有效期:任意未来日期(例如 12/34)
    • CVV:任意三位数(例如 123)
  3. 点击“Pay Now”,确认支付成功提示。
  4. 更多测试卡:Stripe 测试卡.

5.2 验证 Electron 环境

  1. 运行 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(如果使用)

  1. 在 Stripe 仪表板查看 Webhook 事件日志。

使用 Stripe CLI 模拟 Webhook:

stripe listen --forward-to http://localhost:3080/api/stripe/webhook

步骤 6:部署和上线

当测试通过后,可以准备上线!

6.1 切换到生产模式

  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 事件和用户状态更新。

常见问题与解决方案

  1. 支付页面在 Electron 中无法加载
    • 确认 dist/chat/index.html 路径正确。
    • 使用 HashRouter 或自定义协议(app://)。
    • 检查 Vite 构建输出(npm run build)。
  2. Stripe API 请求失败
    • 验证 .env 文件中的密钥。
    • 确保后端服务器运行(端口 3080)。
    • 查看 Stripe 仪表板的 API 错误日志。
  3. Webhook 未触发
    • 确认 Webhook URL 正确。
    • 使用 Stripe CLI 进行本地测试。
    • 检查服务器防火墙或网络设置。
  4. macOS 中文路径问题
    • 将应用移动到非中文路径(例如 /Applications/LibreChat.app)。

在 Electron 中使用 decodeURI

const decodedPath = decodeURI(path.join(__dirname, '../dist/chat/index.html'));
win.loadFile(decodedPath);

参考资源

Read more

决策树算法介绍:原理与案例实现

决策树算法介绍:原理与案例实现

决策树算法介绍:原理与案例实现 决策树算法介绍:原理与案例实现 一、决策树算法概述 决策树是一种基本的分类与回归方法,它基于树形结构进行决策。决策树的每一个节点都表示一个对象属性的测试,每个分支代表该属性测试的一个输出,每个叶节点则代表一个类别或值。决策树学习通常包括三个步骤:特征选择、决策树的生成和决策树的剪枝。 二、决策树算法原理 1. 特征选择 特征选择是决策树学习的核心。它决定了在树的每个节点上选择哪个属性进行测试。常用的特征选择准则有信息增益、增益比和基尼不纯度。 * 信息增益:表示划分数据集前后信息的不确定性减少的程度。选择信息增益最大的属性作为当前节点的测试属性。 * 增益比:在信息增益的基础上考虑了属性的取值数量,避免了对取值数量较多的属性的偏好。 * 基尼不纯度:在CART(分类与回归树)算法中,使用基尼不纯度作为特征选择的准则。基尼不纯度越小,表示纯度越高。 2. 决策树的生成 根据选择的特征选择准则,从根节点开始,递归地为每个节点选择最优的划分属性,并根据该属性的不同取值建立子节点。直到满足停止条件(如所有样本属于同一类,

By Ne0inhk
他给女朋友做了个树莓派复古相机,算法代码可自己编写,成本不到700元

他给女朋友做了个树莓派复古相机,算法代码可自己编写,成本不到700元

手机拍照不够爽,带个单反又太重? 试试做个树莓派复古相机,还能自己编写处理算法的那种—— 成本不到700元。 没错,颜值很高,拍出来的照片也能打: 你也可以快速上手做一个。 如何制作一个树莓派复古相机 目前,这部相机的代码、硬件清单、STL文件(用于3D打印)和电路图都已经开源。 首先是硬件部分。 这部复古相机的硬件清单如下: 树莓派Zero W(搭配microSD卡)、树莓派高清镜头模组、16mm 1000万像素长焦镜头、2.2英寸TFT显示屏、TP4056微型USB电池充电器、MT3608、2000mAh锂电池、电源开关、快门键、杜邦线、3D打印相机外壳、黑色皮革贴片(选用) 至于3D打印的相机外壳,作者已经开源了所需的STL文件,可以直接上手打印。 材料齐全后,就可以迅速上手制作了~ 内部的电路图,是这个样子的: 具体引脚如下: 搭建好后,整体电路长这样: 再加上3D外壳(喷了银色的漆)和镜头,一部简易的树莓派复古相机就做好了。 至于软件部分,

By Ne0inhk
🚀Zeek.ai一款基于 Electron 和 Vite 打造的跨平台(支持 Windows、macOS 和 Linux) AI 浏览器

🚀Zeek.ai一款基于 Electron 和 Vite 打造的跨平台(支持 Windows、macOS 和 Linux) AI 浏览器

是一款基于 Electron 和 Vite 打造的跨平台(支持 Windows、macOS 和 Linux) AI 浏览器。 集成了 SearXNG AI 搜索、开发工具集合、 市面上最流行的 AI 工具门户,以及代码编写和桌面快捷工具等功能, 通过模块化的 Monorepo 架构,提供轻量级、可扩展且高效的桌面体验, 助力 AI 驱动的日常工作流程。

By Ne0inhk