sendcloud golang 发送短信 示例代码

Posted gaoyawei

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sendcloud golang 发送短信 示例代码相关的知识,希望对你有一定的参考价值。

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
", 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
", 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 发送短信 示例代码的主要内容,如果未能解决你的问题,请参考以下文章

短信平台收集及选择

golang sms阿里云发送短信(公司实际项目)

并发之消息队列----基于AMQP实现的golang消息队列MaxQ

Django--短信验证码

各大APP注册时发送短信验证码是怎么实现的?

验证码短信 API 接入指南:Java 语言示例代码