調用阿里雲短信服務

package com.example.demo.untils;

/**
 * Created by JQY on 2019/5/15
 */

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.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import java.util.Random;

/**
 * 阿里雲短信服務:
 * 注意:須要 簽名名稱、模版CODE 以及 RAM訪問控制中的 AccessKeyID 和 AccessKeySecret 
 * 接入阿里雲短信服務:
 * 1。註冊並實名認證(企業認證)(綁定企業支付寶)
 * 2.開通短信服務
 * 3.獲取AccessKey
 * 4.設置短信內容(簽名和模板)
 * 5.發送短信 
 */
public class AliyunSmsUtils {

    //產品名稱:雲通訊短信API產品,開發者無需替換
    static final String product = "Dysmsapi";
    //產品域名,開發者無需替換
    static final String domain = "dysmsapi.aliyuncs.com";

    // TODO 此處須要替換成開發者本身的AK(在阿里雲訪問控制檯尋找)
    static final String accessKeyId = "";  // TODO 修改爲本身的
    static final String accessKeySecret = "";   // TODO 修改爲本身的

    public static SendSmsResponse sendSms(String telephone, 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(telephone);
        //必填:短信簽名-可在短信控制檯中找到
        request.setSignName("你的小可愛");    // TODO 修改爲本身的
        //必填:短信模板-可在短信控制檯中找到
        request.setTemplateCode("");    // TODO 修改爲本身的
        //可選:模板中的變量替換JSON串,如模板內容爲"親愛的${name},您的驗證碼爲${code}"時,此處的值爲
//        request.setTemplateParam("{\"name\":\"Tom\", \"code\":\"123\"}");
        request.setTemplateParam("{\"code\":\"" + getNewcode() + "\"}");
        //選填-上行短信擴展碼(無特殊需求用戶請忽略此字段)
        //request.setSmsUpExtendCode("90997");
        //可選:outId爲提供給業務方擴展字段,最終在短信回執消息中將此值帶回給調用者
        request.setOutId("yourOutId");
        //hint 此處可能會拋出異常,注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
            System.out.println("短信發送成功!");
        } else {
            System.out.println("短信發送失敗!");
        }
        return sendSmsResponse;
    }


  /*  不刪 留着 之後可能有用
  public static QuerySendDetailsResponse querySendDetails(String bizId) 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("15000000000");
        //可選-流水號
        request.setBizId(bizId);
        //必填-發送日期 支持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;
    }
*/

    //如下爲測試代碼,隨機生成驗證碼
    private static int newcode;

    public static int getNewcode() {
        return newcode;
    }

    public static void setNewcode() {

        int n = 4;
        StringBuilder code = new StringBuilder();
        Random ran = new Random();
        for (int i = 0; i < n; i++) {
            code.append(Integer.valueOf(ran.nextInt(10)).toString());
        }

        newcode = Integer.parseInt(code.toString());
        //每次調用生成一位四位數的隨機數
    }

    public static void main(String[] args) throws ClientException, InterruptedException {
        setNewcode();
        String code = Integer.toString(getNewcode());
        System.out.println("發送的驗證碼爲:" + code);
        //發短信
        SendSmsResponse response = sendSms("18888888888", code); // TODO 填寫你須要測試的手機號碼
        System.out.println("短信接口返回的數據----------------");
        System.out.println("Code=" + response.getCode());
        System.out.println("Message=" + response.getMessage());
        System.out.println("RequestId=" + response.getRequestId());
        System.out.println("BizId=" + response.getBizId());

       /* 不刪 留着 之後可能有用
        System.out.println("  ==============================================  ");
        Thread.sleep(3000L);
        //查明細
        if(response.getCode() != null && response.getCode().equals("OK")) {
            QuerySendDetailsResponse querySendDetailsResponse = querySendDetails(response.getBizId());
            System.out.println("短信明細查詢接口返回數據----------------");
            System.out.println("Code=" + querySendDetailsResponse.getCode());
            System.out.println("Message=" + querySendDetailsResponse.getMessage());
            int i = 0;
            for(QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs())
            {
                System.out.println("SmsSendDetailDTO["+i+"]:");
                System.out.println("Content=" + smsSendDetailDTO.getContent());
                System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
                System.out.println("OutId=" + smsSendDetailDTO.getOutId());
                System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
                System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate());
                System.out.println("SendDate=" + smsSendDetailDTO.getSendDate());
                System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus());
                System.out.println("Template=" + smsSendDetailDTO.getTemplateCode());
            }
            System.out.println("TotalCount=" + querySendDetailsResponse.getTotalCount());
            System.out.println("RequestId=" + querySendDetailsResponse.getRequestId());
        }*/

    }

}

 

所須要的依賴java

<!-- 阿里雲短信服務所需 -->



-<dependency>

<groupId>com.aliyun</groupId>

<artifactId>aliyun-java-sdk-core</artifactId>

<version>4.0.6</version>

<!-- 注:如提示報錯,先升級基礎包版,沒法解決可聯繫技術支持 -->


</dependency>


-<dependency>

<groupId>com.aliyun</groupId>

<artifactId>aliyun-java-sdk-dysmsapi</artifactId>

<version>1.1.0</version>

</dependency>
相關文章
相關標籤/搜索