package com.sinata.system.service.biz;
|
|
import com.alibaba.fastjson2.JSON;
|
import com.aliyun.dysmsapi20170525.Client;
|
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
|
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
|
import com.aliyun.teaopenapi.models.Config;
|
import com.sinata.system.config.AliSmsConfig;
|
import lombok.extern.slf4j.Slf4j;
|
import org.apache.commons.lang3.StringUtils;
|
import org.springframework.stereotype.Service;
|
|
import javax.annotation.Resource;
|
import java.util.HashMap;
|
import java.util.Map;
|
|
|
@Service
|
@Slf4j
|
public class AliSmsService {
|
@Resource
|
private AliSmsConfig aliSmsConfig;
|
|
/**
|
* 发送验证码短信
|
*
|
* @param phone 手机号
|
* @param code 验证码
|
* @return
|
*/
|
public boolean sendLoginCode(String phone, String code) {
|
|
Map<String, String> param = new HashMap<>(3);
|
param.put("code", code);
|
return sendSms(phone, aliSmsConfig.getSignName(), aliSmsConfig.getLoginTemplateCode(), param);
|
}
|
|
/**
|
* 审核结果通知短信
|
*
|
* @param phone 手机号
|
* @param result 已通过 未通过
|
* @return
|
*/
|
public boolean sendAuditResult(String phone, String result) {
|
|
Map<String, String> param = new HashMap<>(3);
|
param.put("code", result);
|
return sendSms(phone, aliSmsConfig.getSignName(), aliSmsConfig.getAuditTemplateCode(), param);
|
}
|
|
/**
|
* 阿里发送短信
|
*
|
* @param phone
|
* @param signName
|
* @param templateCode
|
* @param param
|
* @return
|
*/
|
private boolean sendSms(String phone, String signName, String templateCode, Map<String, String> param) {
|
// 可自助调整超时时间
|
System.setProperty("sun.net.client.defaultConnectTimeout", aliSmsConfig.getConnectTimeout());
|
System.setProperty("sun.net.client.defaultReadTimeout", aliSmsConfig.getReadTimeout());
|
try {
|
|
// 初始化请求客户端
|
Client client = createClient();
|
|
// 构造请求对象,请填入请求参数值
|
SendSmsRequest sendSmsRequest = new SendSmsRequest()
|
.setPhoneNumbers(phone)
|
.setSignName(signName)
|
.setTemplateCode(templateCode)
|
.setTemplateParam(JSON.toJSONString(param));
|
if (aliSmsConfig.isDebug()) {
|
log.info("短信 DEBUG code= {}", param);
|
return true;
|
}
|
// 获取响应对象
|
SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
|
// hint 此处可能会抛出异常,注意catch
|
if (StringUtils.equalsIgnoreCase("ok", sendSmsResponse.getBody().getCode())) {
|
return true;
|
} else {
|
log.error("{}短信发送失败:{}", phone, sendSmsResponse.getBody().getMessage());
|
}
|
} catch (Exception e) {
|
throw new RuntimeException("短信发送失败", e);
|
}
|
return false;
|
}
|
|
public Client createClient() throws Exception {
|
Config config = new Config()
|
// 配置 AccessKey ID
|
.setAccessKeyId(aliSmsConfig.getAccessKeyId())
|
// 配置 AccessKey Secret
|
.setAccessKeySecret(aliSmsConfig.getAccessKeySecret());
|
|
// 配置 Endpoint
|
config.endpoint = "dysmsapi.aliyuncs.com";
|
|
return new Client(config);
|
}
|
}
|