SpringBoot整合SMS短信服务

本文涉及的产品
短信服务,200条 3个月
短信服务,100条 3个月
国际/港澳台短信套餐包,全球plus 100条 6个月
简介: 本文介绍了如何在SpringBoot项目中整合阿里云SMS短信服务,包括添加依赖、配置文件、配置类、服务层接口和实现类,以及控制器层的实现,用于发送短信验证码。

概览

  1. 了解阿里云用户权限操作
  2. 开通阿里云短信服务
  3. 添加短信模板
  4. 添加签名
  5. 编写测试代码
  6. 编写可复用的微服务接口,实现验证码的发送

image.png

image.png
image.png

pom依赖

<!--aliyun 短信服务-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</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>

<!-- redis -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--hutool工具包 -->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.18</version>
</dependency>

yml配置


# 短信配置
ly:
  sms:
    accessKeyId: xxxxxxxx
    accessKeySecret: xxxxxxxx
    signName: robindeblog
    verifyTemplateCode: SMS_295690184 # 短信模板名称

# redis配置
spring:
  data:
    redis:
      port: 6379
      host: localhost
      database: 0
      timeout: 1800000

配置类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class MsmConfig {
   

    @Value("${ly.sms.accessKeyId}")
    private String accessKeyId ;

    @Value("${ly.sms.accessKeySecret}")
    private String accessKeySecret;

    @Value("${ly.sms.signName}")
    private String signName;

    @Value("${ly.sms.verifyTemplateCode}")
    private String verifyTemplateCode;
}

service 层

interface

package com.robin.webcliweb.service;

import java.util.Map;

public interface MsmService {
   
    //发送验证码
    boolean send(Map<String, Object> param, String phone);
}

impl

package com.robin.webcliweb.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.robin.webcliweb.config.MsmConfig;
import com.robin.webcliweb.service.MsmService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

@Service
public class MsmServiceImpl implements MsmService {
   


    @Resource
    private MsmConfig msmConfig;
    /**
     * 发送验证码
     * @param param     验证码
     * @param phone     手机号
     * @return
     */
    @Override
    public boolean send(Map<String, Object> param, String phone) {
   

        if(StringUtils.isEmpty(phone)) return false;

        //default 地域节点,默认就好  后面是 阿里云的 id和秘钥(这里记得去阿里云复制自己的id和秘钥哦)
        DefaultProfile profile = DefaultProfile.getProfile("default", msmConfig.getAccessKeyId(), msmConfig.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        //这里不能修改
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        request.putQueryParameter("PhoneNumbers", phone);                    //手机号
        request.putQueryParameter("SignName", msmConfig.getSignName());    //申请阿里云 签名名称(暂时用阿里云测试的,自己还不能注册签名)
        request.putQueryParameter("TemplateCode", msmConfig.getVerifyTemplateCode()); //申请阿里云 模板code(用的也是阿里云测试的)
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));

        try {
   
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (Exception e) {
   
            e.printStackTrace();
        }
        return false;
    }

}

controller层

package com.robin.webcliweb.controller;

import cn.hutool.core.util.RandomUtil;
import com.robin.webcliweb.service.MsmService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class MsmApiController {
   

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;    //注入redis

    //发送短信验证码
    @GetMapping(value = "/send/{phone}")
    public Boolean code(@PathVariable String phone) {
   
        //1、从redis中获取验证码,如果获取到就直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) return false;

        //2、如果获取不到,就进行阿里云发送
        code = RandomUtil.randomNumbers(6).toString();
        Map<String,Object> param = new HashMap<>();
        param.put("code", code);

        //调用方法
        boolean isSend = msmService.send(param,phone);
        if(isSend) {
   
            //往redis中设置数据:key、value、过期值、过期时间单位  MINUTES代表分钟
            redisTemplate.opsForValue().set(phone, code,5, TimeUnit.MINUTES);
            return true;
        } else {
   
            return false;
        }
    }

}
相关文章
|
前端开发 Java Spring
spring boot中如何实现在手机注册和登录时获取验证码(阿里短信服务)
为了实现在手机注册和登录时获取手机验证码,我使用了阿里的短信服务,下面就来介绍一下具体如何实现。将介绍代码层面如何使用的,去阿里开通该服务,以及如何获得你的accessKeyId和accessKeySecret等。
1118 0
spring boot中如何实现在手机注册和登录时获取验证码(阿里短信服务)
|
5月前
|
Java Maven
(短信服务)java SpringBoot 阿里云短信功能实现发送手机验证码
(短信服务)java SpringBoot 阿里云短信功能实现发送手机验证码
1268 0
|
JSON NoSQL Java
SpringBoot入门到精通-基于阿里云短信服务-定义Starter封装通用组件
SpringBoot入门到精通-基于阿里云短信服务-定义Starter封装通用组件
|
监控 Java API
Spring boot项目集成阿里云短信服务发送短信验证码
Spring boot项目集成阿里云短信服务发送短信验证码
1147 0
|
消息中间件 Java Kafka
SpringBoot接入阿里SMS
最近呢用到了短信服务,这次我使用的是阿里的SMS短信服务,就此对于SpringBoot接入短信服务来给大家简单的总结一下。因为也是用到了短信服务的开发工具包,所以接入起来也是非常简单方便的,下面一起来看看。
976 0
|
Java 对象存储
整合阿里云短信服务 SpringBoot
整合阿里云短信服务 SpringBoot
794 0
|
Java Spring
Spring Boot 之注解@Component @ConfigurationProperties(prefix = "sms")
从spring-boot开始,已经支持yml文件形式的配置,@ConfigurationProperties的大致作用就是通过它可以把properties或者yml配置直接转成对象   例如: 配置文件: sms.
3477 0
|
5月前
|
云安全 安全 API
阿里云——OpenAPI使用——短信服务
阿里云——OpenAPI使用——短信服务
278 0
|
10月前
|
安全
阿里云短信服务是可以发送包含下载链接的文本内容的,
阿里云短信服务是可以发送包含下载链接的文本内容的,但是需要注意以下几点:
603 1
|
SQL Java
如何使用阿里云短信服务实现登录页面,手机验证码登录?1
如何使用阿里云短信服务实现登录页面,手机验证码登录?
381 0