2015-10-06 162 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

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