衡水做网站建设服务之家网站推广
一、创建阿里云短信权限用户
1、登陆阿里云之后我们点击头像,接着点击AccessKey:
2、选择开始使用子用户 :
3、我们先要创建一个用户组:
4、依次点击新建的用户组——授权管理,给用户组授权,开通短信验证码服务:
5、接着我们新建一个用户(具体用来操作的账号),一定要勾选OpenAPI调用访问
,这样我们才能通过代码访问:
记得把AccessKey保存下来,以为后面会看不到:
6、接着将这个用户添加到刚刚的用户组即可:
二、开通阿里云短信服务
1、在搜索框搜索短信服务
,点击加载之后,选择免费开通
,即可开通短信服务。
2、我们开通短信服务之后,还要设置签名和模板:
签名就相当于公司名称,模板就是短信的模板,验证码短信分为几部分:
默认会给我们设置一个模板,我们可以直接用这个模板(注意:模板一定要和某个签名绑定,否则发送不了验证码):
但是没有默认的签名,我们需要自己添加,申请里有一定要有理有据,比较正当,等待审核通过即可:
可以在快速学习和测试模块,体验一下短信验证码的使用:
这一块也会有实现短信验证码功能的代码:
三、编写测试代码
我们可以在帮助文档中查看具体的使用步骤:帮助文档
1、首先在项目中导入Java SDK的依赖:
<!--阿里云短信验证码sdk--><dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-core</artifactId><version>4.5.16</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.83</version></dependency><!--springboot集成redis--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
然后编写一个测试类来测试是否能正常发送验证码:
//连接阿里云DefaultProfile profile = DefaultProfile.getProfile("cn-beijing", "Your AccessKey ID", "Your AccessKey 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("PhoneNumbers","xxxx"); //手机号request.putQueryParameter("SignName","xxxx"); //申请阿里云 签名名称request.putQueryParameter("TemplateCode","xxxxx"); //申请阿里云 模板codeHashMap<String, Object> map = new HashMap<>();map.put("code", 123456);request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));//验证码数据,转换json数据传递try{CommonResponse response = client.getCommonResponse(request);System.out.println(response.getData());} catch (ClientException e){e.printStackTrace();}
测试代码写完之后我们就可以执行这段代码进行测试了,结果成功!
四、封装发送短信接口
1、编写Service接口:
public interface SendSms {//手机号、模板代码、验证码public boolean send(String phoneNum, String templateCode, Map<String, Object> code);
}
2、编写接口实现类:
@Service
public class SendSmsImpl implements SendSms {@Overridepublic boolean send(String phoneNum, String templateCode, Map<String, Object> code) {//连接阿里云DefaultProfile profile = DefaultProfile.getProfile("cn-beijing", "LTAI5tMk6A312KwNVnxNuTno", "1MyEwE0uqfHYTFyFAcydutAFBZgGBj");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("PhoneNumbers",phoneNum); //手机号request.putQueryParameter("SignName","唐世华个人签名"); //申请阿里云 签名名称request.putQueryParameter("TemplateCode",templateCode); //申请阿里云 模板coderequest.putQueryParameter("TemplateParam", JSONObject.toJSONString(code));//验证码数据,转换json数据传递,这里要用maptry{CommonResponse response = client.getCommonResponse(request);System.out.println(response.getData());return response.getHttpResponse().isSuccess(); //判断发送是否成功} catch (ClientException e){e.printStackTrace();}return false;}
}
3、编写Controller测试类:
@RestController
@CrossOrigin //跨域支持
public class SendSmsController {@Autowiredprivate SendSms sendSms;@Autowiredprivate RedisTemplate<String, String> redisTemplate;@GetMapping("/send/{phone}")public String code(@PathVariable("phone") String phone){//调用方法模拟真实业务//如果redis缓存中存在手机号的验证码,说明验证码还未过期,可继续使用String code = redisTemplate.opsForValue().get(phone);System.out.println(code);if(!StringUtils.isEmpty(code)){return phone + ":" + code + "已存在,还没有过期,可继续使用!";}//生成验证码并存储到redis中//生成验证码(包含数字和字母)//code = UUID.randomUUID().toString().substring(0, 4);//生成纯数字int uuid = UUID.randomUUID().toString().replaceAll("-","").hashCode();uuid = uuid < 0 ? -uuid : uuid;//String.hashCode() 值会为空code = String.valueOf(uuid).substring(0, 4);HashMap<String, Object> param = new HashMap<>();param.put("code", code);boolean isSend = sendSms.send(phone, "SMS_274310067", param); //发送验证码if(isSend){ //发送成功redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.SECONDS); //将验证码存到redis,设置5分钟过期return phone + ":" + code + "发送成功!";}else {return "发送失败";}}}
完结撒花!!