正在尝试创建条带令牌
这是我的前端提取
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,
})
显然我是新手,但一些建议将不胜感激!!
我会在初始值设定项中添加 API 密钥Stripe.api_key = 'sk_test_3Sq3Q'
,以考虑应用程序代码的结构,并将其与配置文件相结合
第二部分是接收请求参数并创建一个新的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 调用更干净。
希望对您有所帮助!