Commit 6a6b73cf authored by Quxl's avatar Quxl

x

parent 55d1e124
package com.egolm.shop.api.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public interface QiyeWxService {
long DevTime = 1000*60*15;
String PrefixRedisTokenKey = "AccessTokenRedis_";
String UrlGetToken = "/gettoken?corpid={0}&corpsecret={1}";
String UrlSendMsg = "/message/send?access_token={0}";
String getTokenString();
void refreshToken();
void sendMessage(WxMessage wxMessage);
public static class WxMessage {
String touser;
String msgtype = "miniprogram_notice";
MiniprogramNotice miniprogram_notice;
public String getTouser() {
return touser;
}
public void setTouser(String touser) {
this.touser = touser;
}
public String getMsgtype() {
return msgtype;
}
public void setMsgtype(String msgtype) {
this.msgtype = msgtype;
}
public MiniprogramNotice getMiniprogram_notice() {
return miniprogram_notice;
}
public void setMiniprogram_notice(MiniprogramNotice miniprogram_notice) {
this.miniprogram_notice = miniprogram_notice;
}
public static class MiniprogramNotice {
String appid;
String page;
String title;
String description;
Boolean emphasis_first_item = true;
List<Map<String, String>> content_item = new ArrayList<Map<String, String>>();
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean getEmphasis_first_item() {
return emphasis_first_item;
}
public void setEmphasis_first_item(Boolean emphasis_first_item) {
this.emphasis_first_item = emphasis_first_item;
}
public List<Map<String, String>> getContent_item() {
return content_item;
}
public void setContent_item(List<Map<String, String>> content_item) {
this.content_item = content_item;
}
}
}
}
package com.egolm.shop.api.service;
public interface WeixinTokenService {
}
package com.egolm.shop.api.service.impl;
import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.egolm.common.DateUtil;
import com.egolm.common.StringUtil;
import com.egolm.shop.api.service.QiyeWxService;
import com.egolm.shop.common.utils.HttpUtil;
import com.egolm.shop.common.utils.HttpUtil.HttpReqObject;
import com.egolm.shop.common.utils.HttpUtil.HttpRespObject;
import com.egolm.shop.common.utils.HttpUtil.JsonReqObject;
import com.egolm.shop.common.utils.HttpUtil.SSLVersion;
public class QiyeWxServiceImpl implements QiyeWxService {
@Value("${qiyewx.corpid}")
private String corpid;
@Value("${qiyewx.corpsecret}")
private String corpsecret;
@Value("${qiyewx.baseUrl}")
private String baseUrl;
@Autowired
private RedisTemplate<String, String> redis;
@Override
public String getTokenString() {
String redisCacheKey = PrefixRedisTokenKey + corpid;
Long systemTime = System.currentTimeMillis();
String tokenObjectString = redis.opsForValue().get(redisCacheKey);
if(StringUtil.isNotBlank(tokenObjectString)) {
JSONObject tokenObject = JSON.parseObject(tokenObjectString);
Integer errcode = tokenObject.getInteger("errcode");
if(errcode == 0) {
Long expires_in = tokenObject.getLong("expires_in");
String loadTimeString = tokenObject.getString("loadTime");
if(expires_in != null && StringUtil.isNotBlank(loadTimeString)) {
Date loadTime = DateUtil.parse(loadTimeString, "yyyy-MM-dd HH:mm:ss");
Long expireTime = loadTime.getTime() + (expires_in*1000L);
if((expireTime - DevTime) > systemTime) {
String access_token = tokenObject.getString("access_token");
if(StringUtil.isNotBlank(access_token)) {
return access_token;
}
}
}
}
}
String requestUrl = baseUrl + MessageFormat.format(UrlGetToken, corpid, corpsecret);
HttpRespObject resp = HttpUtil.newInstance().setSSLVersion(SSLVersion.SSLv3).post(new HttpReqObject(requestUrl, null, null));
if(resp.getHttpCode() == 200) {
String text = resp.getResponseBody();
JSONObject tokenObject = JSON.parseObject(text);
Integer code = tokenObject.getInteger("errcode");
if(code == 0) {
tokenObject.put("loadTime", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
redis.opsForValue().set(redisCacheKey, tokenObject.toJSONString());
return tokenObject.getString("access_token");
}
}
return null;
}
@Override
public void refreshToken() {
String redisCacheKey = PrefixRedisTokenKey + corpid;
redis.delete(redisCacheKey);
}
@Override
public void sendMessage(WxMessage wxMessage) {
String tokenString = this.getTokenString();
String requestUrl = baseUrl + MessageFormat.format(UrlSendMsg, tokenString);
Map<String, String> headers = new HashMap<String, String>();
headers.put("content-type", "application/x-www-form-urlencoded");
HttpRespObject resp = HttpUtil.newInstance().setSSLVersion(SSLVersion.SSLv3).postJson(new JsonReqObject(requestUrl, wxMessage, headers));
Integer httpCode = resp.getHttpCode();
if(httpCode == 200) {
}
}
}
package com.egolm.shop.api.service.impl;
import com.egolm.shop.api.service.WeixinTokenService;
public class WeixinTokenServiceImpl implements WeixinTokenService {
}
package com.egolm.shop.common.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.PrivateKey;
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;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509KeyManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.egolm.common.FileUtil;
import com.egolm.common.StringUtil;
public class HttpUtil {
public static HttpUtil newInstance() {
return new HttpUtil();
}
private HttpUtil() {}
public HttpUtil setSSLVersion(SSLVersion sslVersion) {
this.sslVersion = sslVersion;
return this;
}
Log logger = LogFactory.getLog(HttpUtil.class);
public HttpRespObject get(HttpReqObject req) {
logger.debug("Get: " + req.toString());
HttpURLConnection connection = null;
try {
String getUrl = req.toGETRequestUrl();
connection = getHttpURLConnection(getUrl);
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
Map<String, String> headers = req.getHeaders();
if (headers != null) {
for (String key : headers.keySet()) {
connection.setRequestProperty(key, headers.get(key));
}
}
connection.setRequestMethod("GET");
connection.connect();
return responseBody(connection);
} catch (HttpReqFault e) {
throw e;
} catch (Exception e) {
throw new HttpReqFault(e);
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
public HttpRespObject postJson(HttpReqObject req) {
logger.debug("PostJson: " + req.toString());
HttpURLConnection connection = null;
OutputStream os = null;
try {
Map<String, String> headers = req.getHeaders();
String rawData = req.getParametersJsonString();
connection = getHttpURLConnection(req.getRequestUrl());
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("Content-Type", "application/json");
for (String key : headers.keySet()) {
connection.setRequestProperty(key, headers.get(key));
}
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.connect();
os = connection.getOutputStream();
os.write(rawData.getBytes());
os.flush();
return responseBody(connection);
} catch (HttpReqFault e) {
throw e;
} catch (Exception e) {
throw new HttpReqFault(e);
} finally {
try {
if(os != null) {
os.close();
}
} catch (Exception e) {
logger.error("", e);
}
if(connection != null) {
connection.disconnect();
}
}
}
public HttpRespObject postJson(JsonReqObject req) {
logger.debug("PostJson: " + req.toString());
HttpURLConnection connection = null;
OutputStream os = null;
try {
Map<String, String> headers = req.getHeaders();
String rawData = req.getRequestBody();
connection = getHttpURLConnection(req.getRequestUrl());
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("Content-Type", "application/json");
for (String key : headers.keySet()) {
connection.setRequestProperty(key, headers.get(key));
}
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.connect();
os = connection.getOutputStream();
os.write(rawData.getBytes());
os.flush();
return responseBody(connection);
} catch (HttpReqFault e) {
throw e;
} catch (Exception e) {
throw new HttpReqFault(e);
} finally {
try {
if(os != null) {
os.close();
}
} catch (Exception e) {
logger.error("", e);
}
if(connection != null) {
connection.disconnect();
}
}
}
public HttpRespObject post(HttpReqObject req) {
logger.debug("Post: " + req.toString());
HttpURLConnection connection = null;
OutputStream os = null;
try {
Map<String, String> headers = req.getHeaders();
String queryString = req.getParametersQueryString();
connection = getHttpURLConnection(req.getRequestUrl());
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("Content-Type", "application/json");
for (String key : headers.keySet()) {
connection.setRequestProperty(key, headers.get(key));
}
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
os = connection.getOutputStream();
os.write(queryString.getBytes());
os.flush();
return responseBody(connection);
} catch (HttpReqFault e) {
throw e;
} catch (Exception e) {
throw new HttpReqFault(e);
} finally {
try {
os.close();
} catch (Exception e) {
logger.error("", e);
}
connection.disconnect();
}
}
public HttpRespObject put(HttpReqObject req) {
logger.debug("Put: " + req.toString());
HttpURLConnection connection = null;
OutputStream os = null;
try {
Map<String, String> headers = req.getHeaders();
String queryString = req.getParametersQueryString();
connection = getHttpURLConnection(req.getRequestUrl());
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("Content-Type", "application/json");
for (String key : headers.keySet()) {
connection.setRequestProperty(key, headers.get(key));
}
connection.setRequestMethod("PUT");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
os = connection.getOutputStream();
os.write(queryString.getBytes());
os.flush();
return responseBody(connection);
} catch (HttpReqFault e) {
throw e;
} catch (Exception e) {
throw new HttpReqFault(e);
} finally {
try {
os.close();
} catch (Exception e) {
logger.error("", e);
}
connection.disconnect();
}
}
public HttpRespObject delete(HttpReqObject req) {
logger.debug("Delete: " + req.toString());
HttpURLConnection connection = null;
OutputStream os = null;
try {
Map<String, String> headers = req.getHeaders();
String queryString = req.getParametersQueryString();
connection = getHttpURLConnection(req.getRequestUrl());
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("Content-Type", "application/json");
for (String key : headers.keySet()) {
connection.setRequestProperty(key, headers.get(key));
}
connection.setRequestMethod("DELETE");
connection.setDoOutput(true);
connection.connect();
os = connection.getOutputStream();
os.write(queryString.getBytes());
os.flush();
return responseBody(connection);
} catch (HttpReqFault e) {
throw e;
} catch (Exception e) {
throw new HttpReqFault(e);
} finally {
try {
os.close();
} catch (Exception e) {
logger.error("", e);
}
connection.disconnect();
}
}
public static String toQueryString(Map<?, ?> parameters) {
return toQueryString(parameters, null);
}
public static String toQueryString(Map<?, ?> parameters, String encode) {
try {
List<String> params = new ArrayList<String>();
if (parameters != null) {
for (Object key : parameters.keySet()) {
Object val = parameters.get(key);
String sKey = String.valueOf(key);
Object[] sVals = (val == null ? null
: (val instanceof Object[] ? (Object[]) val : new Object[] { val }));
if (sVals != null && sVals.length > 0) {
for (Object sVal : sVals) {
params.add(sKey + "=" + (sVal == null ? "" : URLEncoder.encode(String.valueOf(sVal), encode == null ? "utf-8" : encode)));
}
} else {
params.add("sKey=");
}
}
}
return StringUtil.join("&", "", "", "", params);
} catch (UnsupportedEncodingException e) {
throw new UrlEncodeFault(e);
}
}
public static String toFormatQueryString(Map<?, ?> parameters) {
List<String> params = new ArrayList<String>();
if (parameters != null) {
for (Object key : parameters.keySet()) {
Object val = parameters.get(key);
String sKey = String.valueOf(key);
Object[] sVals = (val == null ? null
: (val instanceof Object[] ? (Object[]) val : new Object[] { val }));
if (sVals != null && sVals.length > 0) {
for (Object sVal : sVals) {
params.add(sKey + "=" + (sVal == null ? "" : String.valueOf(sVal)));
}
} else {
params.add("sKey=");
}
}
}
return StringUtil.join("&", "", "", "", params);
}
private HttpRespObject responseBody(HttpURLConnection httpConn) {
InputStream is = null;
try {
int httpCode = httpConn.getResponseCode();
System.out.println(httpCode);
if(httpCode >= 400) {
is = httpConn.getErrorStream();
} else {
is = httpConn.getInputStream();
}
httpConn.getErrorStream();
Map<String, List<String>> responseHeaders = httpConn.getHeaderFields();
List<String> contentTypes = responseHeaders.get("Content-Type");
String charset = null;
String contentType = (contentTypes != null && contentTypes.size() > 0) ? contentTypes.get(0) : "";
String[] typeArray = contentType.split(";");
for (String type : typeArray) {
if (type.startsWith("charset=")) {
charset = type.split("=", 2)[1];
} else if (type.startsWith("encoding=")) {
charset = type.split("=", 2)[1];
}
}
String result = null;
byte[] bytes = FileUtil.streamToBytes(is);
if (charset == null || charset.trim().length() == 0) {
String metaCharset = null;
result = new String(bytes, "utf-8");
String regex = "charset=([^\"'>]+)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(result);
while (matcher.find()) {
metaCharset = matcher.group(1);
if (metaCharset != null && metaCharset.trim().length() > 0) {
break;
}
}
if(metaCharset != null && metaCharset.length() > 0) {
result = new String(bytes, metaCharset);
}
} else {
result = new String(bytes, charset);
}
String responseBody = httpCode < 400 ? result: null;
String errorBody = httpCode >= 400 ? result: null;
HttpRespObject resp = new HttpRespObject(httpCode, responseBody, errorBody);
logger.debug(JSON.toJSONString(resp));
return resp;
} catch (HttpReqFault e) {
throw e;
} catch (Exception e) {
throw new HttpReqFault(e);
} finally {
if(is != null) {
try {
is.close();
} catch (IOException e) {
logger.error("", e);
}
}
}
}
public static void main(String[] args) {
HttpRespObject resp = HttpUtil.newInstance().get(new HttpReqObject("https://api.weixin.qq.com/sns/jscode2session?appid=wx91ddc7334967f112&secret=a0bf1bd9668b6e52392561839abe4a5d&js_code=033rz1Ce15l96y0blLBe13JLBe1rz1CG&grant_type=authorization_code", null, null));
System.out.println(resp);
}
private SSLVersion sslVersion;
private HttpURLConnection getHttpURLConnection(String requestUrl) throws KeyManagementException, NoSuchAlgorithmException, MalformedURLException, IOException {
URLConnection conn = new URL(requestUrl).openConnection();
if(requestUrl.startsWith("https")) {
HttpsURLConnection httpsConn = (HttpsURLConnection)conn;
trustAll(httpsConn);
}
return (HttpURLConnection)conn;
}
private void trustAll(HttpsURLConnection httpsConn) throws NoSuchAlgorithmException, KeyManagementException {
if(this.sslVersion == null) {
throw new SSLVersionFault("SSLVersion cannot be null. For example: SSLv3, TLSv1.0");
}
SSLTrust trust = SSLTrust.getSSLTrust();
TrustManager[] trustManagers = new TrustManager[] {trust.getTrustManager()};
KeyManager[] keyManagers = new KeyManager[] {trust.getKeyManager()};
SSLContext sc = SSLContext.getInstance(sslVersion.version);
sc.init(keyManagers, trustManagers, null);
httpsConn.setSSLSocketFactory(sc.getSocketFactory());
httpsConn.setHostnameVerifier(trust.getHostnameVerifier());
}
private static final class SSLTrust {
private static SSLTrust trust = null;
private KeyManager keyManager = null;
private TrustManager trustManager = null;
private HostnameVerifier hostnameVerifier = null;
private SSLTrust(KeyManager keyManager, TrustManager trustManager, HostnameVerifier hostnameVerifier) {
super();
this.keyManager = keyManager;
this.trustManager = trustManager;
this.hostnameVerifier = hostnameVerifier;
}
public static SSLTrust getSSLTrust() {
if(trust == null) {
KeyManager keyManager = null;
TrustManager trustManager = null;
HostnameVerifier hostnameVerifier = null;
if(trustManager == null) {
trustManager = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
}
if(keyManager == null) {
keyManager = new X509KeyManager() {
public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {return null;}
public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {return null;}
public X509Certificate[] getCertificateChain(String arg0) {return null;}
public String[] getClientAliases(String arg0, Principal[] arg1) {return null;}
public PrivateKey getPrivateKey(String arg0) {return null;}
public String[] getServerAliases(String arg0, Principal[] arg1) {return null;}
};
}
if(hostnameVerifier == null) {
hostnameVerifier = new HostnameVerifier() {
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
};
}
trust = new SSLTrust(keyManager, trustManager, hostnameVerifier);
}
return trust;
}
public KeyManager getKeyManager() {
return keyManager;
}
public TrustManager getTrustManager() {
return trustManager;
}
public HostnameVerifier getHostnameVerifier() {
return hostnameVerifier;
}
}
public static class HttpRespObject {
private final int httpCode;
private final String responseBody;
private final String errorBody;
public HttpRespObject(int httpCode, String responseBody, String errorBody) {
super();
this.httpCode = httpCode;
this.responseBody = responseBody;
this.errorBody = errorBody;
}
public int getHttpCode() {
return httpCode;
}
public String getResponseBody() {
return responseBody;
}
public String getErrorBody() {
return errorBody;
}
public String toString() {
return "Response: " + httpCode + " >>>> " + responseBody != null ? responseBody : (errorBody != null ? errorBody : "");
}
}
public static class JsonReqObject {
private final String requestUrl;
private final Object jsonObject;
private final Map<String, String> headers;
public JsonReqObject(String requestUrl, Object jsonObject, Map<String, String> headers) {
super();
if(requestUrl == null || requestUrl.trim().length() == 0) {
throw new HttpReqFault("URL Cannot be empty");
}
if(jsonObject == null) {
jsonObject = new JSONObject();
}
if(headers == null) {
headers = new HashMap<String, String>();
}
this.requestUrl = requestUrl.trim();
this.jsonObject = jsonObject;
this.headers = headers;
}
public String getRequestUrl() {
return requestUrl;
}
public String getRequestBody() {
return JSON.toJSONString(jsonObject);
}
public Map<String, String> getHeaders() {
return headers;
}
public String toString() {
return requestUrl + " >>>> " + getRequestBody() + " >>>> " + JSON.toJSONString(headers);
}
}
public static class HttpReqObject {
private final String requestUrl;
private final Map<String, Object> parameters;
private final Map<String, String> headers;
public HttpReqObject(String requestUrl, Map<String, Object> parameters, Map<String, String> headers) {
super();
if(requestUrl == null || requestUrl.trim().length() == 0) {
throw new HttpReqFault("URL Cannot be empty");
}
if(parameters == null) {
parameters = new HashMap<String, Object>();
}
if(headers == null) {
headers = new HashMap<String, String>();
}
this.requestUrl = requestUrl.trim();
this.parameters = parameters;
this.headers = headers;
}
public String getRequestUrl() {
return requestUrl;
}
public Map<String, Object> getParameters() {
return parameters;
}
public Map<String, String> getHeaders() {
return headers;
}
public String getParametersJsonString() {
return JSON.toJSONString(parameters);
}
public String getParametersQueryString() {
String queryString = HttpUtil.toQueryString(this.getParameters(), null);
return queryString;
}
public String toGETRequestUrl() {
String queryString = HttpUtil.toQueryString(this.getParameters(), null);
if(requestUrl.contains("?")) {
if(requestUrl.endsWith("?")) {
return requestUrl + queryString;
} else {
return requestUrl + "&" + queryString;
}
} else {
return requestUrl + "?" + queryString;
}
}
public String toString() {
return requestUrl + " >>>> " + JSON.toJSONString(parameters) + " >>>> " + JSON.toJSONString(headers);
}
}
public static enum SSLVersion {
SSLv1("SSLv1"), SSLv2("SSLv2"), SSLv3("SSLv3"), TLSv10("TLSv1.0"), TLSv11("TLSv1.1"), TLSv12("TLSv1.2"), TLSv13("TLSv1.3");
private String version;
SSLVersion(String version) {
this.version = version;
}
}
public static class HttpReqFault extends RuntimeException {
private static final long serialVersionUID = 1L;
public HttpReqFault(Throwable e) {
super(e);
}
public HttpReqFault(String msg) {
super(msg);
}
public HttpReqFault(String msg, Throwable e) {
super(msg, e);
}
}
public static class UrlEncodeFault extends HttpReqFault {
private static final long serialVersionUID = 1L;
public UrlEncodeFault(Throwable e) {
super(e);
}
}
public static class SSLVersionFault extends HttpReqFault {
private static final long serialVersionUID = 1L;
public SSLVersionFault(String msg) {
super(msg);
}
}
}
......@@ -76,3 +76,9 @@ redis.guest.key=B2B_Guest
redis.sms.code.key=B2B_Sms
qiyewx.corpid=ww0e86cf527e3e5218
qiyewx.corpsecret=n6weRHp134mpOF3AUPuyEDrUW8zdoG22wuk1hyfXuZAz
qiyewx.baseUrl=https://qyapi.weixin.qq.com/cgi-bin
qiyewx.msg.redirect.appid=wxa573a87e45933b56
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment