package com.tcm.training.admin.app.auth.service; import com.tcm.training.admin.app.auth.config.AppAliyunSmsProperties; import com.tcm.training.admin.common.PhoneMasker; import com.tcm.training.admin.utils.MsgUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.Collections; import java.util.Map; /** * APP 短信发送阿里云实现。 */ @Service public class AliyunAppSmsSender implements AppSmsSender { private static final Logger log = LoggerFactory.getLogger(AliyunAppSmsSender.class); private final MsgUtils msgUtils; private final AppAliyunSmsProperties properties; /** * 注入阿里云短信工具与模板配置。 */ public AliyunAppSmsSender(MsgUtils msgUtils, AppAliyunSmsProperties properties) { this.msgUtils = msgUtils; this.properties = properties; } /** * 发送 APP 登录验证码。 */ @Override public void sendLoginCode(String phone, String code) { sendCode(phone, code, properties.getTemplates().getLogin(), "登录"); } /** * 发送 APP 注册验证码。 */ @Override public void sendRegisterCode(String phone, String code) { sendCode(phone, code, properties.getTemplates().getRegister(), "注册"); } /** * 发送 APP 忘记密码验证码。 */ @Override public void sendPasswordResetCode(String phone, String code) { sendCode(phone, code, properties.getTemplates().getPasswordReset(), "忘记密码"); } /** * 发送 APP 修改手机号验证码。 */ @Override public void sendPhoneChangeCode(String phone, String code) { sendCode(phone, code, properties.getTemplates().getPhoneChange(), "修改手机号"); } /** * 按场景发送验证码短信,并统一处理配置校验与日志。 */ private void sendCode(String phone, String code, String templateCode, String sceneName) { validateSmsConfig(templateCode); Map params = Collections.singletonMap("code", code); try { msgUtils.sendMsg(phone, params, templateCode, properties.getSignName()); log.info("APP{}验证码发送成功,手机号={}, templateCode={}", sceneName, PhoneMasker.mask(phone), templateCode); } catch (Exception exception) { log.error("APP{}验证码发送失败,手机号={}, templateCode={}", sceneName, PhoneMasker.mask(phone), templateCode, exception); if (exception instanceof IllegalStateException) { throw (IllegalStateException) exception; } throw new IllegalStateException("短信发送失败,请稍后重试"); } } /** * 校验阿里云短信发送配置是否完整。 */ private void validateSmsConfig(String templateCode) { if (isBlank(properties.getAccessKeyId()) || isBlank(properties.getAccessKeySecret()) || isBlank(properties.getSignName()) || isBlank(templateCode)) { throw new IllegalStateException("短信发送配置不完整"); } } /** * 判断字符串是否为空白。 */ private boolean isBlank(String value) { return value == null || value.trim().isEmpty(); } }