views:

37

answers:

1

Hi guys!

I'm trying to convert this PHP cURL function to work with my rails app. The piece of code is from an SMS payment gateway that needs to verify the POST paramters. Since I'm a big PHP noob I have no idea how to handle this problem.

$verify_url = 'http://smsgatewayadress';



    $fields = '';

    $d = array(

            'merchant_ID' => $_POST['merchant_ID'],

            'local_ID' => $_POST['local_ID'],

            'total' => $_POST['total'],

            'ipn_verify' => $_POST['ipn_verify'],

            'timeout' => 10, 
            );



    foreach ($d as $k => $v)

    {

        $fields .= $k . "=" . urlencode($v) . "&";

    }

    $fields = substr($fields, 0, strlen($fields)-1);



    $ch = curl_init($verify_url); //this initiates a HTTP connection to $verify_url, the connection headers will be stored in $ch 

    curl_setopt($ch, CURLOPT_POST, 1); //sets the delivery method as POST

    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); //The data that is being sent via POST. From what I can see the cURL lib sends them as a string that is built in the foreach loop above

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //This verifies if the target url sends a redirect header and if it does cURL follows that link

    curl_setopt($ch, CURLOPT_HEADER, 0); //This ignores the headers from the answer

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //This specifies that the curl_exec function below must return the result to the accesed URL

    $result = curl_exec($ch); //It ransfers the data via POST to the URL, it gets read and returns the result



    if ($result == true)

    {

        //confirmed

        $can_download = true;

    }

    else

    {

        //failed
        $can_download = false;

    }

}



if (strpos($_SERVER['REQUEST_URI'], 'ipn.php'))

    echo $can_download ? '1' : '0'; //we tell the sms sever that we processed the request

I've googled a cURL lib counterpart in Rails and found a ton of options but none that I could understand and use in the same way this script does.

If anyone could give me a hand with converting this script from php to ruby it would be greatly appreciated.

+2  A: 

The most direct approach might be to use the Ruby curb library, which is the most straightforward wrapper for cURL. A lot of the options in Curl::Easy map directly to what you have here. A basis might be:

url = "http://smsgatewayadress/"
Curl::Easy.http_post(url,
  Curl::PostField.content('merchant_ID', params[:merchant_ID]),
  # ...
)
tadman
Hey! Thanks a lot for the quick answer. I'm looking over the Curb documentation right now and I'll try to rewrite the equivalent ruby script. I found equivalent for all the parameters besides `CURLOPT_RETURNTRANSFER`, but I'm still searching. I'll post the script here once it's done, maybe others will need it.
v3rt1go