最近项目中需要发短信,用到了阿里云短信,写篇文章记录一下过程。
1.对接流程
- 注册账号之类的我就省略了。
- 添加签名,就是短信开头那个用【】框起来的。
3.添加模板,具体的短信内容,可以用变量代替。
4.接下来直接使用api中的具体接口即可。
2.方法代码
以发送验证码为例,看一下官方文档还是很简单的。
/**
* 发送验证码
*
* @param phone 手机号码
* @param code 验证码
* @return
*/
public static void getCode(String phone, String code) {
DefaultProfile profile = DefaultProfile.getProfile(AliSmsConfig.RegionId, AliSmsConfig.AccessKeyId, AliSmsConfig.Secret);
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", phone);
request.putQueryParameter("SignName", "xxx");
request.putQueryParameter("TemplateCode", "SMS_11111111");
request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
} catch (ServerException e) {
e.printStackTrace();
throw new BizException("验证码发送失败");
} catch (ClientException e) {
e.printStackTrace();
throw new BizException("验证码发送失败");
}
}