短信扩展
本页面介绍如何扩展短信通道。
短信架构
SmsService (短信服务接口)
│
├── AliyunSmsServiceImpl (阿里云短信)
├── TencentSmsServiceImpl (腾讯云短信)
└── CustomSmsServiceImpl (自定义短信)实现步骤
1. 实现短信接口
java
@Service
public class CustomSmsServiceImpl implements SmsService {
@Override
public String getType() {
return "custom";
}
@Override
public SmsResult send(SmsRequest request) {
// 1. 构建短信参数
String phone = request.getPhone();
String content = request.getContent();
Map<String, String> params = request.getParams();
// 2. 调用第三方短信接口
// HttpUtil.post(...)
// 3. 返回发送结果
SmsResult result = new SmsResult();
result.setSuccess(true);
result.setMsgId("msg_123456");
return result;
}
@Override
public boolean checkBalance() {
// 检查短信余额
return true;
}
}2. 注册短信通道
java
@Configuration
public class SmsConfig {
@Bean
public SmsService customSmsService() {
return new CustomSmsServiceImpl();
}
}3. 配置短信参数
yaml
# application.yml
sms:
type: custom
custom:
apiUrl: https://sms.example.com/send
apiKey: your_api_key
apiSecret: your_api_secret
signName: MISEB4. 配置短信模板
在管理后台配置短信模板
| 场景 | 模板ID | 模板内容 |
|---|---|---|
| 验证码 | TPL001 | 您的验证码是${code},5分钟内有效 |
| 发货通知 | TPL002 | 您的订单${orderNo}已发货 |
短信接口说明
SmsRequest
| 字段 | 类型 | 说明 |
|---|---|---|
| phone | String | 手机号 |
| templateId | String | 模板ID |
| params | Map | 模板参数 |
SmsResult
| 字段 | 类型 | 说明 |
|---|---|---|
| success | Boolean | 是否成功 |
| msgId | String | 消息ID |
| errorCode | String | 错误码 |
| errorMsg | String | 错误信息 |
使用示例
java
@Autowired
private SmsService smsService;
public void sendVerifyCode(String phone, String code) {
SmsRequest request = new SmsRequest();
request.setPhone(phone);
request.setTemplateId("TPL001");
request.setParams(Map.of("code", code));
SmsResult result = smsService.send(request);
if (!result.isSuccess()) {
throw new BusinessException("短信发送失败:" + result.getErrorMsg());
}
}现有短信通道
| 通道 | 类 | 说明 |
|---|---|---|
| 阿里云 | AliyunSmsServiceImpl | 阿里云短信 |
| 腾讯云 | TencentSmsServiceImpl | 腾讯云短信 |
