简体   繁体   中英

Post and redirect to external site from Rails controller?

After the user registration page, web clients will come to this page, which contains only a proceed button. But I want to skip this page and proceed to the payment page. Is there any way to do this action completely in the controller?

<form method="post" action="https://www.ccavenue.com/shopzone/cc_details.jsp">
    <input type=hidden name=Merchant_Id value="<%= @Merchant_id %>">
    <input type=hidden name=Amount value="<%= @Amount %>">
    <input type=hidden name=Order_Id value="<%= @user_id %>">
    <input type=hidden name=Redirect_Url value="<%= @redirect_url %>">
    <input type=hidden name=Checksum value="<%= @checksum %>">
    <input type="submit" class="Register_button" value="Proceed to payment">
</form>

You should do POST request from controller.

uri = URI.parse("https://www.ccavenue.com/shopzone/cc_details.jsp")
http = Net::HTTP.new(uri.host, uri.port)

form_data = {
  "Merchant_Id" => @Merchant_id,
  "Amount" => @Amount,
  "Order_Id" => @user_id,
  "Redirect_Url" => @redirect_url,
  "Checksum" => @checksum
}

request = Net::HTTP::Post.new(uri.request_uri)
request.set_form_data(form_data)

response = http.request(request)

You can use httparty gem to do post request.

No, not the way you're wanting.

As others have said, you can POST from within your controller, and receive the response, but if you want to have the browser post to the remote page, it has to be through a form. A common solution is to submit the form on load via javascript. eg

<body onload="document.forms['myform'].submit();">
    <form id="myform">
        …
    </form>
</body>

This might be years late response, but in case someone is still looking, I found this Repost plugin that could achieve this behaviour.

Could be used just like the normal redirect_to method in controller.

redirect_post('https://external-url.io/endpoint', params: {...})

There's no reason you couldn't post from a controller using uri and net/http in the Ruby standard library and handle the response from the server there.

Some good examples for using net/http can be found here. https://github.com/augustl/net-http-cheat-sheet/blob/master/post_form.rb

Still that's probably not the best way to handle this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM