当前位置:   article > 正文

阿里云实现短信验证_阿里云验证

阿里云验证

短信验证用redis来判断时限一分钟:

1.首先要去阿里云服务器里面开通短信服务,购买短信服务,一般是0.几元就可以,其次获取AccessKey账户密码来实现验证

2.首先引入我们所需要的pom.xml依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <!-- 邮箱验证码  -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-email</artifactId>
        <version>1.4</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.28</version>
    </dependency>
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-core</artifactId>
        <version>4.3.3</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

3.配置我们的yml文件

server:
  port: 8099
#验证码的一分钟有效期设置 redis缓存
spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    timeout: 60000

4.接下来就是代码实现:首先新建一个Service

package com.aliyun.service;
import java.util.Map;
public interface MsmService {

    /**
     * 发送手机验证码
     * @param map
     * @param phone
     * @return
     */
    boolean sendMsm (Map<String, Object> map, String phone);
}

5.ServiceImpl实现类

package com.aliyun.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.service.MsmService;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.stereotype.Service;

import java.util.Map;
@Service
public class MsmServiceImpl implements MsmService {
    @Override
    public boolean sendMsm(Map<String, Object> map, String phone) {
        if (phone.isEmpty()) {
            return false;
        }
        //1.设置阿里云 secrectKey 获取AccessKey账户密码
        DefaultProfile profile=DefaultProfile.getProfile("default","LTAI5tA6eZM8qB6UQ4iwwY2S","14o10h8na5MfYt7kD4ARb1OSw6QLEd");
        //发起 客户端
        IAcsClient client=new DefaultAcsClient(profile);
        //设置短信发送的信息 签名  手机号码  验证 吗
        CommonRequest request=new CommonRequest();
        //1.设置请求方式
        request.setSysMethod(MethodType.POST);
        //2.设置阿里云节点18474821993
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        //设置手机号码
        request.putQueryParameter("PhoneNumbers",phone);
        //设置签名
        request.putQueryParameter("SignName","阿里云短信测试");
        //设置模板
        request.putQueryParameter("TemplateCode","SMS_154950909");
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));
        try {
            CommonResponse response=client.getCommonResponse(request);
            System.out.println(response);
            return  response.getHttpResponse().isSuccess();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}

6.编写RandomUtil类来生成随机数

package com.aliyun.rand;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

public class RandomUtil {
    private static final Random random = new Random();

    private static final DecimalFormat fourdf = new DecimalFormat("0000");

    private static final DecimalFormat sixdf = new DecimalFormat("000000");

    public static String getFourBitRandom() {
        return fourdf.format(random.nextInt(10000));
    }

    public static String getSixBitRandom() {
        return sixdf.format(random.nextInt(1000000));
    }

    /**
     * 给定数组,抽取n个数据
     * @param list
     * @param n
     * @return
     */
    public static ArrayList getRandom(List list, int n) {

        Random random = new Random();

        HashMap<Object, Object> hashMap = new HashMap<Object, Object>();

        // 生成随机数字并存入HashMap
        for (int i = 0; i < list.size(); i++) {

            int number = random.nextInt(100) + 1;

            hashMap.put(number, i);
        }

        // 从HashMap导入数组
        Object[] robjs = hashMap.values().toArray();

        ArrayList r = new ArrayList();

        // 遍历数组并打印数据
        for (int i = 0; i < n; i++) {
            r.add(list.get((int) robjs[i]));
            System.out.print(list.get((int) robjs[i]) + "\t");
        }
        System.out.print("\n");
        return r;
    }
}

7.编写RedisConfig来实现缓存:注意,这里使用的redis是本地的

package com.aliyun.util;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig  {

    private RedisConnectionFactory connectionFactory;

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
        this.connectionFactory = connectionFactory;

        RedisTemplate template = new RedisTemplate<>();

        template.setConnectionFactory(connectionFactory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
//
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();

        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        serializer.setObjectMapper(mapper);

        template.setValueSerializer(serializer);

        //使用StringRedisSerializer来序列化和反序列化redis的key值

        template.setKeySerializer(new StringRedisSerializer());
        /*hash字符串序列化方法*/
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new StringRedisSerializer());

        template.afterPropertiesSet();

        return template;

    }

}

8.再是我们的Controller控制层代码:

package com.aliyun.controller;

import com.aliyun.rand.RandomUtil;
import com.aliyun.service.MsmService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/api/sms")
public class SendController {
    @Resource
    private MsmService msmService;

    /**
     * 用这个redis缓存不会乱码
     */
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @RequestMapping("/senMessage")
    @ResponseBody
    public boolean senMessage (@RequestParam("phone") String phone) {
        redisTemplate.opsForValue().set("1234","12333");
        String code = redisTemplate.opsForValue().get(phone);
        System.out.println(code);
        if (code != null) {
            System.out.println("redis有值");
            return false;
        }
        //设置一分钟失效
        String sixBitRandom = RandomUtil.getSixBitRandom();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("code",sixBitRandom);
        boolean b = msmService.sendMsm(map1 , phone);
        System.out.println(b);
        if (b) {
            //如果发送成功了,这个值会存在一分钟
            redisTemplate.opsForValue().set(phone , code , 1, TimeUnit.MINUTES);
            return true;
        } else {
            return false;
        }
    }
}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/393880
推荐阅读
相关标签
  

闽ICP备14008679号