短信验证码

本文介绍了如何使用阿里云的短信服务发送验证码,包括代码实现、自动装配配置、配置类、模板对象的创建以及在SpringBoot应用中的测试。同时展示了登录时发送短信验证码的流程,涉及UserService和LoginController的交互,以及Redis的使用来存储验证码。
摘要由CSDN通过智能技术生成

阿里云短信

1.1 介绍

短信服务(Short Message Service)由阿里云提供短信平台,调用API即可发送验证码、通知类和营销类短信;国内验证短信秒级触达,到达率最高可达99%。

官方网站:https://www.aliyun.com/product/sms?spm=5176.19720258.J_8058803260.611.48192c4abPvXEp

1.2 代码实现

    public static void main(String[] args_) throws Exception {

        String accessKeyId = "LTAI4GKgob9vZ53k2SZdyAC7";
        String accessKeySecret= "LHLBvXmILRoyw0niRSBuXBZewQ30la";

        //配置阿里云
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";

        com.aliyun.dysmsapi20170525.Client client =  new com.aliyun.dysmsapi20170525.Client(config);

        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers("")
                .setSignName("小笨蛋")
                .setTemplateCode("SMS_205134115")
                .setTemplateParam("{\"code\":\"1234\"}");
        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse response = client.sendSms(sendSmsRequest);

        SendSmsResponseBody body = response.getBody();

    }

2 自动装配

2.1 自动装配配置

根据自动装配原则,在tanhua-autoconfig模块创建/META-INF/spring.factories文件

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.tanhua.autoconfig.TanhuaAutoConfiguration
2.2 自动装配类

tanhua-autoconfig模块创建自动装配的配置类

package com.tanhua.autoconfig;

import com.tanhua.autoconfig.properties.SmsProperties;
import com.tanhua.autoconfig.templates.SmsTemplate;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

@EnableConfigurationProperties({
        SmsProperties.class
})
public class TanhuaAutoConfiguration {

    @Bean
    public SmsTemplate smsTemplate(SmsProperties smsProperties) {
        return new SmsTemplate(smsProperties);
    }
}

2.3 属性配置类

tanhua-autoconfig模块创建配置信息类SmsProperties

package com.tanhua.autoconfig.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

@Data
@ConfigurationProperties(prefix = "tanhua.sms")
public class SmsProperties {

    private String signName;
    private String templateCode;
    private String accessKey;
    private String secret;

}
2.4 短信模板对象

tanhua-autoconfig模块创建模板对象发送信息

public class SmsTemplate {

    private SmsProperties properties;

    public SmsTemplate(SmsProperties properties) {
        this.properties = properties;
    }

    public void sendSms(String mobile,String code)  {
        Config config = new Config()
                .setAccessKeyId(properties.getAccessKey())
                .setAccessKeySecret(properties.getSecret())
                .setEndpoint("dysmsapi.aliyuncs.com");

        try {
            Client client = new Client(config);
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(mobile)
                    .setSignName(properties.getSignName())
                    .setTemplateCode(properties.getTemplateCode())
                    .setTemplateParam("{\"code\":\"" + code + "\"}");

            SendSmsResponse response = client.sendSms(sendSmsRequest);
            System.out.println(response.getBody().toString());
            System.out.println(response.getBody().message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2.6 测试
引导类

tanhua-app-server 端添加引导类com.tanhua.server.AppServerApplication

package com.tanhua.server;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

//启动类
@SpringBootApplication
public class AppServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(AppServerApplication.class,args);
    }
}
yml文件添加配置

tanhua-app-server工程加入短信配置

tanhua: 
  sms:
    signName: 物流云商
    templateCode: SMS_106590012
    accessKey: LTAI4GKgob9vZ53k2SZdyAC7
    secret: LHLBvXmILRoyw0niRSBuXBZewQ30la
测试类

tanhua-app-server工程编写单元测试类

@RunWith(SpringRunner.class)
@SpringBootTest(classes = AppServerApplication.class)
public class SmsTemplateTest {

    //注入
    @Autowired
    private SmsTemplate smsTemplate;

    //测试
    @Test
    public void testSendSms() {
        smsTemplate.sendSms("xxxxxxxxxxx","4567");
    }
}

3 需求分析

3.1 接口

地址:http://192.168.136.160:3000/project/19/interface/api/94

在这里插入图片描述

在这里插入图片描述

4 登录短信验证码

配置文件

tanhua-app-server 端添加配置文件application.yml

#服务端口
server:
  port: 18080
spring:
  application:
    name: tanhua-app-server
  redis:  #redis配置
    port: 6379
    host: 192.168.136.160
  cloud:  #nacos配置
    nacos:
      discovery:
        server-addr: 192.168.136.160:8848
dubbo:    #dubbo配置
  registry:
    address: spring-cloud://localhost
  consumer:
    check: false
tanhua: 
  sms:
    signName: 物流云商
    templateCode: SMS_106590012
    accessKey: LTAI4GKgob9vZ53k2SZdyAC7
    secret: LHLBvXmILRoyw0niRSBuXBZewQ30la
LoginController

tanhua-app-server 工程编写com.tanhua.server.controller.LoginController#login

在LoginController中编写用户登录,发送验证码方法

package com.tanhua.server.controller;


import com.tanhua.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录-发送验证码
     */
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map map) {
        //1、获取手机号码
        String mobile = (String) map.get("phone");
        //2、调用service发送短信
        return userService.sendMsg(mobile);
    }
}

UserService

**tanhua-app-server **工程编写 com.tanhua.server.service.UserService

UserService中编写生成验证码,并发送短信方法

package com.tanhua.server.service;

import com.tanhua.autoconfig.templates.SmsTemplate;
import com.tanhua.domain.db.User;
import com.tanhua.dubbo.api.UserApi;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Date;

@Service
public class UserService {

    @Reference
    private UserApi userApi;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    //对手机号码,发送验证码
    public ResponseEntity sendMsg(String mobile) {
        //1、生成验证码(6位数字)
        String code = RandomStringUtils.randomNumeric(6);
        //2、调用template发送短信
        smsTemplate.sendSms(mobile,code);
        //3、存入redis
        redisTemplate.opsForValue().set("CHECK_CODE_"+mobile,code, Duration.ofMinutes(5));//验证码失效时间
        //4、构建返回值
        return ResponseEntity.ok(null);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小透明add

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值