关于阿里云国际短信服务发送JAVA
基于已经发布到线上的应用或app,否则短信其签名和模板可能不通过。
·
基于已经发布到线上的应用或app,否则短信其签名和模板可能不通过
阿里云短信服务官方网站
阿里云短信申请
首先申请签名和模板,通过后即可配置发送短信的数据。

添加模板后获得模板code

编写业务类
@Configuration
@Slf4j
@PropertySource(value = "classpath:alisms.properties" ,encoding = "utf-8")
public class AliSmsConfig {
private final String codeParameterKey = "code";
@Value("${ali.sms.endpoint}")
private String endpoint;
@Value("${ali.sms.accessKeyId}")
private String accessKeyId;
@Value("${ali.sms.accessKeySecret}")
private String accessKeySecret;
@Value("${ali.sms.signName}")
private String signName;
@Value("${ali_sms_template}")
private String data;
@Resource
private AjaxResult ajaxResult;
@Resource
private RedisService redisService;
public AjaxResult sendMessage(MessageModel messageModel,
String smsParam, String toPhones) {
Config config = new Config()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret);
try {
// 访问的域名
config.endpoint = endpoint;
Client client = new Client(config);
SendSmsRequest sendSmsRequest = new SendSmsRequest()
.setSignName(signName)//短信签名
.setTemplateCode(messageModel.getSmsTemplateCode())//短信模板
.setPhoneNumbers(toPhones)//这里填写接收短信的手机号码
.setTemplateParam(smsParam);//验证码
// 复制代码运行请自行打印 API 的返回值
SendSmsResponse resp = client.sendSms(sendSmsRequest);
SendSmsResponseBody body = resp.getBody();
if(body.getCode().equals("OK")){
log.info("发送短信返回值:{}",JSON.toJSONString(resp));
return ajaxResult.success();
}
return ajaxResult.error(body.getMessage());
} catch (Exception e) {
e.printStackTrace();
throw new ServiceException("发送短信失败");
}
}
/**
* 发送验证码
*
* @param phone 手机号
* @param type 验证码使用的类型
* @return
*/
public AjaxResult sedCode(String phone, int type) {
if (StringUtils.isEmpty(phone)) {
return ajaxResult.error(ResponeConstant.RESPONE_PARAMETER_ERROR);
}
phone = phone.trim();
//校验短信模板
Integer messageModelIndex = SmsTypeEnums.getSmtTemplateIndexByType(type);
if (messageModelIndex == null) {
return ajaxResult.error(ResponeConstant.RESPONE_SMSTEMPLATE_ERROR);
}
String code = getNewCode();
//配置发送参数前,需要校验此手机号发送频率
PhoneVerificationCode phoneVerificationCode = PhoneVerificationCode.builder()
.count(1)//次数默认为1,此处不做计算
.sendTime(System.currentTimeMillis())
.code(code)
.type(type)
.build();
String msg = checkCode(phoneVerificationCode, phone);
if (!StringUtils.isEmpty(msg)) {
return ajaxResult.error(msg);
}
Map<String, String> map = new HashMap<>();
map.put(codeParameterKey, code);
List<MessageModel> messageModels = JSON.parseArray(data, MessageModel.class);
MessageModel messageModel = messageModels.get(messageModelIndex);
String smsParam = JSON.toJSONString(map);
return sendMessage(messageModel, smsParam, phone);
}
/**
* 生成验证码
*
* @return
*/
private String getNewCode() {
String code = RandomUtils.getNumCode(Integer.parseInt(codeLength));
log.info("验证码 code:{}", code);
return code;
}
}
alisms.properties
ali.sms.endpoint=*******.***.com
ali.sms.accessKeyId=LTAI5tC*********
ali.sms.accessKeySecret=xzhlArjELfVG*********
ali.sms.signName=\u775B\u6676\u4E50*******
#json参数转义
ali_sms_template=[{\"smsFreeSignName\":\"\u775B\u6676\u4E50\u5F31\\u5178",\"smsTemplateCode\":\"SMS_2414777\",\"templateName\":\"\u775B\u6676\u4E50\9C6\u5B9D\u5178\u6CE8\u518C"},\
{\"smsFreeSignName\":\"\u775B\u6676\\u89C6\u5B9D\u5178",\"smsTemplateCode\":\"SMS_4680583\",\"templateName\":\"\u775b\5f31\u89c6\u5b9d\u5178\u6ce8\u518c\u002b\u0035\u0039\u0030"}]
sms_every_day_maxsize=20
sms_maxtime_interval=30
sms_max_active_time=300
ali_sms_code_length=6
SmsTypeEnums.java
package com.smt.cloud.module.app.common.enums;
/**
* 发送短信类型
*/
public enum SmsTypeEnums {
//对应ali_sms_template的数据下标
SMT_TYPE_LOGIN_REGISTER(1, "发送短信用于注册", 0),
SMT_TYPE_REGISTER_PWD(3, "用于修改密码", 0),
SMT_TYPE_CONNER(2, "发送短信用于注销", 1),
SMT_TYPE_LOGIN_ENGLISH(1340, "**典注册+1340", 2), //英语
public int getType() {
return type;
}
public String getValue() {
return value;
}
public int getSmtTemplateIndex() {
return smtTemplateIndex;
}
/**
* 和前端对应的发送短信类型
*/
private int type;
private String value;
/**
* 对应的模板类型
*/
private int smtTemplateIndex;
SmsTypeEnums(int type, String value, int smtTemplateIndex) {
this.type = type;
this.value = value;
this.smtTemplateIndex = smtTemplateIndex;
}
/**
* 根据发送类型,获取响应的模板
*
* @param type
* @return
*/
public static Integer getSmtTemplateIndexByType(int type) {
for (SmsTypeEnums obj : SmsTypeEnums.values()) {
if (obj.type == type) {
return obj.smtTemplateIndex;
}
}
return null;
}
}
使用测试工具或阿里云调试即可,请确保余额够用发送短信会产生费用,详细请看阿里云国际/港澳台短信服务定价相关文档。

更多推荐


所有评论(0)