环境搭建
1. 登录阿里云官网:阿里云-计算,为了无法计算的价值
2. 创建AcessKey
AccessKey ID 和 AccessKey Secret 是我们访问阿里云API 的密钥,具有该账户完全的权限,需要我们妥善保管。
点击创建并保存创建好的AccessKeyID和AccessKey Secret。后续不支持再次查看,获取后将它们保存好。
3. 开通短信服务
3.1. 通过搜索找到短信服务,点击产品详情页进行服务购买
3.2. 购买成功后,返回上次页面进入短信控制台
进入控制台后点击快速学习和测试,并将快速学习中的五个步骤依次处理完。
第四步系统设置可以先不管,直接测试短信发送。
4. 集成短信sdk到项目
sdk参考地址:短信服务SDK下载和安装_短信服务(SMS)-阿里云帮助中心
这里有各个版本、语言的SDK,我们按照需要下载即可。下面以Java SDK为例,点击下载Java SDK进入如下页面:
4.1. 在所需要的工程下引入短信服务依赖和fastjson依赖
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>${fastjson.version}</version>
</dependency>
4.2. 核心配置代码
示例代码中直接将配置变量和业务代码写在一起,方便展示。但是,在开发中,我们需要将这些配置单独的抽出来,然后交给spring管理这个bean,以后发生变化了,不需要大面积修改代码。只需修改我们的核心配置类就好了。
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AliMessageConfig {
@Value("${sms.aliyun.accessKeyId:}")
private String accessKeyId;
@Value("${sms.aliyun.accessKeySecret:}")
private String accessKeySecret;
@Value("${sms.aliyun.endpoint:}")
private String endpoint;
@Bean("aliClient")
public Client client() throws Exception {
Config config = new Config()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret)
.setEndpoint(endpoint);
return new Client(config);
}
}
4.3. 核心发送逻辑
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.dysmsapi20170525.models.SendSmsResponseBody;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
@Slf4j
public class AliSmsService {
@Autowired
private Client aliClient;
//业务配置
@Value("${sms.aliyun.templateCode:}")
private String templateCode;
@Value("${sms.send-message:true}")
private boolean sendMessage;
@Value("${sms.sing-name:}")
private String singName;
/**
* 发送短信验证码
* @param phone 手机号
* @param code 验证码
* @return
* @throws Exception
*/
public boolean sendMobileCode(String phone, String code) throws Exception {
Map<String, String> params = new HashMap<>();
params.put("code", code);
return sendTempMessage(phone, singName, templateCode, params);
}
/**
* 发送模板信息
* @param phone 手机号
* @param templateCode 模板code
* @param params 模板信息变量
* @return
* @throws Exception
*/
public boolean sendTempMessage(String phone, String singName, String templateCode, Map<String, String> params) throws Exception {
if (!sendMessage) {
log.error("短信发送通道关闭,发送失败......" + phone);
return false;
}
SendSmsRequest sendSmsRequest = new SendSmsRequest();
sendSmsRequest.setPhoneNumbers(phone);
sendSmsRequest.setSignName(singName);
sendSmsRequest.setTemplateCode(templateCode);
sendSmsRequest.setTemplateParam(JSON.toJSONString(params));
SendSmsResponse sendSmsResponse = aliClient.sendSms(sendSmsRequest);
SendSmsResponseBody responseBody = sendSmsResponse.getBody();
try {
if (!"OK".equalsIgnoreCase(responseBody.getCode())) {
log.error("短信{} 发送失败,失败原因:{}.... ", JSON.toJSONString(sendSmsRequest), responseBody.getMessage());
return false;
}
return true;
} catch (Exception e) {
log.error("短信{} 发送失败,失败原因:{}.... ", JSON.toJSONString(sendSmsRequest), e.getMessage());
return false;
}
}
}
我的文件如下:
由于我使用的是微服务的形式,单独为阿里云短信服务创建了一个服务,当其他服务想要获取到该服务的时候,该服务需要确保被注入到项目中。 所以我在resource目录下继续创建了META-INF,然后继续创建spring目录,然后创建org.springframework.boot.autoconfigure.AutoConfiguration.imports文件,在里面写入配置类和服务类的包名和类名,,目的是为了通过 Spring Boot 的自动配置机制,将你创建的阿里云短信服务模块自动注入到需要使用它的其他微服务中。
5. 测试短信验证码
5.1. 加入参数配置:
5.2. 测试代码:
import com.guan.common.core.baseController.BaseController;
import com.guan.common.core.domain.R;
import com.guan.common.message.service.AliSmsService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class TestController extends BaseController {
@Resource
private AliSmsService aliSmsService;
@GetMapping("/sendCode")
public R<Void> sendCode(String phone, String code) throws Exception {
return toR(aliSmsService.sendMobileCode(phone, code));
}
}