短信模块写成starter

发送短信需要环境
pull/379/head
鲸落 11 months ago
parent c77ca554c0
commit 872977d4c2

@ -18,6 +18,7 @@
<module>ruoyi-common-sensitive</module>
<module>ruoyi-common-datascope</module>
<module>ruoyi-common-datasource</module>
<module>ruoyi-common-sms</module>
</modules>
<artifactId>ruoyi-common</artifactId>

@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common</artifactId>
<version>3.6.4</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ruoyi-common-sms</artifactId>
<description>
ruoyi-common-sms 短信模块
</description>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.0</version> <!-- 或其他兼容版本 -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
<!-- SpringCloud Alibaba Nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- SpringCloud Alibaba Nacos Config -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
</dependencies>
</project>

@ -0,0 +1,24 @@
package com.ruoyi.common.sms;
import com.ruoyi.common.sms.component.SmsComponent;
import com.ruoyi.common.sms.properties.XunDaYunXinProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
@EnableConfigurationProperties(XunDaYunXinProperties.class)
public class XunDaYunXinAutoConfiguration {
@Bean
public SmsComponent smsComponent() {
return new SmsComponent();
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}

@ -0,0 +1,145 @@
package com.ruoyi.common.sms.component;
import com.ruoyi.common.sms.entity.response.SmsEntity;
import com.ruoyi.common.sms.entity.response.SmsResponse;
import com.ruoyi.common.sms.properties.XunDaYunXinProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.*;
@Slf4j
public class SmsComponent {
@Autowired
private XunDaYunXinProperties properties;
@Autowired
private RestTemplate restTemplate;
/**
*
*
* @param mobileContentKvp {"15100000000":"【测试】test1","15100000001":"【测试】test2"}
* @return SmsResponse<SmsEntity>
*/
public SmsResponse sendP2PMsg(Map<String, String> mobileContentKvp) {
Map<String, Object> extraParams = new HashMap<>();
for (Map.Entry<String, String> entry : mobileContentKvp.entrySet()) {
String oldValue = entry.getValue();
String newValue = replaceCode(properties.getTemplate(), oldValue);
entry.setValue(newValue);
}
extraParams.put("mobileContentKvp", mobileContentKvp);
return sendSmsRequest("p2p", extraParams, new ParameterizedTypeReference<SmsResponse>() {
});
}
/**
*
*
* @param mobile , "15100000000,15100000001"
* @param content
* @return SmsResponse<SmsEntity>
*/
public SmsResponse<SmsEntity> sendGroupMsg(String mobile, String content) {
Map<String, Object> extraParams = new HashMap<>();
extraParams.put("mobile", removeDuplicates(mobile));
extraParams.put("content", replaceCode(properties.getTemplate(), content));
return sendSmsRequest("send", extraParams, new ParameterizedTypeReference<SmsResponse<SmsEntity>>() {
});
}
public SmsResponse<?> checkBalance() {
String url = properties.getBaseUrl() + "/smsv2";
Map<String, Object> params = new HashMap<>();
params.put("action", "balance");
params.put("account", properties.getAccount());
params.put("password", properties.getPassword());
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params);
ResponseEntity<SmsResponse<?>> responseEntity = restTemplate.exchange(
url,
HttpMethod.POST,
requestEntity,
new ParameterizedTypeReference<SmsResponse<?>>() {
}
);
return responseEntity.getBody();
}
/**
*
*
* @param action "p2p""send" "balance"
* @param extraParams null
* @param responseType
* @param <T>
* @return SmsResponse
*/
private <T> T sendSmsRequest(String action, Map<String, Object> extraParams, ParameterizedTypeReference<T> responseType) {
// 拼接请求的 URL 地址
String url = properties.getBaseUrl() + "/smsv2";
// 创建请求参数 Map并填充必需的账户信息和操作类型
Map<String, Object> params = new HashMap<>();
params.put("action", action); // 设置请求的操作类型,如发送短信或查询余额
params.put("account", properties.getAccount()); // 设置账户名
params.put("password", properties.getPassword()); // 设置密码
params.put("extno", properties.getExtno()); // 虚拟接入码
// 如果有额外的参数,则将它们添加到请求参数中
if (extraParams != null) {
params.putAll(extraParams);
}
// 构建 HttpEntity 实体,包含请求参数
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params);
// 使用 RestTemplate 的 exchange 方法发送 POST 请求,并指定返回的泛型类型
ResponseEntity<T> responseEntity = restTemplate.exchange(
url, // 请求 URL
HttpMethod.POST, // HTTP 方法类型为 POST
requestEntity, // 请求体包含请求参数
responseType // 指定返回类型的泛型引用,用于保留泛型信息
);
// 返回响应体(根据调用方法传入的类型)
return responseEntity.getBody();
}
/**
*
*
* @param input
* @return String
*/
private String removeDuplicates(String input) {
// 使用 LinkedHashSet 保持插入顺序并去重
Set<String> uniqueSet = new LinkedHashSet<>(Arrays.asList(input.split(",")));
if (uniqueSet.size() >= 1000) {
throw new IllegalArgumentException("群发不建议超过1000个电话号码");
}
// 将去重后的集合转换回字符串
return String.join(",", uniqueSet);
}
/**
*
*
* @param template
* @param code
* @return
*/
public String replaceCode(String template, String code) {
return template.replace("{code}", code);
}
}

@ -0,0 +1,32 @@
package com.ruoyi.common.sms.entity.response;
public class SmsEntity {
private String mid;
private String mobile;
private int result;
// Getters and Setters
public String getMid() {
return mid;
}
public void setMid(String mid) {
this.mid = mid;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
}

@ -0,0 +1,12 @@
package com.ruoyi.common.sms.entity.response;
import lombok.Data;
import java.util.List;
@Data
public class SmsResponse<T> {
private Integer status;
private Integer balance;
private List<T> list;
}

@ -0,0 +1,40 @@
package com.ruoyi.common.sms.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
*
*/
@Data
@ConfigurationProperties(prefix = "xundayunxin")
public class XunDaYunXinProperties {
/**
*
*/
private String baseUrl = "http://47.96.236.136:7862/";
/**
*
*/
private String account = "932425";
/**
*
*/
private String password = "alDE77Gmo";
/**
*
*/
private String extno = "10690367";
/**
*
*/
private boolean encryptionEnabled;
/**
*
*/
private String template = "【信用秒租】验证码为:{code}您正在登录信用秒租请在3分钟内完成验证如非本人操作请忽略本短信。";
}

@ -0,0 +1,2 @@
com.ruoyi.common.sms.XunDaYunXinAutoConfiguration
com.ruoyi.common.sms.component.SmsComponent

@ -76,6 +76,17 @@
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common-sms</artifactId>
<version>3.6.4</version>
</dependency>
</dependencies>
<build>

@ -33,12 +33,13 @@ public class CommonController extends BaseController
/**
* H5
* @param phone
* @return
* @param phone
* @return AjaxResult
*/
@GetMapping("/sendSms")
public AjaxResult getChannelBySign(@RequestParam("phone")String phone, HttpServletRequest request){
return commonService.sendSms(phone);
public AjaxResult sendSms(@RequestParam("phone")String phone, HttpServletRequest request){
String header = request.getHeader("x-sms-source");
return commonService.sendSms(phone,header);
}

@ -175,4 +175,10 @@ public class CustomerController extends BaseController
{
return success(merchantService.findAllMerchantList());
}
@PostMapping("/v1/saveCustomerInfo")
public AjaxResult v1SaveCustomerInfo(@RequestBody Customer customer, HttpServletRequest request){
return customerService.v1SaveCustomerInfo(customer,request);
}
}

@ -148,4 +148,10 @@ public class MerchantController extends BaseController
}
@GetMapping("/v1/getMatchMerchant")
public AjaxResult V1GetMatchMerchant(HttpServletRequest request){
return merchantService.V1GetMatchMerchant(request);
}
}

@ -0,0 +1,12 @@
package com.ruoyi.system.process;
import com.ruoyi.common.core.web.domain.AjaxResult;
/**
*
*/
public interface ProcessHandler {
AjaxResult invoke();
}

@ -0,0 +1,36 @@
package com.ruoyi.system.process.enums;
import com.ruoyi.common.core.exception.ServiceException;
public enum ProcessHandlerEnum {
H5_HANDLER("H5_HANDLER", "H5Handler"),
HALF_HANDLER("HALF_HANDLER", "HalfHandler");
final String code;
final String name;
public String getCode() {
return code;
}
public String getName() {
return name;
}
ProcessHandlerEnum(String code, String name) {
this.code = code;
this.name = name;
}
public static String getNameByCode(String code) {
ProcessHandlerEnum[] processHandlerEnums = values();
for (ProcessHandlerEnum processHandlerEnum : processHandlerEnums) {
if (processHandlerEnum.getCode().equals(code)) {
return processHandlerEnum.getName();
}
}
String msg = String.format("请检查对应的流程处理器是否实现,编码为:%s", code);
throw new ServiceException(msg, 500);
}
}

@ -0,0 +1,14 @@
package com.ruoyi.system.process.handler;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.system.process.ProcessHandler;
import org.springframework.stereotype.Component;
@Component(value = "H5Handler")
public class H5Handler implements ProcessHandler {
@Override
public AjaxResult invoke() {
return null;
}
}

@ -0,0 +1,13 @@
package com.ruoyi.system.process.handler;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.system.process.ProcessHandler;
import org.springframework.stereotype.Component;
@Component(value = "HalfHandler")
public class HalfHandler implements ProcessHandler {
@Override
public AjaxResult invoke() {
return null;
}
}

@ -20,5 +20,5 @@ public interface ICommonService
* @param phone
* @return
*/
AjaxResult sendSms(String phone);
AjaxResult sendSms(String phone,String smsSource);
}

@ -109,4 +109,6 @@ public interface ICustomerService extends IService<Customer>
* @return
*/
AjaxResult saveCustomerInfo(Customer customer, HttpServletRequest request);
AjaxResult v1SaveCustomerInfo(Customer customer, HttpServletRequest request);
}

@ -93,4 +93,6 @@ public interface IMerchantService extends IService<Merchant>
AjaxResult H5applyMerchant(Long merchantId, HttpServletRequest request);
AjaxResult getMatchMerchantNew();
AjaxResult V1GetMatchMerchant(HttpServletRequest request);
}

@ -3,43 +3,100 @@ package com.ruoyi.system.service.impl;
import com.ruoyi.common.core.constant.RedisConstant;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.sms.component.SmsComponent;
import com.ruoyi.system.service.ICommonService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import java.security.SecureRandom;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* Service
*
*
* @author ruoyi
* @date 2024-09-15
*/
@Service
public class CommonServiceImpl implements ICommonService
{
public class CommonServiceImpl implements ICommonService {
@Autowired
private RedisService redisService;
@Autowired
private SmsComponent smsComponent;
@Autowired
private Environment environment;
@Override
public AjaxResult sendSms(String phone) {
if (StringUtils.isEmpty(phone)){
public AjaxResult sendSms(String phone, String smsSource) {
if (StringUtils.isEmpty(phone)) {
return AjaxResult.error("手机号未空");
}
if (phone.length()!=11){
if (phone.length() != 11) {
return AjaxResult.error("手机号长度异常");
}
//发送验证码
SecureRandom secureRandom = new SecureRandom();
int code = secureRandom.nextInt(9000) + 1000;
//发送验证码工具类
//正式环境发送验证码 pc4位 h5注册页6位
String code;
// 判断是否为正式环境
if (isProductionProfileActive()) {
//正式环境操作
code = smsSource.equalsIgnoreCase("h5") ? generateCode(6) : generateCode(4);
// 发送短信
Map<String, String> params = new HashMap<>();
params.put(phone, code);
smsComponent.sendP2PMsg(params);
} else {
// 非正式环境直接设置固定验证码
code = smsSource.equalsIgnoreCase("h5") ? "123456" : "1234";
}
//放入缓存 3分钟
redisService.setCacheObject(RedisConstant.H5_LOGIN_CACHE+phone,1234,3*60l, TimeUnit.SECONDS);
redisService.setCacheObject(RedisConstant.H5_LOGIN_CACHE + phone, code, 3 * 60L, TimeUnit.SECONDS);
return AjaxResult.success("发送成功");
}
/**
*
* if (isProductionProfileActive()) {
* // 进行与生产环境相关的逻辑处理
* } else {
* // 进行非生产环境的处理
* }
*
* @return
*/
public boolean isProductionProfileActive() {
// 获取当前应用的活跃环境
String[] activeProfiles = environment.getActiveProfiles();
// 定义线上环境列表
List<String> proList = new ArrayList<>(Arrays.asList("prod", "pro"));
// 检查活跃环境是否包含在 proList 中
for (String profile : activeProfiles) {
if (proList.contains(profile)) {
return true; // 如果有活跃环境在 proList 中,返回 true
}
}
return false; // 如果没有匹配的环境,返回 false
}
/**
*
*
* @param length
* @return
*/
private String generateCode(int length) {
SecureRandom secureRandom = new SecureRandom();
int bound = (int) Math.pow(10, length);
int min = bound / 10;
return String.valueOf(secureRandom.nextInt(bound - min) + min);
}
}

@ -254,5 +254,29 @@ public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> i
return AjaxResult.success("保存成功");
}
@Override
public AjaxResult v1SaveCustomerInfo(Customer customer, HttpServletRequest request) {
String authorization = request.getHeader("Authorization");
Long customerId = customerTokenService.getCustomerId(authorization, false);
String sign = request.getHeader("sign");
if (StringUtils.isEmpty(sign)) {
return AjaxResult.error("渠道标识不存在");
}
Channel channel = redisService.getCacheObject(CacheConstants.CHANNEL_SIGN + sign);
if (customerId == null) {
return AjaxResult.error("用户不存在或未登录");
}
if (StringUtils.isEmpty(customer.getActurlName())) {
return AjaxResult.error("姓名不能为空");
}
customer.setId(customerId);
customer.setChannelId(channel.getId());
customer.setIsAuth(true);
customer.setStatus(1);
updateById(customer);
return AjaxResult.success("保存成功");
}
}

@ -235,6 +235,28 @@ public class MerchantServiceImpl extends ServiceImpl<MerchantMapper, Merchant> i
return AjaxResult.success(results);
}
@Override
public AjaxResult V1GetMatchMerchant(HttpServletRequest request) {
String authorization = request.getHeader("Authorization");
Long customerId = customerTokenService.getCustomerId(authorization, false);
if (customerId==null){
return AjaxResult.error("用户不存在或未登录");
}
Customer customer = customerMapper.selectById(customerId);
List<Merchant> merchants = matchMerchant(customer);
List<MerchantListDto> merchantListDtos = new ArrayList<>();
for (Merchant merchant:merchants) {
MerchantListDto merchantListDto = new MerchantListDto();
merchantListDto.setMerchantName(merchant.getMerchantName());
merchantListDto.setMerchantDescribe(merchant.getMerchantDescribe());
merchantListDto.setMerchantUrl(merchant.getHitUrl());
merchantListDto.setMerchantId(merchant.getId());
merchantListDtos.add(merchantListDto);
}
return AjaxResult.success(merchantListDtos);
}
private List<Merchant> getMerchantLists() {
LambdaQueryWrapper<Merchant> queryWrapper = new LambdaQueryWrapper<Merchant>().eq(Merchant::getStatus, true);

@ -0,0 +1,48 @@
package com.ruoyi.system;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.sms.component.SmsComponent;
import com.ruoyi.common.sms.entity.response.SmsResponse;
import org.assertj.core.util.Maps;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.HashMap;
import java.util.Map;
import static cn.hutool.extra.spring.SpringUtil.getActiveProfile;
@SpringBootTest
public class RuoYiSystemApplicationTest {
@Autowired
SmsComponent smsComponent;
@Test
public void testGroupMsg(){
String mobile = "15826189779,15826189779,17382317154";
String content = "123456";
SmsResponse groupMsg = smsComponent.sendGroupMsg(mobile, content);
System.out.println(JSONUtil.toJsonStr(groupMsg));
}
@Test
public void testP2pMsg(){
String content = "123456";
Map<String, String> params = new HashMap<>();
params.put("15826189779", content);
SmsResponse sendP2PMsg = smsComponent.sendP2PMsg(params);
System.out.println(JSONUtil.toJsonStr(sendP2PMsg));
}
@Test
public void getActivePro(){
String activeProfile = getActiveProfile();
System.out.println(activeProfile);
}
}
Loading…
Cancel
Save