Short Message had replaced to aliyun

This commit is contained in:
wen 2021-10-27 14:37:02 +08:00
parent d87fe0cb8e
commit c2e084016b
10 changed files with 281 additions and 88 deletions

View File

@ -4,17 +4,20 @@ import com.xhpc.common.api.factory.SmsFallbackFactory;
import com.xhpc.common.core.constant.ServiceNameConstants;
import com.xhpc.common.core.domain.R;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Map;
/**
* program: ruoyi
* User: HongYun
* Date:2021-08-16 16
*/
@FeignClient(contextId = "smsService",value = ServiceNameConstants.XHPC_GENERAL, fallbackFactory = SmsFallbackFactory.class)
@FeignClient(contextId = "smsService", value = ServiceNameConstants.XHPC_GENERAL, fallbackFactory = SmsFallbackFactory.class)
public interface SmsService {
@GetMapping("/sms/send")
R sendNotice(@RequestParam(value = "phone") String phone , @RequestParam(value = "content") String content);
@PostMapping("/sms/send")
R sendNotice(@RequestParam(value = "phone") String phone, @RequestParam(value = "content") String content, Map<String, String> paramMap);
}

View File

@ -7,6 +7,8 @@ import org.slf4j.LoggerFactory;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* program: ruoyi
* User: HongYun
@ -21,9 +23,9 @@ public class SmsFallbackFactory implements FallbackFactory<SmsService> {
logger.error("短信发送服务调用失败:{} //fallback", cause.getMessage());
return new SmsService() {
@Override
public R sendNotice(String phone, String content) {
public R sendNotice(String phone, String content, Map<String, String> paramMap) {
return R.fail("短信发送失败:" +cause.getMessage());
return R.fail("短信发送失败:" + cause.getMessage());
}
};
}

View File

@ -20,6 +20,13 @@
</properties>
<dependencies>
<!-- 阿里巴巴的短信服务依赖 -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>2.0.5</version>
</dependency>
<!-- SpringCloud Alibaba Nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>

View File

@ -5,10 +5,7 @@ import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.common.core.web.page.TableDataInfo;
import com.xhpc.general.service.IXhpcSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@ -28,22 +25,69 @@ public class XhpcSmsController extends BaseController {
* 注册获取手机号验证码
*/
@GetMapping(value = "/getLogonPhoneCode")
public AjaxResult getLogonPhoneCode(@RequestParam("phone") String phone)
{
return xhpcSmsService.getLogonPhoneCode(phone);
public AjaxResult getLogonPhoneCode(@RequestParam("phone") String phone) throws Exception {
String signatureName = null;
String templateId = null;
signatureName = "小华充电";
templateId = "SMS_226786362";
return xhpcSmsService.getLogonPhoneCode(phone, signatureName, templateId);
}
@GetMapping(value = "/getList")
public TableDataInfo getList(Integer status, String phone){
public TableDataInfo getList(Integer status, String phone) {
startPage();
List<Map<String, Object>> list = xhpcSmsService.getList(status, phone);
return getDataTable(list);
}
@GetMapping(value = "/send")
public void send(@RequestParam(value = "phone") String phone ,@RequestParam(value = "content") String content){
@PostMapping(value = "/send")
public void send(@RequestParam(required = false) String phone, String content, @RequestBody Map<String, String> paramMap) {
xhpcSmsService.sendNotice(phone, content);
String signatureName = null;
String templateId = null;
//方便使用PostMan调用接口测试
if (phone != null && content != null) {
//判断内容是什么调用相应的模板
if (content.contains("电量为")) {
signatureName = "小华充电";
templateId = "SMS_226945037";
} else if (content.contains("总费用为")) {
signatureName = "小华充电";
templateId = "SMS_226786374";
} else if (content.contains("余额小于")) {
signatureName = "小华充电";
templateId = "SMS_226935795";
} else if (content.contains("设定的SOC")) {
signatureName = "小华充电";
templateId = "SMS_226826374";
}
} else {
phone = paramMap.get("phone");
content = paramMap.get("content");
paramMap.remove("phone");
paramMap.remove("content");
//判断内容是什么调用相应的模板
if (content.contains("电量为")) {
signatureName = "小华充电";
templateId = "SMS_226945037";
} else if (content.contains("总费用为")) {
signatureName = "小华充电";
templateId = "SMS_226786374";
} else if (content.contains("余额小于")) {
signatureName = "小华充电";
templateId = "SMS_226935795";
} else if (content.contains("设定的SOC")) {
signatureName = "小华充电";
templateId = "SMS_226826374";
}
}
xhpcSmsService.sendNotice(phone, signatureName, templateId, paramMap);
}
}

View File

@ -13,30 +13,37 @@ public interface IXhpcSmsService {
/**
* 登陆回验证码
* 注册获取手机号验证码
*
* @param templateId
* @param signatureName
* @param phone
* @return
*/
AjaxResult getLogonPhoneCode(String phone);
AjaxResult getLogonPhoneCode(String phone, String signatureName, String templateId);
List<Map<String, Object>> getList(Integer status,String phone);
/**
* 发送短信通用方法
*
* @param phone 手机号
* @param content 内容
* @param random 验证码6位 不为空则是获取验证码
* @param phone 手机号
* @param content 内容
* @param random 验证码6位 不为空则是获取验证码
* @param signatureName
* @param templateId
* @param paramMap 模板中的参数
* @return
*/
AjaxResult send(String phone, String content, String random);
AjaxResult send(String phone, String content, String random, String signatureName, String templateId, Map<String, String> paramMap);
/**
* Send a notice, when user's account is less than 5 yuan.
* @param phone
* @param content
* 发送通知短信方法
*
* @param phone 手机号
* @param signatureName 签名
* @param templateId 模板ID
* @param paramMap 模板中的参数
*/
void sendNotice(String phone,String content);
void sendNotice(String phone, String signatureName, String templateId, Map<String, String> paramMap);
}

View File

@ -1,15 +1,21 @@
package com.xhpc.general.service;
import com.alibaba.fastjson.JSONObject;
import com.xhpc.common.core.utils.HttpUtils;
import cn.hutool.json.JSONUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.QuerySendDetailsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.common.redis.service.RedisService;
import com.xhpc.general.domain.XhpcSms;
import com.xhpc.general.mapper.XhpcSmsMapper;
import com.xhpc.general.util.sms.SmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
@ -20,14 +26,11 @@ import java.util.regex.Pattern;
* @date 2021/7/30 18:50
*/
@Service
public class XhpcSmsServiceImpl implements IXhpcSmsService{
public class XhpcSmsServiceImpl implements IXhpcSmsService {
public static RedisService REDIS;
public static final String URL = "http://sms.daiyicloud.com/sms/apiSend/add";
public static final String ACCOUNT ="scxhkj";
public static final String PASSWD ="6A9628548C4CBECCE80A2479CD77679F";
public static final String PRODUCTLD ="20191130000001";
public static final String accessKeyId = "LTAI5tBWjnuQGxGicnThwMF1";
public static final String accessKeySecret = "b0WNtFYtWyTEkZzcr2WOAPoZg6w2Xu";
@Autowired
private RedisService redisService;
@ -35,16 +38,20 @@ public class XhpcSmsServiceImpl implements IXhpcSmsService{
private XhpcSmsMapper xhpcSmsMapper;
@PostConstruct
public void init(){
REDIS =redisService;
public void init() {
REDIS = redisService;
}
@Override
public AjaxResult getLogonPhoneCode(String phone) {
public AjaxResult getLogonPhoneCode(String phone, String signatureName, String templateId) {
String random = getRandom();
String conten ="【小华充电】您的验证码是:"+random+"有效期为5分钟。如非本人操作可不用理会。";
return send(phone, conten, random);
HashMap<String, String> paramMap = new HashMap<>();
paramMap.put("code", random);
String content = null;
return send(phone, content, random, signatureName, templateId, paramMap);
}
@Override
@ -54,7 +61,7 @@ public class XhpcSmsServiceImpl implements IXhpcSmsService{
}
@Override
public AjaxResult send(String phone, String content, String random) {
public AjaxResult send(String phone, String content, String random, String signatureName, String templateId, Map<String, String> paramMap) {
//调用接口
String pattern = "^([1][0-9]{10})";
@ -68,34 +75,38 @@ public class XhpcSmsServiceImpl implements IXhpcSmsService{
XhpcSms xhpcSms =new XhpcSms();
try {
//用户使用的Key
String pvToken = "pvToken:"+phone;
String pvToken = "pvToken:" + phone;
//用户频繁调用的判断的Key
String token = "token:"+phone;
String token = "token:" + phone;
String cacheObject = REDIS.getCacheObject(token);
if(cacheObject !=null){
return AjaxResult.error("1012","操作过于频繁请于1分钟后重试");
if (cacheObject != null) {
return AjaxResult.error("1012", "操作过于频繁请于1分钟后重试");
}
String req = HttpUtils.postFormData(URL, null, assembleSmsReq(phone,content));
JSONObject json = JSONObject.parseObject(req);
if(!"".equals(random) && random !=null){
//使用阿里云发送通知短信
Map<String, String> neededParam = aliyunSmsNotice(phone, signatureName, templateId, paramMap);
if (!"".equals(random) && random != null) {
xhpcSms.setCode(random);
}
xhpcSms.setPhone(phone);
xhpcSms.setContent(content);
xhpcSms.setContent(neededParam.get("templateContent"));
xhpcSms.setCreateTime(new Date());
xhpcSms.setRemark(req);
String ok = json.getString("ok");
if("true".equals(ok)){
REDIS.setCacheObject(pvToken,random,300L, TimeUnit.SECONDS);
xhpcSms.setRemark(neededParam.get("jsonResult"));
//判断发送结果
String statusCode = neededParam.get("statusCode");
if (statusCode.equals("OK")) {
REDIS.setCacheObject(pvToken, random, 300L, TimeUnit.SECONDS);
//1分钟有效时间设置防止用户频繁调用
REDIS.setCacheObject(token,random,60L, TimeUnit.SECONDS);
REDIS.setCacheObject(token, random, 60L, TimeUnit.SECONDS);
xhpcSms.setStatus(0);
xhpcSmsMapper.addXhpcSms(xhpcSms);
return AjaxResult.success();
}else{
} else {
xhpcSms.setStatus(1);
xhpcSmsMapper.addXhpcSms(xhpcSms);
return AjaxResult.error(1012,"服务器繁忙,请稍后再试");
return AjaxResult.error(1012, "服务器繁忙,请稍后再试");
}
} catch (Exception e) {
//e.printStackTrace();
@ -105,16 +116,6 @@ public class XhpcSmsServiceImpl implements IXhpcSmsService{
}
}
private static HashMap<String, String> assembleSmsReq(String phone, String content) {
HashMap<String, String> params = new HashMap<>();
params.put("account", ACCOUNT);
params.put("password", PASSWD);
params.put("content", content);
params.put("mobiles", phone);
params.put("productId", PRODUCTLD);
return params;
}
private String getRandom(){
Random rnd = new Random();
int i = rnd.nextInt(999999);
@ -125,20 +126,28 @@ public class XhpcSmsServiceImpl implements IXhpcSmsService{
}
@Override
public void sendNotice(String phone, String content) {
public void sendNotice(String phone, String signatureName, String templateId, Map<String, String> paramMap) {
XhpcSms xhpcSms = new XhpcSms();
try {
String req = HttpUtils.postFormData(URL,null,assembleSmsReq(phone,content));
JSONObject json = JSONObject.parseObject(req);
//使用阿里云发送通知短信
Map<String, String> neededParam = aliyunSmsNotice(phone, signatureName, templateId, paramMap);
//获取模板内容
String templateContent = neededParam.get("templateContent");
//封装信息
xhpcSms.setPhone(phone);
xhpcSms.setContent(content);
xhpcSms.setContent(templateContent);
xhpcSms.setCreateTime(new Date());
xhpcSms.setRemark(req);
String ok = json.getString("ok");
if("true".equals(ok)) {
xhpcSms.setRemark(neededParam.get("jsonResult"));
//判断发送结果
String statusCode = neededParam.get("statusCode");
if ("OK".equals(statusCode)) {
xhpcSms.setStatus(0);
}else {
} else {
xhpcSms.setStatus(1);
}
} catch (Exception e) {
@ -152,14 +161,67 @@ public class XhpcSmsServiceImpl implements IXhpcSmsService{
for (int i = 0; i < 50; i++) {
Random rnd = new Random();
int j = rnd.nextInt(999999);
System.out.println("number>> " +j);
if(j<100000){
j=j+100000;
System.out.println("number>> " + j);
if (j < 100000) {
j = j + 100000;
}
System.out.println("number " +Long.valueOf(j));
System.out.println("number " + Long.valueOf(j));
}
}
/**
* 使用阿里云服务发送通知短信
*
* @param phone
* @param signatureName
* @param templateId
* @param paramMap 模板参数集合
* @return
* @throws Exception
*/
public Map<String, String> aliyunSmsNotice(String phone, String signatureName, String templateId, Map<String, String> paramMap) throws Exception {
//调用阿里云API发送请求
Client client = SmsUtil.createClient(accessKeyId, accessKeySecret);
SendSmsRequest sendSmsRequest = new SendSmsRequest();
sendSmsRequest.setPhoneNumbers(phone);
sendSmsRequest.setSignName(signatureName);
sendSmsRequest.setTemplateCode(templateId);
//添加模板参数
String templateParam = JSONUtil.toJsonStr(paramMap);
sendSmsRequest.setTemplateParam(templateParam);
SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
//获取发送结果状态码
String statusCode = sendSmsResponse.getBody().getCode();
//获取短信的Biz号
String bizId = sendSmsResponse.getBody().getBizId();
//获取短信的发送日期并将其转换为yyyyMMdd的格式
String date = sendSmsResponse.getHeaders().get("date");
Date realDate = new Date(date);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String formatData = sdf.format(realDate);
//获取所发送的模板信息
QuerySendDetailsRequest querySendDetailsRequest = new QuerySendDetailsRequest();
querySendDetailsRequest.setPhoneNumber(phone);
querySendDetailsRequest.setBizId(bizId);
querySendDetailsRequest.setSendDate(formatData);
querySendDetailsRequest.setCurrentPage(1L);
querySendDetailsRequest.setPageSize(10L);
String templateContent = client.querySendDetails(querySendDetailsRequest).getBody().getSmsSendDetailDTOs().getSmsSendDetailDTO().get(0).getContent();
//获取阿里云的返回值json字符串
SendSmsResponseBody body = sendSmsResponse.getBody();
String jsonResult = JSONUtil.toJsonStr(body);
//存放后面需要使用的返回值
HashMap<String, String> valueParam = new HashMap<>();
valueParam.put("statusCode", statusCode);
valueParam.put("templateContent", templateContent);
valueParam.put("jsonResult", jsonResult);
return valueParam;
}
}

View File

@ -0,0 +1,53 @@
package com.xhpc.general.util.sms;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
/**
* @Author WH
* @Date 2021/10/25 16:16
* @Description 使用阿里云提供SDK进行短信发送
* @Param
* @Return
* @Since version-1.0
*/
public class SmsUtil {
private static String accessKeyId = "LTAI5tBWjnuQGxGicnThwMF1";
private static String accessKeySecret = "b0WNtFYtWyTEkZzcr2WOAPoZg6w2Xu";
/**
* 使用AK&SK初始化账号Client
*
* @param accessKeyId
* @param accessKeySecret
* @return Client
* @throws Exception
*/
public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
Config config = new Config()
// 您的AccessKey ID
.setAccessKeyId(accessKeyId)
// 您的AccessKey Secret
.setAccessKeySecret(accessKeySecret);
// 访问的域名
config.endpoint = "dysmsapi.aliyuncs.com";
return new com.aliyun.dysmsapi20170525.Client(config);
}
public static void main(String[] args_) throws Exception {
java.util.List<String> args = java.util.Arrays.asList(args_);
com.aliyun.dysmsapi20170525.Client client = SmsUtil.createClient(accessKeyId, accessKeySecret);
SendSmsRequest sendSmsRequest = new SendSmsRequest()
.setPhoneNumbers("13060166032")
.setSignName("小华充电")
.setTemplateCode("SMS_226935795")
.setTemplateParam("{\"money\":\"5\"}");
// 复制代码运行请自行打印 API 的返回值
client.sendSms(sendSmsRequest);
}
}

View File

@ -377,11 +377,16 @@ public class XhpcHistoryOrderServiceImpl implements IXhpcHistoryOrderService {
//发送短信
if(user.get("phone") !=null){
if("1".equals(xhpcChargingPile.get("type").toString())){
HashMap<String, String> paramMap = new HashMap<>();
paramMap.put("elec", xhpcChargeOrder.getEndSoc());
paramMap.put("sumMoney", actPrice.toString());
String content = "【小华停止充电】尊敬的用户,你的爱车已停止充电,电量为:" + xhpcChargeOrder.getEndSoc() + "%,总费用为:" + actPrice + "元,充电费用明细,请查询小华充电小程序,谢谢。";
smsService.sendNotice(user.get("phone").toString(),content);
}else{
smsService.sendNotice(user.get("phone").toString(), content, paramMap);
}else {
HashMap<String, String> paramMap = new HashMap<>();
paramMap.put("sumMoney", actPrice.toString());
String content = "【小华停止充电】尊敬的用户,你的爱车已停止充电,总费用为:" + actPrice + "元,充电费用明细,请查询小华充电小程序,谢谢。";
smsService.sendNotice(user.get("phone").toString(),content);
smsService.sendNotice(user.get("phone").toString(), content, paramMap);
}
}
}

View File

@ -383,11 +383,16 @@ public class XhpcRealTimeOrderServiceImpl implements IXhpcRealTimeOrderService {
//发送短信
if(user.get("phone") !=null){
if("1".equals(xhpcChargingPile.get("type").toString())){
HashMap<String, String> paramMap = new HashMap<>();
paramMap.put("elec", xhpcChargeOrder.getEndSoc());
paramMap.put("sumMoney", actPrice.toString());
String content = "【小华停止充电】尊敬的用户,你的爱车已停止充电,电量为:" + xhpcChargeOrder.getEndSoc() + "%,总费用为:" + actPrice + "元,充电费用明细,请查询小华充电小程序,谢谢。";
smsService.sendNotice(user.get("phone").toString(),content);
}else{
smsService.sendNotice(user.get("phone").toString(), content, paramMap);
}else {
HashMap<String, String> paramMap = new HashMap<>();
paramMap.put("sumMoney", actPrice.toString());
String content = "【小华停止充电】尊敬的用户,你的爱车已停止充电,总费用为:" + actPrice + "元,充电费用明细,请查询小华充电小程序,谢谢。";
smsService.sendNotice(user.get("phone").toString(),content);
smsService.sendNotice(user.get("phone").toString(), content, paramMap);
}
}
}

View File

@ -21,6 +21,7 @@ import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -144,9 +145,11 @@ public class RealtimeDataLogic implements ServiceLogic {
if (alerted == null && tel != null) {
R r = chargingController.nativeStopCharging(pileNo, gunId, default_version);
if (r.getCode() == 200) {
HashMap<String, String> paramMap = new HashMap<>();
paramMap.put("battery", stopSoc.toString());
smsService.sendNotice(tel, "【小华充电】尊敬的用户你的车辆已充电达至设定的SOC("
.concat(stopSoc.toString())
.concat("%)已自动停止充电,请您尽快将车辆挪走以方便他人使用充电桩,谢谢合作。"));
.concat("%)已自动停止充电,请您尽快将车辆挪走以方便他人使用充电桩,谢谢合作。"), paramMap);
cacheOrder.put("socalerted", "true");
}
}
@ -155,7 +158,9 @@ public class RealtimeDataLogic implements ServiceLogic {
String alerted = (String) cacheOrder.get("lt5alerted");
String tel = (String) cacheOrder.get("tel");
if (alerted == null && tel != null) {
smsService.sendNotice(tel, "【小华充电】尊敬的用户你的账户余额小于5元,为不影响您的正常充电,请您尽快充值交费,谢谢。");
HashMap<String, String> paramMap = new HashMap<>();
paramMap.put("money", "5");
smsService.sendNotice(tel, "【小华充电】尊敬的用户你的账户余额小于5元,为不影响您的正常充电,请您尽快充值交费,谢谢。", paramMap);
cacheOrder.put("lt5alerted", "true");
}
}