向第三方 API 发送 POST 请求

时间:2021-04-13 14:32:56

标签: api go post request go-micro

我一直想从我的 go 微服务向 Rapyd API 执行一个简单的 POST 请求。 我在网上搜索了很多解决方案,但没有一个奏效... 如果我尝试发出请求,我会收到 400 Bad Request 或包含“Network unreachable”的错误 我尝试使用 Go 结构制作正文有效负载,使用字符串中的 JSON,但似乎没有任何效果,这是我的代码:(抱歉,我不得不插入带有代码段的结构,因为它不适用于代码示例)

type CardRequest struct {
    Amount        float64 `json:"amount"`
    Currency      string  `json:"currency"`
    PaymentMethod PaymentMethod `json:"payment_method"`
    ErrorPaymentURL string `json:"error_payment_url"`
    Capture         bool   `json:"capture"`
}

type PaymentMethod struct {
    Type   string `json:"type"`
    Fields Fields `json:"fields"`
}

type Fields struct {
    Number          string `json:"number"`
    ExpirationMonth string `json:"expiration_month"`
    ExpirationYear  string `json:"expiration_year"`
    Cvv             string `json:"cvv"`
}

    hc := http.Client{}
    form, _ := json.Marshal(CardRequest{
       Amount: 53.5,
       Currency: "THB",
       PaymentMethod: PaymentMethod{
           Type: "th_visa_card",
           Fields: Fields{
               Number: "4111111111111111",
               ExpirationMonth: "10",
               ExpirationYear: "21",
               Cvv: "123",
           },
       },
      ErrorPaymentURL: "https://error_example.net",
      Capture: true})
    http_method := "post"
    url_path := "/v1/payments"
    salt := strconv.Itoa(10000000 + rand.Intn(99999999-10000000))
    timestamp := strconv.Itoa(int(time.Now().Unix()))
    access_key := "my_access_key"
    secret_key := "my_secret_key"
    sign_str := http_method + url_path + salt + timestamp + access_key + secret_key + string(form[:])
    fmt.Println(form)
    h := hmac.New(sha256.New, []byte(secret_key))
    h.Write([]byte(sign_str))
    buf := h.Sum(nil)
    signature := base64.RawURLEncoding.EncodeToString(buf)
    httpReq, err := http.NewRequest("POST", "https://sandboxapi.rapyd.net/v1/payments", bytes.NewBuffer(form))
    // req.PostForm = form
    httpReq.Header.Set("Content-Type", "application/json")
    httpReq.Header.Set("access_key", access_key)
    httpReq.Header.Set("salt", salt)
    httpReq.Header.Set("signature", signature)
    httpReq.Header.Set("timestamp", timestamp)

    resp, err := hc.Do(httpReq)
    if err != nil {
        fmt.Println(err)
        return errors.New(fmt.Sprintf("payment request failed... %v", err))
    }
    bytes, err := httputil.DumpRequest(httpReq, true)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(string(bytes))
    data, err2 := io.ReadAll(resp.Body)
    if err2 != nil {
        fmt.Println(err2)
        return errors.New(fmt.Sprintf("payment body lecture failed... %v", err2))
    }
    fmt.Println(string(data))
    resp.Body.Close()
    // if data.status != "SUCCESS" || data.data.status != "CLO" || data.data.amount != req.Order.Total {
    //  return errors.New(fmt.Sprintf("payment failed... %v", data.status.message))
    // }

非常感谢您阅读我,我不知道该怎么办... 不要犹豫,向我询问更多信息,如果我的英语不好,请见谅!

编辑

使用我的代码出现此错误:Post "https://sandboxapi.rapyd.net/v1/payments": dial tcp: lookup sandboxapi.rapyd.net on [::1]:53: dial udp [::1]:53: connect: cannot assign requested address

并且使用 curl 在详细模式下执行 curl --header "Content-Type: application/json" --request POST --data '{"amount":9.99,"currency":"USD","payment_method":{"type":"us_visa_card","fields":{"number":"4111111111111111","expiration_month":"10","expiration_year":"21","cvv":"123"}},"error_payment_url":"https://error_example.net","capture":true}' -v https://sandboxapi.rapyd.net/v1/payments 我收到:

*   Trying 23.21.18.233...
* TCP_NODELAY set
* Connected to sandboxapi.rapyd.net (23.21.18.233) port 443 (#0)
* schannel: SSL/TLS connection with sandboxapi.rapyd.net port 443 (step 1/3)
* schannel: checking server certificate revocation
* schannel: sending initial handshake data: sending 191 bytes...
* schannel: sent initial handshake data: sent 191 bytes
* schannel: SSL/TLS connection with sandboxapi.rapyd.net port 443 (step 2/3)
* schannel: failed to receive handshake, need more data
* schannel: SSL/TLS connection with sandboxapi.rapyd.net port 443 (step 2/3)
* schannel: encrypted data got 4096
* schannel: encrypted data buffer: offset 4096 length 4096
* schannel: encrypted data length: 4030
* schannel: encrypted data buffer: offset 4030 length 4096
* schannel: received incomplete message, need more data
* schannel: SSL/TLS connection with sandboxapi.rapyd.net port 443 (step 2/3)
* schannel: encrypted data got 1024
* schannel: encrypted data buffer: offset 5054 length 5054
* schannel: encrypted data length: 232
* schannel: encrypted data buffer: offset 232 length 5054
* schannel: received incomplete message, need more data
* schannel: SSL/TLS connection with sandboxapi.rapyd.net port 443 (step 2/3)
* schannel: encrypted data got 115
* schannel: encrypted data buffer: offset 347 length 5054
* schannel: sending next handshake data: sending 126 bytes...
* schannel: SSL/TLS connection with sandboxapi.rapyd.net port 443 (step 2/3)
* schannel: encrypted data got 51
* schannel: encrypted data buffer: offset 51 length 5054
* schannel: SSL/TLS handshake complete
* schannel: SSL/TLS connection with sandboxapi.rapyd.net port 443 (step 3/3)
* schannel: stored credential handle in session cache
> POST /v1/payments HTTP/1.1
> Host: sandboxapi.rapyd.net
> User-Agent: curl/7.55.1
> Accept: */*
> Content-Type: application/json
> Content-Length: 200
>
* upload completely sent off: 200 out of 200 bytes
* schannel: client wants to read 102400 bytes
* schannel: encdata_buffer resized 103424
* schannel: encrypted data buffer: offset 0 length 103424
* schannel: encrypted data got 226
* schannel: encrypted data buffer: offset 226 length 103424
* schannel: decrypted data length: 197
* schannel: decrypted data added: 197
* schannel: decrypted data cached: offset 197 length 102400
* schannel: encrypted data buffer: offset 0 length 103424
* schannel: decrypted data buffer: offset 197 length 102400
* schannel: schannel_recv cleanup
* schannel: decrypted data returned 197
* schannel: decrypted data buffer: offset 0 length 102400
< HTTP/1.1 400 Bad Request
< Date: Wed, 14 Apr 2021 06:16:04 GMT
< Content-Type: text/plain; charset=utf-8
< Content-Length: 11
< Connection: keep-alive
< ETag: W/"b-glZE90e6qywA5CDbvDnksw"
<
Bad Request* Connection #0 to host sandboxapi.rapyd.net left intact

0 个答案:

没有答案