Node.js 實(shí)現(xiàn) Stripe 支付的實(shí)現(xiàn)方法
1. 安裝依賴
npm install stripe express
2. 基礎(chǔ)服務(wù)端實(shí)現(xiàn)
// server.js
const express = require('express');
const stripe = require('stripe')('你的_STRIPE_SECRET_KEY'); // 從 Stripe 控制臺(tái)獲取
const app = express();
app.use(express.json());
app.use(express.static('public'));
// 創(chuàng)建支付意圖
app.post('/create-payment-intent', async (req, res) => {
try {
const { amount, currency = 'usd' } = req.body;
// 創(chuàng)建 PaymentIntent
const paymentIntent = await stripe.paymentIntents.create({
amount: amount, // 金額(以最小單位計(jì),如美分)
currency: currency,
automatic_payment_methods: {
enabled: true,
},
});
res.json({
clientSecret: paymentIntent.client_secret
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// 創(chuàng)建 Checkout Session(更簡(jiǎn)單的方式)
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 處理(用于接收支付狀態(tài)更新)
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);
// 這里處理支付成功后的業(yè)務(wù)邏輯
break;
case 'payment_intent.payment_failed':
console.log('支付失敗');
break;
default:
console.log(`未處理的事件類型: ${event.type}`);
}
res.json({received: true});
});
app.listen(3000, () => {
console.log('服務(wù)器運(yùn)行在 http://localhost:3000');
});3. 前端實(shí)現(xiàn)(使用 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();
// 確認(rèn)支付
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('支付成功!');
}
});關(guān)鍵要點(diǎn):
- 環(huán)境變量:將 Stripe 密鑰存儲(chǔ)在環(huán)境變量中
- 金額單位:Stripe 使用最小貨幣單位(美元用美分)
- Webhook:用于接收異步支付通知
- 測(cè)試模式:使用測(cè)試密鑰和測(cè)試卡號(hào)(如 4242 4242 4242 4242)進(jìn)行開發(fā)
上面只是一個(gè)基礎(chǔ)實(shí)現(xiàn),實(shí)際生產(chǎn)環(huán)境中還需要考慮錯(cuò)誤處理、安全性、訂單管理等更多細(xì)節(jié)。
到此這篇關(guān)于Node.js 實(shí)現(xiàn) Stripe 支付的實(shí)現(xiàn)方法的文章就介紹到這了,更多相關(guān)node.js stripe 支付內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一文詳解如何快速判斷nodejs該項(xiàng)目需要哪個(gè)版本的node環(huán)境
node.js是一種非常流行的javascript運(yùn)行環(huán)境,它可以運(yùn)行在多種操作系統(tǒng)平臺(tái)上,這篇文章主要介紹了如何快速判斷nodejs該項(xiàng)目需要哪個(gè)版本的node環(huán)境的相關(guān)資料,需要的朋友可以參考下2025-06-06
Node.js API詳解之 timer模塊用法實(shí)例分析
這篇文章主要介紹了Node.js API詳解之 timer模塊用法,結(jié)合實(shí)例形式分析了Node.js API中timer模塊基本功能、原理、用法及操作注意事項(xiàng),需要的朋友可以參考下2020-05-05
Node.js 中 http 模塊的深度剖析與實(shí)戰(zhàn)應(yīng)用小結(jié)
本文詳細(xì)介紹了Node.js中的http模塊,從創(chuàng)建HTTP服務(wù)器、處理請(qǐng)求與響應(yīng),到獲取請(qǐng)求參數(shù),每個(gè)環(huán)節(jié)都通過代碼示例進(jìn)行解析,旨在幫助開發(fā)者熟練掌握http模塊,構(gòu)建高效的網(wǎng)絡(luò)應(yīng)用,感興趣的朋友一起看看吧2025-01-01
nodejs實(shí)現(xiàn)聊天機(jī)器人功能
這篇文章主要介紹了nodejs實(shí)現(xiàn)聊天機(jī)器人功能,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-09-09
Pycharm配置Node.js運(yùn)行js代碼詳細(xì)過程
在PyCharm中寫JavaScript代碼并進(jìn)行調(diào)試是非常方便的,但是有些用戶可能對(duì)如何在PyCharm中準(zhǔn)確地運(yùn)行JavaScript代碼感到困惑,這篇文章主要給大家介紹了關(guān)于Pycharm配置Node.js運(yùn)行js代碼的相關(guān)資料,需要的朋友可以參考下2023-11-11
使用node搭建自動(dòng)發(fā)圖文微博機(jī)器人的方法
這篇文章主要介紹了使用node搭建自動(dòng)發(fā)圖文微博機(jī)器人的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03
使用Node.js實(shí)現(xiàn)遍歷文件夾下所有文件
在使用Node.js處理文件或文件夾時(shí),我們有時(shí)需要遍歷文件夾中的所有文件和子文件夾以查找特定的文件或執(zhí)行某些操作,這里將提供一些基本的例子來演示如何使用Node.js遍歷文件夾,需要的朋友可以參考下2023-08-08

