0

I am trying to create a form for the user to buy product from my Ruby on Rails website by using their "Scratch Card for Mobile Phones".

The problem is that the service only provides Module code for PHP. So I have to convert it to Ruby to put into my website. Here are the codes I want to convert to Ruby:

$post_field = 'xyz=123&abc=456';

$api_url = "https://www.nganluong.vn/mobile_card.api.post.v2.php"; 

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$api_url);
curl_setopt($ch, CURLOPT_ENCODING , 'UTF-8'); 
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_field); 
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
$error = curl_error($ch);

I have tried to convert them to Ruby code but always got confused. Can anyone help me convert these codes into working Ruby codes? Thanks in advance!

Here is my silly code so far:

RestClient.post($api_url, $post_field, "Content-Type" => "application/x-www-form-urlencoded")

Basically all that I need is a ruby version of the php curl code. I'm a newbie, not an experienced programmer, so please help.

2
  • 2
    So post what you've got so far... Commented Oct 6, 2015 at 13:55
  • I've updated my question. Commented Oct 6, 2015 at 14:21

2 Answers 2

1

Try something like this:

require 'rest-client'
require 'rack'

post_query = 'xyz=123&abc=456'
api_url = "https://www.nganluong.vn/mobile_card.api.post.v2.php"

query_hash = Rack::Utils.parse_nested_query(post_query)

begin
  response = RestClient.post api_url, :params => query_hash
  print response.code
  print response.body
rescue Exception => e
  print e.message
end
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! How a bout $result = curl_exec($ch);? This is very important, because I need to get the vallue of $result .
1

All the code is doing is sending a payload xyz=123&abc=456 through a POST request to a specified URL.

You might use e.g. the curb gem for this:

response = Curl.post("https://www.nganluong.vn/mobile_card.api.post.v2.php", {:xyz => 123, :abc => 456})
result = response.body_str
status = response.status

1 Comment

Thank you very much! Your answer helped me understand a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.