/* * 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 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.lambdaQuery().eq(Sms::getStatus, 2)); if (serviceOne == null) { logger.error("未找到状态为2的Sms服务"); return false; } SmsTemplateEntity smsTemplateEntity = iSmsTemplateService.getOne(Wrappers.lambdaQuery() .eq(SmsTemplateEntity::getId, serviceOne.getTemplateId())); if (smsTemplateEntity == null) { logger.error("未找到对应的短信模板"); return false; } //发送的手机号 List phonesList = new ArrayList<>(); Map phoneMap = new HashMap(); phoneMap.put("phone", phone); List 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 params = new HashMap(); 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 params) { StringBuilder sb = new StringBuilder(); for (Map.Entry entry : params.entrySet()) { sb.append("&").append(entry.getKey()).append("=").append(entry.getValue()); } return sb.toString().substring(1); } protected static String buildUrlQuery(Map params) { StringBuilder sb = new StringBuilder(); for (Map.Entry 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); } }