Java+阿里云手机验证码发送和验证

技术依赖:spring boot 技能掌握:java,spring boot框架,redis

文章简介:通过接入阿里云的短信服务的发送验证的接口,实现验证码的发送。 
一、准备阶段 
1.1spring boot的项目的搭建 
1.2准备接入接口的资料 
参考阿里云的官方文档:https://help.aliyun.com/document_detail/55284.html?spm=a2c4g.11186623.6.557.2lq7AO 
必须完成的步骤: 
(1)进入阿里云服务台->服务与产品—>短信服务; 
(2)接口调用中获取AccessKey(必须); 
(3)签名管理中,添加一个签名,最好是自己账号的用户名,否则容易审核不通过;记录签名名称; 
(4)模板管理中,添加一个短信模板,记录模板Code 

二、Java代码 
可以下载阿里官方提供的代码。下面是我使用的代码,仅供参考。 
2.1 导入所需要的jar包

<dependency>

   <groupId>com.aliyun</groupId>

   <artifactId>aliyun-java-sdk-core</artifactId>

   <version>4.0.0</version>

</dependency>

<dependency>

   <groupId>com.aliyun</groupId>

   <artifactId>aliyun-java-sdk-dysmsapi</artifactId>

   <version>1.1.0</version>

</dependency>

<!-- Spring Boot Redis依赖 -->

<dependency>

   <groupId>org.springframework.boot</groupId>

   <artifactId>spring-boot-starter-data-redis</artifactId>

   <!-- 1.5的版本默认采用的连接池技术是jedis  

        2.0以上版本默认连接池是lettuce, 在这里采用jedis,

        所以需要排除lettuce的jar -->

   <exclusions>

      <exclusion>

         <groupId>redis.clients</groupId>

         <artifactId>jedis</artifactId>

      </exclusion>

      <exclusion>

         <groupId>io.lettuce</groupId>

         <artifactId>lettuce-core</artifactId>

      </exclusion>

   </exclusions>

</dependency>

 

<!-- 添加jedis客户端 -->

<dependency>

   <groupId>redis.clients</groupId>

   <artifactId>jedis</artifactId>

</dependency>

 

<!--spring2.0集成redis所需common-pool2-->

<!-- 必须加上,jedis依赖此  -->

<dependency>

   <groupId>org.apache.commons</groupId>

   <artifactId>commons-pool2</artifactId>

   <version>2.5.0</version>

</dependency>  

 

2.2 要发送手机验证的接口PhoneController.java

import com.aliyuncs.DefaultAcsClient;

import com.aliyuncs.IAcsClient;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;

import com.aliyuncs.exceptions.ClientException;

import com.aliyuncs.profile.DefaultProfile;

import com.aliyuncs.profile.IClientProfile;

import com.yx.open.util.*;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;

import java.util.Map;

 

@RestController

@SpringBootApplication

@CrossOrigin(origins = "*", maxAge = 3600)//解决跨域的请求

@RequestMapping(value = "/api/code")

public class PhoneCodeController {

 

    //短信API产品名称(短信产品名固定,无需修改)

    static private final String product = "Dysmsapi";

    //短信API产品域名(接口地址固定,无需修改)

    static private final String domain = "dysmsapi.aliyuncs.com";

 

    static private final String accessKeyId = "";

    static private final String accessKeySecret = "";

 

    @RequestMapping(value = "/phoneCode", method = RequestMethod.POST)

    @ResponseBody

    public string sendCode(HttpServletRequest req) throws ClientException {

 

        //设置超时时间-可自行调整

        System.setProperty("sun.net.client.defaultConnectTimeout", "60000");

        System.setProperty("sun.net.client.defaultReadTimeout", "60000");

 

        String userPhone = req.getParameter()("userPhone");

 

        //验证码code

        String code = RandomCode.getRandomNumCode(4);

        //短信签名

        String signName = "";//写你自己申请的签名名称

        //短信模板

        String templateCode = "";//短信模板的CODE

 

        //初始化ascClient,暂时不支持多region(请勿修改)

        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,accessKeySecret);

        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);

        IAcsClient acsClient = new DefaultAcsClient(profile);

 

        //组装请求对象

        SendSmsRequest request = new SendSmsRequest();

 

        request.setPhoneNumbers(userPhone);

        request.setSignName(signName);

        request.setTemplateCode(templateCode);

        request.setTemplateParam("{\"name\":\""+userPhone+"\", \"code\":\""+code+"\"}");

 

        //请求失败这里会抛ClientException异常

        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

        if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {

 

            try {

                RedisClientServer.set("code"+userPhone,code,600);

            }catch (Exception e){

                e.printStackTrace();

                return "";

            }

 

            return "success";

        }else {

            return null;

        }

}

 

2.3 生成随机数字和redis的工具类

RandomCode.java

 

import java.util.Random;

 

public class RandomCode {

    /**

     * 生成数字验证码

     * @param number

     * @return

     */

    public static String getRandomNumCode(int number){

        String codeNum = "";

        int [] numbers = {0,1,2,3,4,5,6,7,8,9};

        Random random = new Random();

        for (int i = 0; i < number; i++) {

            //目的是产生足够随机的数,避免产生的数字重复率高的问题

            int next = random.nextInt(10000);

            codeNum+=numbers[next%10];

        }

        System.out.println(codeNum);

        return codeNum;

    }

 

    /**

     * 生成数字+字母的验证码

     * @param number

     * @return

     */

    public static String getRandomCode(int number){

        String codeNum = "";

        int [] code = new int[3];

        Random random = new Random();

        for (int i = 0; i < number; i++) {

            int num = random.nextInt(10) + 48;

            int uppercase = random.nextInt(26) + 65;

            int lowercase = random.nextInt(26) + 97;

            code[0] = num;

            code[1] = uppercase;

            code[2] = lowercase;

            codeNum+=(char)code[random.nextInt(3)];

        }

        System.out.println(codeNum);

 

        return codeNum;

    }

}

 

 

Redis的工具类  

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

 

import com.alibaba.fastjson.JSON;

 

import redis.clients.jedis.Jedis;

import redis.clients.jedis.JedisPool;

import redis.clients.jedis.JedisPoolConfig;

 

 

/**

 * redis工具类

 *@author 阳旭网络

*/ 

public class RedisClientServer{

 

   private  static  final  Logger   logger = LoggerFactory.getLogger(RedisClientServer.class);

 

   private  static  JedisPool  jedisPool = null;

 

   private  static Jedis jedis = null;

 

   public  static Jedis jedis_object = null;

 

   private static String host = "127.0.0.1";

// private static String password = "";

   private static Integer port = 6379;

 

 

   static{

      if(jedisPool == null){

         JedisPoolConfig  config = new JedisPoolConfig(); 

         //设置最大连接数

         config.setMaxTotal(500);

         //设置最大空闲数

         config.setMaxIdle(20);

         //设置最小空闲数

         config.setMinIdle(8);

         //设置超时时间

         config.setMaxWaitMillis(3000);

         //Idle时进行连接扫描

         config.setTestWhileIdle(true);

         //表示idle object evitor两次扫描之间要sleep的毫秒数

         config.setTimeBetweenEvictionRunsMillis(30000);

         //表示idle object evitor每次扫描的最多的对象数

         config.setNumTestsPerEvictionRun(10);

         //表示一个对象至少停留在idle状态的最短时间,然后才能被idle object evitor

         //扫描并驱逐;这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义

         config.setMinEvictableIdleTimeMillis(60000);

         //初始化连接池

         jedisPool = new JedisPool(config, host, port);

         jedis_object = new   Jedis( host, port);

      }

   }

 

   private  RedisClientServer() {

 

   }

 

   private static Jedis  getJedisInstance(){

 

      try { 

         if(null == jedis){

            jedis = jedisPool.getResource();

//          jedis.auth(password);

         }

      } catch (Exception e) {

         logger.error("实例化jedis失败.........", e);

      }

      return jedis;

   }

 

   /**

    * 向缓存中设置字符串内容 

    *@author 阳旭网络

    *@date 

    */

   public static boolean set(String key, String value) throws Exception {

      Jedis jedis = null;

      try {

         jedis = getJedisInstance();

         jedis.set(key, value);

         return true;

      } catch (Exception e) {

         logger.error("redis set方法失败...key="+key+"  value="+value, e);

      } finally {

         jedisPool.close();

      }

      return false;

   }

 

   /**

    * 向缓存中设置字符串内容 ,设置过期时间

    *@author 阳旭网络

*@date 

*/

   public static boolean set(String key, String value,Integer seconds) throws Exception {

      Jedis jedis = null;

      try {

         jedis = getJedisInstance();

         jedis.set(key, value);

         jedis.expire(key, seconds);

         return true;

      } catch (Exception e) {

         logger.error("redis set方法失败...key="+key+"  value="+value, e);

      } finally {

         jedisPool.close();

      }

      return false;

   }

 

   /**

    * 根据key 获取内容

    *@author 阳旭网络

    *@date 

    */

   public static Object get(String key) {

      Jedis jedis = null;

      try {

         jedis = getJedisInstance();

         Object value = jedis.get(key);

         return value;

      } catch (Exception e) {

         logger.error("redis get方法失败...key="+key);

      } finally {

         jedisPool.close();

      }

      return null;

   }

 

   /**

    * 删除缓存中得对象,根据key

    *@author 阳旭网络

    *@date 

    */

   public static boolean del(String key) {

      Jedis jedis = null;

      try {

         jedis = getJedisInstance();

         jedis.del(key);

         return true;

      } catch (Exception e) {

         e.printStackTrace();

      } finally {

         jedisPool.close();

      }

      return false;

   }

 

   /**

    * 根据key 获取对象

    *@author 阳旭网络

    *@date 

    */

   public static <T> T get(String key, Class<T> clazz) {

      Jedis jedis = null;

      try {

         jedis = getJedisInstance();

         String value = jedis.get(key);

         return JSON.parseObject(value, clazz);

      } catch (Exception e) {

         e.printStackTrace();

      } finally {

         jedisPool.close();

      }

      return null;

   }

 

   /**

    *  设置key过期

    *@author 

    *@date 

    */

   public  static   boolean  expire(String key,int seconds){

      Jedis jedis = null;

      try {

         jedis = getJedisInstance();

         jedis.expire(key, seconds);

         return  true;

      } catch (Exception e) {

         e.printStackTrace();

      } finally {

         jedisPool.close();

      }

      return false;

   }

 

   /**

    * 判断是否存在key

    *@author 

    *@date 

    */

   public static Boolean exists(String key){

      Jedis jedis = null;

      try {

         jedis = getJedisInstance();

         return jedis.exists(key);

      } catch (Exception e) {

         e.printStackTrace();

         return false;

      }finally {

         jedisPool.close();

      }

   }

}

 

三、发送验证码及验证 
写一个验证的接口

@RequestMapping(value = "/register", method = RequestMethod.GET)

@ResponseBody

public String register(HttpServletRequest request){

 try {

      String code = request.getParameter("code");

 

if (!code.equals(RedisClientServer.get("code"+userPhone+page))){

 return  “error”           

}

return null;

}catch (Exception e){

      throw e;

}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值