1. 注册阿里云账号,并实名认证
2. 创建AccessKey
,用小本本记下 AccessKey ID和 AccessKey Secret,它们是你访问阿里云 API 的密钥,具有该账户完全的权限
3. 访问阿里云短信服务
3.1 链接:https://www.aliyun.com/product/sms?spm=5176.19720258.J_9220772140.58.15e32c4a5yRc1L
3.2 选择想要开通的短信套餐,当然也可以先免费试用
3.2 在免费试用列表找到 [短信免费使用套餐包]
3.4 选择0元试用,订单支付完毕后,访问短信服务控制台:
3.5 配置短信签名和模板,签名是指短信内容前使用“【】”的内容,而模板是指具体内容,代码中需要用到的是签名和模板CODE,模板中的${code}表示需要填充的验证码。填写完毕提交审核,快的话1-2个小时。
3.6 接着可以打开OpenAPI看使用示例,需要替换的参数有:手机号码、签名、模板、验证码。
4. 项目中使用
4.1 在pom.xml中加入依赖:
1 <dependency> 2 <groupId>com.aliyun</groupId> 3 <artifactId>aliyun-java-sdk-core</artifactId> 4 <version>4.5.3</version> 5 </dependency>
4.2 新建类:SendSms.java
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.zxin.dev.pojo.Constant;
public class SendSms {
public static void send(String signName, String templateCode, String phone, String code) {
// 填写自己阿里云账号的AccessKey ID和AccessKey Secret, regionId为cn-hangzhou
DefaultProfile profile = DefaultProfile.getProfile(Constant.REGION_ID, Constant.ACCESS_KEY_ID, Constant.ACCESS_SECRET);
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setSysMethod(MethodType.POST);
// 服务相关的信息,不可修改。
request.setSysDomain("dysmsapi.aliyuncs.com");
request.setSysVersion("2017-05-25");
request.setSysAction("SendSms");
request.putQueryParameter("RegionId", "cn-hangzhou");
// 根据需求替换参数
// 短信签名
request.putQueryParameter("SignName", signName);
// 短信模板ID
request.putQueryParameter("TemplateCode", templateCode);
// 目标手机号
request.putQueryParameter("PhoneNumbers", phone);
// 验证码
request.putQueryParameter("TemplateParam", "{\"code\":"+code+"}");
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
}
}
4.3 前端 (vue) 发送验证码和提交表单函数
1 handleSendVerifyCode() { 2 const data = { 3 phone: this.user.phone, 4 purpose: 'register' 5 } 6 sendVerifyCode(data).then(res => { 7 this.$message({ 8 type: 'success', 9 message: res.message 10 }) 11 }) 12 }, 13 handleSubmit() { 14 this.loading = true 15 const data = { 16 name: this.user.name, 17 phone: this.user.phone, 18 verifyCode: this.user.verifyCode 19 } 20 register(data).then(res => { 21 this.loading = false 22 this.drawerVisibleUserRegister = false 23 this.$message({ 24 type: 'success', 25 message: res.message 26 }) 27 }) 28 }
4.4 新建静态常量类(非必需),根据自己需求:
4.5 写发送验证码接口和验证注册信息的接口
1 @PostMapping("sendVerifyCode") 2 public JSONObject sendVerifyCode(HttpServletRequest request, @RequestBody Map<String, String> params) { 3 JSONObject resultJson = new JSONObject(); 4 // 自己写的生成6位随机数字字符的方法(注意: 验证码虽然是字符串,但首位也不能为0,否则发出的是5位数。) 5 String verifyCode = StringUtil.getRandom(6); 6 7 // 在不同的表单发送验证码,使用不同的短信模板 8 switch (params.get("purpose")){ 9 // 注册 10 case "register" : 11 SendSms.send(Constant.SIGE_NAME,Constant.TEMPLATE_CODE_REGISTER,params.get("phone"),verifyCode); 12 break; 13 // 修改密码 14 case "changePassword": 15 SendSms.send(Constant.SIGE_NAME,Constant.TEMPLATE_CODE_CHANGE_PASSWORD,params.get("phone"),verifyCode); 16 break; 17 } 18 JSONObject jsonCode = new JSONObject(); 19 jsonCode.put("phone", params.get("phone")); 20 jsonCode.put("verifyCode", verifyCode); 21 jsonCode.put("createTime", System.currentTimeMillis()); 22 request.getSession().setAttribute("verifyCode", jsonCode); 23 resultJson.put("code", 20000); 24 resultJson.put("message", "短信验证码发送成功"); 25 return resultJson; 26 }
1 @PostMapping("register") 2 public JSONObject register(HttpSession session, @RequestBody Map<String, String> params) { 3 String name = params.get("name"); 4 String phone = params.get("phone"); 5 String verifyCode = params.get("verifyCode"); 6 JSONObject resultJson = new JSONObject(); 7 JSONObject sessionVerifyCode = (JSONObject)session.getAttribute("verifyCode"); 8 if (phone.equals(sessionVerifyCode.get("phone")) && verifyCode.equals(sessionVerifyCode.get("verifyCode"))){ 9 resultJson.put("code", 20000); 10 resultJson.put("message", "注册成功"); 11 }else{ 12 // TODO: 13 resultJson.put("code", 300); 14 resultJson.put("message", "注册失败,验证码不正确"); 15 } 16 return resultJson; 17 }
5. 结果展示
5.1 发送验证码(还需要设置超时时间,1分钟内不可重复点击)
5.2 手机收到短信
5.3 校验通过
最后:这个示例中还有很多需要改进的,但作为学习接入阿里云短信服务的demo已经足够了,其中还有许多小问题,比如getSession = null等等,查了半天资料,发现是自己搭建的环境有些问题。
如果这篇博客还有其他问题,欢迎评论指正!