springboot如何接入阿里云短信
登录阿里云开通短信模块
得到审核通过的签名
审核通过后,阿里云会赠送一条验证码模板,可以直接使用,如果有其他业务情况,可自行申请
引入阿里云短信依赖
pom.xml
<!--引入阿里云短信-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>2.0.18</version>
</dependency>
短信类代码如下:
public class SendMsg {
private static final String accessKeyId = "你的KeyId";
private static final String accessKeySecret = "你的KeySecret";
/**
* 使用AK&SK初始化账号Client
*
* @return Client
* @throws Exception
*/
public static com.aliyun.dysmsapi20170525.Client createClient() throws Exception {
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// 您的 AccessKey ID
.setAccessKeyId(accessKeyId)
// 您的 AccessKey Secret
.setAccessKeySecret(accessKeySecret);
// 访问的域名
config.endpoint = "dysmsapi.aliyuncs.com";
return new com.aliyun.dysmsapi20170525.Client(config);
}
/**
* 发送短信验证码
**/
public static boolean send(String mobies, String content) {
try {
com.aliyun.dysmsapi20170525.Client client = SendMsg.createClient();
com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest();
sendSmsRequest.setSignName("你的短信去签名,例如【中国移动】")
.setTemplateCode("你的短信模板code")
.setPhoneNumbers(mobies)
.setTemplateParam("{\"code\":\"" + content + "\"}");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
// 复制代码运行请自行打印 API 的返回值
SendSmsResponse response = client.sendSmsWithOptions(sendSmsRequest, runtime);
if ("OK".equals(response.getBody().getCode())) {
return true;
} else {
System.out.println(response.getBody().getCode());
return false;
}
} catch (TeaException error) {
// 如有需要,请打印 error
com.aliyun.teautil.Common.assertAsString(error.message);
error.printStackTrace();
return false;
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// 如有需要,请打印 error
com.aliyun.teautil.Common.assertAsString(error.message);
error.printStackTrace();
return false;
}
}
}
最终效果: