java-阿里大魚短信接口

DySmsHelper

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

/**
 * Created on 17/6/7.
 * 短信API產品的DEMO程序,工程中包含了一個SmsDemo類,直接經過
 * 執行main函數便可體驗短信產品API功能(只須要將AK替換成開通了雲通訊-短信產品功能的AK便可)
 * 工程依賴了2個jar包(存放在工程的libs目錄下)
 * 1:aliyun-java-sdk-core.jar
 * 2:aliyun-java-sdk-dysmsapi.jar
 *
 * 備註:Demo工程編碼採用UTF-8
 * 國際短信發送請勿參照此DEMO
 */
public class DySmsHelper {
	
	private final static Logger logger=LoggerFactory.getLogger(DySmsHelper.class);

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

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

    public static void setAccessKeyId(String accessKeyId) {
        DySmsHelper.accessKeyId = accessKeyId;
    }

    public static void setAccessKeySecret(String accessKeySecret) {
        DySmsHelper.accessKeySecret = accessKeySecret;
    }

    public static String getAccessKeyId() {
        return accessKeyId;
    }

    public static String getAccessKeySecret() {
        return accessKeySecret;
    }
    
    
    public static boolean sendSms(String phone,JSONObject templateParamJson,DySmsEnum dySmsEnum) throws ClientException {
    	//可自助調整超時時間
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //update-begin-author:taoyan date:20200811 for:配置類數據獲取
        StaticConfig staticConfig = SpringContextUtils.getBean(StaticConfig.class);
        setAccessKeyId(staticConfig.getAccessKeyId());
        setAccessKeySecret(staticConfig.getAccessKeySecret());
        //update-end-author:taoyan date:20200811 for:配置類數據獲取
        
        //初始化acsClient,暫不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        
        //驗證json參數
        validateParam(templateParamJson,dySmsEnum);
        
        //組裝請求對象-具體描述見控制檯-文檔部份內容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待發送手機號
        request.setPhoneNumbers(phone);
        //必填:短信簽名-可在短信控制檯中找到
        request.setSignName(dySmsEnum.getSignName());
        //必填:短信模板-可在短信控制檯中找到
        request.setTemplateCode(dySmsEnum.getTemplateCode());
        //可選:模板中的變量替換JSON串,如模板內容爲"親愛的${name},您的驗證碼爲${code}"時,此處的值爲
        request.setTemplateParam(templateParamJson.toJSONString());
        
        //選填-上行短信擴展碼(無特殊需求用戶請忽略此字段)
        //request.setSmsUpExtendCode("90997");

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

        boolean result = false;

        //hint 此處可能會拋出異常,注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        logger.info("短信接口返回的數據----------------");
        logger.info("{Code:" + sendSmsResponse.getCode()+",Message:" + sendSmsResponse.getMessage()+",RequestId:"+ sendSmsResponse.getRequestId()+",BizId:"+sendSmsResponse.getBizId()+"}");
        if ("OK".equals(sendSmsResponse.getCode())) {
            result = true;
        }
        return result;
        
    }
    
    private static void validateParam(JSONObject templateParamJson,DySmsEnum dySmsEnum) {
    	String keys = dySmsEnum.getKeys();
    	String [] keyArr = keys.split(",");
    	for(String item :keyArr) {
    		if(!templateParamJson.containsKey(item)) {
    			throw new RuntimeException("模板缺乏參數:"+item);
    		}
    	}
    }
    

//    public static void main(String[] args) throws ClientException, InterruptedException {
//    	JSONObject obj = new JSONObject();
//    	obj.put("code", "1234");
//    	sendSms("13800138000", obj, DySmsEnum.FORGET_PASSWORD_TEMPLATE_CODE);
//    }
}

DySmsEnum 枚舉配置

import org.apache.commons.lang3.StringUtils;

public enum DySmsEnum {
	
	LOGIN_TEMPLATE_CODE("SMS_175435174","openlims","code"),
	FORGET_PASSWORD_TEMPLATE_CODE("SMS_175435174","openlims","code"),
	REGISTER_TEMPLATE_CODE("SMS_175430166","openlims","code"),
	/**會議通知*/
	MEET_NOTICE_TEMPLATE_CODE("SMS_201480469","openlims,"username,title,minute,time"),
	/**個人計劃通知*/
	PLAN_NOTICE_TEMPLATE_CODE("SMS_201470515","openlims","username,title,time");

	/**
	 * 短信模板編碼
	 */
	private String templateCode;
	/**
	 * 簽名
	 */
	private String signName;
	/**
	 * 短信模板必需的數據名稱,多個key以逗號分隔,此處配置做爲校驗
	 */
	private String keys;
	
	private DySmsEnum(String templateCode,String signName,String keys) {
		this.templateCode = templateCode;
		this.signName = signName;
		this.keys = keys;
	}
	
	public String getTemplateCode() {
		return templateCode;
	}
	
	public void setTemplateCode(String templateCode) {
		this.templateCode = templateCode;
	}
	
	public String getSignName() {
		return signName;
	}
	
	public void setSignName(String signName) {
		this.signName = signName;
	}
	
	public String getKeys() {
		return keys;
	}

	public void setKeys(String keys) {
		this.keys = keys;
	}

	public static DySmsEnum toEnum(String templateCode) {
		if(StringUtils.isEmpty(templateCode)){
			return null;
		}
		for(DySmsEnum item : DySmsEnum.values()) {
			if(item.getTemplateCode().equals(templateCode)) {
				return item;
			}
		}
		return null;
	}
}
相關文章
相關標籤/搜索