/**
* 阿里云短信服务
*
* @Author zwm
* @Date 2024-12-24
*/
@Service
@Slf4j
public class AliyunMsgServiceImpl implements MsgService {
//短信API产品名称
private static final String PRODUCT = "Dysmsapi";
//短信API产品域名
private static final String DOMAIN = "dysmsapi.aliyuncs.com";
private static final String ENDPOINT = "cn-hangzhou";
@Autowired
private CustomerCacheService customerCacheService;
@Autowired
private AliyunProperties aliyunAuthProperties;
@Override
public void sendMsg(String telephone) {
if (StringUtil.isEmpty(telephone)) {
Asserts.fail("手机号不能为空");
}
//设置超时时间-可自行调整
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//初始化ascClient需要的几个参数
IClientProfile profile = DefaultProfile.getProfile(ENDPOINT, accessKeyId, accessKeySecret);
try {
DefaultProfile.addEndpoint(ENDPOINT, ENDPOINT, PRODUCT, DOMAIN);
} catch (ClientException e) {
throw new RuntimeException(e);
}
IAcsClient acsClient = new DefaultAcsClient(profile);
//组装请求对象
SendSmsRequest request = new SendSmsRequest();
//使用post提交
request.setMethod(MethodType.POST);
request.setPhoneNumbers(telephone);
//必填:短信签名-可在短信控制台中找到
request.setSignName(signName);
//必填:短信模板-可在短信控制台中找到,发送国际/港澳台消息时,请使用国际/港澳台短信模版
request.setTemplateCode(templateCode);
String msgBody = getMsgBody(telephone);
request.setTemplateParam(msgBody);
SendSmsResponse sendSmsResponse = null;
try {
sendSmsResponse = acsClient.getAcsResponse(request);
} catch (ClientException e) {
log.info("短信发送失败!手机号:{},失败原因:{}", telephone, e.getErrMsg());
throw new RuntimeException(e);
}
if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
log.info("短信发送成功!手机号:{},消息体:{},响应体:{}", telephone, msgBody, sendSmsResponse.getMessage());
}
}
/**
* 拼接要发送的模板消息
*
* @param telephone
* @return
*/
public String getMsgBody(String telephone) {
JSONObject msgJson = new JSONObject();
msgJson.put("code", getAuthCode(telephone));
msgJson.put("time", "1");
return msgJson.toString();
}
/**
* 生成验证码并放入缓存
*
* @param telephone
* @return
*/
public String getAuthCode(String telephone) {
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 6; i++) {
sb.append(random.nextInt(10));
}
//放入缓存
cacheService.setAuthCode(telephone, sb.toString());
return sb.toString();
}
}
阿里云短信发送接口
最新推荐文章于 2025-04-14 18:37:23 发布