3.3 实现

# 实现 在实现类中主要调用了阿里云的短信服务接口进行发送短信操作,其中所涉及的accessKeyId、accessSecret、signName、action、version、domain、regionId、randCode 等等配置字段都会在配置文件中进行写入,然后在配置类中进行映射。 ``` @Service("memberSmsService") public class MemberSmsServiceImpl implements MemberSmsService { Logger logger = LoggerFactory.getLogger(MemberSmsServiceImpl.class); @Autowired SmsConfigurationEntity configurationEntity; @Override public ResponseEntity sendMsg(Map<String, Object> params) { String phone= (String) params.get("phone"); String templateCode= (String) params.get("templateCode"); // 配置属性 DefaultProfile profile = DefaultProfile.getProfile(configurationEntity.getRegionId(), configurationEntity.getAccessKeyId(), configurationEntity.getAccessSecret()); // 客户端 IAcsClient client = new DefaultAcsClient(profile); // 创建请求 CommonRequest request = new CommonRequest(); // 发送请求的方法 request.setMethod(MethodType.POST); // 发送请求的域名 request.setDomain(configurationEntity.getDomain()); //系统规定参数 request.setAction(configurationEntity.getAction()); // 版本信息 已经固定 不能进行更改 request.setVersion(configurationEntity.getVersion()); /* 必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码, 批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式; 发送国际/港澳台消息时,接收号码格式为国际区号+号码,如“85200000000” */ request.putQueryParameter("PhoneNumbers", phone); // 签名 request.putQueryParameter("SignName", configurationEntity.getSignName()); // 阿里云控制台模板编号 request.putQueryParameter("TemplateCode", templateCode); // 模板内需要填充参数信息 request.putQueryParameter("TemplateParam", "{\"code\":" + getRandCode(configurationEntity.getRandCode()) + "}"); // regionId 区域id request.putQueryParameter("RegionId", configurationEntity.getRegionId()); try { CommonResponse response = client.getCommonResponse(request); ResponseEntity responseEntity = new ResponseEntity(); responseEntity.setMessage(GetValueUtils.getPhoneStr(response.getData(),"Message")); responseEntity.setRequestId(GetValueUtils.getPhoneStr(response.getData(),"RequestId")); responseEntity.setCode(GetValueUtils.getPhoneStr(response.getData(),"Code")); return responseEntity; } catch (Exception e) { return null; } } // 获取随机验证码 @Override public String getRandCode(int digits) { StringBuilder sBuilder = new StringBuilder(); Random rd = new Random(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli()); for (int i = 0; i < digits; i++) { sBuilder.append(rd.nextInt(9)); } return sBuilder.toString(); } } ```