package services import ( "bytes" "encoding/json" "eta/eta_mini_api/utils" "fmt" "io" "io/ioutil" "net/http" "net/url" ) func SendSmsCode(mobile, verifyCode string) (sendOk bool, result string, err error) { defer func() { if err != nil { tips := fmt.Sprintf("SendSmsCode err: %v, result: %s", err, result) utils.FileLog.Info(tips) } }() tplId := utils.SMS_TPLID if tplId == "" { tplId = "262642" } expiresTime := "15" postResult, e := sendSms(mobile, tplId, verifyCode, expiresTime) if e != nil { err = fmt.Errorf("post sms err: %v", e) return } result = string(postResult) var netReturn map[string]interface{} if e = json.Unmarshal(postResult, &netReturn); e != nil { err = fmt.Errorf("result unmarshal err: %v", e) return } errCode, ok := netReturn["error_code"].(float64) if !ok { err = fmt.Errorf("err code err") return } if errCode != 0 { err = fmt.Errorf("短信验证码发送失败") return } sendOk = true return } func sendSms(mobile, tplId, code, expirdTime string) (rs []byte, err error) { var Url *url.URL apiURL := "http://v.juhe.cn/sms/send" //初始化参数 param := url.Values{} //配置请求参数,方法内部已处理urlencode问题,中文参数可以直接传参 param.Set("mobile", mobile) //接受短信的用户手机号码 param.Set("tpl_id", tplId) //您申请的短信模板ID,根据实际情况修改 param.Set("tpl_value", "#code#="+code+"&"+"#m#="+expirdTime) //您设置的模板变量,根据实际情况 param.Set("key", utils.JhGnAppKey) //应用APPKEY(应用详细页查询) Url, err = url.Parse(apiURL) if err != nil { fmt.Printf("解析url错误:\r\n%v", err) return nil, err } //如果参数中有中文参数,这个方法会进行URLEncode Url.RawQuery = param.Encode() resp, err := http.Get(Url.String()) if err != nil { fmt.Println("err:", err) return nil, err } defer resp.Body.Close() return ioutil.ReadAll(resp.Body) } const ( SmsApiServiceProviderDefault = "1" // 默认短信服务商-金慧盈通 ) type SmsApiPars struct { PhoneList []string `json:"phonelist" description:"收信手机号码,最多50个一次"` ServiceProvider string `json:"serviceprovider" description:"短信服务提供商:1-金慧盈通;2-高斯通"` SmsContent string `json:"smscontent" description:"短信内容"` Sender string `json:"sender" description:"发送人"` Department string `json:"department" description:"发送人部门"` Purpose string `json:"purpose" description:"用途"` } func PostSmsApi(params SmsApiPars) (result string, err error) { requestUrl := utils.SmsApiUrl if requestUrl == "" { err = fmt.Errorf("短信API地址未配置") return } jsonData, e := json.Marshal(params) if e != nil { err = fmt.Errorf("json marshal err: %v", e) return } resp, e := http.Post(requestUrl, "application/json", bytes.NewBuffer(jsonData)) if e != nil { err = fmt.Errorf("http post err: %v", e) return } defer resp.Body.Close() body, e := io.ReadAll(resp.Body) if e != nil { err = fmt.Errorf("read body err: %v", e) return } result = string(body) return }