add 华为云发送短信

This commit is contained in:
lijiarao
2021-09-14 09:57:01 +08:00
parent d38a28955f
commit 5ee727acae
2 changed files with 339 additions and 0 deletions
@@ -0,0 +1,330 @@
package com.jero.common.util;
//如果JDK版本低于1.8,请使用三方库提供Base64类
//import org.apache.commons.codec.binary.Base64;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.jero.common.exception.JeroBootException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @作者:WangHK
* @类名:HuaWeiMSGSMS
* @功能:TODO_华为短信
* @日期:2021年6月20日
* @公司:天津合众未来科技有限公司
*/
@Component
public class HuaWeiSmsUtil {
@Autowired
private RedisUtil redisUtil;
//无需修改,用于格式化鉴权头域,给"X-WSSE"参数赋值
private static final String WSSE_HEADER_FORMAT = "UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"";
//无需修改,用于格式化鉴权头域,给"Authorization"参数赋值
private static final String AUTH_HEADER_VALUE = "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"";
public static final String BASE_NUMBER = "123456789";
@Value("${huaWeiSms.url}")
private String url;
@Value("${huaWeiSms.appKey}")
private String appKey;
@Value("${huaWeiSms.appSecret}")
private String appSecret;
@Value("${huaWeiSms.open}")
private boolean open;
/**
* @param phone 手机号
* @param codeType 类型:
* 1.登录检查验证码_验证码类
* 2.忘记密码_验证码类
* 3.会员到期提醒_通知类
* 4.发票邮寄通知提醒_通知类
* @param codeTime 失效时间
* 条件必填,国内短信关注,当templateId指定的模板类型为通用模板时生效且必填,必须是已审核通过的,与模板类型一致的签名名称
* 国际/港澳台短信不用关注该参数
* 失效时间为0时不存redis
* @param templateParas 传递参数,通知类需要
*/
public Boolean sendVerificationCode(String phone, String codeType, String codeTime,String templateParas) {
String sender; //通道
String templateId; //模板
String signature; //签名名称
//模板变量,此处以单变量验证码短信为例,请客户自行生成6位验证码,并定义为字符串类型,以杜绝首位0丢失的问题(例如:002569变成了2569)。
//随机生成6位数字
String randomNumber = RandomUtil.randomString(BASE_NUMBER,6);
//设置短信有效时间
codeTime = this.resRedisTime(codeTime);
//传进来为秒数所以除以60
String verificationTime = this.resVerificationTime(codeTime);
//解密手机号
phone = PasswordUtil.decrypt(phone);
long expire = redisUtil.getExpire("_verification:_phone:" + phone);
//值为-2代表没有此数据
if (expire != -2){
if (600 - expire <= 60){
throw new JeroBootException("1分钟内只能发送一次验证码");
}
}
switch (codeType) {
case "1":
//中汽标协-登录检查验证码
sender = "8821062807743";
signature = "中汽标协";
templateId = "9fbee7166af24bbfacc178e417345a21";
templateParas = "[" + randomNumber + "," + phone + "," + verificationTime + "]";
break;
case "2":
//中汽标协-忘记密码
sender = "8821062807743";
signature = "中汽标协";
templateId = "6f8573c5adc54df2a56a6e48556c3044";
templateParas = "[" + randomNumber + "," + phone + "," + verificationTime + "]";
break;
case "3":
//中汽标协-会员到期提醒
sender = "8821062807762";
signature = "中汽标协";
templateId = "3c6321febaa84fecb68d6b0f5bbc0754";
//通知类短信,不需要存redis
codeTime = "0";
break;
case "4":
//中汽标协-发票邮寄通知提醒
sender = "8821062807762";
signature = "中汽标协";
templateId = "077964a02a814149bb01900e43c9a04e";
codeTime = "0";
break;
default:
throw new JeroBootException("codeType flase.");
}
//调用华为短信发送
return this.huaWeiSendSms(phone, codeTime, url, appKey, appSecret, templateParas,sender, templateId, signature,randomNumber);
}
/**
* 调用华为短信发送
*
* @param phone 手机号
* @param codeTime 失效时间
* @param url APP接入地址+接口访问URI
* @param appKey APP_Key
* @param appSecret APP_Secret
* @param sender 通道
* @param templateId 模板
* @param signature 签名名称
* @return
*/
public Boolean huaWeiSendSms(String phone, String codeTime, String url, String appKey, String appSecret,
String templateParas, String sender, String templateId, String signature,String randomNumber) {
//必填,全局号码格式(包含国家码),示例:+86151****6789,多个号码之间用英文逗号分隔
// String receiver = "151****6789"; //短信接收人号码
//选填,短信状态报告接收地址,推荐使用域名,为空或者不填表示不接收状态报告
String statusCallBack = "";
/**
* 选填,使用无变量模板时请赋空值 String templateParas = "";
* 单变量模板示例:模板内容为"您的验证码是${1}"时,templateParas可填写为"[\"369751\"]"
* 双变量模板示例:模板内容为"您有${1}件快递请到${2}领取"时,templateParas可填写为"[\"3\",\"人民公园正门\"]"
* 模板中的每个变量都必须赋值,且取值不能为空
* 查看更多模板和变量规范:产品介绍>模板和变量规范
*/
//请求Body,不携带签名名称时,signature请填null
String body = this.resBody(sender, phone, templateId, templateParas, statusCallBack, signature);
//请求Headers中的X-WSSE参数值
String wsseHeader = this.resWsseHeader(appKey, appSecret);
this.sendSms(url, wsseHeader, body, phone, randomNumber, codeTime);
return Boolean.TRUE;
}
public String resRedisTime(String codeTime) {
//如果没有设置验证码失效时间默认600秒
if (StringUtils.isBlank(codeTime)) {
codeTime = "600";
}
return codeTime;
}
/**
* 设置短信有效时间
*/
public String resVerificationTime(String codeTime) {
//如果没有设置验证码失效时间默认600秒
if (StringUtils.isBlank(codeTime)) {
codeTime = "600";
}
//传进来为秒数所以除以60
int time = Integer.parseInt(codeTime) / 60;
return String.valueOf(time);
}
/**
* 请求Body,不携带签名名称时,signature请填null
*/
public String resBody(String sender, String phone, String templateId, String templateParas, String statusCallBack, String signature) {
String body = buildRequestBody(sender, phone, templateId, templateParas, statusCallBack, signature);
if (null == body || body.isEmpty()) {
throw new JeroBootException("body is null.");
}
return body;
}
/**
* 请求Headers中的X-WSSE参数值
*/
public String resWsseHeader(String appKey, String appSecret) {
String wsseHeader = buildWsseHeader(appKey, appSecret);
if (null == wsseHeader || wsseHeader.isEmpty()) {
throw new JeroBootException("wsse header is null.");
}
return wsseHeader;
}
public void sendSms(String url, String wsseHeader, String body, String phone, String randomNumber, String codeTime) {
try {
//如果JDK版本低于1.8,可使用如下代码
//CloseableHttpClient client = HttpClients.custom()
// .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// @Override
// public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
// return true;
// }
// }).build()).setSSLHostnameVerifier(new DefaultHostnameVerifier()).build();
//如果JDK版本是1.8,可使用如下代码
CloseableHttpClient client = null;
try {
client = HttpClients.custom()
.setSSLContext(new SSLContextBuilder().loadTrustMaterial(null,
(x509CertChain, authType) -> true).build())
.setSSLHostnameVerifier(new DefaultHostnameVerifier())
.build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
if (open){
HttpResponse response = null;
response = client.execute(RequestBuilder.create("POST")//请求方法POST
.setUri(url)
.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
.addHeader(HttpHeaders.AUTHORIZATION, AUTH_HEADER_VALUE)
.addHeader("X-WSSE", wsseHeader)
.setEntity(new StringEntity(body)).build());
//判断发送是否成功
String result = EntityUtils.toString(response.getEntity());
String code = JSON.parseObject(result).getString("code");
String description = JSON.parseObject(result).getString("description");
if (!"000000".equals(code) || !"Success".equals(description)) {
throw new JeroBootException("发送短信失败!");
}
}
//如果时间为0是通知类短信,不需要存redis
if (!"0".equals(codeTime)){
if (!redisUtil.set("_verification:_phone:" + phone, randomNumber, Long.valueOf(codeTime))) {
throw new JeroBootException("redis false.");
}
}
// System.out.println("response.toString(): " + response.toString()); //打印响应头域信息
// System.out.println("EntityUtils.toString(response.getEntity()): " + EntityUtils.toString(response.getEntity())); //打印响应消息实体
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 构造请求Body体
*
* @param sender
* @param receiver
* @param templateId
* @param templateParas
* @param statusCallbackUrl
* @param signature | 签名名称,使用国内短信通用模板时填写
* @return
*/
static String buildRequestBody(String sender, String receiver, String templateId, String templateParas,
String statusCallbackUrl, String signature) {
if (null == sender || null == receiver || null == templateId || sender.isEmpty() || receiver.isEmpty()
|| templateId.isEmpty()) {
throw new JeroBootException("buildRequestBody(): sender, receiver or templateId is null.");
}
List<NameValuePair> keyValues = new ArrayList<NameValuePair>();
keyValues.add(new BasicNameValuePair("from", sender));
keyValues.add(new BasicNameValuePair("to", receiver));
keyValues.add(new BasicNameValuePair("templateId", templateId));
if (null != templateParas && !templateParas.isEmpty()) {
keyValues.add(new BasicNameValuePair("templateParas", templateParas));
}
if (null != statusCallbackUrl && !statusCallbackUrl.isEmpty()) {
keyValues.add(new BasicNameValuePair("statusCallback", statusCallbackUrl));
}
if (null != signature && !signature.isEmpty()) {
keyValues.add(new BasicNameValuePair("signature", signature));
}
return URLEncodedUtils.format(keyValues, Charset.forName("UTF-8"));
}
/**
* 构造X-WSSE参数值
*
* @param appKey
* @param appSecret
* @return
*/
static String buildWsseHeader(String appKey, String appSecret) {
if (null == appKey || null == appSecret || appKey.isEmpty() || appSecret.isEmpty()) {
throw new JeroBootException("buildWsseHeader(): appKey or appSecret is null.");
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
String time = sdf.format(new Date()); //Created
String nonce = UUID.randomUUID().toString().replace("-", ""); //Nonce
byte[] passwordDigest = DigestUtils.sha256(nonce + time + appSecret);
String hexDigest = Hex.encodeHexString(passwordDigest);
//如果JDK版本是1.8,请加载原生Base64类,并使用如下代码
String passwordDigestBase64Str = Base64.getEncoder().encodeToString(hexDigest.getBytes()); //PasswordDigest
//如果JDK版本低于1.8,请加载三方库提供Base64类,并使用如下代码
//String passwordDigestBase64Str = Base64.encodeBase64String(hexDigest.getBytes(Charset.forName("utf-8"))); //PasswordDigest
//若passwordDigestBase64Str中包含换行符,请执行如下代码进行修正
//passwordDigestBase64Str = passwordDigestBase64Str.replaceAll("[\\s*\t\n\r]", "");
return String.format(WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, time);
}
}
@@ -299,6 +299,15 @@ justauth:
prefix: 'demo::'
timeout: 1h
defaultPassword: HZWLsoft.com123
#华为云发送短信
huaWeiSms:
#APP接入地址+接口访问URI
url: https://rtcsms.cn-north-1.myhuaweicloud.com:10743/sms/batchSendSms/v1
#APP_Key
appKey: g9zviC58Uw3qXZK6r56empl2aXP3
appSecret: eGt7RfKNia8cK4Z3Vnw5QE4Uy108
# 短信开关
open: false
standards:
url: http://loaclhots:8081/api
token: Aa123456!!