Node.js 实现 Stripe 支付的实现方法

 更新时间:2025年11月17日 09:21:56   作者:明金同学  
本文介绍了使用Stripe支付系统的实现方法,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

1. 安装依赖

npm install stripe express

2. 基础服务端实现

// server.js
const express = require('express');
const stripe = require('stripe')('你的_STRIPE_SECRET_KEY'); // 从 Stripe 控制台获取
const app = express();
app.use(express.json());
app.use(express.static('public'));
// 创建支付意图
app.post('/create-payment-intent', async (req, res) => {
  try {
    const { amount, currency = 'usd' } = req.body;
    // 创建 PaymentIntent
    const paymentIntent = await stripe.paymentIntents.create({
      amount: amount, // 金额(以最小单位计,如美分)
      currency: currency,
      automatic_payment_methods: {
        enabled: true,
      },
    });
    res.json({
      clientSecret: paymentIntent.client_secret
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});
// 创建 Checkout Session(更简单的方式)
app.post('/create-checkout-session', async (req, res) => {
  try {
    const session = await stripe.checkout.sessions.create({
      payment_method_types: ['card'],
      line_items: [
        {
          price_data: {
            currency: 'usd',
            product_data: {
              name: '商品名称',
            },
            unit_amount: 2000, // $20.00
          },
          quantity: 1,
        },
      ],
      mode: 'payment',
      success_url: 'http://localhost:3000/success',
      cancel_url: 'http://localhost:3000/cancel',
    });
    res.json({ id: session.id });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});
// Webhook 处理(用于接收支付状态更新)
app.post('/webhook', express.raw({type: 'application/json'}), (req, res) => {
  const sig = req.headers['stripe-signature'];
  const webhookSecret = '你的_WEBHOOK_SECRET';
  let event;
  try {
    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('PaymentIntent 成功:', paymentIntent.id);
      // 这里处理支付成功后的业务逻辑
      break;
    case 'payment_intent.payment_failed':
      console.log('支付失败');
      break;
    default:
      console.log(`未处理的事件类型: ${event.type}`);
  }
  res.json({received: true});
});
app.listen(3000, () => {
  console.log('服务器运行在 http://localhost:3000');
});

3. 前端实现(使用 Stripe.js)

<!-- public/index.html -->
<!DOCTYPE html>
<html>
<head>
  <script src="https://js.stripe.com/v3/"></script>
</head>
<body>
  <button id="checkout-button">支付 $20</button>
  <script>
    const stripe = Stripe('你的_STRIPE_PUBLISHABLE_KEY');
    document.getElementById('checkout-button').addEventListener('click', async () => {
      // 方法 1: 使用 Checkout Session
      const response = await fetch('/create-checkout-session', {
        method: 'POST',
      });
      const session = await response.json();
      // 重定向到 Stripe Checkout
      const result = await stripe.redirectToCheckout({
        sessionId: session.id
      });
      if (result.error) {
        alert(result.error.message);
      }
    });
  </script>
</body>
</html>

4. 使用 Payment Intents 的更灵活方式

// 前端代码
const elements = stripe.elements();
const cardElement = elements.create('card');
cardElement.mount('#card-element');
const form = document.getElementById('payment-form');
form.addEventListener('submit', async (event) => {
  event.preventDefault();
  // 从后端获取 client secret
  const response = await fetch('/create-payment-intent', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({amount: 2000})
  });
  const {clientSecret} = await response.json();
  // 确认支付
  const {error, paymentIntent} = await stripe.confirmCardPayment(clientSecret, {
    payment_method: {
      card: cardElement,
      billing_details: {
        name: '客户姓名'
      }
    }
  });
  if (error) {
    console.log('支付失败:', error);
  } else if (paymentIntent.status === 'succeeded') {
    console.log('支付成功!');
  }
});

关键要点:

  1. 环境变量:将 Stripe 密钥存储在环境变量中
  2. 金额单位:Stripe 使用最小货币单位(美元用美分)
  3. Webhook:用于接收异步支付通知
  4. 测试模式:使用测试密钥和测试卡号(如 4242 4242 4242 4242)进行开发

上面只是一个基础实现,实际生产环境中还需要考虑错误处理、安全性、订单管理等更多细节。

到此这篇关于Node.js 实现 Stripe 支付的实现方法的文章就介绍到这了,更多相关node.js stripe 支付内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Node.js连接postgreSQL并进行数据操作

    Node.js连接postgreSQL并进行数据操作

    自从MySQL被Oracle收购以后,PostgreSQL逐渐成为开源关系型数据库的首选。这篇文章就给大家介绍了关于Node.js如何连接postgreSQL数据库,并进行数据操作的方法,有需要的朋友们可以参考借鉴,下面来一起看看吧。
    2016-12-12
  • Node.js开启Https的实践详解

    Node.js开启Https的实践详解

    最近因为工作需要,需要将网站切换到了https。其实去年就想迁的迁移过去,但是资金紧缺就找了个免费的证书,实际效果不是很好。但是最近腾讯云推出了免费的ssl证书申请。楼主是亲测有效的。下面通过本文来一起看看Node.js开启Https的详细步骤吧,有需要的可以参考借鉴。
    2016-10-10
  • node中使用log4js4.x版本记录日志的方法

    node中使用log4js4.x版本记录日志的方法

    这篇文章主要介绍了node中使用log4js4.x版本记录日志的方法,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-08-08
  • Egg框架的功能、原理,以及基本使用方法概述

    Egg框架的功能、原理,以及基本使用方法概述

    这篇文章主要介绍了Egg框架的功能、原理,以及基本使用方法,结合实例形式较为详细的分析了Egg框架的基本功能、原理、使用方法与相关注意事项,需要的朋友可以参考下
    2023-04-04
  • Node.js版本发布策略频率与稳定性的平衡

    Node.js版本发布策略频率与稳定性的平衡

    这篇文章主要为大家介绍了Node.js版本发布策略频率与稳定性的平衡,帮助大家大家更清晰了解node发展史,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-10-10
  • node.js读取命令行参数详解

    node.js读取命令行参数详解

    本文主要讲解了node.js如何获取命令行参数,有需要的朋友可以参考下
    2022-10-10
  • node.js 基于cheerio的爬虫工具的实现(需要登录权限的爬虫工具)

    node.js 基于cheerio的爬虫工具的实现(需要登录权限的爬虫工具)

    这篇文章主要介绍了node.js 基于cheerio的爬虫工具的实现(需要登录权限的爬虫工具) ,需要的朋友可以参考下
    2019-04-04
  • Node.js使用定时器的三种方法

    Node.js使用定时器的三种方法

    在Node.js中使用定时器是一项常见且重要的任务,本文主要介绍了Node.js使用定时器的三种方法,包括setTimeout、setInterval和setImmediate等方法,感兴趣的可以了解一下
    2024-02-02
  • node.js中的path.dirname方法使用说明

    node.js中的path.dirname方法使用说明

    这篇文章主要介绍了node.js中的path.dirname方法使用说明,本文介绍了path.dirname的方法说明、语法、使用实例和实现源码,需要的朋友可以参考下
    2014-12-12
  • node.js中TCP Socket多进程间的消息推送示例详解

    node.js中TCP Socket多进程间的消息推送示例详解

    这篇文章主要给大家介绍了关于node.js中TCP Socket多进程间的消息推送的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-07-07

最新评论