admin
2021-04-03 32d6c2ea8039b4771fd6b1ded8b022733e32352f
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
package com.yeshi.buwan.service.imp;
 
import com.github.qcloudsms.SmsSingleSenderResult;
import com.yeshi.buwan.dto.config.TencentSMSConfig;
import com.yeshi.buwan.exception.SMSException;
import com.yeshi.buwan.service.inter.SMSService;
import com.yeshi.buwan.util.Constant;
import com.yeshi.buwan.util.RedisKeyEnum;
import com.yeshi.buwan.util.RedisManager;
import com.yeshi.buwan.util.StringUtil;
import org.springframework.stereotype.Service;
import org.yeshi.utils.sms.TencentSMSUtil;
 
import javax.annotation.Resource;
 
@Service
public class SMSServiceImpl implements SMSService {
 
    @Resource
    private RedisManager redisManager;
 
    @Override
    public void sendBindVCode(String uid, String phone, int codeLength) throws SMSException {
        String limitKey = RedisKeyEnum.getRedisKey(RedisKeyEnum.SMSLIMIT, uid + "");
        String key = RedisKeyEnum.getRedisKey(RedisKeyEnum.SMSVCode, phone + "-" + 0);
        if (!StringUtil.isNullOrEmpty(redisManager.getCommonString(limitKey)))
            throw new SMSException(1001, "请过60秒再试");
 
 
        String msgCode = StringUtil.getNumberVerifyCode(codeLength);
 
        TencentSMSConfig tencentSMSConfig = Constant.tencentSMSConfig;
 
        // 验证码模板
        String msg = tencentSMSConfig.getContentBind().replace("[签名]", tencentSMSConfig.getSign()).replace("[验证码]",
                msgCode);
        SmsSingleSenderResult result = TencentSMSUtil.sendSingleMsg(Integer.parseInt(tencentSMSConfig.getAppId()), tencentSMSConfig.getAppKey(), phone, msg);
        if (result == null)
            throw new SMSException(2, "短信发送失败");
        if (result.result == 1025) {
            throw new SMSException(result.result, "今日验证码发送超限,请明日再试");
        } else if (result.result != 0) {// 发送失败
            throw new SMSException(result.result, "短信发送失败");
        }
        //保存验证码
        redisManager.cacheCommonString(key, msgCode, 60 * 5);
        //60s后再发送
        redisManager.cacheCommonString(limitKey, "1", 60);
    }
 
    @Override
    public boolean verifyBindVCode(String phone, String code) {
        String key = RedisKeyEnum.getRedisKey(RedisKeyEnum.SMSVCode, phone + "-" + 0);
        String cacheCode = redisManager.getCommonString(key);
        if (cacheCode != null && cacheCode.equalsIgnoreCase(code)) {
            redisManager.removeCommonString(key);
            return true;
        }
        return false;
    }
}