2015-10-06 167 views
0

我正试图为用户使用他们的“移动电话刮刮卡”从我的Ruby on Rails网站上购买产品。将cURL从PHP转换为ruby代码

问题是该服务只提供PHP的模块代码。所以我必须将它转换为Ruby才能放入我的网站。以下是我想要转换为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); 

我试图将它们转换为Ruby代码,但总是感到困惑。任何人都可以帮助我将这些代码转换为有效的Ruby代码?提前致谢!

这是迄今为止我傻代码:

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

基本上所有我需要的是PHP的卷曲代码的红宝石版本。我是一个新手,不是一个有经验的程序员,所以请帮忙。

+2

所以张贴到目前为止你有什么... –

+0

我已经更新了我的问题。 –

回答

1

尝试这样:

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 
+0

非常感谢!如何回合$结果= curl_exec($ ch);?这非常重要,因为我需要获得$ result的价值。 –

+0

@PeterNguyen,已更新答案 –

+0

感谢您的更新:)) –

1

所有代码正在通过POST请求向指定的URL发送有效负载xyz=123&abc=456

您可以使用例如该curb宝石本:

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

非常感谢!你的回答帮助我理解了很多。 –