首页 > 解决方案 > 使用 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,
})

显然我是新手,但我将不胜感激一些建议!

标签: javascriptruby-on-railsstripe-payments

解决方案


我会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 会更干净。

希望这对你有帮助!


推荐阅读