java 调用阿里云短信接口

1.情景展示

阿里云短信接口调用,如何用java实现?

2.具体分析

先去阿里云申请账号,拿到分配的秘钥,以及配置好短信模板。

所需jar包

<!-- 阿里云短信 -->
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.6.0</version>
    <exclusions>
        <exclusion>
            <artifactId>gson</artifactId>
            <groupId>com.google.code.gson</groupId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
    <version>2.2.1</version>
</dependency>
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.9.0</version>
</dependency>

如果需要最新版,去maven中央仓库获取即可:https://mvnrepository.com/

3.具体实现

先搞一个参数配置实体类;

import lombok.*;
import lombok.experimental.Accessors;

import java.util.Map;

/**
 * 短信配置类
 * @description:
 * @author: Marydon
 * @date: 2022-06-02 9:41
 * @version: 1.0
 * @email: marydon20170307@163.com
 */
@Builder
@Accessors(chain = true)
@Setter
@Getter
public class MsgConfig {
    // 发送短信的产品
    @Builder.Default
    private String product = "Dysmsapi";
    // 发送短信的域名
    @Builder.Default
    private String domain = "dysmsapi.aliyuncs.com";
    // 区域ID
    @Builder.Default
    private String regionId = "cn-hangzhou";
    // AccessKey ID
    private String accessKeyId;
    // AccessKey Secret
    private String secret;
    // 短信签名
    @Builder.Default
    private String signName = "阿里云";
    // 短信模板CODE
    private String templateCode;
    // 接收短信的手机号
    private String phone;
    // 动态配置的模板参数名称及参数值
    private Map<String, String> templateParams;
    // 短信发送成功/失败(默认值:false)
    private boolean isSuccess;
    // 短信发送成功/失败 信息
    private String message;

    @Override
    public String toString() {
        return "MsgConfig{" +
                "product='" + product + '\'' +
                ", domain='" + domain + '\'' +
                ", regionId='" + regionId + '\'' +
                ", accessKeyId='" + accessKeyId + '\'' +
                ", secret='" + secret + '\'' +
                ", signName='" + signName + '\'' +
                ", templateCode='" + templateCode + '\'' +
                ", phone='" + phone + '\'' +
                ", templateParams=" + templateParams +
                ", isSuccess=" + isSuccess +
                ", message='" + message + '\'' +
                '}';
    }

    public static void main(String[] args) {
        System.out.println(MsgConfig.builder().build().isSuccess);
    }
}

说明:

短信签名,与你注册账号时的签名保持一致,而且调短信接口的时候,不能随意更改,否则,会提示:

该账号下找不到对应签名。

具体实现:

import code.marydon.encapsulation.dataType.MapBuilder;
import code.marydon.encapsulation.dataType.StringUtils;
import com.alibaba.fastjson2.JSONObject;
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.profile.DefaultProfile;
import com.aliyuncs.regions.ProductDomain;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;

/**
 * 阿里云短信工具类
 * @description:
 * @author: Marydon
 * @date: 2022-05-31 16:02
 * @version: 1.0
 * @email: marydon20170307@163.com
 */
@Slf4j
public final class AliYunMsgUtils{

    // 私有化构造方法(防止外部实例化)
    private AliYunMsgUtils() {}

    private static AliYunMsgUtils msgUtils = null;

    // 单例
    public static AliYunMsgUtils getInstance() {
        return msgUtils == null ? new AliYunMsgUtils() : msgUtils;
    }

    // AccessKey ID
    private final String ACCESS_KEY_ID = "ID";
    // AccessKey Secret
    private final String ACCESS_KEY_SECRET = "秘钥";
    // 短信模板CODE
    private final String TEMPLATE_CODE = "SMS_210079199";

    /*
     * 发送短信
     * @description:
     * @date: 2022/6/1 15:43
     * @param: config 初始化参数
     * @return: code.marydon.encapsulation.msg.MsgConfig 返回它自己,方便后期调试
     */
    @NotNull
    public static MsgConfig sendMsg(MsgConfig config) {
        try {
            AliYunMsgUtils aliYunMsgUtils = AliYunMsgUtils.getInstance();

            String accessKeyId;
            if (StringUtils.isEmpty(config.getAccessKeyId())) {
                accessKeyId = aliYunMsgUtils.ACCESS_KEY_ID;
                config.setAccessKeyId(accessKeyId);
            } else {
                accessKeyId = config.getAccessKeyId();
            }
            String accessKeySecret;
            if (StringUtils.isEmpty(config.getSecret())) {
                accessKeySecret = aliYunMsgUtils.ACCESS_KEY_SECRET;
                config.setSecret(accessKeySecret);
            } else {
                accessKeySecret = config.getSecret();
            }

            DefaultProfile profile = DefaultProfile.getProfile(config.getRegionId(), accessKeyId, accessKeySecret);
            IAcsClient client = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();
            // 固定值(必须配置)
            request.setSysProductDomain(new ProductDomain(config.getProduct(), config.getDomain()));
            request.setSignName(config.getSignName());
            String templateCode;
            if (StringUtils.isEmpty(config.getTemplateCode())) {
                templateCode = aliYunMsgUtils.TEMPLATE_CODE;
                config.setTemplateCode(templateCode);
            } else {
                templateCode = config.getTemplateCode();
            }

            request.setTemplateCode(templateCode);
            // 设置接收短信的手机号
            request.setPhoneNumbers(config.getPhone());
            // 模板变量集合,在阿里云当中${name}配置
            request.setTemplateParam(new Gson().toJson(config.getTemplateParams()));
            // 调用
            SendSmsResponse response = client.getAcsResponse(request);
            // 返回结果
            JSONObject json = JSONObject.parseObject(new Gson().toJson(response));
            log.info(json.toString());

            config.setSuccess(json.get("code").equals("OK"));
            config.setMessage((String) json.get("message"));
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            config.setMessage(e.getMessage());
        }
        return config;
    }
}

调用:

public static void main(String[] args) {
    // 配置短信参数
    MsgConfig msgConfig = MsgConfig.builder().build()
            .setPhone("手机号")
            .setSignName("博客园")
            .setTemplateCode("SMS_210079199")
            .setTemplateParams(MapBuilder.build().put("模板参数", "1234").get());
    // 发送短信
    msgConfig = sendMsg(msgConfig);
    // 打印结果
    System.out.println(msgConfig.toString());
}

阿里云接口返回结果,如下:

{"requestId":"6633E9B9-FF9B-52ED-907B-EDB6D7CC6F45","bizId":"207611654156631160^0","code":"OK","message":"OK"}

调用阿里云接口,实际请求遵照以下格式:

http://dysmsapi.aliyuncs.com/?PhoneNumbers=接收短信的手机号&Action=SendSms&Timestamp=2022-06-02T07%3A57%3A10Z&SignName=%E9%83%91%E5%B7%9E%E6%96%B0%E7%9B%8A%E5%8D%8E&TemplateCode=SMS_210079199&SignatureVersion=1.0&Format=JSON&SignatureNonce=e8a9e05b-b72d-48b0-852a-b35a6bfcbf9716541566309211&Version=2017-05-25&AccessKeyId=你的KEY&Signature=QYBqUP%2Fx9Q8%2BNSR8KMniwUbYqJQ%3D&SignatureMethod=HMAC-SHA1&TemplateParam=%7B%22模板变量名称%22%3A%221234%22%7D&RegionId=cn-hangzhou

如果我们拿着这个链接,去网页请求,会得到如下结果:

写在最后

  哪位大佬如若发现文章存在纰漏之处或需要补充更多内容,欢迎留言!!!

 相关推荐:

posted @ 2022-06-02 16:29  Marydon  阅读(2629)  评论(0编辑  收藏  举报