- 网易云发送短信
package main
import (
"crypto/sha1"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"strconv"
"strings"
"time"
)
const (
// 发送验证码的请求路径url
ServerUrl = "https://api.netease.im/sms/sendcode.action"
// 网易云分配的账号,替换申请的appkey
AppKey = ``
// 网易云分配的密钥,替换申请的appSecret
AppSecret = ``
// 接收人手机号
Mobile = ``
// 验证码长度,范围4-10,默认4
CodeLen = "6"
// 短信模板id
templateId = ``
)
func SendNetEaseTemplateMessage() (string,error) {
var r http.Request
r.ParseForm()
r.Form.Add("mobile", Mobile)
r.Form.Add("templateid", templateId)
r.Form.Add("codeLen", CodeLen)
bodyStr := strings.TrimSpace(r.Form.Encode())
client := http.Client{}
req, err := http.NewRequest("POST", ServerUrl, strings.NewReader(bodyStr))
if err != nil {
return "",err
}
nonce := RandIntRunes()
// 当前时间
currentTime := fmt.Sprintf("%d",time.Now().Unix())
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("AppKey", AppKey)
req.Header.Set("CurTime", currentTime)
req.Header.Set("Nonce", nonce)
hash := sha1.New()
hash.Write([]byte(fmt.Sprintf("%s%s%s", AppSecret, nonce, currentTime)))
checksum := hex.EncodeToString(hash.Sum(nil))
req.Header.Set("CheckSum", checksum)
resp, err := client.Do(req)
if err != nil {
return "",err
}
bytes, err := ioutil.ReadAll(resp.Body)
respData := map[string]interface{}{}
err = json.Unmarshal(bytes, &respData)
if err != nil {
return "", err
}
return respData["obj"].(string), nil
}
//获得随机字符串
func RandIntRunes() string {
i := rand.New(rand.NewSource(time.Now().UnixNano())).Int()
str := strconv.Itoa(i)
sli := str[:6]
return sli
}
func main() {
SendNetEaseTemplateMessage()
}