Skip to content

短信扩展

本页面介绍如何扩展短信通道。

短信架构

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: MISEB

4. 配置短信模板

在管理后台配置短信模板

场景模板ID模板内容
验证码TPL001您的验证码是${code},5分钟内有效
发货通知TPL002您的订单${orderNo}已发货

短信接口说明

SmsRequest

字段类型说明
phoneString手机号
templateIdString模板ID
paramsMap模板参数

SmsResult

字段类型说明
successBoolean是否成功
msgIdString消息ID
errorCodeString错误码
errorMsgString错误信息

使用示例

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腾讯云短信

下一步

成都艾唯特软件有限公司