113 lines
2.6 KiB
Go
113 lines
2.6 KiB
Go
package sms
|
||
|
||
import (
|
||
"fmt"
|
||
"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
|
||
"github.com/gin-gonic/gin"
|
||
"gorm.io/gorm"
|
||
"health-go/config"
|
||
"health-go/models"
|
||
"math/rand"
|
||
"net/http"
|
||
"strconv"
|
||
"time"
|
||
)
|
||
|
||
func Request(c *gin.Context) {
|
||
var user struct {
|
||
Tel string `json:"tel"`
|
||
}
|
||
if err := c.ShouldBindJSON(&user); err != nil {
|
||
c.JSON(http.StatusBadRequest, gin.H{
|
||
"code": 400,
|
||
"msg": "无效的请求参数",
|
||
"data": nil,
|
||
})
|
||
return
|
||
}
|
||
if PreValidate(user.Tel) == "notExist" {
|
||
c.JSON(http.StatusOK, gin.H{
|
||
"code": 200,
|
||
"data": nil,
|
||
"msg": "用户不存在, 正在注册"})
|
||
register(user.Tel)
|
||
return
|
||
}
|
||
|
||
if PreValidate(user.Tel) == "reachLimit" {
|
||
c.JSON(http.StatusOK, gin.H{
|
||
"code": 200,
|
||
"data": nil,
|
||
"msg": "已达到发送上限"})
|
||
return
|
||
}
|
||
|
||
if PreValidate(user.Tel) == "ok" {
|
||
config.DB.Table("user").Where("tel = ?", user.Tel).Update("SMS_try",
|
||
gorm.Expr("SMS_try + ?", 1))
|
||
code := GenerateCode()
|
||
callBack := SendMsg(user.Tel, code)
|
||
if callBack == "success" {
|
||
config.RDC.Set(config.CTX, user.Tel, code, 5*time.Minute)
|
||
c.JSON(http.StatusOK, gin.H{
|
||
"code": 200,
|
||
"data": nil,
|
||
"msg": "验证码已发送"})
|
||
return
|
||
} else if callBack == "frequency_limit" {
|
||
c.JSON(http.StatusOK, gin.H{
|
||
"code": 200,
|
||
"data": nil,
|
||
"msg": "服务端发送频率限制",
|
||
})
|
||
return
|
||
} else {
|
||
|
||
}
|
||
}
|
||
|
||
}
|
||
|
||
func SendMsg(tel string, code string) string {
|
||
client, err := dysmsapi.NewClientWithAccessKey(
|
||
"cn-hangzhou",
|
||
"LTAI5tAYdQcmbGAAiMhGs8sT",
|
||
"PU5WmUbAOsSQ8lQNTMPMD170ONxBLl")
|
||
request := dysmsapi.CreateSendSmsRequest()
|
||
request.Scheme = "https"
|
||
request.PhoneNumbers = tel //手机号变量值
|
||
request.SignName = "Biter健康助手" //签名
|
||
request.TemplateCode = "SMS_472460337" //模板编码
|
||
request.TemplateParam = "{\"code\":\"" + code + "\"}"
|
||
response, err := client.SendSms(request)
|
||
// Aliyun SMS API callback response code
|
||
fmt.Println(response.Code)
|
||
if response.Code == "isv.BUSINESS_LIMIT_CONTROL" {
|
||
return "frequency_limit"
|
||
}
|
||
if err != nil {
|
||
fmt.Print(err.Error())
|
||
return "send failed: " + err.Error()
|
||
}
|
||
return "success"
|
||
}
|
||
|
||
// GenerateCode 生成6位随机验证码
|
||
func GenerateCode() string {
|
||
rand.NewSource(time.Now().UnixNano())
|
||
code := rand.Intn(899999) + 100000
|
||
res := strconv.Itoa(code)
|
||
return res
|
||
}
|
||
|
||
// 注册
|
||
func register(userTel string) {
|
||
user := models.User{Tel: userTel}
|
||
// 写入数据库,用户ID自增
|
||
if err := config.DB.Select("tel").Create(&user).Error; err != nil {
|
||
fmt.Println("register error:", err)
|
||
return
|
||
}
|
||
fmt.Println("register success for", userTel)
|
||
}
|