Golang与PHP https调用标头不同的结果

 书友53034809 发布于 2023-02-10 09:55

我正在尝试在Google App Engine Go中实现Vault of Satoshi的API.他们的参考API是PHP:


我的Go代码如下所示:

func GenerateSignatureFromValues(secretKey string, endpoint string, values url.Values) string {
    query:=[]byte(values.Encode())
    toEncode:=[]byte(endpoint)
    toEncode = append(toEncode, 0x00)
    toEncode = append(toEncode, query...)
    key:=[]byte(secretKey)
    hmacHash:=hmac.New(sha512.New, key)
    hmacHash.Write(toEncode)
    answer := hmacHash.Sum(nil)
    return base64.StdEncoding.EncodeToString(([]byte(strings.ToLower(hex.EncodeToString(answer)))))
}

func Call(c appengine.Context) map[string]interface{} {
    serverURL:="https://api.vaultofsatoshi.com"
    apiKey:="ENTER_YOUR_API_KEY_HERE"
    apiSecret:="ENTER_YOUR_API_SECRET_HERE"
    endpoint:="/info/order_detail"
    tr := urlfetch.Transport{Context: c}
    values := url.Values{}
    values.Set("nonce", strconv.FormatInt(time.Now().UnixNano()/1000, 10))
    signature:=GenerateSignatureFromValues(apiSecret, endpoint, values)
    req, _:=http.NewRequest("POST", serverURL+endpoint, nil)
    req.Form=values
    req.Header.Set("Api-Key", apiKey)
    req.Header.Set("Api-Sign", signature)
    resp, err:=tr.RoundTrip(req)
    if err != nil {
        c.Errorf("API post error: %s", err)
        return nil
    }
    defer resp.Body.Close()
    body, _:= ioutil.ReadAll(resp.Body)
    result := make(map[string]interface{})
    json.Unmarshal(body, &result)
    return result
}

这两段代码都为同一输入生成相同的签名.但是,当我运行PHP代码(使用正确的密钥和密钥)时,服务器会以适当的响应进行响应,但是当我运行Go代码时,服务器会以"无效签名"响应.此错误表示Go生成的HTTP请求必须以某种方式格式错误 - HTTP标头的值是错误的(如果标题值完全丢失,则出现不同的错误),或POST字段编码的方式由于某种原因是错误的.

任何人都可以帮我找到这两个代码生成不同HTTP请求的原因,以及如何使Go生成请求,如PHP代码?

1 个回答
  • 请参阅Request.Form的文档:

     // Form contains the parsed form data, including both the URL
     // field's query parameters and the POST or PUT form data.
     // This field is only available after ParseForm is called.
     // The HTTP client ignores Form and uses Body instead.
     Form url.Values
    

    特别是"HTTP客户端忽略表单并使用正文".

    有了这条线:

    req, _:= http.NewRequest("POST", serverURL+endpoint, nil)
    

    您应该使用此代替nil:

    bytes.NewBufferString(values.Encode())
    

    另请注意,订单map不保证.url.Valuesmap[string][]string.因此,您应该使用Encode()一次,并在正文和签名中使用相同的结果.有可能通过使用Encode()两次,订单可能会有所不同.这是Go和PHP之间的重要区别.

    你也应该养成处理的习惯error而不是忽视它.

    2023-02-10 09:58 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有