codex
codex

Reputation: 35

How to i get ruby to return json response to be used in rails controller

I'm working with an Api, so far so good i am able to send requests and receive response, but i want the ruby code to send the json response and message that can be accessible from my rails controller so that i can get simple_form to render the error or success messages and also handle redirection from the rails controller, i also want to save transaction details from the response in a model, here's my lib code

class SimplePay
  require 'net/https'
  require 'uri'
  require 'json'

  def self.pay(api_key, token, amount, amount_currency, status)
    uri = URI.parse('https://checkout.simplepay.ng/v2/payments/card/charge/')
    header = {'Content-Type': 'text/json'}
    data = {
        'token': token,
        'amount': amount,
        'amount_currency': amount_currency
    }
    http = Net::HTTP.new(uri.host, uri.port)
    request = Net::HTTP::Post.new(uri.request_uri, header)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    request = Net::HTTP::Post.new(uri.request_uri, header)
    request.basic_auth(api_key, '')
    request.set_form_data(data)

    response = http.request(request)
    res = JSON.parse(response.read_body)
    response_code =  res['response_code']
    if response.kind_of? Net::HTTPSuccess
      if response_code.eql? 20000
        puts 'success'
      else
        puts 'Failed'
      end
    elsif status.eql? true
      puts 'Success But Not Charged'
    elsif status.eql? false
      raise error 'Failed To Charge Card'
    elsif response.kind_of? Net::HTTPBadRequest
      raise error 'Failed 400'
    elsif response.kind_of? Net::HTTPError
      raise error 'Failed 404'
    else
      raise error 'Unknown Error'
    end
  end
end

How do i go about achieving this?

Upvotes: 2

Views: 2939

Answers (1)

aks
aks

Reputation: 9491

I would say send a Hash to the controller and then when you are sending it just doing a .to_json will make it into a json

Upvotes: 1

Related Questions