gpt4 book ai didi

javascript - 如何以及是否在 stripe 新库 @stripe/react-stripe-js 中使用服务器端

转载 作者:行者123 更新时间:2023-12-05 01:37:39 61 4
gpt4 key购买 nike

我的目标是为产品创建一个简单的支付页面。

在官方文档中,它说在服务器端需要生成 token 才能创建交易,使用:

stripe.paymentIntents.create({
amount: req.body.amount,
currency: 'usd'
})

并使用返回的 key 创建交易。

但是,其他一些官方示例仅使用客户端,如下所示:

const { error, paymentMethod } = await stripe.createPaymentMethod({
type: 'card',
card: elements.getElement(CardElement),
})

没有服务器 key stripe.confirmCardPayment('{CLIENT_SECRET}', {

文档说 CLIENT_SECRET 是必需的,但也有没有它的示例。

知道为什么和有什么区别吗?

最佳答案

除非你使用 Stripe 的新 client-only Checkout没有一些服务器端代码,就无法在自定义 Stripe 集成中处理付款。

如您所见,官方 docs React Stripe.js 仅包含客户端代码。但是,此页面上的代码示例并不代表处理付款所需的完整集成。这些示例仅演示如何使用 React Stripe.js 和 createPaymentMethod 在前端收集和标记信用卡详细信息。功能。以这种方式编写文档是为了更轻松地在浏览器中跟踪和运行代码示例,而无需设置服务器。

开始了解端到端支付集成中涉及哪些 API 的好地方是:

https://stripe.com/docs/payments/accept-a-payment

(提示上述指南中的每个代码示例都有一个 React 版本,您可以使用 Tab 键进入)

如果您有兴趣查看基于这些 React 示例构建的完整工作集成,我建议您查看我们为最近的开发人员办公时间节目构建的以下演示:

https://github.com/tmarek-stripe/demo-react-stripe-js

具体来说,我建议查看服务器端部分 (here)创建付款意向,客户端部分 (here)创建付款方式并确认付款意向。

要复习的内容太多了!如果您愿意,您可以观看视频,了解如何创建(几乎完整的)与 React Stripe.js 的集成:

React Stripe.js - Developer Office Hours | Youtube

一旦涵盖了基础知识,我建议您查看另一个示例以获得更完整的端到端集成:

Type-safe Payments with Next.js, TypeScript, and Stripe

在查看此完整集成时,请注意在使用 Stripe.js 时如何不需要手动创建付款方式。它是可选的,因为成功的付款意向会自动为您创建付款方式。

在服务器端创建支付意向:

// Create a PaymentIntent with the specified amount.
const response = await fetchPostJSON('/api/payment_intents', {
amount: input.customDonation
});

https://github.com/stripe-samples/nextjs-typescript-react-stripe-js/blob/master/components/ElementsForm.tsx#L84-L88

并确认客户端不需要任何 createPaymentMethod 调用!

const cardElement = elements!.getElement(CardElement);

// Use your card Element with other Stripe.js APIs
const { error, paymentIntent } = await stripe!.confirmCardPayment(
response.client_secret,
{
payment_method: {
card: cardElement!,
billing_details: { name: input.cardholderName }
}
}
);

https://github.com/stripe-samples/nextjs-typescript-react-stripe-js/blob/master/components/ElementsForm.tsx#L99-L110

简而言之:

希望对您有所帮助!

关于javascript - 如何以及是否在 stripe 新库 @stripe/react-stripe-js 中使用服务器端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60761945/

61 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com