调用发送短信代码
1、此处:String template = “SMS_22*****05”;这里修改为你自己的短信模板
@Autowired
private SendSmsImpl sendSms;
@CrossOrigin
@PostMapping("/aliyun")
@ApiOperation(value = "发送阿里云短信验证码",response = R.class)
public R aliyun(@Validated RequestAliyunNoteEntity requestAliyunNoteEntity) {
String account = requestAliyunNoteEntity.getAccount();
String template = "SMS_22*****05";
HashMap<String, Object> mp = new HashMap<>();
StringBuilder sb = new StringBuilder();
Random random = new Random();
for(int i=0;i<6;i++){
sb.append(random.nextInt(10));
}
mp.put("code",sb);
boolean send = sendSms.send(account, template, mp);
if(send){
Boolean aBoolean = clientCodeService.saveNote(account, sb.toString());
if(aBoolean){
return R.ok();
}else{
return R.error("出现了点意外!");
}
}else{
return R.error("刚刚发生了什么事儿?");
}
}
二、发送短信的主要代码
public interface SendSms {
boolean send(String phoneNum, String templateCode, Map<String,Object> code);
}
1、此处:DefaultProfile profile = DefaultProfile.getProfile(“cn-hangzhou”, “参数2”, “参数3”); 需要将2、3参数修改为自己的accessKeyId和secret 2、此处:request.putQueryParameter(“SignName”, “参数2”);参数2需要修为自己的前面名称,否则不可用
@Service
public class SendSmsImpl implements SendSms{
@Override
public boolean send(String phoneNum, String CODE, Map<String, Object> code) {
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "####5tNzdq3Gw8Wh########", "####qRNeKwUrEQjsAwIbIb########");
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setMethod(MethodType.POST);
request.setDomain("dysmsapi.aliyuncs.com");
request.setVersion("2017-05-25");
request.setAction("SendSms");
request.putQueryParameter("RegionId", "cn-hangzhou");
request.putQueryParameter("PhoneNumbers", phoneNum);
request.putQueryParameter("SignName", "帮运天下");
request.putQueryParameter("TemplateCode", CODE);
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(code));
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
return response.getHttpResponse().isSuccess();
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
return false;
}
}
最终效果图:
|