新手问题 请问腾讯翻译 api 签名的问题

zcq100 · April 26, 2017 · Last by ice_7 replied at April 26, 2017 · 2737 hits

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
digest = OpenSSL::Digest.new('sha1')
signStr = Base64.strict_encode64("#{OpenSSL::HMAC.digest(digest, secret_key, src_str)}")

这个是之前我用腾讯文智那个接口的时候用的签名的代码

zcq100 closed this topic. 18 May 11:31
You need to Sign in before reply, if you don't have an account, please Sign up first.