【问题标题】:writing cURL like function in a rails app在 Rails 应用程序中编写类似 cURL 的函数
【发布时间】:2011-04-19 08:27:00
【问题描述】:

我正在尝试将此 PHP cURL 函数转换为与我的 rails 应用程序一起使用。这段代码来自需要验证 POST 参数的 SMS 支付网关。由于我是 PHP 大菜鸟,我不知道如何处理这个问题。

$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

我在 Rails 中搜索了一个 cURL lib 对应项,发现了很多选项,但没有一个我可以像这个脚本那样理解和使用。

如果有人能帮我把这个脚本从 php 转换为 ruby​​,我将不胜感激。

【问题讨论】:

    标签: php ruby-on-rails sms payment-gateway libcurl


    【解决方案1】:

    最直接的方法可能是使用 Ruby curb 库,它是 cURL 最直接的包装器。 Curl::Easy 中的许多选项直接映射到您在此处拥有的内容。一个基础可能是:

    url = "http://smsgatewayadress/"
    Curl::Easy.http_post(url,
      Curl::PostField.content('merchant_ID', params[:merchant_ID]),
      # ...
    )
    

    【讨论】:

    • 嘿!非常感谢您的快速回答。我现在正在查看 Curb 文档,我将尝试重写等效的 ruby​​ 脚本。除了CURLOPT_RETURNTRANSFER,我发现所有参数都等效,但我仍在搜索。脚本完成后我会在这里发布,也许其他人会需要它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 2015-05-26
    相关资源
    最近更新 更多