阿里大於短信服務_總結_01_短信驗證碼接入

1、代碼實現

1.接入配置類—Env.java 

package com.ray.sms.aliyun.config;

/**@desc  : 阿里大於短信服務 接入配置
 * 
 * @author: shirayner
 * @date  : 2017年11月6日 下午6:27:53
 */
public class Env {

    //1. 此處須要替換成開發者本身的AK(在阿里雲訪問控制檯尋找)
    public static final String ACCESSKEY_ID = "LTAIysLddrUmdw3l";
    public static final String ACCESSKEY_SECRET = "MhjTxvbJe8S4j8xaVE9fnJzaAerg4i";

    
    //2.產品名稱:雲通訊短信API產品,開發者無需替換
    public static final String PRODUCT = "Dysmsapi";
    //產品域名,開發者無需替換
    public static final String DOMAIN = "dysmsapi.aliyuncs.com";
    
    
    //3.短信簽名和模板,替換成本身的
    public static final String SIGN_NAME  = "雲通訊";
    public static final String TEMPLATE_CODE  = "SMS_109545088";




}
View Code

 

2.短信服務—ShortMessageService.java

package com.ray.sms.aliyun.service;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.alibaba.fastjson.JSONObject;
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 com.ray.sms.aliyun.config.Env;

/**@desc  : 短信服務
 * 
 * @author: shirayner
 * @date  : 2017年11月6日 下午7:35:03
 */
public class ShortMessageService {

    /**
     * @desc :1.發送短信
     *  
     * @param phoneNumber  手機號
     * @param code  驗證碼
     * @return
     * 
     * 
     * 
     * @throws ClientException SendSmsResponse
     */
    public static SendSmsResponse sendSms(String phoneNumber ,String code) throws ClientException {
        //1.準備好短信模板變量——驗證碼code
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("code", code);
        String TemplateParam=jsonObject.toJSONString();

        //2.可自助調整超時時間
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //3.初始化acsClient,暫不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", Env.ACCESSKEY_ID, Env.ACCESSKEY_SECRET);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", Env.PRODUCT, Env.DOMAIN);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //4.組裝請求對象-具體描述見控制檯-文檔部份內容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待發送手機號
        request.setPhoneNumbers(phoneNumber);
        //必填:短信簽名-可在短信控制檯中找到
        request.setSignName(Env.SIGN_NAME);
        //必填:短信模板-可在短信控制檯中找到
        request.setTemplateCode(Env.TEMPLATE_CODE);
        //可選:模板中的變量替換JSON串,如模板內容爲"親愛的${name},您的驗證碼爲${code}"時,此處的值爲
        request.setTemplateParam(TemplateParam);

        //選填-上行短信擴展碼(無特殊需求用戶請忽略此字段)
        //request.setSmsUpExtendCode("90997");

        //可選:outId爲提供給業務方擴展字段,最終在短信回執消息中將此值帶回給調用者
        request.setOutId("yourOutId");

        //5.hint 此處可能會拋出異常,注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

        return sendSmsResponse;
    }


    /**
     * @desc :2.短信發送記錄查詢接口
     *   用於查詢短信發送的狀態,是否成功到達終端用戶手機
     * @param bizId  
     * @param phoneNumber
     * @return
     * @throws ClientException QuerySendDetailsResponse
     */
    public static QuerySendDetailsResponse querySendDetails(String bizId,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", Env.ACCESSKEY_ID, Env.ACCESSKEY_SECRET);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", Env.PRODUCT, Env.DOMAIN);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //組裝請求對象
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        //必填-號碼
        request.setPhoneNumber(phoneNumber);
        //可選-流水號
        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;
    }

    
}
View Code

 

3.驗證碼生成器—CheckSumBuilder.java

package com.ray.sms.aliyun.util;

import java.util.Random;

/**@desc  : 驗證碼工具類
 * 
 * @author: shirayner
 * @date  : 2017年11月7日 上午10:07:46
 */
public class CheckSumBuilder {
    
    /**
     * @desc :1.隨機產生字符串
     *  
     * @param length 字符串長度
     * @param type 類型 (0: 僅數字; 2:僅字符; 別的數字:數字和字符)
     * @return 
     *   String  隨機串
     */
    public static String getRandomStr(int length, int type){
        String str = "";
        int beginChar = 'a';
        int endChar = 'z';
        
        // 只有數字
        if (type == 0){
            beginChar = 'z' + 1;
            endChar = 'z' + 10;
        }
        // 只有小寫字母
        else if (type == 2){
            beginChar = 'a';
            endChar = 'z';
        }
        // 有數字和字母
        else{
            beginChar = 'a';
            endChar = 'z' + 10;
        }

        // 生成隨機類
        Random random = new Random();
        for (int i = 0; i < length; i++){
            int tmp = (beginChar + random.nextInt(endChar - beginChar));
            // 大於'z'的是數字
            if (tmp > 'z'){
                tmp = '0' + (tmp - 'z');
            }
            str += (char) tmp;
        }

        return str;
    }

    /**
     * @desc :2.獲取6位數字驗證碼
     *  
     * @return 
     *   String  6位數字驗證碼
     */
    public static String getCheckSum() {
        return getRandomStr(6, 0);
    }
    
}
View Code

 

4.測試類—ShortMessageServiceTest.java

package com.ray.sms.aliyun.service;

import org.junit.Test;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.ray.sms.aliyun.util.CheckSumBuilder;

/**@desc  : 
 * 
 * @author: shirayner
 * @date  : 2017年11月6日 下午7:41:46
 */
public class ShortMessageServiceTest {

    @Test
    public void testsms() throws ClientException, InterruptedException {
        //1.準備好請求參數:phoneNumber、TemplateParam
        String phoneNumber="14326756454";
        String code=CheckSumBuilder.getCheckSum();

        //2.調用接口,發短信
        SendSmsResponse response = ShortMessageService.sendSms(phoneNumber,code);
        
        //3.獲取發送結果
        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());

        Thread.sleep(3000L);

        //查明細
        if(response.getCode() != null && response.getCode().equals("OK")) {
            QuerySendDetailsResponse querySendDetailsResponse = ShortMessageService.querySendDetails(response.getBizId(),phoneNumber);
            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());
        }

    }
}
View Code

 

 

 

2、參考資料

1.阿里短信服務API接入指南及示例html

2.阿里短信服務APIjava

相關文章
相關標籤/搜索