首页 > 其他分享 >实现阿里云短信服务

实现阿里云短信服务

时间:2024-10-26 14:20:56浏览次数:3  
标签:服务 String import 阿里 result aliyun error 短信 com

导入依赖

        <!-- 阿里云短信服务依赖 -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>dysmsapi20170525</artifactId>
            <version>3.0.0</version>
        </dependency>

配置文件

aliyun:
  sms:
    AccessKey: "" #创建AccessKey后,即可获取
    AccessKeySecret: "" #同上
    SignName: "" #创建签名,签名是指发送短信的标题, 一般是项目的名字
    TemplateCode: "" #模板,是指发送短信的格式
    endpoint: "dysmsapi.aliyuncs.com" # 阿里云短信服务API的访问地址

配置类

package com.tanhua.sso.config;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.teaopenapi.models.Config;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "aliyun.sms")
@Slf4j
@Data
public class SmSConfig {
    private String AccessKey;
    private String AccessKeySecret;
    private String SignName;
    private String TemplateCode;
    private String endpoint;
    @Bean
    public  Client createClient(){
        Config config = new Config()
                .setAccessKeyId(AccessKey)
                .setAccessKeySecret(AccessKeySecret);
        config.endpoint = endpoint;
        try {
            Client client = new Client(config);
            return new Client(config);
        }catch (Exception e){
            log.error("创建Client时出现异常{}",e.getMessage());
            return null;
        }
    }
}

service

package com.tanhua.sso.service;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.tanhua.sso.config.SmSConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service
public class SmsService {


    @Autowired
    private SmSConfig smSConfig;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * 发送短信验证码
     *
     * @param mobile 手机号码
     * @throws Exception 如果发送过程中出现错误
     */
    public int sendSms(String mobile){
        Client client = smSConfig.createClient();
        if(client==null){
            return 0; //错误
        }
        // 创建一个对象节点
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode objectCode = objectMapper.createObjectNode();
        int codeValue = RandomUtils.nextInt(100000, 999999);
        objectCode.put("code", codeValue);
        // 创建发送短信请求
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(smSConfig.getSignName())
                .setTemplateCode(smSConfig.getTemplateCode())
                .setPhoneNumbers(mobile)
                .setTemplateParam(objectCode.toString());

        RuntimeOptions runtime = new RuntimeOptions();

        try {
            // 发送短信并获取响应
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            SendSmsResponseBody sendSmsResponseBody = sendSmsResponse.getBody();
            log.info("code:{}\nmessage:{}\nbizId:{}\nrequestId:{}", sendSmsResponseBody.getCode(),sendSmsResponseBody.getMessage(),sendSmsResponseBody.getBizId(),sendSmsResponseBody.getRequestId());
            if(sendSmsResponseBody.getMessage().equals("OK")){
                log.info("验证码发送成功,验证码:{}",codeValue);
                return codeValue;
            }
            return 0;
        } catch (TeaException error) {
            // 处理特定的TeaException
            log.error("发送短信时发生错误: {}", error.getMessage());
            if (error.getData() != null && error.getData().containsKey("Recommend")) {
                log.error("推荐解决方案: {}", error.getData().get("Recommend"));
            }
            throw new RuntimeException("发送短信时发生错误", error);
        } catch (Exception error) {
            // 处理其他异常
            log.error("发送短信时发生未知错误: {}", error.getMessage(), error);
            throw new RuntimeException("发送短信时发生未知错误", error);
        }
    }


    public Map<String,Object> sendCheckCode(String mobile){
        HashMap<String, Object> result = new HashMap<>(2);
        try {
            String redisKey = "CHECK_CODE_"+mobile;
            String value = redisTemplate.opsForValue().get(redisKey);
            if(StringUtils.isNotEmpty(value)){ //长度不为0且不为null
                result.put("code",1);
                result.put("msg","上一次发送的验证码还未失效");
                return result;
            }
            int code = sendSms(mobile);
            if(code==0){
                result.put("code",2);
                result.put("msg","发送短信验证码失败");
                return result;
            }
            //发送验证码成功
            result.put("code",3);
            result.put("msg","ok");
            //将验证码存储到redis,3分钟后失效
            redisTemplate.opsForValue().set(redisKey,String.valueOf(code),3, TimeUnit.MINUTES);
            return result;
        }catch (Exception e){
            result.put("code", 4);
            result.put("msg", "发送验证码出现异常");
            return result;
        }

    }
}

获取AccessKey和AccessKeySecret

获取SigName和TemplateCode

标签:服务,String,import,阿里,result,aliyun,error,短信,com
From: https://blog.csdn.net/weixin_65019617/article/details/143252900

相关文章

  • 基于Vue+NodeJS+express的预约上门维修服务运营与数据分析系统(源码+node+vue+部署文
    收藏关注不迷路!!......
  • Web、RESTful API 在微服务中的作用是什么?
    Web、RESTfulAPI在微服务中的作用是什么?在当今的软件开发领域,微服务架构正变得越来越流行。而在微服务架构中,Web和RESTfulAPI起着至关重要的作用。一、微服务架构简介微服务架构是一种将应用程序拆分为一组小型服务的架构风格。每个服务都可以独立部署、扩展和维护。这些......
  • 雨云服务器全教程
    1.注册雨云服务器首先,您需要访问雨云服务器的官方网站并注册一个账号。1.打开浏览器,访问雨云服务器的官方网站:[雨云服务器注册官网(有五折优惠!)]2.点击页面右上角的“注册”按钮,进入注册页面。3.填写注册信息,包括用户名、密码、邮箱等,并点击“注册”按钮完成注册。......
  • java计算机毕业设计淮工志愿者服务系统(开题+程序+论文)
    本系统(程序+源码)带文档lw万字以上 文末可获取一份本项目的java源码和数据库参考。系统程序文件列表开题报告内容一、研究背景随着社会的发展,志愿服务在各个领域的重要性日益凸显。在传统的志愿服务模式下,存在着诸多问题,如信息传播不畅、资源分配不合理、管理缺乏系统性等......
  • HttpClient—请求第三方的服务
    1.介绍1.1简介HttpClient是ApacheJakartaCommons项目中的一个子项目,为开发人员提供了一个高效、功能丰富、支持最新HTTP协议的客户端工具包。它不仅可以支持HTTP/1.1和HTTP/2等最新版本的HTTP协议,还包括一系列高级特性,如连接池管理、SSL支持、自动重试机制、......
  • vscode远程连接linux服务器
    要在远程服务器上使用VisualStudioCode(VSCode)的图形界面,可以通过以下几种方法实现。最常见的方法是使用VSCode的RemoteDevelopment插件,这样你可以在本地机器上使用VSCode连接并编辑远程服务器上的文件。方法一:使用VSCodeRemote-SSH插件1.安装Remote......
  • 【如何安装linux系统】【为什么我要用vmware虚拟机呢?】【阿里云镜像】
    如何安装linux系统为什么我要用vmware虚拟机呢?阿里云镜像(下载镜像)(安装虚拟机)http://mirrors.aliyun.com/......
  • 【深入理解SpringCloud微服务】Hystrix作用与原理剖析
    【深入理解SpringCloud微服务】Hystrix作用与原理剖析Hystrix的作用熔断降级隔离Hystrix有限流的功能吗?Hystrix的原理@HystrixCommand注解是如何起作用的工作流程1、构建命令对象2、执行命令3、检查缓存是否开启并且是否命中4、检查断路器是否打开5、检查线程池或信号量......
  • LINUX服务器磁盘空间扩容方案
    1、关闭服务器,插入硬盘,开机2、开机后,注意引导界面,按F1键进入BIOS进行设置3、进入BIOS后,选择systemsetting--storage,进入磁盘阵列配置4、选择MainMenu--configurationManagement5、进入configurationManagement界面,选择“Create…”选项,这就是要创建虚盘来配置RAID进入“Crea......
  • 【服务器知识】nginx不够,那我们就试试openresty
    文章目录概述OpenResty的核心特性包括:OpenResty的工作原理:如何使用OpenResty:OpenResty勾子函数......