SpringBoot integrates Alibaba Cloud SMS short message service and realizes the function of sending SMS verification code Redis Java SMS verification code

Alibaba Cloud SMS short message service and realize the function of sending SMS verification code SpringBoot integrates Alibaba Cloud SMS

Brief introduction

Short Message Service (Short Message Service) is the communication capability preferred by the majority of corporate customers to quickly reach mobile phone users.
Call the API or use the group sending assistant to send verification codes, notifications and marketing SMS;
domestic verification SMS can reach within seconds, and the arrival rate99%;
International/Hong Kong, Macau and Taiwan SMS covers more than 200 countries and regions, safe and stable, and widely used by overseas companies.

Technology used this time

  • Need to be familiar with Spring Boot Operating procedures

  • Will be used Maven

  • Know the basics Redis operating

  • HTML basis

Don't talk nonsense, just open the topic!

First you need to go to the official website of Alibaba Cloud to get your AccessKey and AccessKey Secert

Portals get AccessKey tutorials address

Ready to work

  • Open Alibaba Cloud sms Console

Portal Ali cloud SMS console ,

  • You can select in the console first fast Learn to take a look at the basic operations first, you can test the basic SMS sending!

    When you first come in, there will be a few small circles and you can click on those circles to learn

img

Domestic news => signature management => add signature

img

Precautions

Application instructions cannot be written casually! Otherwise, it will not pass the review! !

Domestic news => signature management => create template

img

Precautions

${xxxx} represents the parameter can be passed in using java

Application instructions cannot be written casually! Otherwise, it will not pass the review! !

After both applications are completed, I went to have a cup of tea in about 10 minutes, and the review was completed at most.Twohour

After the application is successful

Remember the name of the signature and the template code

To use later

img img

It is best to pay a few dollars in Alibaba Cloud first, otherwise the text messages may not be sent! !


Start integration

  • Create a SpringBoot project~~
  • Open the pom.xml file and add dependencies that can be used in this demo
  • Ali cloud sdk can rely on Ali cloud help document be acquired
 <!--Aliyun sms Begin-->
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.1.0</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.67</version>
</dependency>
<!--Aliyun sms end-->

<!--Redis Begin-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--Redis End-->

Test: you can open it first Test have a test

package cn.yufire.sms;

import com.alibaba.fastjson.JSON;
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 org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.HashMap;
import java.util.Map;

@SpringBootTest
class AliyunSmsDemoApplicationTests {
    
    

    @Test
    void sendSms() {
    
    

        // 指定地域名称 短信API的就是 cn-hangzhou 不能改变  后边填写您的  accessKey 和 accessKey Secret
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "您的accesskey", "您的accessKeySecret");
        IAcsClient client = new DefaultAcsClient(profile);

        // 创建通用的请求对象
        CommonRequest request = new CommonRequest();
        // 指定请求方式
        request.setMethod(MethodType.POST);
        // 短信api的请求地址  固定
        request.setDomain("dysmsapi.aliyuncs.com");
        // 签名算法版本  固定
        request.setVersion("2017-05-25");
        //请求 API 的名称。
        request.setAction("SendSms");
        // 上边已经指定过了 这里不用再指定地域名称
//        request.putQueryParameter("RegionId", "cn-hangzhou");
        // 您的申请签名
        request.putQueryParameter("SignName", "您的签名名称");
        // 您申请的模板 code
        request.putQueryParameter("TemplateCode", "您的模板code");
        // 要给哪个手机号发送短信  指定手机号
        request.putQueryParameter("PhoneNumbers", "要发送的手机号");

        // 创建参数集合
        Map<String, Object> params = new HashMap<>();
        // 生成短信的验证码  
        String code = String.valueOf(Math.random()).substring(3, 9);
        // 这里的key就是短信模板中的 ${xxxx}
        params.put("code", code);

        // 放入参数  需要把 map转换为json格式  使用fastJson进行转换
        request.putQueryParameter("TemplateParam", JSON.toJSONString(params));

        try {
    
    
            // 发送请求 获得响应体
            CommonResponse response = client.getCommonResponse(request);
            // 打印响应体数据
            System.out.println(response.getData());
            // 打印 请求状态 是否成功
            System.out.println(response.getHttpResponse().isSuccess());
        } catch (ServerException e) {
    
    
            e.printStackTrace();
        } catch (ClientException e) {
    
    
            e.printStackTrace();
        }

    }


}

Test Results

img

# 响应数据
{
    
    "Message":"OK","RequestId":"E18E096C-CF46-431C-B81E-14AD8F564994","BizId":"490017688565398557^0","Code":"OK"}
# 是否请求成功
true


You can create Service and Controller to form an interface that provides external services.

  • application.yml Configuration file
server:
  port: 8080
spring:
  redis:
    host: 127.0.0.1
    port: 6379
aliyun:
  accessKeyID: 你的accessKeyID
  accessKeySecret: 你的accessKeySecret
  • Create service layer
package cn.yufire.sms.service;

public interface SendSmsService {
    
    

    /**
     * 发送短信验证码的接口
     *
     * @param phoneNum 手机号
     * @param code     验证码
     * @return
     */
    boolean sendSms(String phoneNum, String code);

}

  • Create the implementation class of the service
package cn.yufire.sms.service.impl;

import cn.yufire.sms.service.SendSmsService;
import com.alibaba.fastjson.JSON;
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 lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Data // lombok的注解
public class SendSmsServiceImpl implements SendSmsService {
    
    

    private static final Logger logger = LoggerFactory.getLogger(SendSmsServiceImpl.class);
    // 这里采用 注入的方式传递参数
    @Value("${aliyun.accessKeyID}")
    private String accessKeyID;
    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;

    @Override
    public boolean sendSms(String phoneNum, String code) {
    
    

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyID, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("SignName", "签名名称");
        request.putQueryParameter("PhoneNumbers", phoneNum);
        request.putQueryParameter("TemplateCode", "模板code");

        Map<String, Object> params = new HashMap<>();
        params.put("code", code);

        request.putQueryParameter("TemplateParam", JSON.toJSONString(params));

        try {
    
    
            CommonResponse response = client.getCommonResponse(request);
//            System.out.println(response.getData());  // 返回的消息
            logger.info(JSON.parseObject(response.getData(), Map.class).get("Message").toString());
            return response.getHttpResponse().isSuccess();

        } catch (ServerException e) {
    
    
            e.printStackTrace();
        } catch (ClientException e) {
    
    
            e.printStackTrace();
        }

        return false;
    }
}

  • Create Controller
package cn.yufire.sms.controller;

import cn.yufire.sms.service.SendSmsService;
import com.aliyuncs.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin // 跨域支持
public class SendSmsController {
    
    

    @Autowired
    private SendSmsService sendSmsService;

    // 注入redis操作模板
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @GetMapping("/sendSms")
    public String sendSms(@RequestParam("phoneNum") String phoneNum) {
    
    
        // 获取到操作String的对象
        ValueOperations<String, String> stringR = redisTemplate.opsForValue();

        // 根据手机号进行查询
        String phone = stringR.get(phoneNum);

        // 如果手机号在redis中不存在的话才进行发送验证码操作
        if (StringUtils.isEmpty(phone)) {
    
    
            // 生成6位随机数
            String code = String.valueOf(Math.random()).substring(3, 9);
            // 调用业务层接口 发送验证码
            boolean sendSmsFlag = sendSmsService.sendSms(phoneNum, code);
            if (sendSmsFlag) {
    
    
                // 发送成功之后往redis中存入该手机号以及验证码 并设置超时时间 5 分钟
                stringR.set(phoneNum, code, 5, TimeUnit.MINUTES);
            }
            return "发送验证码到:" + phoneNum + "成功! " + "Message:" + sendSmsFlag;
        } else {
    
    
            return "该手机号:" + phoneNum + " 剩余:" + redisTemplate.getExpire(phoneNum) + "秒后可再次进行发送!";
        }
    }

    @GetMapping("/checkCode/{key}/{code}")
    public String checkCode(@PathVariable("key") String number, @PathVariable("code") String code) {
    
    

        // 获取到操作String的对象
        ValueOperations<String, String> stringR = redisTemplate.opsForValue();
        // 根据Key进行查询
        String redisCode = stringR.get(number);
        if (code.equals(redisCode)) {
    
    
            return "成功";
        } else {
    
    
            return redisCode == null ? "请先获取验证码在进行校验!" : "错误";
        }
    }
}

Request access interface

PostMan is used here

testing successfully!img

On the phone at this time

img

In Redis at this time

img

Precautions

  • Never leak Alibaba Cloud's accessKey and accessSecret
  • You can set the safe sending frequency of SMS and other settings in the sms console
  • There are also help files in the console!

img

End to spread flowers

Author: yufire © [email protected]

Guess you like

Origin blog.csdn.net/weixin_43420255/article/details/105916173