1. 程式人生 > >SpringBoot實現簡訊傳送

SpringBoot實現簡訊傳送

開發工具:IDEA、Gradle

1.由於筆者使用阿里雲的簡訊介面,所以需要去阿里雲獲取相關服務支援,每個新使用者都有免費的初始條數,之後需要簡單的配置簽名與資訊模版和AccessKey;

2.匯入相關jar包,在build.gradle檔案內加入如下座標:

    // 簡訊支援
    implementation('com.aliyun:aliyun-java-sdk-core:3.7.1')
    implementation('com.aliyun:aliyun-java-sdk-dysmsapi:1.1.0')

3.在application.properties配置檔案內加入簡訊相關配置:

# 阿里雲簡訊介面
accessKeyId=你的AccessKeyId
accessKeySecret=你的accessKeySecret

4.實現傳送功能:

package xyz.lsm1998.me.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

/**
 * 作者:劉時明
 * 日期:2018/10/30
 * 時間:16:42
 * 說明:
 */
public class SmsUtils
{
    //產品名稱:雲通訊簡訊API產品,開發者無需替換
    static final String product = "Dysmsapi";
    //產品域名,開發者無需替換
    static final String domain = "dysmsapi.aliyuncs.com";

    private static String accessKeyId;
    private static String accessKeySecret;

    static
    {
        Properties properties=new Properties();
        try
        {
            File file= ResourceUtils.getFile("classpath:application.properties");
            properties.load(new FileInputStream(file));
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        accessKeyId=properties.getProperty("accessKeyId");
        accessKeySecret=properties.getProperty("accessKeySecret");
    }

    public static void main(String[] args) throws Exception
    {
        SendSmsResponse response = sendSms("17774582000","456789");
        System.out.println(response.getCode());
        System.out.println(response.getMessage());
        QuerySendDetailsResponse qr=querySendDetails("17774582000");
        System.out.println("該使用者收到的簡訊條數:"+qr.getTotalCount());
        for (QuerySendDetailsResponse.SmsSendDetailDTO o:qr.getSmsSendDetailDTOs())
        {
            System.out.println("傳送時間:"+o.getSendDate());
        }
        
    }

    // 傳送方法
    public static SendSmsResponse sendSms(String phoneNumbers, String code) throws ClientException
    {
        //可自助調整超時時間
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暫不支援region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //組裝請求物件-具體描述見控制檯-文件部分內容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待發送手機號
        request.setPhoneNumbers(phoneNumbers);
        //必填:簡訊簽名-可在簡訊控制檯中找到
        request.setSignName("你的簡訊簽名");
        //必填:簡訊模板-可在簡訊控制檯中找到     
        request.setTemplateCode("你的模板Id");
        //設定引數
        request.setTemplateParam("{\"code\":" + code + "}");
        //可選:outId為提供給業務方擴充套件欄位,最終在簡訊回執訊息中將此值帶回給呼叫者
        //request.setOutId("123");
        //hint 此處可能會丟擲異常,注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        return sendSmsResponse;
    }

    // 查詢方法
    public static QuerySendDetailsResponse querySendDetails(String phoneNumber) throws ClientException
    {
        //可自助調整超時時間
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暫不支援region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //組裝請求物件
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        //必填-號碼
        request.setPhoneNumber(phoneNumber);
        //必填-傳送日期 支援30天內記錄查詢,格式yyyyMMdd
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        request.setSendDate(ft.format(new Date()));
        //必填-頁大小
        request.setPageSize(10L);
        //必填-當前頁碼從1開始計數
        request.setCurrentPage(1L);

        //hint 此處可能會丟擲異常,注意catch
        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);
        return querySendDetailsResponse;
    }
}

PS:如果讀者在測試傳送功能過程中出現如下錯誤:

java.lang.NoClassDefFoundError: javax/xml/bind/DatatypeConverter

則改變build.gradle檔案:

    // 簡訊支援
    //implementation('com.aliyun:aliyun-java-sdk-core:3.7.1')
    implementation('com.aliyun:aliyun-java-sdk-core:3.3.1')
    implementation('com.aliyun:aliyun-java-sdk-dysmsapi:1.1.0')

將sdk-core改為3.3.1版本即可,具體原因筆者暫時不詳。