以下是一个简单的使用腾讯云短信服务发送短信的 Go 代码实现:

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "net/url"
    "strconv"
    "strings"
    "time"
)

const (
    appID     = "your_app_id"
    appKey    = "your_app_key"
    sign      = "your_sign"
    template  = "your_template_id"
    smsAPIURL = "https://yun.tim.qq.com/v5/tlssmssvr/sendsms"
)

type smsResponse struct {
    Result int    `json:"result"`
    Errmsg string `json:"errmsg"`
    Sid    string `json:"sid"`
}

func sendSMS(mobile string, code int) error {
    params := url.Values{}
    params.Set("sdkappid", appID)
    params.Set("random", strconv.FormatInt(time.Now().Unix(), 10))
    params.Set("time", strconv.FormatInt(time.Now().Unix(), 10))

    phoneNumbers := []string{"86" + mobile}
    phoneNumbersJSON, _ := json.Marshal(phoneNumbers)
    params.Set("mobile", string(phoneNumbersJSON))

    smsSign := sign
    smsSignJSON, _ := json.Marshal(smsSign)
    params.Set("sign", string(smsSignJSON))

    smsTemplate := template
    smsTemplateJSON, _ := json.Marshal(smsTemplate)
    params.Set("tpl_id", string(smsTemplateJSON))

    smsParams := []string{strconv.Itoa(code)}
    smsParamsJSON, _ := json.Marshal(smsParams)
    params.Set("params", string(smsParamsJSON))

    signParams := appKey + "&" + params.Encode()
    sign := fmt.Sprintf("%x", hmacSHA256(signParams, []byte(appKey)))

    req, _ := http.NewRequest("POST", smsAPIURL, strings.NewReader(params.Encode()))
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    req.Header.Set("Authorization", sign)

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return err
    }
    defer resp.Body.Close()

    var result smsResponse
    err = json.NewDecoder(resp.Body).Decode(&result)
    if err != nil {
        return err
    }

    if result.Result != 0 {
        return fmt.Errorf("send sms error: %s", result.Errmsg)
    }

    return nil
}

func hmacSHA256(data string, key []byte) []byte {
    h := hmac.New(sha256.New, key)
    h.Write([]byte(data))
    return h.Sum(nil)
}

func main() {
    err := sendSMS("your_mobile_number", 123456)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("sms sent successfully")
    }
}

请注意,在这个示例中,您需要将变量 your_app_idyour_app_keyyour_signyour_template_id 替换为您自己的腾讯云短信服务的应用 ID、应用 Key、短信签名和短信模板 ID。同时,您需要将 your_mobile_number 替换为您要发送短信的手机号码。

golang 简单的sms 腾讯短信发送代码

原文地址: https://www.cveoy.top/t/topic/vC6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录