Java接入阿里云短信服务实例代码

Java接入阿里云短信推送服务实例代码

在阿里云官网开通短信服务功能,配置好签名,申请完模板后,快速上手代码。

1.引入pom依赖
<dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>dysmsapi20170525</artifactId>
            <version>2.0.23</version>
        </dependency>
2.注册服务
package com.storage.sysmgr.client;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.teaopenapi.models.Config;

public class SmsClient {

    // 替换您的 AccessKey ID
    private static final String accessKeyId = "accessKeyId";

    // 替换您的 AccessKey Secret
    private static final String accessKeySecret = "accessKeySecret";

    private Client client;

    private static final SmsClient smsClient = smsClient();

    private static SmsClient smsClient() {
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        // 替换您的 endpoint 
        // Endpoint 是请求接口服务的网络域名,在平台开发者门户上查看
        config.endpoint = "endpoint.aliyun.com";
        SmsClient smsClient = new SmsClient();
        try {
            smsClient.client = new Client(config);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return smsClient;
    }

    public static Client getInstance() {
        return smsClient.client;
    }

}

3.封装接口组件类
package com.storage.sysmgr.utils;

import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.storage.sysmgr.client.SmsClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author
 */
@Slf4j
@Component
public class SmsUtil {

    // 替换您的 Sign Name
    private static final String signName = "signName";

    /**
     * 发送单条短信
     *
     * @param phoneNumbers  电话号码
     * @param templateCode  模板编码
     * @param templateParam 模板参数(json字符串格式)
     * @return SendSmsResponse
     * @throws Exception
     */
    public static SendSmsResponse sendSms(String phoneNumbers, String templateCode, String templateParam) throws Exception {
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(signName)
                .setPhoneNumbers(phoneNumbers)
                .setTemplateCode(templateCode)
                .setTemplateParam(templateParam);
        try {
            return SmsClient.getInstance().sendSmsWithOptions(sendSmsRequest, new com.aliyun.teautil.models.RuntimeOptions());
        } catch (TeaException error) {
            com.aliyun.teautil.Common.assertAsString(error.message);
            log.error(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            com.aliyun.teautil.Common.assertAsString(error.message);
            log.error(error.message);
        }
        return null;
    }

    /**
     * 查询发送信息详情
     *
     * @param bizId       业务ID(非必填)
     * @param phoneNumber 手机号
     * @param sendDate    发送日期 yyyyMMdd
     * @param currentPage
     * @param pageSize    1-50
     * @return QuerySendDetailsResponse
     * @throws Exception
     */
    public static QuerySendDetailsResponse querySendDetails(String bizId, String phoneNumber, String sendDate, Long currentPage, Long pageSize) throws Exception {
        QuerySendDetailsRequest querySendDetailsRequest = new QuerySendDetailsRequest()
                .setBizId(bizId)
                .setPhoneNumber(phoneNumber)
                .setSendDate(sendDate)
                .setCurrentPage(currentPage)
                .setPageSize(pageSize);
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            return SmsClient.getInstance().querySendDetailsWithOptions(querySendDetailsRequest, runtime);
        } catch (TeaException error) {
            com.aliyun.teautil.Common.assertAsString(error.message);
            log.error(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            com.aliyun.teautil.Common.assertAsString(error.message);
            log.error(error.message);
        }
        return null;
    }

    /**
     * 查询时间范围短信统计信息
     *
     * @param startDate 开始时间 yyyyMMdd
     * @param endDate   结束时间 yyyyMMdd
     * @param pageIndex
     * @param pageSize  1-50
     * @return QuerySendStatisticsResponse
     * @throws Exception
     */
    public static QuerySendStatisticsResponse QuerySendStatistics(String startDate, String endDate, Integer pageIndex, Integer pageSize) throws Exception {
        QuerySendStatisticsRequest querySendStatisticsRequest = new QuerySendStatisticsRequest()
                .setIsGlobe(1)
                .setStartDate(startDate)
                .setEndDate(endDate)
                .setPageIndex(pageIndex)
                .setPageSize(pageSize);
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            return SmsClient.getInstance().querySendStatisticsWithOptions(querySendStatisticsRequest, runtime);
        } catch (TeaException error) {
            com.aliyun.teautil.Common.assertAsString(error.message);
            log.error(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            com.aliyun.teautil.Common.assertAsString(error.message);
            log.error(error.message);
        }
        return null;
    }
}

4.调用接口返回结果示例
4.1 发送单条短信
SmsUtil.sendSms(phoneNumbers, templateCode, templateParam);
{
    "headers": {
        "access-control-allow-origin": "*",
        "date": "Wed, 31 May 2023 10:35:14 GMT",
        "content-length": "110",
        "x-acs-request-id": "00000F-00000-00D1",
        "connection": "keep-alive",
        "content-type": "application/json;charset=utf-8",
        "access-control-expose-headers": "*",
        "x-acs-trace-id": "dsadadsad5898795sdas"
    },
    "statusCode": 200,
    "body": {
        "bizId": "83838383838383^0",
        "code": "OK",
        "message": "OK",
        "requestId": "00000F-00000-00D1"
    }
}
4.2 查询信息详情
SmsUtil.querySendDetails(bizId, phoneNumber, sendDate, 1L, 50L);
{
    "headers": {
        "access-control-allow-origin": "*",
        "date": "Wed, 31 May 2023 07:06:49 GMT",
        "transfer-encoding": "chunked",
        "vary": "Accept-Encoding",
        "x-acs-request-id": "00000F-00000-00D1",
        "connection": "keep-alive",
        "content-type": "application/json;charset=utf-8",
        "access-control-expose-headers": "*",
        "x-acs-trace-id": "dsdsd6s56s56ds65"
    },
    "statusCode": 200,
    "body": {
        "code": "OK",
        "message": "OK",
        "requestId": "00000F-00000-00D1",
        "smsSendDetailDTOs": {
            "smsSendDetailDTO": [
                {
                    "content": "【signName】验证码为11111(切勿将验证码告知他人)。",
                    "errCode": "DELIVERED",
                    "outId": null,
                    "phoneNum": "18600000000",
                    "receiveDate": "2023-05-31 14:50:03",
                    "sendDate": "2023-05-31 14:49:58",
                    "sendStatus": 3,
                    "templateCode": "SMS_0000000"
                }
            ]
        },
        "totalCount": "1"
    }
}
4.3 发送信息统计
SmsUtil.QuerySendStatistics(startDate, endDate, 1, 50);
{
    "headers": {
        "access-control-allow-origin": "*",
        "date": "Thu, 01 Jun 2023 08:13:20 GMT",
        "content-length": "219",
        "x-acs-request-id": "00000F-00000-00D1",
        "connection": "keep-alive",
        "content-type": "application/json;charset=utf-8",
        "access-control-expose-headers": "*",
        "x-acs-trace-id": "ds45sd4d5s45d45s45"
    },
    "statusCode": 200,
    "body": {
        "code": "OK",
        "data": {
            "targetList": [
                {
                    "noRespondedCount": 1,
                    "respondedFailCount": 2,
                    "respondedSuccessCount": 3,
                    "sendDate": "20230530",
                    "totalCount": 6
                }
            ],
            "totalSize": 1
        },
        "message": null,
        "requestId": "00000F-00000-00D1"
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值