// Copyright 2019 autocareai.com. All rights reserved. // Use of this source code is governed by autocareai.com. package thirdparty import ( "bytes" "crypto/md5" "encoding/base64" "encoding/hex" "encoding/xml" "io/ioutil" "net/http" "smart-thirdparty/errors" "smart-thirdparty/parser" "strings" "time" "github.com/jaryhe/gopkgs/logger" jsoniter "github.com/json-iterator/go" "go.uber.org/zap" ) var json = jsoniter.ConfigCompatibleWithStandardLibrary 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) (err error) { var result *messageCodeResult rl := parser.Conf.ThirdParty.RongLian 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.MarshalToString(sendBody) logger.Error("thirdpary", zap.String("call", "vcodeHttpPost"), zap.String("params", prams), zap.String("error", err.Error())) return errors.VCodeSendFailed } err = xml.Unmarshal(xmlResult, &result) if result != nil && result.StatusCode == "000000" { return nil } else { prams, _ := json.MarshalToString(sendBody) logger.Error("thirdpary", zap.String("call", "vcodeHttpPost"), zap.String("params", prams), zap.String("error", result.StatusMsg)) 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)) }