将Ruby代码转换为PHP(Vicurex API)

时间:2013-12-04 04:08:18

标签: php ruby api curl

我试图将一些示例Ruby API代码从https://vircurex.com/welcome/api?locale=en转换为PHP。这是提供的Ruby代码:

t = Time.now.gmtime.strftime("%Y-%m-%dT%H:%M:%S");
trx_id = Digest::SHA2.hexdigest("#{t}-#{rand}")
user_name = "MY_USER_NAME"
secret_word = "123456789"
tok = Digest::SHA2.hexdigest("#{secret_word};#{user_name};#{t};#{trx_id};create_order;sell;10;btc;50;nmc")
Order.call_https("https://vircurex.com", "/api/create_order.json?account=#{user_name}&id=#{trx_id}&token=#{tok}&timestamp=#{t}&ordertype=sell&amount=10&currency1=btc&unitprice=50&currency2=nmc")

def self.call_https(my_url,my_params)
  uri = URI.parse(my_url)
  http = Net::HTTP.new(uri.host, '443')
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER
  response=""
  resp=""
  http.start do |http|
    cmd = my_params
    req = Net::HTTP::Get.new(cmd)
    response = http.request(req)
    resp = response.body
  end
  return ActiveSupport::JSON.decode(resp)
end

以下是我在PHP中尝试提出的内容,但我对Ruby一无所知,因此很难弄清楚原始代码在做什么:

date_default_timezone_set("UTC");
$t = date("Y-m-d H:i:s", time());
$trx_id = hash("sha256", $t."-".rand()); // i think this is wrong
$user_name = "MY_USER_NAME";
$secret_word = "123456789";
$tok = hash("sha256", $secret_word.";".$user_name.";".$t.";".$trx_id.";create_order;sell;10;btc;50;nmc");
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, "https://vircurex.com/api/create_order.json?account=$username&id=$trx_id&token=$tok&timestamp=$t&ordertype=sell&amount=10&currency1=btc&unitprice=50&currency2=nmc");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$resp = curl_exec($ch);
return json_decode($resp);

熟悉这两种语言的人可以帮帮我吗?谢谢!

我的代码收到以下回复:

stdClass Object
(
    [status] => 8003
    [statustxt] => Authentication failed
)

很明显,有些东西没有正确翻译。我只需要生成一些可用的PHP代码,以便与列出的API一起使用。如果您愿意,可以创建一个帐户来测试代码。

1 个答案:

答案 0 :(得分:1)

问题分为两行:

首先,改变这一行:

$t = date("Y-m-d H:i:s", time());

为:

$t = date("Y-m-d\TH:i:s", time());

第二,解决这个问题:

curl_setopt($ch, CURLOPT_URL, "https://vircurex.com/api/create_order.json?account=$username&id=$trx_id&token=$tok&timestamp=$t&ordertype=sell&amount=10&currency1=btc&unitprice=50&currency2=nmc");

$username param更改为$user_name

curl_setopt($ch, CURLOPT_URL, "https://vircurex.com/api/create_order.json?account=$user_name&id=$trx_id&token=$tok&timestamp=$t&ordertype=sell&amount=10&currency1=btc&unitprice=50&currency2=nmc");

我成功收到了Vircurex的另一个API调用的有效回复,因为当前在Vircurex网站上报告的create_order API已被禁用。无论如何,我没有认证问题。