All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ajaxjs.framework.service.AliyunSMS Maven / Gradle / Ivy

Go to download

AJAXJS aims to full-stack, not only the server-side framework, but also integrates the front-end library. It'€™s written in HTML5 + Java, a successor to the JVM platform, efficient, secure, stable, cross-platform and many other advantages, but it abandoned the traditional enterprise architecture brought about by the large and bloated, emphasizing the lightweight, and fast, very suitable for the Internet fast application.

The newest version!
package com.ajaxjs.framework.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SimpleTimeZone;
import java.util.TreeMap;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.springframework.util.AlternativeJdkIdGenerator;
import org.springframework.util.Base64Utils;

import com.ajaxjs.net.http.Get;
import com.ajaxjs.util.StrUtil;
import com.ajaxjs.util.logger.LogHelper;

/**
 * 阿里云发送短信
 */
public class AliyunSMS {
	private static final LogHelper LOGGER = LogHelper.getLog(AliyunSMS.class);

	/**
	 * 请求的时间戳。按照ISO8601 标准表示,并需要使用UTC时间,格式为yyyy-MM-ddTHH:mm:ssZ。
	 */
	static String getTimestamp() {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
		df.setTimeZone(new SimpleTimeZone(0, "GMT"));// 这里一定要设置GMT时区

		return df.format(new Date());
	}

	/**
	 * 初始化请求参数
	 *
	 * @return
	 */
	static Map initParams() {
		Map paras = new HashMap<>();
		// 1. 系统参数
		paras.put("SignatureMethod", "HMAC-SHA1");
		paras.put("SignatureNonce", new AlternativeJdkIdGenerator().generateId().toString());
		paras.put("SignatureVersion", "1.0");
		paras.put("Timestamp", getTimestamp());
		paras.put("Format", "JSON");
		paras.put("Action", "SendSms");
		paras.put("Version", "2017-05-25");

		return paras;
	}

	/**
	 * 设置业务API参数
	 *
	 * @param paras
	 * @param entity
	 */
	static void setParams(Map paras, AliyunSmsEntity entity) {
		// 2. 业务API参数
		paras.put("AccessKeyId", entity.getAccessKeyId());
		paras.put("PhoneNumbers", entity.getPhoneNumbers());
		paras.put("SignName", entity.getSignName());
		paras.put("TemplateParam", entity.getTemplateParam());
		paras.put("TemplateCode", entity.getTemplateCode());

		// 3. 去除签名关键字Key
		if (paras.containsKey("Signature"))
			paras.remove("Signature");
	}

	/**
	 * 根据参数Key排序(顺序)
	 *
	 * @param paras
	 * @return
	 */
	static String sort(Map paras) {
		// 4. 参数KEY排序
		TreeMap sortParas = new TreeMap<>();
		sortParas.putAll(paras);

		// 5. 构造待签名的字符串
		Iterator it = sortParas.keySet().iterator();
		StringBuilder sortQueryStringTmp = new StringBuilder();

		while (it.hasNext()) {
			String key = it.next();
			sortQueryStringTmp.append("&").append(StrUtil.urlEncode(key)).append("=").append(StrUtil.urlEncode(paras.get(key)));
		}

		return sortQueryStringTmp.toString();
	}

	/**
	 * 构造待签名的请求串
	 *
	 * @param sortQueryStringTmp
	 * @param accessSecret
	 * @return
	 */
	static String makeSignature(String sortQueryStringTmp, String accessSecret) {
		StringBuilder stringToSign = new StringBuilder();
		stringToSign.append("GET").append("&");

		stringToSign.append(StrUtil.urlEncode("/")).append("&");
		stringToSign.append(StrUtil.urlEncode(sortQueryStringTmp.substring(1)));// 去除第一个多余的&符号

		String sign = sign(accessSecret + "&", stringToSign.toString());

		// 6. 签名最后也要做特殊URL编码
		return StrUtil.urlEncode(sign);
	}

	/**
	 * 签名采用HmacSHA1算法 + Base64,编码采用UTF-8
	 *
	 * @param accessSecret
	 * @param stringToSign
	 * @return
	 */
	static String sign(String accessSecret, String stringToSign) {
		try {
			Mac mac = Mac.getInstance("HmacSHA1");
			mac.init(new SecretKeySpec(accessSecret.getBytes("UTF-8"), "HmacSHA1"));
			byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));

			return Base64Utils.encodeToString(signData);
		} catch (Exception e) {
			LOGGER.warning(e);
			return null;
		}
	}

	private final static String SMS_API = "http://dysmsapi.aliyuncs.com/?Signature=";

	/**
	 * @param entity
	 * @return true 表示发送成功
	 */
	public static String send(AliyunSmsEntity entity) {
		Map paras = initParams();
		setParams(paras, entity);

		String sortQueryStringTmp = sort(paras);
		String signature = makeSignature(sortQueryStringTmp, entity.getAccessSecret());

		// 最终打印出合法GET请求的URL
		Map map = Get.api(SMS_API + signature + sortQueryStringTmp);

		return "OK".equals(map.get("Code")) ? "OK" : map.get("Message").toString();
	}

//    public static void main(String[] args) {
//        AliyunSmsEntity entity = new AliyunSmsEntity();
//        entity.setAccessKeyId("LTAI5tHSCU5WeCRXuyc1g9pj");
//        entity.setAccessSecret("tq1zrGuSoyddbufP2MfrEY14gePbgP");
//        entity.setSignName("工赋合肥");
//        entity.setTemplateCode("SMS_219870130");
//        entity.setTemplateParam("{\"code\":878799}");
//        entity.setPhoneNumbers("18709864408");
//
//        System.out.println(send(entity));
//    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy