组件封装-阿里云短信发送

介绍

短信服务(Short Message Service)是阿里云为用户提供的一种通信服务的能力。 支持向国内和国际快速发送验证码、短信通知和推广短信,服务范围覆盖全球200多个国家和地区。国内短信支持三网合一专属通道,与工信部携号转网平台实时互联。电信级运维保障,实时监控自动切换,到达率高达99%。完美支撑双11期间20亿短信发送,6亿用户触达。

依赖

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.0.3</version>
</dependency>

封装

实体类

阿里短信发送返回的responseData实体

import java.io.Serializable;

import lombok.Getter;
import lombok.Setter;

/**
 * 阿里短信发送返回的responseData实体
 * 
 *
 */
@Getter
@Setter
public class ResponseData implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public ResponseData() {
	}
	
	public ResponseData(String message, String requestId, String bizId, String code) {
		this.message = message;
		this.requestId = requestId;
		this.bizId = bizId;
		this.code = code;
	}

	private String message;
	
	private String requestId;
	
	private String bizId;
	
	private String code;
}

 签名证明文件

import lombok.Getter;
import lombok.Setter;

/**
 * 签名证明文件
 * 
 *
 */
@Getter
@Setter
public class SignFile {

	/**
	 * 签名的证明文件格式,支持上传多张图片。当前支持jpg、png、gif或jpeg格式的图片。个别场景下,申请签名需要上传证明文件
	 */
	private String fileSuffix;
	
	/**
	 * 签名的资质证明文件经base64编码后的字符串。图片不超过2 MB
	 */
	private String fileContents;

}

 阿里短信模板接收类

import lombok.Getter;
import lombok.Setter;

/**
 * 阿里短信模板接收类
 * 
 *
 */
@Getter
@Setter
public class Template {

	private String templateContent;
	
	private int templateType;
	
	private String templateName;
	
	private String message;
	
	private String requestId;
	
	private String templateCode;
	
	private String createDate;
	
	private String code;
	
	private String reason;
	
	private int templateStatus;
	
}

常量类

短信常量

/**
 * 短信常量类
 * 
 *
 */
public class SmsConstant {
	
	/**
	 * 短信发送服务类型
	 */
	public static String SMS_TYPE = "smsType";

	/**
	 * accessKeyId
	 */
	public static String ACCESS_KEY_ID = "accessKeyId";
	
	/**
	 * accessSecert
	 */
	public static String ACCESS_SECERT = "accessSecert";
	
	/**
	 * 手机号码
	 */
	public static String PHONE_NUMBERS = "phoneNumbers";
	
	/**
	 * 短信签名
	 */
	public static String SIGN_NAME = "signName";
	
	/**
	 * 短信模板ID
	 */
	public static String TEMPLATE_CODE = "templateCode";
	
	/**
	 * 短信模板变量
	 */
	public static String TEMPLATE_PARAM = "templateParam";
	
	/**
	 * 上行短信扩展码
	 */
	public static String SMS_UP_EXTEND_CODE = "smsUpExtendCode";
	
	/**
	 * 外部流水
	 */
	public static String OUT_ID = "outId";
	
	/**
	 * 结果
	 */
	public static String RESULT = "result";
	
}

枚举类

短信服务类型枚举

/**
 * 短信服务类型枚举类
 * 
 *
 */
public enum SmsTypeEnum {

	/**
	 * 阿里短信
	 */
	aliSms
}

API 

封装阿里短信API

import java.util.List;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

/**
 * 阿里短信服务
 * 
 *
 */
public class AliSms {
		
	private static String REGIN_ID_NAME = "RegionId";
	
	private static String REGIN_ID_VALUE = "cn-hangzhou";
	
	private static String DOMAIN = "dysmsapi.aliyuncs.com";
	
	private static String VERSION = "2017-05-25";
	
	private static String PHONE_NUMBERS = "PhoneNumbers";
	
	private static String SIGN_NAME = "SignName";
	
	private static String TEMPLATE_CODE = "TemplateCode";
	
	private static String TEMPLATE_PARAM = "TemplateParam";
	
	private static String SMS_UP_EXTEND_CODE = "SmsUpExtendCode";
	
	private static String OUT_ID = "OutId";
	
	private static String PHONE_NUMBER_JSON = "PhoneNumberJson";
	
	private static String SIGN_NAME_JSON = "SignNameJson";
	
	private static String TEMPLATE_PARAM_JSON = "TemplateParamJson";
	
	private static String SMS_UP_EXTEND_CODE_JSON = "SmsUpExtendCodeJson";
	
	private static String PHONE_NUMBER = "PhoneNumber";
	
	private static String SEND_DATE = "SendDate";
	
	private static String PAGE_SIZE = "PageSize";
	
	private static String CURRENT_PAGE = "CurrentPage";
	
	private static String BIZ_ID = "BizId";
	
	private static String TEMPLATE_TYPE = "TemplateType";
	
	private static String TEMPLATE_NAME = "TemplateName";
	
	private static String TEMPLATE_CONTENT = "TemplateContent";
	
	private static String SEND_SMS_ACTION = "SendSms";
	
	private static String SEND_BATCH_SMS_ACTION = "SendBatchSms";
	
	private static String QUERY_SEND_DETAILS_ACTION = "QuerySendDetails";
	
	private static String QUERY_SMS_SIGN_ACTION = "QuerySmsSign";
	
	private static String QUERY_SMS_TEMPLATE_ACTION = "QuerySmsTemplate";
	
	private static String ADD_SMS_TEMPLATE_ACTION = "AddSmsTemplate";
	
	private static String MODIFY_SMS_TEMPLATE_ACTION = "ModifySmsTemplate";
	
	private static String DELETE_SMS_TEMPLATE_ACTION = "DeleteSmsTemplate";
	
	private static String ADD_SMS_SIGN_ACTION = "AddSmsSign";
	
	private static String MODIFY_SMS_SIGN_ACTION = "ModifySmsSign";
	
	private static String DELETE_SMS_SIGN_ACTION = "DeleteSmsSign";
		
	private static String SIGN_SOURCE = "SignSource";
	
	private static String REMARK = "Remark";
	
    private String accessKeyId;
    
    private String accessSecret;
    
	public AliSms() {
	}
	
	public AliSms(String accessKeyId, String accessSecert) {
		this.accessKeyId = accessKeyId;
		this.accessSecret = accessSecert;
	}
    
    /**
     * 短信发送,支持向多个不同的手机号码发送同样内容的短信
     * @param phoneNumbers 必填,接收短信的手机号码。
						      格式:
						      国内短信:11位手机号码,例如15951955195。
						      国际/港澳台消息:国际区号+号码,例如85200000000。
						      支持对多个手机号码发送短信,手机号码之间以英文逗号(,)分隔。上限为1000个手机号码。批量调用相对于单条调用及时性稍有延迟
     * @param signName 必填,短信签名名称
     * @param templateCode 必填,短信模板ID
     * @param templateParam 必填,短信模板变量对应的实际值,JSON格式
     * @param smsUpExtendCode 非必填,上行短信扩展码,无特殊需要此字段的用户请忽略此字段
     * @param outId 非必填,外部流水扩展字段
     * @return
     * @throws ServerException
     * @throws ClientException
     */
	public CommonResponse sendSms(String phoneNumbers, String signName, String templateCode, String templateParam, 
			String smsUpExtendCode, String outId) throws ServerException, ClientException {
		//初始化acsClient,<accessKeyId>和"<accessSecret>"在短信控制台查询即可。
        DefaultProfile profile = DefaultProfile.getProfile(REGIN_ID_VALUE, accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(DOMAIN);
        request.setVersion(VERSION);
        request.setAction(SEND_SMS_ACTION);
        request.putQueryParameter(REGIN_ID_NAME, REGIN_ID_VALUE);
        request.putQueryParameter(PHONE_NUMBERS, phoneNumbers);
        request.putQueryParameter(SIGN_NAME, signName);
        request.putQueryParameter(TEMPLATE_CODE, templateCode);
        request.putQueryParameter(TEMPLATE_PARAM, templateParam);
        request.putQueryParameter(SMS_UP_EXTEND_CODE, smsUpExtendCode);
        request.putQueryParameter(OUT_ID, outId);
		return client.getCommonResponse(request);
	}
	
	/**
	 * 批量发送短信
	 * @param PhoneNumberJson 必填,接收短信的手机号码,JSON数组格式。
							    手机号码格式:
							    国内短信:11位手机号码,例如15900000000。
							    国际/港澳台消息:国际区号+号码,例如85200000000。
	 * @param SignNameJson 必填,短信签名名称,JSON数组格式
	 * @param TemplateCode 必填,短信模板CODE
	 * @param TemplateParamJson 必填,短信模板变量对应的实际值,JSON格式
	 * @param SmsUpExtendCodeJson 非必填,上行短信扩展码,JSON数组格式。无特殊需要此字段的用户请忽略此字段
	 * @return
	 * @throws ServerException
	 * @throws ClientException
	 */
	public CommonResponse sendBatchSms(String phoneNumberJson, String signNameJson, String templateCode, 
			String templateParamJson, String smsUpExtendCodeJson) throws ServerException, ClientException{
		//初始化acsClient,<accessKeyId>和"<accessSecret>"在短信控制台查询即可。
        DefaultProfile profile = DefaultProfile.getProfile(REGIN_ID_VALUE, accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(DOMAIN);
        request.setVersion(VERSION);
        request.setAction(SEND_BATCH_SMS_ACTION);
        request.putQueryParameter(REGIN_ID_NAME, REGIN_ID_VALUE);
        request.putQueryParameter(PHONE_NUMBER_JSON, phoneNumberJson);
        request.putQueryParameter(SIGN_NAME_JSON, signNameJson);
        request.putQueryParameter(TEMPLATE_CODE, templateCode);
        request.putQueryParameter(TEMPLATE_PARAM_JSON, templateParamJson);
        request.putQueryParameter(SMS_UP_EXTEND_CODE_JSON, smsUpExtendCodeJson);
        return client.getCommonResponse(request);
	}
	
	/**
	 * 查询某个手机号的短信发送情况。短信发送状态有:提交,成功,失败
	 * @param MessageId 短信发送ID
	 * @return
	 * @throws ServerException
	 * @throws ClientException
	 */
	public CommonResponse querySendDetails(String phoneNumber, String sendDate, String pageSize, String currentPage, 
			String bizId) throws ServerException, ClientException{
		//初始化acsClient,<accessKeyId>和"<accessSecret>"在短信控制台查询即可。
        DefaultProfile profile = DefaultProfile.getProfile(REGIN_ID_VALUE, accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(DOMAIN);
        request.setVersion(VERSION);
        request.setAction(QUERY_SEND_DETAILS_ACTION);
        request.putQueryParameter(REGIN_ID_NAME, REGIN_ID_VALUE);
        request.putQueryParameter(PHONE_NUMBER, phoneNumber);
        request.putQueryParameter(SEND_DATE, sendDate);
        request.putQueryParameter(PAGE_SIZE, pageSize);
        request.putQueryParameter(CURRENT_PAGE, currentPage);
        request.putQueryParameter(BIZ_ID, bizId);
        return client.getCommonResponse(request);
	}
		
	/**
	 * 查询短信模板的审核状态
	 * @param templateCode 短信模板CODE
	 * @return
	 * @throws ServerException
	 * @throws ClientException
	 */
	public CommonResponse querySmsTemplate(String templateCode) throws ServerException, ClientException{
		//初始化acsClient,<accessKeyId>和"<accessSecret>"在短信控制台查询即可。
        DefaultProfile profile = DefaultProfile.getProfile(REGIN_ID_VALUE, accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(DOMAIN);
        request.setVersion(VERSION);
        request.setAction(QUERY_SMS_TEMPLATE_ACTION);
        request.putQueryParameter(REGIN_ID_NAME, REGIN_ID_VALUE);
        request.putQueryParameter(TEMPLATE_CODE, templateCode);
        return client.getCommonResponse(request);
	}
	
	/**
	 * 修改短信模板
	 * @param templateType 必填,短信类型。其中:
						   0:验证码。
						   1:短信通知。
						   2:推广短信。
						   3:国际/港澳台消息
	 * @param templateName 必填,模板名称,长度为1~30个字符
	 * @param templateContent 必填,模板内容,长度为1~500个字符
	 * @param remark 必填,短信模板申请说明。请在申请说明中描述您的业务使用场景,长度为1~100个字符
	 * @return
	 * @throws ServerException
	 * @throws ClientException
	 */
	public CommonResponse modifySmsTemplate(String templateType, String templateName, String templateContent, String remark) throws ServerException, ClientException{
		//初始化acsClient,<accessKeyId>和"<accessSecret>"在短信控制台查询即可。
        DefaultProfile profile = DefaultProfile.getProfile(REGIN_ID_VALUE, accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(DOMAIN);
        request.setVersion(VERSION);
        request.setAction(MODIFY_SMS_TEMPLATE_ACTION);
        request.putQueryParameter(REGIN_ID_NAME, REGIN_ID_VALUE);
        request.putQueryParameter(TEMPLATE_TYPE, templateType);
        request.putQueryParameter(TEMPLATE_NAME, templateName);
        request.putQueryParameter(TEMPLATE_CONTENT, templateContent);
        request.putQueryParameter(REMARK, remark);
        return client.getCommonResponse(request);
	}
	
	/**
	 * 申请短信模板
	 * @param templateType 必填,短信类型。其中:
						   0:验证码。
						   1:短信通知。
						   2:推广短信。
						   3:国际/港澳台消息
	 * @param templateName 必填,模板名称,长度为1~30个字符
	 * @param templateContent 必填,模板内容,长度为1~500个字符
	 * @param remark 必填,短信模板申请说明。请在申请说明中描述您的业务使用场景,长度为1~100个字符
	 * @return
	 * @throws ServerException
	 * @throws ClientException
	 */
	public CommonResponse addSmsTemplate(String templateType, String templateName, String templateContent, String remark) throws ServerException, ClientException{
		//初始化acsClient,<accessKeyId>和"<accessSecret>"在短信控制台查询即可。
        DefaultProfile profile = DefaultProfile.getProfile(REGIN_ID_VALUE, accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(DOMAIN);
        request.setVersion(VERSION);
        request.setAction(ADD_SMS_TEMPLATE_ACTION);
        request.putQueryParameter(REGIN_ID_NAME, REGIN_ID_VALUE);
        request.putQueryParameter(TEMPLATE_TYPE, templateType);
        request.putQueryParameter(TEMPLATE_NAME, templateName);
        request.putQueryParameter(TEMPLATE_CONTENT, templateContent);
        request.putQueryParameter(REMARK, remark);
        return client.getCommonResponse(request);
	}
	
	/**
	 * 删除短信模板
	 * @param templateCode 短信模板CODE
	 * @return
	 * @throws ServerException
	 * @throws ClientException
	 */
	public CommonResponse deleteSmsTemplate(String templateCode) throws ServerException, ClientException{
		//初始化acsClient,<accessKeyId>和"<accessSecret>"在短信控制台查询即可。
        DefaultProfile profile = DefaultProfile.getProfile(REGIN_ID_VALUE, accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(DOMAIN);
        request.setVersion(VERSION);
        request.setAction(DELETE_SMS_TEMPLATE_ACTION);
        request.putQueryParameter(REGIN_ID_NAME, REGIN_ID_VALUE);
        request.putQueryParameter(TEMPLATE_CODE, templateCode);
        return client.getCommonResponse(request);
	}
	
	/**
	 * 查询短信签名申请状态
	 * @param signName 签名名称
	 * @return
	 * @throws ServerException
	 * @throws ClientException
	 */
	public CommonResponse querySmsSign(String signName) throws ServerException, ClientException{
		//初始化acsClient,<accessKeyId>和"<accessSecret>"在短信控制台查询即可。
        DefaultProfile profile = DefaultProfile.getProfile(REGIN_ID_VALUE, accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(DOMAIN);
        request.setVersion(VERSION);
        request.setAction(QUERY_SMS_SIGN_ACTION);
        request.putQueryParameter(REGIN_ID_NAME, REGIN_ID_VALUE);
        request.putQueryParameter(SIGN_NAME, signName);
        return client.getCommonResponse(request);
	}
	
	/**
	 * 申请短信签名
	 * @param signName 必填,签名名称 
	 * @param signSource 必填,签名来源。其中:
					     0:企事业单位的全称或简称。
					     1:工信部备案网站的全称或简称。
					     2:APP应用的全称或简称。
					     3:公众号或小程序的全称或简称。
					     4:电商平台店铺名的全称或简称。
					     5:商标名的全称或简称
	 * @param remark 必填,短信签名申请说明。请在申请说明中详细描述您的业务使用场景,申请工信部备案网站的全称或简称请在此处填写域名,长度不超过200个字符
	 * @param signFileList 必填,签名的证明文件
 						   key: 签名的证明文件格式,支持上传多张图片。当前支持jpg、png、gif或jpeg格式的图片。个别场景下,申请签名需要上传证明文件
 						   value: 签名的资质证明文件经base64编码后的字符串。图片不超过2 MB。个别场景下,申请签名需要上传证明文件
	 * @return
	 * @throws ServerException
	 * @throws ClientException
	 */
	public CommonResponse addSmsSign(String signName, String signSource, String remark, List<SignFile> signFileList) throws ServerException, ClientException{
		//初始化acsClient,<accessKeyId>和"<accessSecret>"在短信控制台查询即可。
        DefaultProfile profile = DefaultProfile.getProfile(REGIN_ID_VALUE, accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(DOMAIN);
        request.setVersion(VERSION);
        request.setAction(ADD_SMS_SIGN_ACTION);
        request.putQueryParameter(REGIN_ID_NAME, REGIN_ID_VALUE);
        request.putQueryParameter(SIGN_NAME, signName);
        request.putQueryParameter(SIGN_SOURCE, signSource);
        request.putQueryParameter(REMARK, remark);
        if(signFileList != null) {
        	for(int i = 1;i <= signFileList.size();i++) {
        		request.putQueryParameter("SignFileList." + i + ".FileSuffix", signFileList.get(i - 1).getFileSuffix());
        		request.putQueryParameter("SignFileList." + i + ".FileContents", signFileList.get(i - 1).getFileContents());
        	}
        }
        return client.getCommonResponse(request);
	}
	
	/**
	 * 修改短信签名
	 * @param signName 必填,签名名称 
	 * @param signSource 必填,签名来源。其中:
					     0:企事业单位的全称或简称。
					     1:工信部备案网站的全称或简称。
					     2:APP应用的全称或简称。
					     3:公众号或小程序的全称或简称。
					     4:电商平台店铺名的全称或简称。
					     5:商标名的全称或简称
	 * @param remark 必填,短信签名申请说明。请在申请说明中详细描述您的业务使用场景,申请工信部备案网站的全称或简称请在此处填写域名,长度不超过200个字符
	 * @param signFileList 必填,签名的证明文件
 						   key: 签名的证明文件格式,支持上传多张图片。当前支持jpg、png、gif或jpeg格式的图片。个别场景下,申请签名需要上传证明文件
 						   value: 签名的资质证明文件经base64编码后的字符串。图片不超过2 MB。个别场景下,申请签名需要上传证明文件
	 * @return
	 * @throws ServerException
	 * @throws ClientException
	 */
	public CommonResponse modifySmsSign(String signName, String signSource, String remark, List<SignFile> signFileList) throws ServerException, ClientException{
		//初始化acsClient,<accessKeyId>和"<accessSecret>"在短信控制台查询即可。
        DefaultProfile profile = DefaultProfile.getProfile(REGIN_ID_VALUE, accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(DOMAIN);
        request.setVersion(VERSION);
        request.setAction(MODIFY_SMS_SIGN_ACTION);
        request.putQueryParameter(REGIN_ID_NAME, REGIN_ID_VALUE);
        request.putQueryParameter(SIGN_NAME, signName);
        request.putQueryParameter(SIGN_SOURCE, signSource);
        request.putQueryParameter(REMARK, remark);
        if(signFileList != null) {
        	for(int i = 1;i <= signFileList.size();i++) {
        		request.putQueryParameter("SignFileList." + i + ".FileSuffix", signFileList.get(i - 1).getFileSuffix());
        		request.putQueryParameter("SignFileList." + i + ".FileContents", signFileList.get(i - 1).getFileContents());
        	}
        }
        return client.getCommonResponse(request);
	}
	
	/**
	 * 删除短信签名
	 * @param signName 签名名称
	 * @return
	 * @throws ServerException
	 * @throws ClientException
	 */
	public CommonResponse deleteSmsSign(String signName) throws ServerException, ClientException{
		//初始化acsClient,<accessKeyId>和"<accessSecret>"在短信控制台查询即可。
        DefaultProfile profile = DefaultProfile.getProfile(REGIN_ID_VALUE, accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(DOMAIN);
        request.setVersion(VERSION);
        request.setAction(DELETE_SMS_SIGN_ACTION);
        request.putQueryParameter(REGIN_ID_NAME, REGIN_ID_VALUE);
        request.putQueryParameter(SIGN_NAME, signName);
        return client.getCommonResponse(request);
	}

	public String getAccessKeyId() {
		return accessKeyId;
	}

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

	public String getAccessSecret() {
		return accessSecret;
	}

	public void setAccessSecret(String accessSecret) {
		this.accessSecret = accessSecret;
	}
	
}

工厂类 

package com.huatek.frame.common.utils.sms;

import java.util.HashMap;
import java.util.Map;

import org.springframework.util.ObjectUtils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.xxxxxx.xxxxx.xxxxxx.xxxxx.xxx.xxx.AliSms;
import com.xxxxxx.xxxxx.xxxxxx.xxxxx.xxx.xxx.ResponseData;
import com.xxxxxx.xxxxx.xxxxxx.xxxxx.xxx.xxx.Template;

/**
 * 短信发送工厂类
 * 
 *
 */
public class SmsFactory {
	
	/**
	 * 短信发送,支持向多个不同的手机号码发送同样内容的短信
	 * @param map
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> sendSms(Map<String, Object> map) throws Exception {
		if(ObjectUtils.isEmpty(map.get(SmsConstant.SMS_TYPE))) {
			throw new RuntimeException("参数smsType不能为空!");
		}
		Map<String, Object> resultMap = new HashMap<String, Object>(4);
		if(SmsTypeEnum.aliSms.equals(map.get(SmsConstant.SMS_TYPE))) {
			resultMap = aliSendSms(map);
		}
		return resultMap;
	}
	
	/**
	 * 获取模板内容
	 * @param map
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> querySmsTemplate(Map<String, Object> map) throws Exception {
		if(ObjectUtils.isEmpty(map.get(SmsConstant.SMS_TYPE))) {
			throw new RuntimeException("参数smsType不能为空!");
		}
		Map<String, Object> resultMap = new HashMap<String, Object>(4);
		if(SmsTypeEnum.aliSms.equals(map.get(SmsConstant.SMS_TYPE))) {
			resultMap = aliQuerySmsTemplate(map);
		}
		return resultMap;
	}
		
	/**
	 * 阿里短信发送
	 * @param map
	 * @return
	 * @throws ClientException 
	 * @throws ServerException 
	 * @throws Exception
	 */
	private static Map<String, Object> aliSendSms(Map<String, Object> map) throws ServerException, ClientException {
		if(map.get(SmsConstant.ACCESS_KEY_ID) == null || map.get(SmsConstant.ACCESS_SECERT) == null
				|| map.get(SmsConstant.PHONE_NUMBERS) == null || map.get(SmsConstant.SIGN_NAME) == null
				|| map.get(SmsConstant.TEMPLATE_CODE) == null || map.get(SmsConstant.TEMPLATE_PARAM) == null) {
			throw new RuntimeException("参数accessKeyId、accessSecert、phoneNumbers、signName、templateCode和templateParam不能为空!");
		}
		String appKey = map.get(SmsConstant.ACCESS_KEY_ID).toString();
		String masterSecret = map.get(SmsConstant.ACCESS_SECERT).toString();
		AliSms aliSms = getAliSmsService(appKey, masterSecret);
		// 接收短信的手机号码
		String phoneNumbers = map.get(SmsConstant.PHONE_NUMBERS).toString();
		// 短信签名名称
		String signName = map.get(SmsConstant.SIGN_NAME).toString();
		// 短信模板ID
		String templateCode = map.get(SmsConstant.TEMPLATE_CODE).toString();
		// 短信模板变量对应的实际值
		String templateParam = map.get(SmsConstant.TEMPLATE_PARAM).toString();
		// 上行短信扩展码
		String smsUpExtendCode = map.get(SmsConstant.SMS_UP_EXTEND_CODE) == null ? null : map.get(SmsConstant.SMS_UP_EXTEND_CODE).toString();
		// 外部流水扩展字段
		String outId = map.get(SmsConstant.OUT_ID) == null ? null : map.get(SmsConstant.OUT_ID).toString();
		CommonResponse response = aliSms.sendSms(phoneNumbers, signName, templateCode, templateParam, smsUpExtendCode, outId);
		ResponseData responseData = JSONObject.parseObject(response.getData(), ResponseData.class);
		Map<String, Object> resultMap = new HashMap<String, Object>(4);
		resultMap.put(SmsConstant.RESULT, responseData);
		return resultMap;
	}
	
	private static Map<String, Object> aliQuerySmsTemplate(Map<String, Object> map) throws ServerException, ClientException {
		if(map.get(SmsConstant.ACCESS_KEY_ID) == null || map.get(SmsConstant.ACCESS_SECERT) == null
				|| map.get(SmsConstant.TEMPLATE_CODE) == null) {
			throw new RuntimeException("参数accessKeyId、accessSecert和templateCode不能为空!");
		}
		String appKey = map.get(SmsConstant.ACCESS_KEY_ID).toString();
		String masterSecret = map.get(SmsConstant.ACCESS_SECERT).toString();
		AliSms aliSms = getAliSmsService(appKey, masterSecret);
		// 短信签名名称
		String templateCode = map.get(SmsConstant.TEMPLATE_CODE).toString();
		CommonResponse response = aliSms.querySmsTemplate(templateCode);
		Template template = JSONObject.parseObject(response.getData(), Template.class);
		Map<String, Object> resultMap = new HashMap<String, Object>(4);
		resultMap.put(SmsConstant.RESULT, template.getTemplateContent());
		return resultMap;
	}
	
	private static Map<String, Object> aliQuerySmsSign(Map<String, Object> map) throws ServerException, ClientException {
		if(map.get(SmsConstant.ACCESS_KEY_ID) == null || map.get(SmsConstant.ACCESS_SECERT) == null
				|| map.get(SmsConstant.SIGN_NAME) == null) {
			throw new RuntimeException("参数accessKeyId、accessSecert和signName不能为空!");
		}
		String appKey = map.get(SmsConstant.ACCESS_KEY_ID).toString();
		String masterSecret = map.get(SmsConstant.ACCESS_SECERT).toString();
		AliSms aliSms = getAliSmsService(appKey, masterSecret);
		// 短信签名名称
		String signName = map.get(SmsConstant.SIGN_NAME).toString();
		CommonResponse response = aliSms.querySmsSign(signName);
		Map<String, Object> resultMap = new HashMap<String, Object>(4);
		resultMap.put(SmsConstant.RESULT, response);
		return resultMap;
	}
	
	/**
	 * 获取阿里短信服务
	 * @param accessKeyId
	 * @param accessSecert
	 * @return
	 */
	private static AliSms getAliSmsService(String accessKeyId, String accessSecert) {
		return new AliSms(accessKeyId, accessSecert);
	}
	
}

API

SmsFactory提供方法如下:

sendSms:发送短信

方法名称:

public static Map<String, Object> sendSms(Map<String, Object> map) throws Exception;

阿里短信map参数:

名称

类型

是否必须

默认值

描述

smsType

Enum

短信服务类型,阿里短信枚举值为SmsTypeEnum.aliSms

accessKeyId

String

accessKeyId

accessSecret

String

accessSecret

phoneNumbers

String

接受短信的手机号码.

格式:

国内短信:11位手机号码,例如15900000000.

国际/港澳台消息:国际区号+号码,例如85200000000.

支持对多个手机号码发送短信,手机号码之间以英文逗号(,)分隔.上限为1000个手机号码.批量调用相对于单条调用及时性稍有延迟

signName

String

短信签名名称

templateCode

String

短信模板ID

templateParam

String

短信模板变量对应的实际值,JSON格式

smsUpExtendCode

String

上行短信扩展码,无特殊需要此字段的用户请忽略此字段

outId

String

外部流水扩展字段

使用

private String accessKeyId = "xxxxxxxxxxxxxxxxxx";

private String accessSecert = "xxxxxxxxxxxxxxxxxxx";

public void sendSms(HttpServletRequest request) throws Exception{

    // 接收短信的手机号码
    String phoneNumbers = request.getParameter("phoneNumbers");
    // 短信签名名称
    String signName = request.getParameter("signName");
    // 短信模板ID
    String templateCode = request.getParameter("templateCode");
    // 短信模板变量对应的实际值
    String templateParam = request.getParameter("templateParam");
    // 上行短信扩展码
    String smsUpExtendCode = request.getParameter("smsUpExtendCode");
    // 外部流水扩展字段
    String outId = request.getParameter("outId");

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("smsType", SmsTypeEnum.aliSms);
    map.put("accessKeyId", accessKeyId);
    map.put("accessSecert", accessSecert);
    map.put("phoneNumbers", phoneNumbers);
    map.put("signName", signName);
    map.put("templateCode", templateCode);
    map.put("templateParam", templateParam);
    map.put("smsUpExtendCode", smsUpExtendCode);
    map.put("outId", outId);
    SmsFactory.sendSms(map);
}

参考

如果您需要调用API,请在阿里云控制台上创建AccessKey

访问密钥AccessKeyAK)相当于登录密码,只是使用场景不同。AccessKey用于程序方式调用短信服务API,而登录密码用于登录控制台。

您可以使用AccessKey构造一个API请求(或者使用短信服务SDK)来操作资源。如何创建AccessKey,请参考创建AccessKey

AccessKey包括AccessKeyIdAccessKeySecret

  • AccessKeyId用于标识用户。
  • AccessKeySecret是用来验证用户的密钥。AccessKeySecret必须保密。

阿里短信API:

https://help.aliyun.com/document_detail/101300.html?spm=a2c4g.11186623.6.602.379a52feQXPQuA

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值