码迷,mamicode.com
首页 > 其他好文 > 详细

sendcloud golang 发送短信 示例代码

时间:2018-11-06 13:26:00      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:msu   head   pen   pos   bytes   UNC   http   str   temp   

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))
}

 

sendcloud golang 发送短信 示例代码

标签:msu   head   pen   pos   bytes   UNC   http   str   temp   

原文地址:https://www.cnblogs.com/gaoyawei/p/9914554.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!