javascript - 使用 Ruby on Rails 后端和 Reactjs 前端创建条带令牌
问题描述
尝试创建条带令牌
这是我的前端获取
const response = fetch('api/v1/charges', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(paymentData),
});
然后 stripe 给出了在服务器端创建令牌的示例代码。哪里是放置这个的理想地方?控制器、模型、初始化器?
Stripe.api_key = 'sk_test_3Sq3Q'
token = params[:stripeToken]
charge = Stripe::Charge.create({
amount: 999,
currency: 'usd',
description: 'Example charge',
source: token,
})
显然我是新手,但我将不胜感激一些建议!
解决方案
我会Stripe.api_key = 'sk_test_3Sq3Q'
在初始化程序中添加 API 密钥,以考虑应用程序代码的结构以及将其与配置文件相结合
第二部分是接收请求参数并创建一个新的对象Stripe::Charge
。这将在控制器中。
另一种方法是将与 Stripe 相关的逻辑封装在一个小的 Stripe 客户端类中。此类可以具有处理与 Stripe API 的连接的方法。
例子:
class StripeClient
def create_charge(options)
# Here can be handled different exceptions as
# what to return in case of a failure?
Stripe::Charge.create({
amount: options[:amount],
currency: options[currency],
description: options[:description],
source: options[:token],
})
end
end
从控制器然后使用StripeClient
token = params[:stripeToken]
options = {
amount: 999,
currency: 'usd',
description: 'Example charge',
source: token
}
StripeClient.new.create_charge(options)
根据我的经验,我发现在特定的类或模块中调用第三方 API 会更干净。
希望这对你有帮助!
推荐阅读
- javascript - 如何在 C# 代码块中使用 javascript 变量
- elasticsearch - 如何在 Elasticsearch 7 NEST 7 中设置“max_result_window”
- c++ - 传递 unique_ptr 时调试和发布配置的移动不一致?
- javascript - 如何使用 Javascript 格式化数字?
- javascript - JavaScript 对象动态检索值
- php - 自定义帖子类型内容未显示在单页上
- datetime - 如何将儒略日期转换为雪花中的时间戳
- xfs - 我如何知道自动提款机交易是成功还是失败?
- docker - Light4J Oauth2 docker-compose 错误提示找不到指定的 Dockerfile
- java - Mockito - 任何 java.sql.Clob