我正在尝试将Rails应用程序连接到第三方API。在他们的示例代码中,连接到他们的服务的代码全部在PHP中。我对PHP
不熟悉。
这是代码:
<?php
// Token generation
$timestamp = time();
$uri = "https://api.website.com/post.json";
$password = "somePassword";
$security_token = sha1($timestamp.$uri.$password);
// Webservice call
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$post = array();
$post["timestamp"] = $timestamp;
$post["security_token"] = $security_token;
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
curl_setopt($ch, CURLOPT_POST, true);
// USE THIS CODE TO CHECK THAT SSL CERTIFICATE IS VALID:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, "path/to/certifcate/file/certificate.crt");
$ret = curl_exec($ch);
// Check response
if(curl_errno($ch)) {
curl_close($ch);
die("CURL error: ".curl_error($ch));
}
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($http_code != 200) {
die("Server error, HTTP code: $http_code");
}
curl_close($ch);
// Parse response
try {
$json = json_decode($ret);
var_dump($json);
}
catch(Exception $e) {
die("Failed to decode server response");
}
?>
任何将其转换为纯cURL
的帮助将不胜感激!
答案 0 :(得分:0)
这就是我的做法,效果很好。
uri = URI.parse("https://apilink/post.json")
pass = 'supper-password'
timestamp = Time.now
token = Digest::SHA1(timestamp + uri + pass)
request = Net::HTTP::Post.new(uri)
# request.body = "timestamp&security_token"
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
render json: response.code