You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Node.js中使用Stripe Connect支付网关?求示例代码

Node.js 中使用 Stripe 的核心思路与示例代码

没问题!我来分享几个在 Node.js 里用 Stripe 开发的核心思路,附上实用的示例代码,帮你快速上手~

一、前期准备

  • 先在 Stripe 后台注册账号,获取 Secret Key(测试环境用sk_test_xxx,生产环境用sk_live_xxx),然后安装 Stripe SDK:
    npm install stripe
    
  • 把密钥配置到环境变量里(比如用.env文件),绝对不要把敏感密钥硬编码到代码里!

二、核心功能示例

1. 创建支付 Intent(处理一次性支付)

这是最常用的一次性支付场景:前端收集用户卡片信息后,后端创建支付Intent并返回clientSecret给前端,前端用这个密钥完成支付确认。

// 导入依赖并初始化Stripe
require('dotenv').config();
const express = require('express');
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const app = express();

app.use(express.json());

// 创建支付Intent的接口
app.post('/create-payment-intent', async (req, res) => {
  const { amount, currency = 'usd' } = req.body;

  try {
    const paymentIntent = await stripe.paymentIntents.create({
      amount: amount * 100, // Stripe用最小货币单位,比如10美元要传1000(分)
      currency: currency,
      payment_method_types: ['card'], // 限制支付方式为卡片
    });

    // 返回clientSecret给前端
    res.json({ clientSecret: paymentIntent.client_secret });
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

app.listen(3000, () => console.log('Server running on port 3000'));

提示:前端需要用Stripe.js调用confirmCardPayment方法,传入clientSecret完成支付流程,这里只展示后端核心逻辑。

2. 处理 Stripe Webhook(获取支付状态通知)

支付成功/失败、退款、订阅更新等事件,Stripe会主动通过Webhook通知你的后端,这一步是保证业务逻辑一致性的关键(比如支付成功后更新订单状态)。

// 配置Webhook签名密钥(从Stripe后台的Webhook设置里获取)
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;

// 注意这里要用express.raw解析请求体,不能用json
app.post('/stripe-webhook', express.raw({ type: 'application/json' }), async (req, res) => {
  const sig = req.headers['stripe-signature'];
  let event;

  try {
    // 验证签名,确保请求确实来自Stripe,防止恶意伪造
    event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
  } catch (err) {
    return res.status(400).send(`Webhook Error: ${err.message}`);
  }

  // 根据不同事件类型处理业务逻辑
  switch (event.type) {
    case 'payment_intent.succeeded':
      const paymentIntent = event.data.object;
      console.log(`支付成功!订单ID: ${paymentIntent.metadata.orderId}`);
      // 这里可以写更新数据库订单状态、发送邮件通知用户等逻辑
      break;
    case 'payment_intent.payment_failed':
      const failedIntent = event.data.object;
      console.log(`支付失败,原因: ${failedIntent.last_payment_error?.message}`);
      // 通知用户支付失败,或者触发重试逻辑
      break;
    // 其他常用事件:invoice.paid(订阅账单支付成功)、customer.subscription.deleted(订阅取消)等
    default:
      console.log(`未处理的事件类型: ${event.type}`);
  }

  // 告诉Stripe已收到事件
  res.json({ received: true });
});

测试Webhook可以用Stripe CLI,把线上事件转发到本地服务,命令类似:stripe listen --forward-to localhost:3000/stripe-webhook

3. 创建订阅(会员制/周期性支付)

如果你的业务是订阅制服务,用Stripe Subscriptions来管理周期性支付会更省心:

app.post('/create-subscription', async (req, res) => {
  const { customerId, priceId } = req.body;
  // customerId是Stripe里的用户ID,priceId是你在Stripe后台创建的定价ID(比如每月9.99美元的会员)

  try {
    const subscription = await stripe.subscriptions.create({
      customer: customerId,
      items: [{ price: priceId }],
      payment_behavior: 'default_incomplete', // 允许后续补充支付方式
      expand: ['latest_invoice.payment_intent'], // 展开获取支付Intent的信息
    });

    res.json({
      subscriptionId: subscription.id,
      clientSecret: subscription.latest_invoice.payment_intent.client_secret,
    });
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

三、关键注意事项

  • 环境隔离:测试阶段用测试密钥和Stripe提供的测试卡片(比如4242 4242 4242 4242),上线前务必切换到生产密钥
  • 错误处理:Stripe API会返回详细的错误信息,要捕获并转化为用户能看懂的提示
  • 签名验证:Webhook的签名验证一定要做,这是防止恶意请求的关键
  • 货币单位:Stripe要求金额用最小货币单位,比如人民币要传分,美元传分,所以记得把金额乘以100

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

火山引擎 最新活动