package thirdparty import ( "bytes" "crypto/md5" "gd_management/common.in/config" "gd_management/errors" "encoding/base64" "encoding/hex" "encoding/json" "encoding/xml" "io/ioutil" "net/http" "strings" "time" "go.uber.org/zap" ) type messageCodeResult struct { StatusCode string `xml:"statusCode"` StatusMsg string `xml:"statusMsg"` templateSMS `xml:"TemplateSMS"` } type templateSMS struct { SmsMessageSid string `xml:"smsMessageSid"` DateCreated string `xml:"dateCreated"` } //构建容联云短信验证码请求体 func SendTemplateSMS(to string, data []interface{}, templateId int, rl config.RongLianNode) (err error) { var result *messageCodeResult sendBody := map[string]interface{}{ "to": to, "templateId": templateId, "appId": rl.RongLianAppId, "datas": data, } //获取时间戳 yyyymmddHHiiss signTime := time.Now().Format("20060102150405") //签名生成(大写) sign := strings.ToUpper(md5Encrypt(rl.RongLianSid + rl.RongLianToken + signTime)) url := "https://" + rl.RongLianServerIp + ":" + rl.RongLianServerPort + "/" + rl.RongLianSoftVersion + "/Accounts/" + rl.RongLianSid + "/SMS/TemplateSMS?sig=" + sign //生成验证header authen := base64.URLEncoding.EncodeToString([]byte(rl.RongLianSid + ":" + signTime)) //请求数据 xml xmlResult, err := vcodeHttpPost(url, sendBody, authen) if err != nil { prams, _ := json.Marshal(sendBody) l.Error("thirdpary", zap.String("call", "vcodeHttpPost"), zap.String("params", string(prams)), zap.String("error", err.Error())) return errors.VCodeSendFailed } err = xml.Unmarshal(xmlResult, &result) if result != nil && result.StatusCode == "000000" { return nil } else { if result.StatusCode == "160040" { return errors.VCodeOutOfLimit } prams, _ :=json.Marshal(sendBody) //prams, _ := json.MarshalToString(sendBody) s, _ := json.Marshal(result) l.Error("thirdpary", zap.String("call", "vcodeHttpPost"), zap.String("params", string(prams)), zap.String("result", string(s))) return errors.VCodeSendFailed } } //请求第三方接口 func vcodeHttpPost(url string, data map[string]interface{}, authen string) (body []byte, err error) { bytesData, err := json.Marshal(data) if err != nil { return nil, err } reader := bytes.NewReader(bytesData) request, err := http.NewRequest("POST", url, reader) if err != nil { return nil, err } request.Header.Set("Content-Type", "application/json;charset=UTF-8") request.Header.Set("Authorization", authen) client := http.Client{} resp, err := client.Do(request) if err != nil { return nil, err } defer resp.Body.Close() respBytes, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } return respBytes, nil } func md5Encrypt(str string) string { h := md5.New() h.Write([]byte(str)) return hex.EncodeToString(h.Sum(nil)) }