springboot调用阿里云短信验证服务
到修改密码这里,我采用了阿里的短信验证服务在springboot里面使用阿里云短信服务。
·
自留一个springboot调用阿里云短信服务的文章,以防忘记
文章目录
前言
到修改密码这里,我采用了阿里的短信验证服务
一、官网地址
阿里云官网 ,后面很多云服务都需要用到这个网址,本文章展示短信验证服务
二、使用步骤
1、平台申请步骤
1.1、登录注册省略,点击搜索框,直接搜索短信服务进入短信服务主页
1.2、添加签名与模板
点击国内服务,点击添加签名,根据要求填写,通过率不高
然后点击模板管理,添加模板与上述一样的添加完成即可
现在就等通过,一般1到2个小时就可以出结果了
2.SpringBoot项目配置
1.1、引入坐标
代码如下(示例):
<!-- 阿里云短信验证-->
<!-- https://mvnrepository.com/artifact/com.aliyun/dysmsapi20170525 -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>2.0.24</version>
</dependency>
1.2、创建AccessKey工具类
这个类保存你的AccessKey(如何获取,参考:获取阿里云AccessKey)
代码如下(示例):
package com.wendeyu.result;
/**
* @author Jason Wen
* @version 1.0
*/
public class ALIBABA_CLOUD_ACCESS {
public static final String ALIBABA_CLOUD_ACCESS_KEY_ID="填自己的id";
public static final String ALIBABA_CLOUD_ACCESS_KEY_SECRET="填自己的secret";
}
1.3、创建发送工具类
package com.wendeyu.util;
import com.aliyun.tea.TeaException;
import com.wendeyu.result.ALIBABA_CLOUD_ACCESS;
/**
* @author Jason Wen
* @version 1.0
*
* 短信验证码
*/
public class Sample {
/**
* 使用AK&SK初始化账号Client
* @param accessKeyId
* @param accessKeySecret
* @return Client
* @throws Exception
*/
public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) 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);
}
/**
* 发送验证码
* @param phone 电话
* @param verificationCode 验证码
*/
public static void sendingCode (String phone, String verificationCode){
com.aliyun.dysmsapi20170525.Client client = null;
try {
client = Sample.createClient(ALIBABA_CLOUD_ACCESS.ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS.ALIBABA_CLOUD_ACCESS_KEY_SECRET);
} catch (Exception e) {
e.printStackTrace();
}
com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
.setSignName("这里填你在阿里云申请的签名名称")
.setTemplateCode("这里填你在阿里云申请的模板CODE")
.setPhoneNumbers(phone)//手机号
.setTemplateParam("{\"code\":\"" + verificationCode + "\"}");//这里是发送内容,可以先尝试发送,工具结果修改
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
client.sendSmsWithOptions(sendSmsRequest, runtime);
} catch (TeaException error) {
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
}
3、使用
//在对应的地方直接调用刚刚类里面的方法,传入手机号和验证码即可
Sample.sendingCode(phone, verificationCode);
总结
在springboot里面使用阿里云短信服务
更多推荐
所有评论(0)