我有一个简单的Rails应用程序向外部网站发出请求并返回一个带有回调的json url响应到我的站点,以通知我的Rails应用程序有关响应。 json url示例为https://voguepay.com/?v_transaction_id=demo-1345109950&type=json
,响应正文如下:
{"merchant_id":"demo","transaction_id":"demo-1345109950","email":"testuser@buyerdomain.com","total":"10","total_paid_by_buyer":"10.00","total_credited_to_merchant":"9.90","extra_charges_by_merchant":"0.00","merchant_ref":"","memo":"Donation of N10 to Test User","status":"Approved","date":"2012-01-01 11:39:11","referrer":"http:\/\/sellerdomain.com\/buy_now.html","method":"VoguePay","fund_maturity":"2012-01-03"}
我想将此响应转换为Rails方法,而不是简单地给出我需要进行查询的属性。例如,从响应主体我需要做出如下操作:
def notify
response = Json.parse('https://voguepay.com/?v_transaction_id=demo-1345109950&type=json').body
response.status
response.date
response.merchant_id
response.total
end
上面的代码只是一个解释我想要实现的内容的示例。任何帮助都会很棒。
我已经尝试了typhoeus和yajl-ruby个宝石,但是当请求进来时,我的所有身份验证方法都被删除了,并且我不断收到错误消息,无法验证csrf元令牌。即使我跳过它,当前用户也会自动注销(使用设计认证)。使用的代码示例如下:
class NotificationsController < ApplicationController
skip_before_filter :verify_authenticity_token
def notify
@transaction_id = params[:transaction_id]
do_notify
end
private
def do_notify
hydra = Typhoeus::Hydra.new
request = Typhoeus::Request.new("https://voguepay.com/?v_transaction_id=#{@transaction_id}&type=json")
request.on_complete do |response|
logger.info("#{response.request.url} in #{response.time} seconds") #remove in production to avoid huge logs
transaction = Yajl::Parser.parse(response.body) #or Yajl::Parser.parse(response.body)
#Now we have the following keys in our transaction hash you can do whatever
transaction[:merchant_id]
transaction[:transaction_id]
transaction[:email]
transaction[:total]
transaction[:merchant_ref]
transaction[:memo]
transaction[:status]
transaction[:date]
transaction[:referrer]
transaction[:method]
@plan = Plan.find_by_id(transaction[:merchant_ref])
if(transaction[:total] == 0)
logger.error "Invalid total for transaction:#{@transaction_id}"
#do not subscribe the user or generate invoice, notify user of error n cancel order
elsif(transaction[:status] != 'Approved')
logger.error "Failed transaction for transaction:#{@transaction_id}"
#do not subscribe the user or generate invoice, notify user of error n cancel order
elsif(transaction[:total] >= @plan.naira_price.to_s)
current_user.award_user_credits(@plan.hjc.to_i)
end
end
hydra.queue(request)
hydra.run
end
end
我不想使用我想手动创建的gem来查看csrf元令牌是否会受到影响。所以我对如何实现这一点的任何想法都会很棒。我正在使用rails 3.2.9。
谢谢!
答案 0 :(得分:6)
你可以这样做:
def notify
response = JSON('https://voguepay.com/?v_transaction_id=demo-1345109950&type=json').body
response["status"]
response["date"]
response["merchant_id"]
response["total"]
end