SpringBoot实现阿里云短信发送的示例代码

2022-07-15,,,,

阿里云accessid和secret请自行进入阿里云申请

sms.template.code

请进入阿里云,进行短信服务进行魔板添加

开源代码地址在文章末尾

话不多说,直接上代码:

application.properties:

server.port=8002
#server.servlet.context-path=/
spring.datasource.url=jdbc:mysql://localhost:3306/ssm_message?useunicode=true&characterencoding=utf-8&servertimezone=asia/shanghai
spring.datasource.username=root
spring.datasource.password=19961117lhh
spring.datasource.driver-class-name=com.mysql.cj.jdbc.driver
#开启驼峰命名
mybatis.configuration.map-underscore-to-camel-case=true
#设置超时时间-可自行调整
sms.default.connect.timeout=sun.net.client.defaultconnecttimeout
sms.default.read.timeout=sun.net.client.defaultreadtimeout
sms.timeout=10000
#初始化ascclient需要的几个参数
#短信api产品名称(短信产品名固定,无需修改)
sms.product=dysmsapi
#短信api产品域名(接口地址固定,无需修改)
sms.domain=dysmsapi.aliyuncs.com
#替换成你的ak (产品密)
#你的accesskeyid,填你自己的 上文配置所得  自行配置
sms.access.key.id=xxxx
#你的accesskeyid,填你自己的 上文配置所得  自行配置
sms.access.key.secret=xxxx
#阿里云配置你自己的短信模板填入
sms.template.code=sms_238470888

messagecontroller

package com.example.demo.controller;

import com.alibaba.fastjson.json;
import com.aliyuncs.dysmsapi.model.v20170525.sendsmsresponse;
import com.example.demo.service.messageservice;
import com.example.demo.utils.messageutils;
import io.swagger.annotations.api;
import io.swagger.annotations.apioperation;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.util.stringutils;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;

import java.util.hashmap;
import java.util.map;

@api(description = "短信接口")
@requestmapping("/smslogin")
@restcontroller
public class messagecontroller {
    @autowired
    public messageservice messageservice;

    @autowired
    public messageutils messageutils;

    @apioperation(value = "获取短信验证码接口", notes = "获取短信验证码接口")
    @getmapping("/sendmessage")
    public map<string, object> getsmsmessage(string phone) {
        map<string, object> map = new hashmap<>();
        if (phone == null || phone == "") {
            map.put("code", "fail");
            map.put("msg", "手机号为空");
            return map;
        }
        map smsmap = messageutils.getphonemsg(phone);
        if("ok".equals(smsmap.get("status"))){
            map data = messageservice.selectsmsdatabyphone(phone);
            map.put("phone", phone);
            map.put("smscode", smsmap.get("msg"));
            // 将验证码存入数据库  也可以考虑用redis等方式 这里就用数据库做例子
            if (data != null) {
                messageservice.updatesmsdatabyphone(map);
            } else {
                messageservice.insert(map);
            }
            smsmap.put("msg", "成功");
        }
        return smsmap;
    }

    @apioperation(value = "短信校验登录接口", notes = "短信校验登录接口")
    @getmapping("/login")
    public map<string, object> login(string phone, string smscode) {
        map<string, object> map = new hashmap<>();
        if (stringutils.isempty(phone) || stringutils.isempty(smscode)) {
            map.put("code", "fail");
            map.put("msg", "请检查数据");
            return map;
        }
        // 取出对应的验证码进行比较即可
        map smsmap = messageservice.selectsmsdatabyphone(phone);
        if (smsmap == null) {
            map.put("code", "fail");
            map.put("msg", "该手机号未发送验证码");
            return map;
        }
        string code = (string) smsmap.get("sms_code");
        if (!smscode.equals(code)) {
            map.put("code", "fail");
            map.put("msg", "验证码不正确");
            return map;
        }
        map.put("code", "ok");
        map.put("msg", "success");
        return map;
    }
}

messageutils

package com.example.demo.utils;

import com.aliyuncs.defaultacsclient;
import com.aliyuncs.iacsclient;
import com.aliyuncs.dysmsapi.model.v20170525.sendsmsrequest;
import com.aliyuncs.dysmsapi.model.v20170525.sendsmsresponse;
import com.aliyuncs.exceptions.clientexception;
import com.aliyuncs.http.methodtype;
import com.aliyuncs.profile.defaultprofile;
import com.aliyuncs.profile.iclientprofile;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.beans.factory.annotation.value;
import org.springframework.http.responseentity;
import org.springframework.stereotype.component;
import org.springframework.web.client.resttemplate;

import java.util.hashmap;
import java.util.map;


@component
public class messageutils {
    @autowired
    resttemplate resttemplate;

    @value("${sms.default.connect.timeout}")
    private string default_connect_timeout;

    @value("${sms.default.read.timeout}")
    private string default_read_timeout;

    @value("${sms.timeout}")
    private string sms_timeout;

    @value("${sms.product}")
    private string sms_product;

    @value("${sms.domain}")
    private string sms_domain;

    @value("${sms.access.key.id}")
    private string sms_accesskeyid;

    @value("${sms.access.key.secret}")
    private string sms_accesskeysecret;

    @value("${sms.template.code}")
    private string template_code;

    private static string code;//code对应你短信目标里面的参数

    public map getphonemsg(string phone) {
        if (phone == null || phone == "") {
            system.out.println("手机号为空");
            return null;
        }
        // 设置超时时间-可自行调整
        system.setproperty(default_connect_timeout, sms_timeout);
        system.setproperty(default_read_timeout, sms_timeout);
        // 初始化ascclient需要的几个参数
        final string product = sms_product;
        final string domain = sms_domain;
        // 替换成你的ak
        final string accesskeyid = sms_accesskeyid;
        final string accesskeysecret = sms_accesskeysecret;
        // 初始化ascclient,暂时不支持多region
        iclientprofile profile = defaultprofile.getprofile("cn-hangzhou",
                accesskeyid, accesskeysecret);

        map map = new hashmap();
        try {
            defaultprofile.addendpoint("cn-hangzhou", "cn-hangzhou", product,
                    domain);

            //获取验证码
            code = vcode();
            iacsclient acsclient = new defaultacsclient(profile);
            // 组装请求对象
            sendsmsrequest request = new sendsmsrequest();
            // 使用post提交
            request.setmethod(methodtype.post);
            // 必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
            request.setphonenumbers(phone);
            // 必填:短信签名-可在短信控制台中找到
            request.setsignname("java学习");
            // 必填:短信模板-可在短信控制台中找到
            request.settemplatecode(template_code);
            // 可选:模板中的变量替换json串,如模板内容为"亲爱的${name},您的验证码为$[code]"时,此处的值为
            // 友情提示:如果json中需要带换行符,请参照标准的json协议对换行符的要求,比如短信内容中包含\r\n的情况在json中需要表示成\\r\\n,否则会导致json在服务端解析失败
            request.settemplateparam("{ \"code\":\"" + code + "\"}");
            // 可选-上行短信扩展码(无特殊需求用户请忽略此字段)
            // request.setsmsupextendcode("90997");
            // 可选:outid为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
            request.setoutid("youroutid");
            // 请求失败这里会抛clientexception异常
            sendsmsresponse sendsmsresponse = acsclient.getacsresponse(request);
            map.put("status", sendsmsresponse.getcode());
            if (sendsmsresponse.getcode() != null
                    && sendsmsresponse.getcode().equals("ok")) {
                // 请求成功
                map.put("msg", code);
            } else {
                //如果验证码出错,会输出错误码告诉你具体原因
                map.put("msg", sendsmsresponse.getmessage());
            }
        } catch (exception e) {
            e.printstacktrace();
            map.put("status", "fail");
            map.put("msg", "获取短信验证码失败");
        }
        return map;
    }

    /**
     * 生成6位随机数验证码
     *
     * @return
     */
    public static string vcode() {
        string vcode = "";
        for (int i = 0; i < 6; i++) {
            vcode = vcode + (int) (math.random() * 9);
        }
        return vcode;
    }

}

主要代码已贴上

具体开源代码:

前端代码

后端代码

以上就是springboot实现阿里云短信发送示例代码的详细内容,更多关于springboot阿里云短信发送的资料请关注其它相关文章!

《SpringBoot实现阿里云短信发送的示例代码.doc》

下载本文的Word格式文档,以方便收藏与打印。