阿里云的手机短信验证

控制层

 //发送验证码
    @RequestMapping("/sendVerifyCode")
    @ResponseBody
    public ResponseEntity sendVerifyCode(String iphone, HttpServletRequest request){
    
    
        System.out.println(""+iphone);
        int httpStatus = wechatUserService.sendVerifyCode(iphone, request.getServletContext());
        Map<String, Integer> map = new HashMap<>();
        map.put("httpStatus", httpStatus);
        return ResponseEntity.ok(map);
    }

业务逻辑层

   //发送验证码
    int sendVerifyCode(String iphone, ServletContext session);
   //发送验证码
    @Override
    public int sendVerifyCode(String iphone, ServletContext context) {
    
    
        // 随机生成六位随机数
        StringBuffer code = new StringBuffer();
        for (int x = 0; x <= 5; x++) {
    
    
            int random = (int) (Math.random() * (10 - 1));
            code.append(random);
        }

        // 设置AccessKey
        final String accessKeyId = "xxxx";
        final String accessKeySecret = "xxxx";
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        // 组装请求对象
        CommonRequest request = new CommonRequest();
        //使用post提交
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");

        Map<String, String> queryParameters=request.getSysQueryParameters();
        // 需要发送的手机号
        queryParameters.put("xxxx", iphone);
        // 短信签名-可在短信控制台中找到
        queryParameters.put("xxxx", "xxx");
        // 设置短信模板
        queryParameters.put("xxxx", "xxxx");
        // 模板中显示的验证码信息
        queryParameters.put("xxx", "{\"code\":\"" + code.toString() + "\"}");

        CommonResponse response = null;
        try {
    
    
            response = acsClient.getCommonResponse(request);
        } catch (ServerException e) {
    
    
            e.printStackTrace();
        } catch (ClientException e) {
    
    
            e.printStackTrace();
        }
        long timestamp=System.currentTimeMillis()/1000;
        VerifyIphoneCode verifyIphoneCode = new VerifyIphoneCode(iphone,code.toString(),timestamp);
        System.out.println(""+iphone);
        //以手机号为key进行存储
        context.setAttribute(iphone,verifyIphoneCode);
        return response.getHttpStatus();
    }

接收的实体类 时间戳,手机号 ,手机验证码存储

    private String iphone;
    private String verifyCode;
    private Long timestamp;

猜你喜欢

转载自blog.csdn.net/sqL520lT/article/details/111058140
今日推荐