API 签名参考 https://www.qcloud.com/document/product/551/7393#4.-.E9.89.B4.E6.9D.83.E5.A4.B1.E8.B4.A5
构造出来的 URI
https://tmt.api.qcloud.com/v2/index.php?Action=TextTranslate&Nonce=3453&SecretId=AKIDuwtmroC8ZptGovfkOqAJH3iBFE3gBp9M&SignatureMethod=HmacSHA256&Timestamp=1493195694&source=zh&sourceText=chinese%2B&target=en&Signature=ODQ1Y2IyYTc0Y2M0N2UzYWYzZGUyMGFjYmNiNGVkOGJjNWNiZDljOTNhMjQy%0AMDkxZDEzZjc5NzZmNGNjNzkxMw%3D%3D%0A 但是始终会返回 4100,认证错误,secrectid 和 secrectkey 都是核对过了的,签名通不过,帮忙看下谢谢。 代码
require "translate/version"
require "openssl"
require "base64"
require 'net/http'
class Translate
def initialize secret_id,secret_key
@secret_id=secret_id
@secret_key=secret_key
@params={}
end
def translate text,source="zh",target="en"
text=URI.encode_www_form_component text
self.params={'Action': 'TextTranslate','sourceText':text,'source': source,'target': target}
uri=URI("https://tmt.api.qcloud.com/v2/index.php?#{query}&Signature=#{URI.encode_www_form_component sign}")
p uri.to_s
Net::HTTP.get(uri)
end
def params= hash
option={
"SecretId"=>@secret_id,
"SignatureMethod"=>"HmacSHA256",
"Timestamp" =>Time.now.to_i,
"Nonce"=>rand(10000)
}
@params=option.merge hash
end
def query
@params.to_query
end
def sign
str="GETtmt.api.qcloud.com/v2/index.php?#{query}"
Base64.encode64(OpenSSL::HMAC.hexdigest("SHA256", @secret_key, str))
end
end
class Hash
def to_query
self.map{|k,v|[k,URI.encode_www_form_component(v)].join("=")}
.sort
.join("&")
end
end