Ruby:如何使用凭据初始化活动的商家网关实例?

Posted

技术标签:

【中文标题】Ruby:如何使用凭据初始化活动的商家网关实例?【英文标题】:Ruby: How to initialize an active merchant gateway instance with credentials? 【发布时间】:2018-06-21 14:08:15 【问题描述】:

来自http://www.rubydoc.info/github/Shopify/active_merchant/ActiveMerchant%2FBilling%2FBase.gateway

我应该使用这个初始化一个 active_merchant 实例

gateway = ActiveMerchant::Billing::Base.gateway( gateway_name ).new(
:username => :some_credential 
:password => :some_other_credential
)

但我不知道:username:password 提前,但他们在夹具文件https://github.com/activemerchant/active_merchant/blob/master/test/fixtures.yml 这里。那么如何正确地做到这一点呢?

例如,在fixtures.yml文件中我们可以看到这个..

adyen: username: '' password: '' merchant_account: ''

因此我们可以用这个来初始化..

gateway = ActiveMerchant::Billing::Base.gateway( 'adien' ).new(
username:         => :some_credential 
password:         => :some_other_credential
merchant_account: => some_more_credential
)

我需要能够在不硬编码上述示例中的username:password:merchant_account: 参数的情况下初始化网关实例。

提前致谢!

【问题讨论】:

【参考方案1】:

我想我可以回答我自己的问题。应该使用自己的哈希传递每个不同的初始化..

require 'active_merchant'

    settings = name: 'braintree_blue', merchant_id: 'x', public_key: 'y', private_key: 'z'
    another_settings = name: 'trust_commerce', login: 'TestMerchant', password: 'password'

Gateway = ActiveMerchant::Billing::Base::gateway(settings[:name]).new(settings)
Another_Gateway = ActiveMerchant::Billing::Base::gateway(another_settings[:name]).new(another_settings)

puts Gateway.options
puts Another_Gateway.options

请注意,我可以传递不同的选项而无需硬编码任何键,这是我想要的。

【讨论】:

【参考方案2】:

用户名、密码和商家帐户是实例变量,因此您需要使用instance_variable_set 更改它们

gateway.instance_variable_set(:@username, :some_username)
gateway.instance_variable_set(:@password, :some_password)
gateway.instance_variable_set(:@merchant_account, :some_merchant_account)

【讨论】:

但这仅适用于 adien 示例。如果网关只需要两个凭据,如 @username 和 @password,该怎么办?如果只需要一个像 @apikey 这样的凭证怎么办?【参考方案3】:

你应该看看环境变量。它们让您可以在安全的地方定义变量并在需要时引用它们。

您可以在某个地方定义PASSWORD=mysecretpassword,然后在Rails 代码中将其称为ENV["PASSWORD"]

有很多方法可以做到这一点。看这里:

http://railsapps.github.io/rails-environment-variables.html

【讨论】:

我在寻求一种方法,而不是将“用户名:”和“密码:”和“商家帐户:”硬编码到示例代码中,而不是“:some_credential”,“:some_other_credential”部分(您的解决方案显然可以解决)。我想我错误地选择了“凭据参数”这个术语,所以现在编辑......

以上是关于Ruby:如何使用凭据初始化活动的商家网关实例?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 ruby​​ on rails 中集成多个支付网关(多个商家)?

活动商家上的条带网关不工作

美国以外的 Ruby on Rails 和 Paypal

在 iOS 代码中嵌入 API 凭据

如何在 Spree 上根据信用卡类型使用不同的支付网关?

什么是 gem 支持多产支付网关?