2017-02-01 49 views
0

我有多個客戶端依靠我的服務器來處理分段計費請求。在處理費用時,我想向我的客戶返回JSON是否已成功創建費用,如果不是,則說明原因。可以查看我的服務器hereRails:從服務器返回條帶響應的JSON

我的控制器的代碼如下:

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 

我想打電話給我用下面的URL的RESTful API:

curl -XPOST https://murmuring-wave-13313.herokuapp.com/charges.json?stripeToken=tok_*****************&[email protected] 

我假設我需要訪問一些metadata,但我不確定如何。

這會導致500 Response

我怎樣才能正確地構建我的收費控制器,以回報條紋的迴應JSON?

回答

0

所以我揍我自己。我意識到當你製作Stripe::Charge對象後,JSON序列化的Charge對象被分配給它。

因此,您只需撥打charge.attribute_name即可訪問Charge實例中的所有元數據。例如,如果是有效費用,charge.status將返回「成功」。因爲分配給JSON的是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 
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 

您的日誌中有哪些錯誤?

+0

我發現我莊嚴擰起來,忘了犯'format.html {渲染:模板=>「收費/創建」}'此條件內heroku,所以我得到的錯誤將不會與我原來的問題(我不認爲至少)有關。對於任何混淆抱歉。 – beckah

相關問題