我有多个客户端依赖我的服务器来处理Stripe充电请求。处理费用后,我想向我的客户发回JSON,说明费用是否已成功创建,如果不是,则说明原因。
我的服务器可以查看here。
我的控制器的代码如下:
class ChargesController < ApplicationController
protect_from_forgery
skip_before_action :verify_authenticity_token
def new
end
def create
# Amount in cents
@amount = 500
customer = Stripe::Customer.create(
:email => params[:stripeEmail],
:source => params[:stripeToken]
)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => @amount,
:description => 'Rails Stripe customer',
:currency => 'usd'
)
#*WHAT I TRIED DOING THAT DIDN'T WORK*
# respond_to do |format|
# msg = { :status => "ok", :message => "Success!"}
# format.json { render :json => msg }
# end
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to new_charge_path
end
end
我尝试使用以下网址调用我的RESTful API:
curl -XPOST https://murmuring-wave-13313.herokuapp.com/charges.json?stripeToken=tok_*****************&stripeEmail=rsheeler@gmail.com
我假设我需要访问部分metadata,但我不确定如何使用。
这导致500 Response
如何正确构建Charges控制器以返回Stripe响应的JSON?
答案 0 :(得分:0)
为什么这不起作用?
#*WHAT I TRIED DOING THAT DIDN'T WORK*
respond_to do |format|
msg = { :status => "ok", :message => "Success!"}
format.json { render :json => msg } # don't do msg.to_json
format.html { render :template => "charges/create"}
end
您的日志中有哪些错误?
答案 1 :(得分:0)
所以我在打自己。我意识到,在您创建Stripe::Charge
对象后,会为其分配一个JSON序列化的Charge
对象。
因此,您只需拨打Charge
即可访问charge.attribute_name
实例中的所有元数据。例如,如果它是有效的费用,charge.status
将返回“成功”。因为分配回费用的是JSON,如果请求的格式是JSON,您只需返回render charge
。
工作充电控制器如下所示:
class ChargesController < ApplicationController
protect_from_forgery
skip_before_action :verify_authenticity_token
def new
end
def create
# Amount in cents
@amount = 500
customer = Stripe::Customer.create(
:email => params[:stripeEmail],
:source => params[:stripeToken]
)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => @amount,
:description => 'Rails Stripe customer',
:currency => 'usd'
)
# If in test mode, you can stick this here to inspect `charge`
# as long as you've imported byebug in your Gemfile
byebug
respond_to do |format|
format.json { render :json => charge }
format.html { render :template => "charges/create"}
end
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to new_charge_path
end
end