lin
2024-04-02 94d3bc1411a2b5fb1978bc6908b957a800b1cb26
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.sms.service.impl;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.common.config.SmsConfig;
import org.springblade.common.utils.HttpClientUtils;
import org.springblade.common.utils.UtilRandom;
import org.springblade.common.utils.sms.AlipaySignature;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.modules.resource.entity.Sms;
import org.springblade.modules.resource.service.ISmsService;
import org.springblade.modules.sms.entity.SmsTemplateEntity;
import org.springblade.modules.sms.mapper.SmsTemplateMapper;
import org.springblade.modules.sms.service.ISmsSendService;
import org.springblade.modules.sms.service.ISmsTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
 
/**
 * 短信模版表 服务实现类
 *
 * @author BladeX
 * @since 2024-03-06
 */
@Service
public class SmsSendServiceImpl extends ServiceImpl<SmsTemplateMapper, SmsTemplateEntity> implements ISmsSendService {
    @Autowired
    private BladeRedis redisTemplate;
    private static Logger logger = LoggerFactory.getLogger(SmsSendServiceImpl.class);
    // 确保这些字符串被适当地定义和管理
    public static final String SMS_VALIDATE_PHONE = "sms:validate:code:";
    public static final String SMS_VALIDATE_PHONE_NUM = "sms:validate:phone:";
    private static final String SMS_SEND_FAILED = "短信发送失败!";
    private static final String MESSAGE_SOP_EQUALS_MES_RESPONSE_CODE = "message_sop_equalsMes_response";
    private static final String SEND_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
 
 
    @Autowired
    private ISmsService iSmsService;
 
    @Autowired
    private ISmsTemplateService iSmsTemplateService;
 
    @Override
    public Boolean smsSend(String phone) {
 
        Sms serviceOne = iSmsService.getOne(Wrappers.<Sms>lambdaQuery().eq(Sms::getStatus, 2));
        if (serviceOne == null) {
            logger.error("未找到状态为2的Sms服务");
            return false;
        }
        SmsTemplateEntity smsTemplateEntity = iSmsTemplateService.getOne(Wrappers.<SmsTemplateEntity>lambdaQuery()
            .eq(SmsTemplateEntity::getId, serviceOne.getTemplateId()));
        if (smsTemplateEntity == null) {
            logger.error("未找到对应的短信模板");
            return false;
        }
 
        //发送的手机号
        List<Map> phonesList = new ArrayList<>();
 
        Map phoneMap = new HashMap();
        phoneMap.put("phone", phone);
 
        List<String> varList = new ArrayList<>();
        Integer code = UtilRandom.randomCount(111111, 999999);
 
        varList.add(code.toString());
        phoneMap.put("varList", varList);
 
        phonesList.add(phoneMap);
        //短信主题
        String subject = "对外接口不同内容发送-动态模板";
        //短信内容
        String content = smsTemplateEntity.getContent();
        //短信模板
        String template_id = null;
        //发送时间
        SimpleDateFormat df = new SimpleDateFormat(SEND_TIME_FORMAT);
        String send_time = df.format(new Date());
        //优先级,高级=5,中级=3,低级=1
        String priority = "1";
        //不同内容发送类型,1=动态模板发送,2=文件内容发送
        String type = "1";
        Map params = new HashMap();
        params.put("phones", phonesList);
        params.put("subject", subject);
        params.put("content", content);
        params.put("template_id", template_id);
        params.put("send_time", send_time);
        params.put("priority", priority);
        params.put("type", type);
        //创建人主键
        params.put("sop_create_by", serviceOne.getSmsCode());
        String s = null;
        try {
            s = testGet(params, "message.sop.differentMes", serviceOne);
            JSONObject jsonObject = JSON.parseObject(s);
            JSONObject messageSopEqualsMesResponse = (JSONObject) jsonObject.get(MESSAGE_SOP_EQUALS_MES_RESPONSE_CODE);
            if (messageSopEqualsMesResponse.get("code").equals(200)) {
                // 将验证码存入redis
                redisTemplate.setEx(SMS_VALIDATE_PHONE + phone, code, 300L);
                redisTemplate.setEx(SMS_VALIDATE_PHONE_NUM + phone, 1, 60L);
                return true;
            }
        } catch (Exception e) {
            logger.error(SMS_SEND_FAILED, e);
            throw new RuntimeException(e);
        }
        return false;
    }
 
    public String testGet(Object bizContent, String method, Sms serviceOne) throws Exception {
 
        // 公共请求参数
        Map<String, String> params = new HashMap<String, String>();
        params.put("app_id", serviceOne.getAccessKey());
        params.put("method", method);
        params.put("format", "json");
        params.put("charset", "utf-8");
        params.put("sign_type", "RSA2");
        params.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        params.put("version", "1.0");
 
        // 业务参数
        params.put("biz_content", JSON.toJSONString(bizContent));
        String content = AlipaySignature.getSignContent(params);
        String sign = AlipaySignature.rsa256Sign(content, serviceOne.getSecretKey(), "utf-8");
        params.put("sign", sign);
 
        System.out.println("----------- 请求信息 -----------");
        System.out.println("请求参数:" + buildParamQuery(params));
        System.out.println("商户秘钥:" + serviceOne.getSecretKey());
        System.out.println("待签名内容:" + content);
        System.out.println("签名(sign):" + sign);
        System.out.println("URL参数:" + buildUrlQuery(params));
 
        System.out.println("----------- 返回结果 -----------");
        String responseData = HttpClientUtils.doGet(serviceOne.getRemark(), params);// 发送请求
        System.out.println("返回数据" + responseData);
        return responseData;
    }
 
    protected static String buildParamQuery(Map<String, String> params) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
        }
        return sb.toString().substring(1);
    }
 
    protected static String buildUrlQuery(Map<String, String> params) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            try {
                sb.append("&").append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString().substring(1);
    }
}