导入依赖
<!-- 阿里云短信服务依赖 -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>3.0.0</version>
</dependency>
配置文件
aliyun:
sms:
AccessKey: "" #创建AccessKey后,即可获取
AccessKeySecret: "" #同上
SignName: "" #创建签名,签名是指发送短信的标题, 一般是项目的名字
TemplateCode: "" #模板,是指发送短信的格式
endpoint: "dysmsapi.aliyuncs.com" # 阿里云短信服务API的访问地址
配置类
package com.tanhua.sso.config;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.teaopenapi.models.Config;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "aliyun.sms")
@Slf4j
@Data
public class SmSConfig {
private String AccessKey;
private String AccessKeySecret;
private String SignName;
private String TemplateCode;
private String endpoint;
@Bean
public Client createClient(){
Config config = new Config()
.setAccessKeyId(AccessKey)
.setAccessKeySecret(AccessKeySecret);
config.endpoint = endpoint;
try {
Client client = new Client(config);
return new Client(config);
}catch (Exception e){
log.error("创建Client时出现异常{}",e.getMessage());
return null;
}
}
}
service
package com.tanhua.sso.service;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.tanhua.sso.config.SmSConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
public class SmsService {
@Autowired
private SmSConfig smSConfig;
@Autowired
private RedisTemplate<String,String> redisTemplate;
/**
* 发送短信验证码
*
* @param mobile 手机号码
* @throws Exception 如果发送过程中出现错误
*/
public int sendSms(String mobile){
Client client = smSConfig.createClient();
if(client==null){
return 0; //错误
}
// 创建一个对象节点
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode objectCode = objectMapper.createObjectNode();
int codeValue = RandomUtils.nextInt(100000, 999999);
objectCode.put("code", codeValue);
// 创建发送短信请求
SendSmsRequest sendSmsRequest = new SendSmsRequest()
.setSignName(smSConfig.getSignName())
.setTemplateCode(smSConfig.getTemplateCode())
.setPhoneNumbers(mobile)
.setTemplateParam(objectCode.toString());
RuntimeOptions runtime = new RuntimeOptions();
try {
// 发送短信并获取响应
SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
SendSmsResponseBody sendSmsResponseBody = sendSmsResponse.getBody();
log.info("code:{}\nmessage:{}\nbizId:{}\nrequestId:{}", sendSmsResponseBody.getCode(),sendSmsResponseBody.getMessage(),sendSmsResponseBody.getBizId(),sendSmsResponseBody.getRequestId());
if(sendSmsResponseBody.getMessage().equals("OK")){
log.info("验证码发送成功,验证码:{}",codeValue);
return codeValue;
}
return 0;
} catch (TeaException error) {
// 处理特定的TeaException
log.error("发送短信时发生错误: {}", error.getMessage());
if (error.getData() != null && error.getData().containsKey("Recommend")) {
log.error("推荐解决方案: {}", error.getData().get("Recommend"));
}
throw new RuntimeException("发送短信时发生错误", error);
} catch (Exception error) {
// 处理其他异常
log.error("发送短信时发生未知错误: {}", error.getMessage(), error);
throw new RuntimeException("发送短信时发生未知错误", error);
}
}
public Map<String,Object> sendCheckCode(String mobile){
HashMap<String, Object> result = new HashMap<>(2);
try {
String redisKey = "CHECK_CODE_"+mobile;
String value = redisTemplate.opsForValue().get(redisKey);
if(StringUtils.isNotEmpty(value)){ //长度不为0且不为null
result.put("code",1);
result.put("msg","上一次发送的验证码还未失效");
return result;
}
int code = sendSms(mobile);
if(code==0){
result.put("code",2);
result.put("msg","发送短信验证码失败");
return result;
}
//发送验证码成功
result.put("code",3);
result.put("msg","ok");
//将验证码存储到redis,3分钟后失效
redisTemplate.opsForValue().set(redisKey,String.valueOf(code),3, TimeUnit.MINUTES);
return result;
}catch (Exception e){
result.put("code", 4);
result.put("msg", "发送验证码出现异常");
return result;
}
}
}