import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Service
@Slf4j
public class HuaweiySmsMsgSendStyleImpl extends AbSmsMsgSendStyle {
/**
* 设置不验证主机
*/
private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
@Override
public boolean send(String phone, String content, Map<String, String> properties, String modelId) throws IOException {
log.warn("华为短信发送---------------------------开始----------------");
// APP接入地址+接口访问URI, IP:Port表示IoT云通信的IP和端口号,IP和端口信息在申请开通接入完成后会自动分配,可在控制台-国内短信-开通接入页面进行查看。
String url = properties.get("url");
// 实际账号
String account = properties.get("account");
// 实际密码
String password = properties.get("password");
// 短信签名
String signature = properties.get("signature");
// 手机号,支持传入多个,需要list格式
String[] msisdn = {phone};
// 模板编号
String templateId = modelId;
// sx102 id
String messageId = properties.get("sx102Id");
//
String statusCallback = properties.get("statusCallback");
//处理模板
String unprocessedContent = properties.get("unprocessedContent");
String parameter = properties.get("parameter");
// 存储参数值
Map<String, String> templateParas = new HashMap<String, String>();
if (StringUtils.isNotBlank(parameter)){
// 解析 JSON 数据
JSONObject jsonData = JSON.parseObject(parameter);
// 提取模板中的参数名
List<String> placeholders = extractPlaceholders(unprocessedContent);
// 遍历模板中的参数名,从数据中提取对应的参数值
for (String placeholder : placeholders) {
String paramValue = jsonData.getString(placeholder);
templateParas.put(placeholder, paramValue);
}
}
// 状态报告接收地址,为空或者不填表示不接收状态报告
log.warn("平台模板内容-----"+content+";处理后模板内容-----"+JSON.toJSONString(templateParas));
if (StringUtils.isBlank(url) || StringUtils.isBlank(account) || StringUtils.isBlank(password) || StringUtils.isBlank(signature) || StringUtils.isBlank(phone) || StringUtils.isBlank(templateId)) {
log.error(String.format("华为短信参数值不符合要求:url: %s; account: %s; password: %s;signature: %s;mobiles: %s;templateId: %s;messageId: %s;",
url, account, password, signature, phone, templateId,messageId));
return false;
}
// 请求Body
Map<String, Object> body = buildRequestBody(msisdn, templateId, templateParas, account, password, signature, statusCallback);
if (null == body || body.isEmpty()) {
log.error("华为短信参数body为空");
return false;
}
HttpsURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
try {
trustAllHttpsCertificates();
} catch (Exception e) {
log.error("证书验证异常:", e);
throw new RuntimeException(e);
}
try {
URL realUrl = new URL(url);
connection = (HttpsURLConnection) realUrl.openConnection();
connection.setHostnameVerifier(DO_NOT_VERIFY);
connection.setDoInput(true); // 设置可输入
connection.setDoOutput(true); // 设置该连接是可以输出的
connection.setRequestMethod("POST"); // 设置请求方式
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
// connection.connect();
ObjectMapper objectMapper = new ObjectMapper();
PrintWriter pw = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
pw.write(objectMapper.writeValueAsString(body));
pw.flush();
pw.close();
br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
int status = connection.getResponseCode();
if (200 == status) { // 200
is = connection.getInputStream();
} else { // 400/401
is = connection.getErrorStream();
}
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line = null;
StringBuilder result = new StringBuilder();
while ((line = br.readLine()) != null) { // 读取数据
result.append(line + "\n");
}
connection.disconnect();
System.out.println(result.toString());
String resultCode = JSON.parseObject(result.toString()).getString("resultCode");
String resultDesc = JSON.parseObject(result.toString()).getString("resultDesc");
if(StringUtils.isNotBlank(resultCode)&&"0".equals(resultCode)){
log.error("ex102Id:"+messageId+"华为短信发送---------------------------结束----------------处理成功,等待发送");
return true;
}else{
log.error("ex102Id:"+messageId+"华为短信发送---------------------------结束----------------处理失败,"+resultDesc);
return false;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
if (null != br) {
br.close();
}
log.error("ex102Id:"+messageId+"华为短信发送---------------------------结束----------------处理失败");
return false;
} catch (Exception e) {
e.printStackTrace();
log.error("ex102Id:"+messageId+"华为短信发送---------------------------结束----------------处理失败");
return false;
}
}
}
// msisdn, smsTemplateId, paramValues, account,password,signature,statusCallback
static Map<String, Object> buildRequestBody(String[] msisdn, String smsTemplateId, Map<String, String> paramValues,
String account, String password, String signature, String statusCallback) {
if (null == msisdn || null == smsTemplateId || null == account || null == password || null == signature || null == statusCallback) {
System.out.println("buildRequestBody(): mobiles, templateId or templateParas or account or password or signature or statusCallback is null.");
return null;
}
List<String> mobiles = new ArrayList<String>();
// 多个手机号参数
for(String mobile: msisdn) {
mobiles.add(mobile);
}
Map<String, Object> map = new HashMap<String, Object>();
List<MtSmsMessage> requestLists = new ArrayList<MtSmsMessage>();
MtSmsMessage mtSmsMessage = new MtSmsMessage();
mtSmsMessage.setMobiles(mobiles);
mtSmsMessage.setTemplateId(smsTemplateId);
//当发送短信使用的是无变量模板时,不需要给TemplateParas对象赋值。
if(!CollectionUtils.isEmpty(paramValues)){
mtSmsMessage.setTemplateParas(paramValues);
}
mtSmsMessage.setSignature(signature);
requestLists.add(mtSmsMessage);
map.put("account", account);
map.put("password", password);
map.put("requestLists", requestLists);
map.put("statusCallback", statusCallback);
log.warn("华为短信参数值-------------------------------"+ JSON.toJSONString(map));
return map;
}
static class MtSmsMessage {
List<String> mobiles;
String templateId;
Map<String, String> templateParas;
String signature;
String messageId;
String extCode;
List<NamedParameter> extendInfos;
/**
* 返回 mobiles
*
* @return mobiles值
*/
public List<String> getMobiles() {
return mobiles;
}
/**
* 对mobiles进行赋值
*
* @param mobiles mobiles值
*/
public void setMobiles(List<String> mobiles) {
this.mobiles = mobiles;
}
/**
* 返回 templateId
*
* @return templateId值
*/
public String getTemplateId() {
return templateId;
}
/**
* 对templateId进行赋值
*
* @param templateId templateId值
*/
public void setTemplateId(String templateId) {
this.templateId = templateId;
}
/**
* 返回 templateParas
*
* @return templateParas值
*/
public Map<String, String> getTemplateParas() {
return templateParas;
}
/**
* 对templateParas进行赋值
*
* @param templateParas templateParas值
*/
public void setTemplateParas(Map<String, String> templateParas) {
this.templateParas = templateParas;
}
/**
* 返回 signature
*
* @return signature值
*/
public String getSignature() {
return signature;
}
/**
* 对signature进行赋值
*
* @param signature signature值
*/
public void setSignature(String signature) {
this.signature = signature;
}
/**
* 返回 messageId
*
* @return messageId值
*/
public String getMessageId() {
return messageId;
}
/**
* 对messageId进行赋值
*
* @param messageId messageId值
*/
public void setMessageId(String messageId) {
this.messageId = messageId;
}
/**
* 返回 extCode
*
* @return extCode值
*/
public String getExtCode() {
return extCode;
}
/**
* 对extCode进行赋值
*
* @param extCode extCode值
*/
public void setExtCode(String extCode) {
this.extCode = extCode;
}
/**
* 返回 extendInfos
*
* @return extendInfos值
*/
public List<NamedParameter> getExtendInfos() {
return extendInfos;
}
/**
* 对extendInfos进行赋值
*
* @param extendInfos extendInfos值
*/
public void setExtendInfos(List<NamedParameter> extendInfos) {
this.extendInfos = extendInfos;
}
}
class NamedParameter {
String key;
String value;
/**
* 返回 key
*
* @return key值
*/
public String getKey() {
return key;
}
/**
* 对key进行赋值
*
* @param key key值
*/
public void setKey(String key) {
this.key = key;
}
/**
* 返回 value
*
* @return value值
*/
public String getValue() {
return value;
}
/**
* 对value进行赋值
*
* @param value value值
*/
public void setValue(String value) {
this.value = value;
}
}
static void trustAllHttpsCertificates() throws Exception {
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return;
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
};
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
// 如果您不需要校验证书时,请使用如下代码
sslContext.init(null,trustAllCerts,SecureRandom.getInstanceStrong());
// 如果您需要校验证书时,请使用如下代码
// 构建TrustManagerFactory
//File trustFile = new File("你的trustStore证书库文件路径");
//FileInputStream fsTruststoreFile = new FileInputStream(trustFile);
//KeyStore trustStore = KeyStore.getInstance("JKS");
//String trustStorePwd = "你的trustStore证书库密码明文";
//trustStore.load(fsTruststoreFile, trustStorePwd.toCharArray());
//TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
//tmf.init(trustStore);
// 构建KeyManagerFactory
//File keyFile = new File("你的keyStore证书库文件路径");
//FileInputStream fsKeystoreFile = new FileInputStream(keyFile);
//KeyStore keyStore = KeyStore.getInstance("JKS");
//String keyStorePwd = "你的keyStore证书库密码明文";
//keyStore.load(fsKeystoreFile, keyStorePwd.toCharArray());
//KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
//kmf.init(keyStore, keyStorePwd.toCharArray());
//sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), SecureRandom.getInstanceStrong());
//HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
private static List<String> extractPlaceholders(String template) {
List<String> placeholders = new ArrayList<>();
Pattern pattern = Pattern.compile("\\$\\{(.*?)}");
Matcher matcher = pattern.matcher(template);
while (matcher.find()) {
String placeholder = matcher.group(1);
placeholders.add(placeholder);
}
return placeholders;
}
@Override
public String getName() {
return "华为IoT云短信";
}
}
完整案例直接拿走用
576

被折叠的 条评论
为什么被折叠?



