Created
June 24, 2018 12:21
-
-
Save hallazzang/5c37705eca80802e7b20f921ce89e99e to your computer and use it in GitHub Desktop.
[Go] Send SMS message with CoolSMS API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/hmac" | |
"crypto/md5" | |
"crypto/rand" | |
"encoding/hex" | |
"encoding/json" | |
"errors" | |
"fmt" | |
"net/http" | |
"net/url" | |
"strconv" | |
"time" | |
) | |
// put your api key and secret | |
// https://www.coolsms.co.kr/index.php?mid=service_setup&act=dispSmsconfigCredential | |
const ( | |
apiKey = "" | |
apiSecret = "" | |
) | |
func sendSMS(to, from, text string) (bool, error) { | |
var b []byte | |
// get unix timestamp | |
ts := strconv.Itoa(int(time.Now().Unix())) | |
// generate salt (length of 5~30) | |
b = make([]byte, 30) | |
if _, err := rand.Read(b); err != nil { | |
return false, err | |
} | |
salt := string(b) | |
// HMAC hash | |
h := hmac.New(md5.New, []byte(apiSecret)) | |
h.Write([]byte(ts + salt)) | |
sig := hex.EncodeToString(h.Sum(nil)) | |
// call API | |
data := url.Values{ | |
// authentication information | |
"api_key": {apiKey}, | |
"timestamp": {ts}, | |
"salt": {salt}, | |
"signature": {sig}, | |
// send parameters | |
"to": {to}, | |
"from": {from}, | |
"text": {text}, | |
} | |
resp, err := http.PostForm("https://api.coolsms.co.kr/sms/2/send", data) | |
if err != nil { | |
return false, err | |
} | |
defer resp.Body.Close() | |
var r struct { | |
GroupID string `json:"group_id"` | |
SuccessCount int `json:"success_count"` | |
ErrorCount int `json:"error_count"` | |
} | |
if err := json.NewDecoder(resp.Body).Decode(&r); err != nil { | |
return false, err | |
} | |
if r.SuccessCount == 0 { | |
return false, errors.New("sms send failed") | |
} | |
return true, nil | |
} | |
func main() { | |
// sender's phone number must be registered first | |
// https://www.coolsms.co.kr/index.php?mid=service_setup&act=dispSmsconfigSenderNumbers | |
fmt.Println(sendSMS("sms to", "sms from", "content")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment