com.hn.sms.chuangrui.ChuangRuiSms Maven / Gradle / Ivy
package com.hn.sms.chuangrui;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.hn.config.HnConfigUtils;
import com.hn.config.exception.ConfigException;
import com.hn.sms.Sms;
import com.hn.sms.chuangrui.domain.ChuangRuiParam;
import com.hn.sms.exception.SmsException;
import com.hn.utils.AssertUtils;
/**
* 创瑞短信配置
*/
public class ChuangRuiSms implements Sms {
private static final Log log = LogFactory.get();
/**
* 短信网关地址
*/
private static final String WEB_URL = "http://api.1cloudsp.com/api/v2/single_send";
private ChuangRuiParam param;
public ChuangRuiSms(ChuangRuiParam param) {
this.param = param;
}
public ChuangRuiSms(String scene) {
this.param = getRequestParam(scene);
}
/**
* 短信发送
*
* @param phone 手机号
* @param code 验证码
* @return {boolean}
*/
public boolean send(String phone, String code) {
AssertUtils.notNull(param, "param is null");
AssertUtils.notNull(phone, "手机号必填");
// AssertUtils.notNull(code,"短信验证码必填");
param.setMobile(phone);
param.setAuthCode(code);
String result = HttpUtil.post(WEB_URL, param);
JSONObject jsonObject = JSONUtil.parseObj(result);
if ("0".equals(jsonObject.getStr("code"))) {
log.info("创瑞短信返回结果:{}", result);
return true;
}
log.error("创瑞短信返回结果:{}", result);
throw new SmsException("短信发送失败," + jsonObject.getStr("msg"));
}
/**
* 配置前缀名
*/
private static final String CONFIG_KEY = "sms.chuangRui";
private ChuangRuiParam getRequestParam(String scene) {
if(StrUtil.isNotBlank(scene)){
scene = "-".concat(scene);
}
// 从数据库读取配置
String accessKey = AssertUtils.notNull(HnConfigUtils.getConfig(CONFIG_KEY.concat(scene).concat(".accesskey")),
ConfigException.exception("创瑞短信开发key未配置"));
String secret = AssertUtils.notNull(HnConfigUtils.getConfig(CONFIG_KEY.concat(scene).concat(".secret")),
ConfigException.exception("创瑞短信开发秘钥未配置"));
String sign = AssertUtils.notNull(HnConfigUtils.getConfig(CONFIG_KEY.concat(scene).concat(".sign")),
ConfigException.exception("创瑞短信签名未配置"));
String templateId = AssertUtils.notNull(HnConfigUtils.getConfig(CONFIG_KEY.concat(scene).concat(".templateId")),
ConfigException.exception("创瑞短信模板ID未配置"));
ChuangRuiParam param = new ChuangRuiParam();
param.setAccessKey(accessKey);
param.setSecret(secret);
param.setSign(sign);
param.setTemplateId(templateId);
return param;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy