写的比较粗糙,有错误的地方希望指正,不会英语,部分变量用拼音命名,打扰了
package sendmsg
import (
"bytes"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
const (
ak = "xxxxxxx"
sk = "xxxxxxx"
requestURL = "http://dysmsapi.aliyuncs.com/?Signature="
actionStr = "&Action=SendSms&Format=JSON&OutId=123"
dateStr = "&Version=2017-05-25"
msgTemplete = "&SignatureVersion=1.0&TemplateCode=模板ID&TemplateParam="
singStr = "&SignatureMethod=HMAC-SHA1&SignatureNonce="
singName = "&RegionId=cn-hangzhou&SignName="
lianJIe = "&"
signLinaJie = "GET&%2F&"
)
//SimpleMessage ...
type SimpleMessage struct {
Message string `json:"Message"`
Code string `json:"Code"`
}
//MessageContent ...
type MessageContent struct {
Code string `json:"code"`
}
//SendMsg 发送短信
func SendMsg(phone, msgJSON string) bool {
body := "send msg"
content := url.QueryEscape(msgJSON)
signString := setQueryStr(phone, content, “skw493jei3j34ij34i”)
singstr := signLinaJie + url.QueryEscape(signString)
sign := hmac4Go(singstr, sk+lianJIe)
client := &http.Client{}
var req *http.Request
req, err = http.NewRequest("GET", requestURL+url.QueryEscape(sign)+lianJIe+signString, strings.NewReader(body))
var resp *http.Response
resp, err = client.Do(req)
if err != nil {
fmt.Println("http get error.", err)
return false
}
fmt.Println(resp.Body)
defer resp.Body.Close()
var bodys []byte
bodys, err = ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("http readAll body error ", err)
return false
}
fmt.Println(string(bodys))
var msg SimpleMessage
if len(bodys) > 0 {
err = json.Unmarshal(bodys, &msg)
if err != nil {
fmt.Println("http json body error ", err)
return false
}
fmt.Println(msg)
}
if msg.Code == "OK" {
return true
}
return false
}
//setQueryStr 设置查询请求
func setQueryStr(phone, content string, id int64) string {
var cstZone = time.FixedZone("GMT", 0)
keyTime := time.Now().In(cstZone).Format("2006-01-02T15:04:05Z")
singNameS := url.QueryEscape("SignName")
buf := bytes.Buffer{}
buf.WriteString("AccessKeyId=")
buf.WriteString(ak)
buf.WriteString(actionStr)
buf.WriteString("&PhoneNumbers=")
buf.WriteString(phone + singName + singNameS + singStr)
buf.WriteString(strconv.FormatInt(id, 10) + msgTemplete + content)
buf.WriteString("&Timestamp=" + url.QueryEscape(keyTime) + dateStr)
signString := buf.String()
return signString
}
//hmac4Go 加密
func hmac4Go(name, sk string) string {
mac := hmac.New(sha1.New, []byte(sk))
mac.Write([]byte(name))
encodeString := base64.StdEncoding.EncodeToString(mac.Sum(nil))
return encodeString
}
有疑问加站长微信联系(非本文作者)