package main
import (
"bytes"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"sort"
"time"
"math/rand"
"strconv"
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
)
func random(min, max int) int {
rand.Seed(time.Now().Unix())
randNum := rand.Intn(max - min) + min
return randNum
}
func postData(apiUrl string, data url.Values) string {
res, err := http.PostForm(apiUrl, data)
if err != nil {
return err.Error()
}
defer res.Body.Close()
result, _ := ioutil.ReadAll(res.Body)
return string(result)
}
func main() {
apiUrl := "https://api.yisu.com/sms/sendSms"
accessId := "*****"
accessSecret := "*****"
vars, _ := json.Marshal(map[string]string{"code":"123123","min":"5"})
params := make(url.Values)
params["accessId"] = []string{accessId}
params["nonce"] = []string{strconv.Itoa(random(10000000, 99999999))} // 随机数
params["timestamp"] = []string{strconv.Itoa(int(time.Now().Unix()))} // 时间戳
params["phone"] = []string{"13800000000"} // 手机号码
params["templateCode"] = []string{"100001"} // 模板号码
params["templateVars"] = []string{string(vars)} // 模板变量
var buf bytes.Buffer
keys := make([]string, 0, len(params))
for k, _ := range params {
keys = append(keys, k)
}
sort.Strings(keys)
for i := range keys {
k := keys[i]
buf.WriteString(k)
buf.WriteString("=")
buf.WriteString(params.Get(k))
buf.WriteString("&")
}
buf.Truncate(buf.Len() - 1)
hashed := hmac.New(sha1.New, []byte(accessSecret))
hashed.Write(buf.Bytes())
params["signature"] = []string{base64.StdEncoding.EncodeToString(hashed.Sum(nil))} // 签名
result := postData(apiUrl, params)
fmt.Println(result)
}