当前位置: 首页 > 工具软件 > Go Sendcloud > 使用案例 >

sendcloud golang 发送短信 示例代码

顾昊穹
2023-12-01
package main

import (
	"fmt"
	"crypto/md5"
	"encoding/hex"
	"sort"
	"strings"
	"net/url"
	"bytes"
	"net/http"
	"io/ioutil"
)

var urls  = "http://www.sendcloud.net/smsapi/send"
var token = "xxxxxx"

type postData struct {
	MsgType        int    `json:"msgType"`
	Phone          string `json:"phone"`
	SmsUser        string `json:"smsUser"`
	TemplateId     int    `json:"templateId"`
	Vars           string `json:"vars"`
}



func main() {

	postData := map[string]string{
		"msgType":    "0",
		"smsUser":    "xxxx",
		"templateId": "19807",
		"phone":      "xxxxxx",
		"vars":       "{%name%:\"xxxxx\",%rulename%:\"aaaa\",%num%:\"1\"}",
	}
	var keys []string
	for k := range postData {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	param_str := ""
	for _, k := range keys {
		fmt.Println("Key:", k, "Value:", postData[k])
		str := k + "=" + postData[k] + "&"
		param_str += str
	}
	param_str = token  + "&" + param_str + token
	signature := Md5(param_str)
	signature = strings.ToUpper(signature)
	postData["signature"] = signature
	postValues := url.Values{}
	for postKey, PostValue := range postData{
		postValues.Set(postKey, PostValue)
	}
	postDataStr := postValues.Encode()
	postDataBytes := []byte(postDataStr)
	postBytesReader := bytes.NewReader(postDataBytes)
	httpReq, _ := http.NewRequest("POST", urls, postBytesReader)
	httpReq.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	httpClient := &http.Client{}
	httpResp, err := httpClient.Do(httpReq)
	if err != nil {
		fmt.Printf("http get strUrl=%s response error=%s\n", urls, err.Error())
	}
	defer httpResp.Body.Close()
	body, errReadAll := ioutil.ReadAll(httpResp.Body)
	if errReadAll != nil {
		fmt.Printf("get response for strUrl=%s got error=%s\n", urls, errReadAll.Error())
	}
	fmt.Println(string(body))
}


//生成32位md5字串
func Md5(s string) string {
	h := md5.New()
	h.Write([]byte(s))
	return hex.EncodeToString(h.Sum(nil))
}

 

转载于:https://www.cnblogs.com/gaoyawei/p/9914554.html

 类似资料: