package pay import ( "encoding/json" "io/ioutil" "net/http" "strings" "time" "github.com/astaxie/beego" ) var ( callBackNumMap = map[int]int64{ 1: 1, 2: 2, 3: 4, 4: 8, 5: 16, 6: 32, 7: 64, 8: 128, 9: 256, 10: 512, 11: 1024, 12: 2048, } ) func callBackBusinessService(outTradeNo, url string, data interface{}) { body, _ := json.Marshal(data) // callBackResponseData is 业务方回调过来的数据 type callBackResponseData struct { Code int Message string Data interface{} } number := 1 for { client := &http.Client{} req, err := http.NewRequest(http.MethodPost, url, strings.NewReader(string(body))) req.Header.Set("Content-Type", "application/json") resp, err := client.Do(req) if err != nil { beego.Error("网络请求错误") second := callBackNumMap[number] timeSleep := float64(time.Second) * float64(second) number++ beego.Info("当前等待: ", number, "订单号: ", outTradeNo) time.Sleep(time.Duration(int64(timeSleep))) continue } bodyResp, err := ioutil.ReadAll(resp.Body) beego.Info("bodyResp: ", string(bodyResp)) if err != nil { beego.Error("从 业务方 response sbody中取数据失败") second := callBackNumMap[number] timeSleep := float64(time.Second) * float64(second) number++ beego.Info("当前等待: ", number, "订单号: ", outTradeNo) time.Sleep(time.Duration(int64(timeSleep))) continue } resp.Body.Close() // 解析业务方数据 businessResp := new(callBackResponseData) if err := json.Unmarshal(bodyResp, businessResp); err != nil { beego.Error("解析业务方返回的数据失败", string(bodyResp)) return } if businessResp.Code == 0 || businessResp.Message == "SUCCESS" { beego.Info("回调业务方成功: ", "订单号: ", outTradeNo, "回调了%v次", number) return } if number >= 12 { beego.Info("当前等待: ", number, "订单号: ", outTradeNo, "结束回调") return } second := callBackNumMap[number] timeSleep := float64(time.Second) * float64(second) beego.Info("当前等待: ", number, "订单号: ", outTradeNo) number++ time.Sleep(time.Duration(int64(timeSleep))) } }