简介

代码

package main

import (
	"fmt"
	"github.com/alibabacloud-go/darabonba-openapi/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v2/client"
	"math/rand"
	"strings"
	"time"
)

func main() {
	accessKeyId := "你的accessKeyId"
	accessKeySecret := "你的accessKeySecret "
	endpoint := "dysmsapi.aliyuncs.com"
	c := &client.Config{AccessKeyId: &accessKeyId, AccessKeySecret: &accessKeySecret, Endpoint: &endpoint}

	newClient, err := dysmsapi20170525.NewClient(c)
	if err != nil {
		panic(err)
	}
	phoneNumber := "要发送的手机号"
	templateCode := "SMS_154950909"
	signName := "阿里云短信测试"
	code := "{\"code\":" + GenerateSmsCode(6) + "}"
	request := &dysmsapi20170525.SendSmsRequest{
		PhoneNumbers:  &phoneNumber,
		TemplateCode:  &templateCode,
		SignName:      &signName,
		TemplateParam: &code,
	}
	sms, err := newClient.SendSms(request)
	if err != nil {
		panic(err)
	}
	fmt.Println(sms)
}

// GenerateSmsCode 生成验证码;length代表验证码的长度
func GenerateSmsCode(length int) string {
	numberic := [10]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	rand.Seed(time.Now().Unix())
	var sb strings.Builder
	for i := 0; i < length; i++ {
		fmt.Fprintf(&sb, "%d", numberic[rand.Intn(len(numberic))])
	}
	return sb.String()
}

返回的sms

{
   "headers": {
      "access-control-allow-headers": "X-Requested-With, X-Sequence, _aop_secret, _aop_signature, x-acs-action, x-acs-version, x-acs-date, Content-Type",
      "access-control-allow-methods": "POST, GET, OPTIONS, PUT, DELETE",
      "access-control-allow-origin": "*",
      "access-control-max-age": "172800",
      "connection": "keep-alive",
      "content-length": "110",
      "content-type": "application/json;charset=utf-8",
      "date": "Sun, 12 Jun 2022 02:15:49 GMT",
      "x-acs-request-id": "6BC0AE17-B50A-5B0F-B5BF-10AEDC602909",
      "x-acs-trace-id": "fc4f2bf6ec8a9f9541103cfa0395c47a"
   },
   "body": {
      "BizId": "361607455000149340^0",
      "Code": "OK",
      "Message": "OK",
      "RequestId": "6BC0AE17-B50A-5B0F-B5BF-10AEDC602909"
   }
}