SpringBoot 2.2.5 整合阿里云短信,实现发送自定义模板短信的功能

完整代码地址在结尾!!

第一步,注册阿里云账号

  1. 并且开通短信功能,在控制台创建签名,模板,accessKey,后面要用到,此处不多赘述,不懂请自行百度查询

第二步,在pom.xml加入依赖,如下

<!-- 阿里短信依赖 -->
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.4.6</version>
</dependency>
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
    <version>2.1.0</version>
</dependency>

<!-- fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.73</version>
</dependency>

第三步,配置application.yml,避免端口冲突

server:
  port: 8081

spring:
  application:
    name: sms-demo-server

sms:
  aliyun:
    accessKeyID:  xxx # 你的accessKeyID
    accessKeySecret:  xxx # 你的accessKeySecret
    domain: dysmsapi.aliyuncs.com # 固定不变
    regionId: cn-hangzhou # 固定不变
    templateCode: xxx # 你的模板code
    signName: xxx # 你的签名

第四步,创建类服务类,AliYunSmsService,AliYunSmsServiceImpl,如下

AliYunSmsService

public interface AliYunSmsService {

    /**
     * 发送短信的接口
     *
     * @param phoneNum 手机号
     * @param message     消息
     * @return
     */
    boolean sendSms(String phoneNum, String message);

}

AliYunSmsServiceImpl

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 com.luoyu.sms.service.AliYunSmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service
public class AliYunSmsServiceImpl implements AliYunSmsService {

    //aliyuncs的参数
    @Value("${sms.aliyun.accessKeyID}")
    private String accessKeyID;

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

    //短信api的请求地址  固定
    @Value("${sms.aliyun.domain}")
    private String domain;

    //指定地域名称 短信API的就是 cn-hangzhou 不能改变
    @Value("${sms.aliyun.regionId}")
    private String regionId;

    //您的申请签名
    @Value("${sms.aliyun.signName}")
    private String signName;

    //你的模板
    @Value("${sms.aliyun.templateCode}")
    private String templateCode;

    /**
     * 发送短信接口
     *
     * @param phoneNum 手机号
     * @param message     消息
     * @return
     */
    @Override
    public boolean sendSms(String phoneNum, String message) {

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

        // 创建通用的请求对象
        CommonRequest request = new CommonRequest();
        // 指定请求方式
        request.setSysMethod(MethodType.POST);
        // 短信api的请求地址  固定
        request.setSysDomain(domain);
        //签名算法版本  固定
        request.setSysVersion("2017-05-25");
        //请求 API 的名称
        request.setSysAction("SendSms");
        //指定地域名称
        request.putQueryParameter("RegionId", regionId);
        // 要给哪个手机号发送短信  指定手机号
        request.putQueryParameter("PhoneNumbers", phoneNum);
        // 您的申请签名
        request.putQueryParameter("SignName", signName);
        // 您申请的模板 code
        request.putQueryParameter("TemplateCode", templateCode);

        Map<String, Object> params = new HashMap<>();
        //这里的key就是短信模板中的 ${xxxx}
        params.put("password", message);

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

        try {
            CommonResponse response = client.getCommonResponse(request);
            log.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;
    }
}

第五步,创建类单元测试类,SmsApplicationTests,并进行测试,如下

import com.luoyu.sms.service.AliYunSmsService;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@Slf4j
// 获取启动类,加载配置,确定装载 Spring 程序的装载方法,它回去寻找 主配置启动类(被 @SpringBootApplication 注解的)
@SpringBootTest
class SmsApplicationTests {

    @Autowired
    private AliYunSmsService aliYunSmsService;

    @Test
    void aliYunSendSmsTest() {
        String phone = "xxx";
        String code = "10086";
        aliYunSmsService.sendSms(phone, code);
    }

    @BeforeEach
    void testBefore(){
        log.info("测试开始!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    }

    @AfterEach
    void testAfter(){
        log.info("测试结束!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    }

}

注意

  1. 如果使用短信验证码格式的签名:code只能是 符合规则[a-zA-Z0-9] ,否则报错信息:params must be [a-zA-Z0-9] for verification sms。
  2. 短信服务里面选择不同的签名格式,请求的模板也可以不同,具体情况具体对待。
  3. 如果控制台返回信息:短信所使用签名场景非法,那么说明:签名的试用场景与短信类型不匹配。解决:检查下创建签名时选择的适用场景是验证码还是通用,如果是验证码,把场景改为通用即可。
  4. 如果控制台返回信息:账户余额不足。则需要充值一点钱。

完整代码地址:https://github.com/Jinhx128/springboot-demo

注:此工程包含多个module,本文所用代码均在sms-demo模块下

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。