
在某些业务场景下,立即扣款可能不符合需求。例如:
手动捕获为这些场景提供了解决方案,将支付流程分解为“授权”和“捕获”两个独立步骤,从而提供更大的控制权。
要实现 Stripe 的手动捕获功能,主要涉及以下两个核心步骤:创建 PaymentIntent 时指定手动捕获模式,以及在适当时候执行捕获操作。
在创建 PaymentIntent 对象时,需要将 capture_method 参数设置为 'manual'。这将指示 Stripe 在完成支付流程后仅授权资金,而不是立即从客户账户中扣除。
示例代码 (Node.js):
const stripe = require('stripe')('YOUR_STRIPE_SECRET_KEY'); // 替换为您的Stripe密钥
async function createManualPaymentIntent(amountInCents, currencyCode, customerId = null) {
try {
const paymentIntent = await stripe.paymentIntents.create({
amount: amountInCents, // 金额,以最小货币单位表示(例如,美元为美分)
currency: currencyCode, // 货币代码,例如 'usd'
customer: customerId, // 可选:关联客户ID
payment_method_types: ['card'], // 支付方式类型,例如银行卡
capture_method: 'manual', // 关键:设置为手动捕获
confirm: true, // 自动确认 PaymentIntent
description: '订单预授权', // 描述信息
// 其他可选参数,如 metadata, receipt_email 等
});
console.log(`PaymentIntent ID: ${paymentIntent.id} 已创建,状态为: ${paymentIntent.status}`);
// 当 confirm: true 时,如果支付成功,状态通常会是 'requires_capture'
return paymentIntent;
} catch (error) {
console.error('创建 PaymentIntent 失败:', error.message);
throw error;
}
}
// 示例调用 (假设授权 $10.00 美元)
// createManualPaymentIntent(1000, 'usd')
// .then(pi => console.log('手动捕获 PaymentIntent 创建成功。'))
// .catch(err => console.error('手动捕获 PaymentIntent 创建失败。'));当客户完成支付流程(例如,通过 Stripe Elements 输入卡信息并提交)后,如果 PaymentIntent 的 confirm 属性设置为 true,Stripe 会自动尝试授权这笔支付。如果授权成功,PaymentIntent 的状态将变为 requires_capture,表示资金已被预留,等待您的后续捕获指令。
在您决定实际扣款时(例如,在 5 分钟后、订单发货后或人工审核通过后),您需要调用 Stripe API 的捕获端点来完成资金的捕获。
示例代码 (Node.js):
const stripe = require('stripe')('YOUR_STRIPE_SECRET_KEY'); // 替换为您的Stripe密钥
async function captureAuthorizedPayment(paymentIntentId) {
try {
const capturedPaymentIntent = await stripe.paymentIntents.capture(
paymentIntentId
);
console.log(`PaymentIntent ID: ${capturedPaymentIntent.id} 已捕获,状态为: ${capturedPaymentIntent.status}`);
// 成功捕获后,状态将变为 'succeeded'
return capturedPaymentIntent;
} catch (error) {
console.error('捕获 PaymentIntent 失败:', error.message);
throw error;
}
}
// 示例调用 (假设在一段时间后捕获之前创建的 PaymentIntent)
// 假设之前创建的 paymentIntentId 为 'pi_xxxxxxxxxxxxxx'
// captureAuthorizedPayment('pi_xxxxxxxxxxxxxx')
// .then(pi => console.log('支付已成功捕获。'))
// .catch(err => console.error('支付捕获失败。'));在实际应用中,您可能会将 captureAuthorizedPayment 函数集成到您的后端逻辑中,例如:
Stripe 的手动捕获功能为需要延迟支付处理的业务场景提供了强大的灵活性和控制力。通过将支付流程分解为授权和捕获两个阶段,商家可以更好地管理资金流转时机,优化用户体验,并应对复杂的业务需求。理解并正确实施 capture_method: 'manual' 和 paymentIntents.capture() 是构建健壮且灵活的 Stripe 支付解决方案的关键。
以上就是Stripe 支付意图的手动捕获:实现延迟支付与灵活资金管理的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号