Sms.go 2.34 KB
package Api

import (
	"encoding/json"
	"github.com/aarongao/tools"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
	"github.com/gin-gonic/gin"
	"letu/DB"
	"letu/Lib"
	"time"
)

// @Title 发送短信验证码
// @Description 发送短信验证码
// @Accept  json
// @Produce  json
// @Param   Mobile     18616619599    string     true        "手机号"
// @Param   Location     {"Latitude": 119, "Longitude": 39}    string     true        "位置"
// @Success 200 {object} tools.ResponseSeccess "{"errcode":0,"result":"ok"}验证码3分钟内有效"
// @Failure 500 {object} tools.ResponseError "{"errcode":1,"errmsg":"错误原因"}"
// @Router /Sms/Send? [post]
func Send(c *gin.Context) {
	c.Header("Access-Control-Allow-Origin", c.Request.Header.Get("Origin"))
	c.Header("Access-Control-Allow-Credentials", "true")

	if c.PostForm("Mobile") == "" {
		c.JSON(200, tools.ResponseError{
			1,
			"手机号不正确",
		})
		return
	}
	if c.PostForm("Location") == "" {
		c.JSON(200, tools.ResponseError{
			1,
			"缺少位置信息",
		})
		return
	}

	cacheCode := DB.Redis.Get(c.PostForm("Mobile"))
	if cacheCode != nil {
		c.JSON(200, tools.ResponseError{
			1,
			"code没有过期",
		})
		return
	}

	code := Lib.SmsCode(6)

	client, err := dysmsapi.NewClientWithAccessKey("cn-hangzhou", "LTAI4FdQeNMQXRU6u5J3EFQc", "PwvyF5rRNBWLDya41WrCpvENevYZGi")

	request := dysmsapi.CreateSendSmsRequest()
	request.Scheme = "https"

	request.PhoneNumbers = c.PostForm("Mobile")
	request.SignName = "乐游图"
	request.TemplateCode = "SMS_182595013"
	request.TemplateParam = "{\"code\":\"" + string(code) + "\"}"

	response, err := client.SendSms(request)
	var reserr string
	if err != nil {
		println(err.Error())
		reserr = err.Error()
	} else {
		reserr = response.Code
		if response.Code == "OK" {
			DB.Redis.Set(c.PostForm("Mobile"), code, time.Second*60*3)
		}
	}

	var Location DB.SLocation
	json.Unmarshal([]byte(c.PostForm("Location")), &Location)

	//go func(res *dysmsapi.SendSmsResponse) {
	DB.CActionLog.Insert(DB.SActionLog{
		"",
		"",
		c.PostForm("Mobile"),
		1,
		"注册验证码",
		time.Now().Unix(),
		Location,
		string(code),
		reserr,
	})
	//}(response)

	if response.Code == "OK" {

		c.JSON(200, tools.ResponseSeccess{
			0,
			"ok",
		})
	} else {

		c.JSON(200, tools.ResponseSeccess{
			1,
			"验证码发送失败",
		})
	}
}

func CreateAccessLog() {

}