I am a newbie in ruby. I want to post a form data which includes an API key and some other field data to another website which will verify and send an http response 200 or 400 to my website. If I am able to connect to the api, the website responds with a URL redirect to my website with additional query string which my website will respond to. I don't how to do the following:
How to make my site respond to the redirect I get from the website through a controller and action. Assuming the controller is:
class BooksController < ApplicationController
def create
Do something
flash[:notice] = " book was created successfully"
end
end
Configure my route to respond to the redirect
here is the code I am trying to use on view
<form action="/master/master" method="POST" >
<script
src="https://js.example.co/v7/inline.js"
data-key= <%= ENV["EXAMPLE_PUBLIC_KEY"] %>
data-email= <%= current_user.email %>
data-booktitle= <%= current_user.books.title %>
data-ref= <% SecureRandom.random_number %>
>
</script>
</form>
This is just the basics of how to post a form to an external website. You'll have to fill in the details yourself since I have no clue what the external website does or what that script is supposed to accomplish.
Setting up a form to post to a remote url is pretty easy:
# Rails 4 and earlier
<% form_tag("http://example.com/test.php", method: :post) %>
<%= hidden_field_tag :key, ENV["EXAMPLE_PUBLIC_KEY"] %>
<%= hidden_field_tag :title, current_user.books.title %>
<%= hidden_field_tag :ref, SecureRandom.random_number %>
<%= submit_tag %>
<% end %>
# Rails 5+
<%= form_with(url: "http://example.com/test.php", method: :post) do |f| %>
<%= f.hidden_field :key, value: ENV["EXAMPLE_PUBLIC_KEY"] %>
# ...
<% end %>
Handling the callback from the external website isn't really different then any other route in your rails app:
get '/some/path', to: 'foo#bar'
You just create a route that responds to GET, and configure whatever service that handles the form submission to redirect back to it.