sms.go
2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package service
import (
"fmt"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/common"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/redis"
protocol "openapi/pkg/domain"
"openapi/pkg/infrastructure/sms"
"openapi/pkg/infrastructure/sms/yunpian"
"strings"
)
// SmsCode 发送短信验证码
func SmsCode(header *protocol.RequestHeader, request *protocol.SmsCodeRequest) (rsp interface{}, err error) {
code := common.RandomStringWithChars(6, protocol.Nums)
var smsSvr sms.ISmsService = &yunpian.YPSmsService{}
content := fmt.Sprintf("【买买买信息科技】%v(手机验证码,请完成验证),如非本人操作,请忽略本短信", code)
// save log to db
log.Debug(fmt.Sprintf("【sms】 smscode phone:%v code:%v", request.Phone, code))
// save to redis
if err = redis.Set(smsRedisKey(request.Phone), code, sms.DefaultSmsCodeTimeOut); err != nil {
logError(err)
err = protocol.NewCustomMessage(1001, "请求超时,请检查手机号是否正确或网络连接状态")
return nil, err
}
if err = smsSvr.Send(&sms.Options{Phone: request.Phone, SendType: sms.SendSingle, Content: content}); err != nil {
logError(err)
err = protocol.NewCustomMessage(1001, "请求超时,请检查手机号是否正确或网络连接状态")
return nil, err
}
return
}
// CheckSmsCode 检查短信验证码
func CheckSmsCode(header *protocol.RequestHeader, request *protocol.CheckSmsCodeRequest) (rsp interface{}, err error) {
var value string
if value, err = redis.Get(smsRedisKey(request.Phone)); err != nil || len(value) == 0 {
logError(err)
err = protocol.NewCustomMessage(1004, "验证码已失效")
return nil, err
}
if !strings.EqualFold(value, request.Code) {
err = protocol.NewCustomMessage(1004, "验证码错误,重新输入")
return nil, err
}
redis.Del(smsRedisKey(request.Phone))
return
}
// SendSmsNotice 发送短信通知
func SendSmsNotice(header *protocol.RequestHeader, request *protocol.SendSmsNoticeRequest) (rsp interface{}, err error) {
var smsSvr sms.ISmsService = &yunpian.YPSmsService{}
options := sms.NewOptions(
sms.WithPhone(request.Phone),
sms.WithSendType(sms.SendSingleByTpl),
sms.WithTpl(request.TplId, request.TplValues),
)
err = smsSvr.Send(options)
return
}
func logError(err error) {
log.Error(fmt.Sprintf("【sms】 %v", err.Error()))
}
func smsRedisKey(phone string) string {
return strings.Join([]string{"sms", "smscode", phone}, ":")
}