在使用Ruby on Rails框架与Stripe API进行集成时,遇到NoMethodError: undefined method 'sources' for #<Stripe::Customer>
错误,通常是因为Stripe API版本更新导致的。Stripe经常更新其API,并且某些方法可能会在不同版本之间发生变化。
Stripe是一个在线支付处理平台,提供了丰富的API来处理支付、订阅、客户管理等功能。Stripe::Customer
对象代表一个Stripe中的客户,而sources
方法用于访问客户的支付来源(如信用卡、银行账户等)。
sources
方法,或者这个方法在最新的API版本中已经被重命名或移除。确保你的Stripe gem版本与Stripe API版本兼容。可以在Gemfile
中指定Stripe gem的版本,并运行bundle update stripe
来更新gem。
# Gemfile
gem 'stripe', '~> 2022-11-07' # 使用最新的稳定版本
如果sources
方法已经被移除或重命名,你需要根据最新的Stripe API文档更新代码。例如,从Stripe API 2020-08-27开始,sources
方法已被payment_methods
取代。
# 旧代码
customer = Stripe::Customer.retrieve("cus_...")
sources = customer.sources
# 新代码
customer = Stripe::Customer.retrieve("cus_...")
payment_methods = customer.payment_methods
确保在Rails应用中正确配置了Stripe gem。通常在config/initializers/stripe.rb
文件中进行配置。
# config/initializers/stripe.rb
Stripe.api_key = ENV['STRIPE_SECRET_KEY']
运行一个简单的测试来确保Stripe gem配置正确并且可以正常调用API。
# test.rb
require 'stripe'
Stripe.api_key = ENV['STRIPE_SECRET_KEY']
begin
customer = Stripe::Customer.retrieve("cus_...")
puts customer.payment_methods
rescue Stripe::StripeError => e
puts "Error: #{e.message}"
end
这种错误常见于需要管理客户支付信息的应用,如电子商务网站、订阅服务等。确保API版本和代码同步更新是保持应用稳定运行的关键。
通过以上步骤,你应该能够解决NoMethodError: undefined method 'sources' for #<Stripe::Customer>
错误,并确保你的Rails应用与Stripe API正确集成。
领取专属 10元无门槛券
手把手带您无忧上云