yangys
2024-05-18 040976de6f9934b99f30268a28e2ecf42260e217
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
package com.qianwen.core.sms;
 
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.sms.SmsManager;
import java.time.Duration;
import java.util.Collection;
import com.qianwen.core.redis.cache.BladeRedis;
import com.qianwen.core.sms.model.SmsCode;
import com.qianwen.core.sms.model.SmsData;
import com.qianwen.core.sms.model.SmsResponse;
import com.qianwen.core.sms.props.SmsProperties;
import com.qianwen.core.tool.utils.StringUtil;
import org.springframework.http.HttpStatus;
 
 
public class QiniuSmsTemplate implements SmsTemplate {
    private final SmsProperties smsProperties;
    private final SmsManager smsManager;
    private final BladeRedis bladeRedis;
 
    public QiniuSmsTemplate(final SmsProperties smsProperties, final SmsManager smsManager, final BladeRedis bladeRedis) {
        this.smsProperties = smsProperties;
        this.smsManager = smsManager;
        this.bladeRedis = bladeRedis;
    }
 
    @Override // com.qianwen.core.sms.SmsTemplate
    public SmsResponse sendMessage(SmsData smsData, Collection<String> phones) {
        try {
            Response response = this.smsManager.sendMessage(this.smsProperties.getTemplateId(), StringUtil.toStringArray(phones), smsData.getParams());
            return new SmsResponse(response.isOK(), Integer.valueOf(response.statusCode), response.toString());
        } catch (QiniuException e) {
            e.printStackTrace();
            return new SmsResponse(Boolean.FALSE.booleanValue(), Integer.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()), e.getMessage());
        }
    }
 
    @Override // com.qianwen.core.sms.SmsTemplate
    public SmsCode sendValidate(SmsData smsData, String phone) {
        SmsCode smsCode = new SmsCode();
        boolean temp = sendSingle(smsData, phone);
        if (temp && StringUtil.isNotBlank(smsData.getKey())) {
            String id = StringUtil.randomUUID();
            String value = smsData.getParams().get(smsData.getKey());
            this.bladeRedis.setEx(cacheKey(phone, id), value, Duration.ofMinutes(30L));
            smsCode.setId(id).setValue(value);
        } else {
            smsCode.setSuccess(Boolean.FALSE.booleanValue());
        }
        return smsCode;
    }
 
    @Override // com.qianwen.core.sms.SmsTemplate
    public boolean validateMessage(SmsCode smsCode) {
        String id = smsCode.getId();
        String value = smsCode.getValue();
        String phone = smsCode.getPhone();
        String cache = (String) this.bladeRedis.get(cacheKey(phone, id));
        if (StringUtil.isNotBlank(value) && StringUtil.equalsIgnoreCase(cache, value)) {
            this.bladeRedis.del(cacheKey(phone, id));
            return true;
        }
        return false;
    }
}