gosdk/push/getui_sms.go

105 lines
2.5 KiB
Go

package push
import (
"encoding/json"
"errors"
"fmt"
"git.u8t.cn/open/gosdk/util"
log "github.com/sirupsen/logrus"
"github.com/smbrave/goutil"
"github.com/spf13/cast"
"time"
)
type GetuiSms struct {
appid string
appkey string
masterSecret string
templateId string
token string
}
func NewGetuiSms(appid, appkey, masterSecret, templateId string) *GetuiSms {
return &GetuiSms{
appkey: appkey,
appid: appid,
masterSecret: masterSecret,
templateId: templateId,
}
}
func (g *GetuiSms) getResult(rspBody []byte) (map[string]interface{}, error) {
result := make(map[string]interface{})
if err := json.Unmarshal(rspBody, &result); err != nil {
log.Errorf("json[%s] error :%s", string(rspBody), err.Error())
return nil, err
}
code := cast.ToInt(result["result"])
data := cast.ToStringMap(result["data"])
if code == 20000 {
return data, nil
}
if code != 0 {
log.Errorf("json[%s] rsp error", string(rspBody))
return nil, errors.New(string(rspBody))
}
return data, nil
}
func (g *GetuiSms) Token() string {
timestamp := cast.ToString(time.Now().UnixMilli())
signStr := fmt.Sprintf("%s%s%s", g.appkey, timestamp, g.masterSecret)
reqUrl := "https://openapi-smsp.getui.com/v1/sps/auth_sign"
params := make(map[string]string)
params["timestamp"] = timestamp
params["appId"] = g.appid
params["sign"] = util.Sha256(signStr)
reqBody, _ := json.Marshal(params)
rspBody, err := HttpPostJson(reqUrl, nil, reqBody)
if err != nil {
log.Errorf("http post [%s] error :%s", string(reqBody), err.Error())
return ""
}
result, err := g.getResult(rspBody)
if err != nil {
log.Errorf("get Result error :%s", err.Error())
return ""
}
token := cast.ToString(result["authToken"])
g.token = token
return g.token
}
func (g *GetuiSms) Send(phone string, data map[string]string) error {
reqUrl := "https://openapi-smsp.getui.com/v1/sps/push_sms_list"
params := make(map[string]interface{})
params["authToken"] = g.Token()
params["appId"] = g.appid
params["smsTemplateId"] = g.templateId
params["smsParam"] = data
params["recNum"] = []string{goutil.Md5(phone)}
reqBody, _ := json.Marshal(params)
rspBody, err := HttpPostJson(reqUrl, nil, reqBody)
if err != nil {
log.Errorf("http post [%s] error :%s", string(reqBody), err.Error())
return err
}
fmt.Println(string(reqBody), string(rspBody))
_, err = g.getResult(rspBody)
if err != nil {
log.Errorf("get Result error :%s", err.Error())
return err
}
return nil
}