lin
2024-03-29 5123f48f469dba99f6929a3f6abbe3690ce3e8c2
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
/*
 *      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.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.sms.entity.SmsTemplateEntity;
import org.springblade.modules.sms.mapper.SmsTemplateMapper;
import org.springblade.modules.sms.service.ISmsSendService;
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:";
 
    @Autowired
    private SmsConfig smsConfig;
 
    @Override
    public Boolean smsSend(String phone) {
        //发送的手机号
        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 = "您正在验证投票操作,验证码:#P_1#。如非本人操作,则密码可能已泄露,建议立即修改密码或联系客服。";
//        String content = "尊敬的#P_1#,你得工资#P_2#,测试#P_3#";
        //短信模板
        String template_id = null;
        //发送时间
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        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", smsConfig.getSopCreateBy());
        String s = null;
        try {
            s = testGet(params, "message.sop.differentMes");
            JSONObject jsonObject = JSON.parseObject(s);
            JSONObject messageSopEqualsMesResponse = (JSONObject) jsonObject.get("message_sop_equalsMes_response");
            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("短信发送失败!", e);
            throw new RuntimeException(e);
        }
        return false;
    }
 
    public String testGet(Object bizContent, String method) throws Exception {
 
        // 公共请求参数
        Map<String, String> params = new HashMap<String, String>();
        params.put("app_id", smsConfig.getSmsAppId());
        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, smsConfig.getSmsPrivateKey(), "utf-8");
        params.put("sign", sign);
 
        System.out.println("----------- 请求信息 -----------");
        System.out.println("请求参数:" + buildParamQuery(params));
        System.out.println("商户秘钥:" + smsConfig.getSmsPrivateKey());
        System.out.println("待签名内容:" + content);
        System.out.println("签名(sign):" + sign);
        System.out.println("URL参数:" + buildUrlQuery(params));
 
        System.out.println("----------- 返回结果 -----------");
        String responseData = HttpClientUtils.doGet(smsConfig.getSmsUrl(), 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);
    }
}