Commit c555abf9 authored by hezhen's avatar hezhen

Merge branch 'hz_master'

parents 964dcfe3 dce81cde
package com.github.wxiaoqi.security.common.util;
import javax.servlet.http.HttpServletRequest;
public class UserAgentUtil {
/**
* 关键字: 微信浏览器
*/
public static final String KEY_WEIXIN_BROWSER = "micromessenger";
/**
* 判断是否微信浏览器
*
* @param user_agent
* @return
*/
public static boolean isWexinBrowser(HttpServletRequest request) {
// 可能会出现npe
String user_agent = "";
user_agent = request.getHeader("user-agent");
// 修改如下
return user_agent != null && user_agent.toLowerCase().indexOf(KEY_WEIXIN_BROWSER) > 0;
}
}
......@@ -239,7 +239,7 @@ public class AppPermissionService {
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public JSONObject register(String username, String password, String headimgurl,
String nickname, String mobilecode, String openId, String unionid, Integer type,String code) {
log.info("register------code====="+code);
log.info("register------code====="+code+"----开始进入方法---time===="+System.currentTimeMillis()/1000L);
String activityCode = null;
// 判断参数和验证码
if (StringUtils.isBlank(username) || StringUtils.isBlank(password) || StringUtils.isBlank(mobilecode)) {
......@@ -247,7 +247,7 @@ public class AppPermissionService {
}
String redisLockKey = RedisKey.CONSTANT_CODE_PREFIX + username + mobilecode;
String mobilecodeRedis = userRedisTemplate.opsForValue().get(redisLockKey) == null ? "" : userRedisTemplate.opsForValue().get(redisLockKey).toString();
log.error("注册接口,获取redis中的验证码:" + mobilecodeRedis);
log.info("注册接口,获取redis中的验证码:" + mobilecodeRedis+"---time===="+System.currentTimeMillis()/1000L);
// 获取到缓存的验证码后要先清空缓存对应键的值
userRedisTemplate.delete(redisLockKey);
if (StringUtils.isBlank(mobilecodeRedis)) {
......@@ -282,7 +282,7 @@ public class AppPermissionService {
appUserLogin.setUpdatetime(now);
appUserLoginBiz.insertSelective(appUserLogin);
Integer userid = appUserLogin.getId();
log.error("注册:新增登陆用户信息: " + userid);
log.info("注册:新增登陆用户信息: " + userid+"---time===="+System.currentTimeMillis()/1000L);
// 新增用户详情
AppUserDetail rsUserDetail = new AppUserDetail();
rsUserDetail.setUserid(userid);
......@@ -292,7 +292,9 @@ public class AppPermissionService {
rsUserDetail.setUpdatetime(now);
rsUserDetail.setIsdel(0);
rsUserDetail.setCrtHost(getIp());
setCreateIPInfo(rsUserDetail);
//setCreateIPInfo(rsUserDetail);
log.info("注册:解析地址后: " + userid+"---time===="+System.currentTimeMillis()/1000L);
//邀请人id关系绑定
Integer parentId=0;
if (StringUtils.isNotBlank(code)){
......@@ -314,21 +316,27 @@ public class AppPermissionService {
//生成邀请码 长度改为8 不然重复率太高
rsUserDetail.setCode(ReferralCodeUtil.encode(userid));
appUserDetailBiz.insertSelective(rsUserDetail);
log.error("注册:新增用户详情: " + userid);
log.info("注册:新增用户详情: " + userid+"---time===="+System.currentTimeMillis()/1000L);
/* //绑定上下线关系
if(parentId!=null&&parentId>0){
relationBiz.bindRelation(userid,parentId,1);
}*/
//临时会员绑定
insertUserMemberByUserIdAndPhone(userid, username);
log.info("注册:临时会员绑定: " + userid+"---time===="+System.currentTimeMillis()/1000L);
//参加新人活动
jionActivity(userid);
log.info("注册:参加新人活动: " + userid+"---time===="+System.currentTimeMillis()/1000L);
//创建钱包
walletBiz.createWalletByUserId(appUserLogin.getId());
log.info("注册:创建钱包: " + userid+"---time===="+System.currentTimeMillis()/1000L);
// 登录结果要做做统一处理
JSONObject data = autoLogin(userid, username, headimgurl, nickname,code,activityCode,1);
log.info("注册:登录结果要做做统一处理: " + userid+"---time===="+System.currentTimeMillis()/1000L);
// 到im注册,获取返回结果
Map<String, Object> map = registerIm(username, appUserLogin.getPassword(), nickname);
log.info("注册:到im注册: " + userid+"---time===="+System.currentTimeMillis()/1000L);
if (map != null) {
Integer imUserId = Integer.parseInt(map.get("userId").toString());
//String access_token=map.get("access_token").toString();
......@@ -345,6 +353,7 @@ public class AppPermissionService {
//data.put("imToken",access_token);
data.put("imUserId", imUserId);
}
log.info("注册:处理im账号: " + userid+"---time===="+System.currentTimeMillis()/1000L);
if (data != null) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("userId", userid);
......@@ -352,6 +361,7 @@ public class AppPermissionService {
log.info("注册成功获取积分:发送消息 exchange = {}, routingKey = {}, json = {}", RabbitConstant.INTEGRAL_TOPIC, RabbitConstant.INTEGRAL_ROUTING_KEY, jsonObject.toJSONString());
mqSenderFeign.sendMessage(RabbitConstant.INTEGRAL_TOPIC, RabbitConstant.INTEGRAL_ROUTING_KEY, jsonObject.toJSONString());
sendQueue(username, password, headimgurl, nickname, mobilecode, openId, unionid, type, code, activityCode, userid,RegisterQueueDTO.SIGN_NEW);
log.info("注册:发消息队列: " + userid+"---time===="+System.currentTimeMillis()/1000L);
return JsonResultUtil.createSuccessResultWithObj(data);
} else {
return JsonResultUtil.createDefaultFail();
......@@ -535,7 +545,7 @@ public class AppPermissionService {
userDetail.setUpdatetime(now);
userDetail.setIsdel(0);
userDetail.setCrtHost(getIp());
setCreateIPInfo(userDetail);
//setCreateIPInfo(userDetail);
appUserDetailBiz.insertSelective(userDetail);
} /*else {
......@@ -949,7 +959,7 @@ public class AppPermissionService {
//设置来源
rsUserDetail.setChannel(UserSourceEnum.APPLET.getCode());
rsUserDetail.setCrtHost(getIp());
setCreateIPInfo(rsUserDetail);
//setCreateIPInfo(rsUserDetail);
rsUserDetail.setState(1);
appUserDetailBiz.insertSelective(rsUserDetail);
log.error("注册:新增用户详情: " + userid);
......@@ -1083,7 +1093,7 @@ public class AppPermissionService {
public void setCreateIPInfo(AppUserDetail appUserDetail) {
String crtHost = appUserDetail.getCrtHost();
if (log.isDebugEnabled()) {
log.debug("解析的地址:【{}】", crtHost);
log.debug("解析的地址:【{}】", crtHost+"---time==="+System.currentTimeMillis()/1000L);
}
try {
analyticalIPByWebSiteAndIPAddress(IPAddress.BASE_IP_PARSING_URL2, crtHost, appUserDetail);
......@@ -1100,13 +1110,15 @@ public class AppPermissionService {
private void analyticalIPByWebSiteAndIPAddress(String url, String crtHost, AppUserDetail appUserDetail) {
String ipAddress = restTemplate.getForObject(String.format("%s%s", url, crtHost), String.class);
String data = JSONObject.parseObject(ipAddress).getString(IPAddress.BASE_DATA);
JSONObject ipJsonObject = JSONObject.parseObject(data);
String cityName = ipJsonObject.getString(IPAddress.CITY_NAME);
RegionDTO regionDTO = regionFeign.getRegionByCityName(StringUtils.isEmpty(cityName) ? "东莞" : cityName);
if (null != regionDTO) {
appUserDetail.setProvinceCode(Integer.valueOf(String.valueOf(regionDTO.getParentId())));
appUserDetail.setCityCode(Integer.valueOf(String.valueOf(regionDTO.getId())));
log.debug("解析的调用网站后:【{}】", crtHost+"---time==="+System.currentTimeMillis()/1000L);
String data = JSONObject.parseObject(ipAddress).getString(IPAddress.BASE_DATA);
JSONObject ipJsonObject = JSONObject.parseObject(data);
String cityName = ipJsonObject.getString(IPAddress.CITY_NAME);
RegionDTO regionDTO = regionFeign.getRegionByCityName(StringUtils.isEmpty(cityName) ? "东莞" : cityName);
log.debug("解析的调用服务后:【{}】", crtHost+"---time==="+System.currentTimeMillis()/1000L);
if (null != regionDTO) {
appUserDetail.setProvinceCode(Integer.valueOf(String.valueOf(regionDTO.getParentId())));
appUserDetail.setCityCode(Integer.valueOf(String.valueOf(regionDTO.getId())));
}
}
......
......@@ -7,7 +7,7 @@ public class RedisKey {
/**
* 常量缓存key前缀
*/
public static final String CONSTANT_CACHE_PREFIX ="cache:constant:";
public static final String TOKEN_CACHE_PREFIX ="cache:token:";
/**
* 地区常量缓存key前缀(子读取列表)
......
package com.xxfc.platform.universal.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.security.KeyStore;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import com.github.wxiaoqi.security.common.util.MyX509TrustManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
* @Author vitoHuang
* @Time 2015年8月14日
* @Mark HTTPS请求工具
*/
@Slf4j
public class HTTPSUtils{
/**
* HTTPS json 请求
* @param requestUrl 请求地址
* @param requestMethod 请求方式 POST/GET
* @param msg json方式的请求参数
* @return 返回相应的字符串 异常会输出null
*/
public static String httpRequest(String requestUrl, String requestMethod, String msg){
log.error("进入方法httpRequest()httpRequest="+requestUrl);
OutputStream outputStream = null;
InputStream inputStream = null;
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = {new MyX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 当有数据需要提交时
log.error("httpUrlConn="+httpUrlConn);
if (null != msg) {
outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(msg.getBytes("UTF-8"));
}
// 将返回的输入流转换成字符串
inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
log.error("inputStreamReader="+inputStreamReader);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer buffer = new StringBuffer();
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
httpUrlConn.disconnect();
return buffer.toString();
} catch (ConnectException ce) {
log.error("Weixin server connection timed out.");
} catch (Exception e) {
log.error("https request error:"+e.getMessage());
}finally{
if(outputStream != null)try{outputStream.close();}catch (Exception e) {}
if(inputStream != null)try{inputStream.close();;}catch (Exception e) {}
}
return null;
}
/**
* HTTPS json 请求
* @param requestUrl
* @param requestMethod
* @param msg
* @return 对字符串进行封装成JSON
*/
public static JSONObject httpRequestToJSON(String requestUrl, String requestMethod, String msg){
log.error("进入方法httpRequestToJSON-----");
String json = httpRequest(requestUrl, requestMethod, msg);
log.error("json-----"+json);
JSONObject jsonObject = null;
if(StringUtils.isNotBlank(json)) jsonObject = JSON.parseObject(json);
return jsonObject;
}
}
package com.xxfc.platform.universal.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URLDecoder;
@Slf4j
public class HttpRequestUtil {
/**
* post请求
* @param url url地址
* @return
*/
public static String httpPost(String url){
//post请求返回结果
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
String str = "";
try {
HttpResponse result = httpClient.execute(method);
url = URLDecoder.decode(url, "UTF-8");
/**请求发送成功,并得到响应**/
if (result.getStatusLine().getStatusCode() == 200) {
try {
/**读取服务器返回过来的json字符串数据**/
str = EntityUtils.toString(result.getEntity(),"UTF-8");
} catch (Exception e) {
log.error("post请求提交失败:" + url, e);
}
}
} catch (IOException e) {
log.error("post请求提交失败:" + url, e);
}
return str;
}
/**
* 发送get请求
* @param url 路径
* @return
*/
public static String httpGet(String url){
//get请求返回结果
String strResult = null;
try {
DefaultHttpClient client = new DefaultHttpClient();
//发送get请求
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
/**请求发送成功,并得到响应**/
if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
strResult = EntityUtils.toString(response.getEntity(),"UTF-8");
} else {
log.error("get请求提交失败:" + url);
}
} catch (IOException e) {
log.error("get请求提交失败:" + url, e);
}
return strResult;
}
}
package com.xxfc.platform.universal.utils;
import com.github.wxiaoqi.security.common.util.MD5Util;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/*
'微信支付服务器签名支付请求请求类
'============================================================================
'api说明:
'init(app_id, app_secret, partner_key, app_key);
'初始化函数,默认给一些参数赋值,如cmdno,date等。
'setKey(key_)'设置商户密钥
'getLasterrCode(),获取最后错误号
'GetToken();获取Token
'getTokenReal();Token过期后实时获取Token
'createMd5Sign(signParams);生成Md5签名
'genPackage(packageParams);获取package包
'createSHA1Sign(signParams);创建签名SHA1
'sendPrepay(packageParams);提交预支付
'getDebugInfo(),获取debug信息
'============================================================================
'*/
public class RequestHandler {
/** Token获取网关地址地址 */
private String tokenUrl;
/** 预支付网关url地址 */
private String gateUrl;
/** 查询支付通知网关URL */
private String notifyUrl;
/** 商户参数 */
private String appid;
private String appkey;
private String partnerkey;
private String appsecret;
private String key;
/** 请求的参数 */
private SortedMap parameters;
/** Token */
private String Token;
private String charset;
/** debug信息 */
private String debugInfo;
private String last_errcode;
private HttpServletRequest request;
private HttpServletResponse response;
/**
* 初始构造函数。
*
* @return
*/
public RequestHandler(HttpServletRequest request,
HttpServletResponse response) {
this.last_errcode = "0";
this.request = request;
this.response = response;
//this.charset = "GBK";
this.charset = "UTF-8";
this.parameters = new TreeMap();
// 验证notify支付订单网关
notifyUrl = "https://gw.tenpay.com/gateway/simpleverifynotifyid.xml";
}
/**
* 初始化函数。
*/
public void init(String app_id, String app_secret, String partner_key) {
this.last_errcode = "0";
this.Token = "token_";
this.debugInfo = "";
this.appid = app_id;
this.partnerkey = partner_key;
this.appsecret = app_secret;
this.key = partner_key;
}
public void init() {
}
/**
* 获取最后错误号
*/
public String getLasterrCode() {
return last_errcode;
}
/**
*获取入口地址,不包含参数值
*/
public String getGateUrl() {
return gateUrl;
}
/**
* 获取参数值
*
* @param parameter
* 参数名称
* @return String
*/
public String getParameter(String parameter) {
String s = (String) this.parameters.get(parameter);
return (null == s) ? "" : s;
}
//设置密钥
public void setKey(String key) {
this.partnerkey = key;
}
//设置微信密钥
public void setAppKey(String key){
this.appkey = key;
}
// 特殊字符处理
public String UrlEncode(String src) throws UnsupportedEncodingException {
return URLEncoder.encode(src, this.charset).replace("+", "%20");
}
// 获取package的签名包
public String genPackage(SortedMap<String, String> packageParams)
throws UnsupportedEncodingException {
String sign = createSign(packageParams);
StringBuffer sb = new StringBuffer();
Set es = packageParams.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
sb.append(k + "=" + UrlEncode(v) + "&");
}
// 去掉最后一个&
String packageValue = sb.append("sign=" + sign).toString();
// System.out.println("UrlEncode后 packageValue=" + packageValue);
return packageValue;
}
/**
* 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
*/
public String createSign(SortedMap<String, String> packageParams) {
StringBuffer sb = new StringBuffer();
Set es = packageParams.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if (null != v && !"".equals(v) && !"sign".equals(k)
&& !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + this.getKey());
System.out.println("md5 sb:" + sb);
String sign = MD5Util.MD5Encode(sb.toString(), this.charset).toUpperCase();
System.out.println("packge签名:" + sign);
return sign;
}
//输出XML
public String parseXML() {
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
Set es = this.parameters.entrySet();
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
String v = (String)entry.getValue();
if(null != v && !"".equals(v) && !"appkey".equals(k)) {
sb.append("<" + k +">" + getParameter(k) + "</" + k + ">\n");
}
}
sb.append("</xml>");
return sb.toString();
}
/**
* 设置debug信息
*/
protected void setDebugInfo(String debugInfo) {
this.debugInfo = debugInfo;
}
public void setPartnerkey(String partnerkey) {
this.partnerkey = partnerkey;
}
public String getDebugInfo() {
return debugInfo;
}
public String getKey() {
return key;
}
}
package com.xxfc.platform.universal.utils;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XmlFriendlyReplacer;
import com.thoughtworks.xstream.io.xml.XppDriver;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class WeiXinPayUtil{
private final static String WeXinPay_URL ="https://api.mch.weixin.qq.com/pay/unifiedorder";
private final static String WeXinRefund_URL ="https://api.mch.weixin.qq.com/secapi/pay/refund";
public static String getPrepayId(String xml,String method){
return HTTPSUtils.httpRequest(WeXinPay_URL, method, xml);
}
@SuppressWarnings("deprecation")
private static XStream xstream = new XStream(/*new XppDriver() {
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
// 对所有xml节点的转换都增加CDATA标记
boolean cdata = true;
@SuppressWarnings({ "rawtypes" })
public void startNode(String name, Class clazz) {
super.startNode(name, clazz);
}
protected void writeText(QuickWriter writer, String text) {
if (cdata) {
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
} else {
writer.write(text);
}
}
};
}
}*/
new XppDriver(new
XmlFriendlyReplacer("_-", "_"){
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
// 对所有xml节点的转换都增加CDATA标记
boolean cdata = true;
@SuppressWarnings({ "rawtypes" })
public void startNode(String name, Class clazz) {
super.startNode(name, clazz);
}
protected void writeText(QuickWriter writer, String text) {
if (cdata) {
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
} else {
writer.write(text);
}
}
};
}
})
);
public static String toXml(WxPrepay wxPrepay){
xstream.alias("xml", wxPrepay.getClass());
return xstream.toXML(wxPrepay);
}
/**
* 获取随机字符串
* @return
*/
public static String getNonceStr() {
// 随机数
String currTime = getCurrTime();
// 8位日期
String strTime = currTime.substring(8, currTime.length());
// 四位随机数
String strRandom = buildRandom(4) + "";
// 10位序列号,可以自行调整。
return strTime + strRandom;
}
/**
* 获取当前时间 yyyyMMddHHmmss
* @return String
*/
public static String getCurrTime() {
Date now = new Date();
SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String s = outFormat.format(now);
return s;
}
/**
* 取出一个指定长度大小的随机正整数.
*
* @param length
* int 设定所取出随机数的长度。length小于11
* @return int 返回生成的随机数。
*/
public static int buildRandom(int length) {
int num = 1;
double random = Math.random();
if (random < 0.1) {
random = random + 0.1;
}
for (int i = 0; i < length; i++) {
num = num * 10;
}
return (int) ((random * num));
}
/**
* 元转换成分
* @param
* @return
*/
public static String getMoney(String amount) {
if(amount==null){
return "";
}
// 金额转化为分为单位
String currency = amount.replaceAll("\\$|\\¥|\\,", ""); //处理包含, ¥ 或者$的金额
int index = currency.indexOf(".");
int length = currency.length();
Long amLong = 0l;
if(index == -1){
amLong = Long.valueOf(currency+"00");
}else if(length - index >= 3){
amLong = Long.valueOf((currency.substring(0, index+3)).replace(".", ""));
}else if(length - index == 2){
amLong = Long.valueOf((currency.substring(0, index+2)).replace(".", "")+0);
}else{
amLong = Long.valueOf((currency.substring(0, index+1)).replace(".", "")+"00");
}
return amLong.toString();
}
/**
* ArrayToXml
* @param arr
* @return
*/
public static String ArrayToXml(Map<String, String> arr) {
String xml = "<xml>";
Iterator<Entry<String, String>> iter = arr.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, String> entry = iter.next();
String key = entry.getKey();
String val = entry.getValue();
if (IsNumeric(val)) {
xml += "<" + key + ">" + val + "</" + key + ">";
} else
xml += "<" + key + "><![CDATA[" + val + "]]></" + key + ">";
}
xml += "</xml>";
return xml;
}
public static boolean IsNumeric(String str) {
if (str.matches("\\d *")) {
return true;
} else {
return false;
}
}
}
package com.xxfc.platform.universal.utils;
public class WxPrepay {
private String appid;
private String mch_id;
private String nonce_str;
private String sign;
private String body;
private String out_trade_no;
private String attach;
private String total_fee;
private String spbill_create_ip;
private String notify_url;
private String trade_type;
private String openid;
private String out_refund_no;
private String refund_fee;
private String op_user_id;
public WxPrepay(){};
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getMch_id() {
return mch_id;
}
public void setMch_id(String mch_id) {
this.mch_id = mch_id;
}
public String getNonce_str() {
return nonce_str;
}
public void setNonce_str(String nonce_str) {
this.nonce_str = nonce_str;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getOut_trade_no() {
return out_trade_no;
}
public void setOut_trade_no(String out_trade_no) {
this.out_trade_no = out_trade_no;
}
public String getAttach() {
return attach;
}
public void setAttach(String attach) {
this.attach = attach;
}
public String getTotal_fee() {
return total_fee;
}
public void setTotal_fee(String total_fee) {
this.total_fee = total_fee;
}
public String getSpbill_create_ip() {
return spbill_create_ip;
}
public void setSpbill_create_ip(String spbill_create_ip) {
this.spbill_create_ip = spbill_create_ip;
}
public String getNotify_url() {
return notify_url;
}
public void setNotify_url(String notify_url) {
this.notify_url = notify_url;
}
public String getTrade_type() {
return trade_type;
}
public void setTrade_type(String trade_type) {
this.trade_type = trade_type;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getOut_refund_no() {
return out_refund_no;
}
public void setOut_refund_no(String out_refund_no) {
this.out_refund_no = out_refund_no;
}
public String getRefund_fee() {
return refund_fee;
}
public void setRefund_fee(String refund_fee) {
this.refund_fee = refund_fee;
}
public String getOp_user_id() {
return op_user_id;
}
public void setOp_user_id(String op_user_id) {
this.op_user_id = op_user_id;
}
}
package com.xxfc.platform.universal.weixin.api;
import java.util.Map.Entry;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.*;
import com.github.wxiaoqi.security.common.util.MD5;
import com.github.wxiaoqi.security.common.util.MD5Util;
import com.github.wxiaoqi.security.common.util.OrderUtil;
import com.github.wxiaoqi.security.common.util.process.SystemConfig;
import com.xxfc.platform.universal.utils.RequestHandler;
import com.xxfc.platform.universal.utils.WeiXinPayUtil;
import com.xxfc.platform.universal.utils.WxPrepay;
import com.xxfc.platform.universal.weixin.util.HTTPUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
......@@ -43,10 +40,13 @@ public class WXPay {
* @param openid
* @return
*/
public static String webPay(String total_fee,String body,String notify_url,String orderNo,String spbill_create_ip,String openid){
public static String webPay(String total_fee,String body,String notify_url,String orderNo,String spbill_create_ip,String openid,String wyAppid){
WXPrepay prePay = new WXPrepay();
prePay.setAppid(SystemConfig.WINXIN_AppID);//pay.getAppId()
if (StringUtils.isBlank(wyAppid)){
wyAppid=SystemConfig.WINXIN_AppID;
}
prePay.setAppid(wyAppid);//pay.getAppId()
prePay.setBody(body);
prePay.setPartnerKey(SystemConfig.WINXIN_PARTNER_KEY);//pay.getPartnerKey()
prePay.setMch_id(SystemConfig.WINXIN_PARTNER);//pay.getPartnerId()
......@@ -65,7 +65,7 @@ public class WXPay {
String jsParam = "";
if (prepayid != null && prepayid.length() > 10) {
// 生成微信支付参数,此处拼接为完整的JSON格式,符合支付调起传入格式
jsParam = WXPay.createPackageValueWeb(SystemConfig.WINXIN_AppID, SystemConfig.WINXIN_PARTNER_KEY, prepayid);
jsParam = WXPay.createPackageValueWeb(wyAppid, SystemConfig.WINXIN_PARTNER_KEY, prepayid);
}
return jsParam;
......@@ -115,6 +115,7 @@ public class WXPay {
}
}
sb.append("key=" + AppKey);
log.info("-----签名sign==="+sb.toString());
String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
return sign;
}
......@@ -374,7 +375,93 @@ public class WXPay {
System.out.println(response_body);
}
public static String getPackage(String total_fee,String body,String notify_url,String orderNo,String spbill_create_ip,String openid,String appid,String appsecret){
Map<String,String> map = new LinkedHashMap<String,String>();
Random random = new Random();
String randomStr = MD5.GetMD5String(String.valueOf(random.nextInt(10000)));
String noceStr = MD5Util.MD5Encode(randomStr, "utf-8").toLowerCase();
SortedMap<String, String> packageParams = new TreeMap<String, String>();
packageParams.put("appid",appid);
packageParams.put("mch_id", SystemConfig.WINXIN_PARTNER);
packageParams.put("nonce_str", noceStr);
packageParams.put("body", body);
packageParams.put("attach", "");
packageParams.put("out_trade_no", orderNo);
// 这里写的金额为1 分到时修改
packageParams.put("total_fee",total_fee);
packageParams.put("spbill_create_ip", spbill_create_ip);
packageParams.put("notify_url", notify_url);
String trade_type = "JSAPI";
packageParams.put("trade_type", trade_type);
packageParams.put("openid", openid);
RequestHandler reqHandler = new RequestHandler(null, null);
reqHandler.init(appid, appsecret, SystemConfig.WINXIN_PARTNER_KEY);
String sign = reqHandler.createSign(packageParams);
WxPrepay wxPrepay = new WxPrepay();
wxPrepay.setAppid(appid);
wxPrepay.setMch_id(SystemConfig.WINXIN_PARTNER);
wxPrepay.setNonce_str(noceStr);
wxPrepay.setSign(sign);
wxPrepay.setBody(body);
wxPrepay.setOut_trade_no(orderNo);
wxPrepay.setTotal_fee(total_fee);
wxPrepay.setSpbill_create_ip(spbill_create_ip);
wxPrepay.setNotify_url(notify_url);
wxPrepay.setTrade_type(trade_type);
wxPrepay.setOpenid(openid);
wxPrepay.setAttach("");
String xml = WeiXinPayUtil.toXml(wxPrepay);
log.error("post_prepay_xml: " + xml);
//获取prepay_id
map = StringtoMap(WeiXinPayUtil.getPrepayId(xml,"POST"));
//获取prepay_id后,拼接最后请求支付所需要的package
SortedMap<String, String> finalpackage = new TreeMap<String, String>();
String timestamp = OrderUtil.GetTimestamp();
String packages = "prepay_id="+map.get("prepay_id");
finalpackage.put("appId", appid);
finalpackage.put("timeStamp", timestamp);
finalpackage.put("nonceStr", noceStr);
finalpackage.put("package", packages);
finalpackage.put("signType", "MD5");
//要签名
String finalsign = reqHandler.createSign(finalpackage);
String finaPackage = "\"appId\":\"" + appid + "\",\"timeStamp\":\"" + timestamp
+ "\",\"nonceStr\":\"" + noceStr + "\",\"package\":\""
+ packages + "\",\"signType\" : \"MD5" + "\",\"paySign\":\""
+ finalsign + "\"";
return finaPackage;
}
public static Map<String,String> StringtoMap(String str){
log.error("respon_prepay_xml: " + str);
Map<String,String> map = new LinkedHashMap<String,String>();
try {
Document document = DocumentHelper.parseText(str);
Element root = document.getRootElement();
List<Element> elementList = root.elements();
for(Element e : elementList){
map.put(e.getName(), e.getText());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map;
}
}
\ No newline at end of file
......@@ -63,6 +63,11 @@ public class OrderPayBiz extends BaseBiz<OrderPayMapper, OrderPay> {
MQServiceBiZ mqServiceBiZ;
@Value("${universal.url}")
String weixinHost;
@Value("${wx.appid}")
private String wy_appid;
@Value("${wx.appSercet}")
private String wy_secret;
public JSONObject preparepay(OrderPayVo orderPayVo) {
......@@ -102,13 +107,16 @@ public class OrderPayBiz extends BaseBiz<OrderPayMapper, OrderPay> {
String sellerAccount = null;
if (type == 2 && payWay == 1) {
sellerAccount = SystemConfig.APP_PARTNER;
jsParam = WXPay.webPay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), orderPayVo.getBuyerAccount());
jsParam = WXPay.webPay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), orderPayVo.getBuyerAccount(),null);
} else if (type == 1 && payWay == 1) {
sellerAccount = SystemConfig.APP_PARTNER;
jsParam = WXPay.apppay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), 0);
} else if (type == 1 && payWay == 2) {
sellerAccount = SystemConfig.ALIPAY_PID;
jsParam = generateAliPayment(orderPayVo, notifyUrl);
}else if (type == 3 && payWay == 1){
sellerAccount = SystemConfig.APP_PARTNER;
jsParam = WXPay.webPay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), orderPayVo.getBuyerAccount(),wy_appid);
}
log.info("报名费回调路径jsParam:" + jsParam);
if (!StringUtils.isBlank(jsParam)) {
......
package com.xxfc.platform.universal.biz;
import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.xxfc.platform.universal.utils.HttpRequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@Service
@Slf4j
public class WeixinService {
/**
* 网页
*/
@Value("${wx.appid}")
private String wy_appid;
@Value("${wx.appSercet}")
private String wy_secret;
public static final String frontSessionKey = "frontWeixKey";
public JSONObject getAccessToken(String code){
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?";
String params = "appid="+wy_appid+"&secret="+wy_secret+"&code="+code+"&grant_type=authorization_code";
String result = HttpRequestUtil.httpGet(url + params);
JSONObject data = JSON.parseObject(result);
return data;
}
public JSONObject getValidateData(String access_token,String openid){
String url = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + openid;
String result = HttpRequestUtil.httpGet(url);
JSONObject data = JSON.parseObject(result);
return data;
}
public JSONObject getRefreshToken(String refresh_token){
String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + wy_appid + "&grant_type=refresh_token&refresh_token=" + refresh_token;
String result = HttpRequestUtil.httpGet(url);
JSONObject data = JSON.parseObject(result);
return data;
}
public JSONObject getUserInfo(String access_token,String openid){
String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
String result = HttpRequestUtil.httpGet(url);
JSONObject data = JSON.parseObject(result);
return data;
}
public String getAuthorize(String redirec_url){
String oauth_api = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={APPID}&redirect_uri={REDIRECT_URI}&response_type=code&scope={SCOPE}&state={STATE}#wechat_redirect";
oauth_api = oauth_api.replace("{APPID}", wy_appid)
.replace("{REDIRECT_URI}", redirec_url)
.replace("{SCOPE}", "snsapi_base").replace("{STATE}", "state");
log.info("---oauth_api===="+oauth_api);
return oauth_api;
}
//获取缓存
public String getSession(HttpServletRequest request){
try {
HttpSession session = request.getSession();
String frontSessionValue1 = (String) session.getAttribute(frontSessionKey);
log.info("---session获取===="+frontSessionValue1+"---sessionId==="+session.getId());
if (StringUtils.isBlank(frontSessionValue1)) {
return null;
}
String openId = Base64.decodeStr(frontSessionValue1);
return openId;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}
......@@ -3,6 +3,7 @@ package com.xxfc.platform.universal.config;
import com.github.wxiaoqi.security.auth.client.interceptor.ServiceAuthRestInterceptor;
import com.github.wxiaoqi.security.auth.client.interceptor.UserAuthRestInterceptor;
import com.github.wxiaoqi.security.common.handler.GlobalExceptionHandler;
import com.xxfc.platform.universal.interceptor.WeChatH5LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
......@@ -29,6 +30,10 @@ public class WebConfiguration implements WebMvcConfigurer {
addPathPatterns(getIncludePathPatterns()).addPathPatterns("/3p/**");
registry.addInterceptor(getUserAuthRestInterceptor()).
addPathPatterns(getIncludePathPatterns());
registry.addInterceptor(getUserAuthRestInterceptor()).
addPathPatterns(getIncludePathPatterns());
/* registry.addInterceptor(getWeChatH5LoginInterceptor()
).addPathPatterns(getWxIncludePathPatterns());*/
}
@Bean
......@@ -41,6 +46,10 @@ public class WebConfiguration implements WebMvcConfigurer {
return new UserAuthRestInterceptor();
}
@Bean
WeChatH5LoginInterceptor getWeChatH5LoginInterceptor() { return new WeChatH5LoginInterceptor();
}
/**
* 需要用户和服务认证判断的路径
* @return
......@@ -53,6 +62,14 @@ public class WebConfiguration implements WebMvcConfigurer {
Collections.addAll(list, urls);
return list;
}
private ArrayList<String> getWxIncludePathPatterns() {
ArrayList<String> list = new ArrayList<>();
String[] urls = {
"/info/**"
};
Collections.addAll(list, urls);
return list;
}
/* @Bean(name = "customTaskExecutor")
TaskExecutor getTaskExecutor(){
......
package com.xxfc.platform.universal.controller;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.UserAgentUtil;
import com.xxfc.platform.universal.biz.WeixinService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
/**
* 用户
*/
@RestController
@RequestMapping("info")
@IgnoreUserToken
@Slf4j
public class UserInfoController {
@Autowired
WeixinService weixinService;
@Value("${wx.sendUrl}")
private String sendUrl;
@RequestMapping(value = "getOpenId", method = RequestMethod.GET) //匹配的是href中的download请求
public ObjectRestResponse getOpenId(HttpServletRequest request) throws Exception {
boolean isWx = UserAgentUtil.isWexinBrowser(request);
if (isWx) {
//session里面获取用户信息
String openId=weixinService.getSession(request);
log.info("---进入方法getOpenId----openId===="+openId);
if (StringUtils.isBlank(openId)){
JSONObject json = new JSONObject();
json.put("sendUrl",sendUrl);
return ObjectRestResponse.createFailedResultWithObj(1001,"",json);
}
return ObjectRestResponse.succ(openId);
}
return ObjectRestResponse.succ();
}
}
package com.xxfc.platform.universal.controller;
import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.universal.biz.WeixinService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.mockito.internal.util.collections.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* @author Administrator
*/
@Controller
@RequestMapping("/auth")
@Slf4j
public class WeixinController {
public static final String WECHAT_AUTOLOGIN_CALLBACKURL_KEY = "callback";
public static final String frontSessionKey = "frontWeixKey";
@Autowired
WeixinService weixinService;
@Value("${wx.url}")
private String url;
@RequestMapping(value ="/app/unauth/wxLogin",method = RequestMethod.GET)
@IgnoreUserToken
public String wxLogin(@RequestParam(value = "redirec_url")String redirec_url){
log.info("-----微信wxLogin---redirec_url=="+redirec_url);
if (StringUtils.isBlank(redirec_url)){
redirec_url="";
}
try {
String encrypt_curr_url = Base64.encode(redirec_url.getBytes("utf-8"));
redirec_url=url+"?" + WECHAT_AUTOLOGIN_CALLBACKURL_KEY+ "=" + encrypt_curr_url;
String oauth_api=weixinService.getAuthorize(redirec_url);
return String.format("redirect:"+oauth_api);
}catch (Exception e){
e.printStackTrace();
log.info("网络异常===" + e.getMessage());
return String.format("网络异常");
}
}
/**
* 微信浏览器获取用户信息
* @param code
* @param callback
* @return
*/
@GetMapping(value = "/app/unauth/userInfo")
public String getUserInformation(String code, String callback, HttpServletRequest request) {
log.info("-----微信回调userInfo---code=="+code+"----redirec_url==="+callback);
try {
authUser(code,request);
callback =new String(Base64.decode(callback), "utf-8");
log.info("callback===" + callback);
}catch (Exception e){
e.printStackTrace();
log.info("网络异常===" + e.getMessage());
}
return String.format("redirect:"+callback);
}
public void authUser(String code,HttpServletRequest request){
if (StringUtils.isBlank(code)){
log.info("----code为空---");
throw new BaseException(ResultCode.FAILED_CODE, Sets.newSet("code为空"));
}
String openid = null;
String access_token = null;
try {
JSONObject jsonData = weixinService.getAccessToken(code);
openid = jsonData.getString("openid");
access_token = jsonData.getString("access_token");
String refresh_token = jsonData.getString("refresh_token");
log.info("-----微信回调userInfo---openid=="+openid+"----access_token==="+access_token);
//验证access_token是否失效
JSONObject validateData = weixinService.getValidateData(access_token, openid);
if (!"0".equals(validateData.getString("errcode"))){
//刷新access_token
JSONObject refreshData= weixinService.getRefreshToken(refresh_token);
access_token = refreshData.getString("access_token");
}
String encode = Base64.encode(openid);
HttpSession session = request.getSession();
session.removeAttribute(frontSessionKey);
session.setAttribute(frontSessionKey, encode);
}catch (Exception e){
e.printStackTrace();
log.info("网络异常===" + e.getMessage());
throw new BaseException(ResultCode.FAILED_CODE, Sets.newSet("网络异常"));
}
}
}
package com.xxfc.platform.universal.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.common.util.UserAgentUtil;
import com.xxfc.platform.universal.biz.WeixinService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
* 微信登陆拦截器
*
* @author
*
*/
@Slf4j
public class WeChatH5LoginInterceptor extends HandlerInterceptorAdapter {
@Value("${wx.sendUrl}")
private String sendUrl;
@Autowired
WeixinService weixinService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String curr_domain = request.getServerName();
log.info("curr_domain:" + curr_domain);
log.info("address:" + request.getRequestURL().toString());
log.info("params:" + request.getQueryString());
boolean isWx = UserAgentUtil.isWexinBrowser(request);
if (isWx) {
//session里面获取用户信息
String openId=weixinService.getSession(request);
if (StringUtils.isNotBlank(openId)){
return true;
}
Map<String,Object> result=new HashMap<>();
result.put("status",1001);
JSONObject json = new JSONObject();
json.put("sendUrl",sendUrl);
result.put("data",json);
response.getWriter().write(result.toString());
return false;
}
return true;
}
}
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