Commit 48f71334 by 彭祥礼

院线通提交订单

parent 3f407358
......@@ -5,10 +5,9 @@ import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.winsun.auth.core.base.controller.BaseController;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.bean.YxtAddress;
import com.winsun.bean.YxtCoupon;
import com.winsun.mapper.YxtAddressMapper;
import com.winsun.mapper.YxtCouponMapper;
import com.winsun.bean.*;
import com.winsun.mapper.*;
import com.winsun.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -35,6 +34,12 @@ public class YxtCardController extends BaseController {
private YxtCouponMapper yxtCouponMapper;
@Autowired
private YxtAddressMapper yxtAddressMapper;
@Autowired
private YxtOrderMapper yxtOrderMapper;
@Autowired
private YxtSalesLimitMapper yxtSalesLimitMapper;
@Autowired
private YxtOrderDetailMapper yxtOrderDetailMapper;
/**
* 进入院线通兑换券销售界面
......@@ -130,6 +135,296 @@ public class YxtCardController extends BaseController {
}
return ResponseData.error("新增地址失败!!!");
}
/**
* 下单新增订单
* @return
*/
@RequestMapping("/addYxtOrder")
public ResponseData<Map<String,Object>> addYxtOrder(@RequestParam("order") String order){
Map<String,Object> objectMap = new Hashtable<>();
try {
//目前可购买兑换券数量
int totalNums = returnCardNum();
YxtOrder yxtOrder = JSON.parseObject(order, YxtOrder.class);
String uuid = UUID.randomUUID().toString();
String orderNum = "YXT0018"+ ProduceIdUtil.getId();
yxtOrder.setOrderNum(orderNum);
Integer goodsNum = yxtOrder.getGoodsNum();
String orderType = yxtOrder.getOrderType();
if(orderType.equals("实体订单")){
//快递状态(0:无须快递,1待寄出:,2:寄出,3:已寄出)
yxtOrder.setExpressState(1);
Integer addressId = yxtOrder.getAddressId();
if(StringUtils.isBlank(addressId.toString())){
return ResponseData.error("地址不能为空!!!");
}
}
yxtOrder.setUpdateDate(new Date());
// 一个学校一个月累计购买数为300
String openId = "oLLfr0_XJc2mcaRqRl3sOQ7GwmVw";//临时测试用
Wrapper<YxtSalesLimit> salesLimitWrapper = new EntityWrapper<>();
salesLimitWrapper.eq(StringUtils.isNotBlank(openId),"open_id",openId);
YxtSalesLimit salesLimit = yxtSalesLimitMapper.selectList(salesLimitWrapper).get(0);
int dayNum = 0;
if(null != salesLimit && null != salesLimit.getSalesNum()){
dayNum = salesLimit.getSalesNum();
}
Integer num0 = yxtOrderMapper.insert(yxtOrder);
YxtOrder yxtOrder1 = getYxtOrder(yxtOrder.getUserId(),yxtOrder.getOrderNum());
Integer residuNum = 5 - dayNum;
if("实体订单".equals(orderType)){
// 快递订单不需分配兑换券账号和密码,由快递寄出
if(num0==1){
objectMap.put("yxtOrder",yxtOrder1);
return ResponseData.success(objectMap);
}
}else{
if((dayNum + goodsNum) > 5){
yxtOrderMapper.deleteById(yxtOrder1.getId());
return ResponseData.error("每人每天限购5张,目前可购买数量为"+ residuNum +"!");
}else{
if(totalNums < goodsNum && "电子订单".equals(orderType)){
yxtOrderMapper.deleteById(yxtOrder1.getId());
return ResponseData.error("可购买的兑换券数量不足,目前兑换券数量为"+ totalNums +";请刷新下单界面,重新购买!");
}
}
if(null != yxtOrder1){
Wrapper<YxtCoupon> couponWrapper = new EntityWrapper<>();
couponWrapper.eq("state", "1");
couponWrapper.eq("shelf_state", "1");
List<YxtCoupon> couponList = yxtCouponMapper.selectList(couponWrapper);
List<YxtCoupon> coupIds = new ArrayList<>();
for (YxtCoupon yxtCoupon : couponList) {
coupIds.add(yxtCoupon);
}
List<YxtCoupon> yxtCoupons = new ArrayList<>();
int num1 = 0;
int num2 = 0;
for (YxtCoupon coup : coupIds) {
num2++;
if(num2 > totalNums){
break;
}
yxtCoupons.add(coup);
YxtOrderDetail detail = new YxtOrderDetail();
detail.setYxtId(coup.getId());
detail.setOrderId(yxtOrder1.getId());
num1 += yxtOrderDetailMapper.insert(detail);
}
// 添加兑换券到订单详情后,更新兑换券状态,不允许再次购买
if(num1 == totalNums){
for (YxtCoupon coup : yxtCoupons) {
Wrapper<YxtCoupon> yxtCouponWrapper = new EntityWrapper<>();
yxtCouponWrapper.eq("id",coup.getId());
YxtCoupon yxtCoupon = new YxtCoupon();
yxtCoupon.setState(3);
yxtCouponMapper.update(yxtCoupon,yxtCouponWrapper);
}
objectMap.put("yxtCoupons",yxtCoupons);
}else{
return ResponseData.error("添加订单详情失败");
}
}else{
return ResponseData.error("获取新增订单的信息失败");
}
if(num0==1){
objectMap.put("yxtOrder",yxtOrder1);
return ResponseData.success(objectMap);
}
}
}catch (Exception e){
log.info(e.getMessage());
return ResponseData.error("院线通下单失败!!!");
}
return ResponseData.error("院线通下单失败!!!");
}
/**
* 发起支付
* @param orderNum
* @param totalPrice
*/
@RequestMapping("/activePay")
public ResponseData<Map<String,Object>> activePay(
@RequestParam("orderNum") String orderNum,
@RequestParam("totalPrice") Double totalPrice,@RequestParam("openId") String openId){
int totalPrice0 = (int)(totalPrice * 100);
String nonceStr = Sha1Util.getNonceStr();
// 统一下单请求参数
PayRequest payRequest = new PayRequest();
payRequest.setAppid(WxConfig.APPID);
payRequest.setMch_id(WxConfig.MAC_ID);
payRequest.setNonce_str(nonceStr);
payRequest.setSign("sign");
payRequest.setBody("yuan_xian_tong");
payRequest.setOut_trade_no(orderNum);
payRequest.setTotal_fee(Integer.toString(totalPrice0));
payRequest.setSpbill_create_ip("120.24.88.216");
payRequest.setNotify_url(WxConfig.NOTIFY_URL);
payRequest.setTrade_type("JSAPI");
//临时测试用
payRequest.setOpenid("o22lhwRZP2zbXff7UHH3J8oqH8A0");
log.info("pay——openid:"+openId);
//payRequest.setOpenid(openId);
// 统一下单加密参数
SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
parameters.put("appid", payRequest.getAppid());
parameters.put("mch_id", payRequest.getMch_id());
parameters.put("nonce_str", payRequest.getNonce_str());
parameters.put("body", payRequest.getBody());
parameters.put("out_trade_no", payRequest.getOut_trade_no());
parameters.put("total_fee", payRequest.getTotal_fee());
parameters.put("spbill_create_ip", payRequest.getSpbill_create_ip());
parameters.put("notify_url", payRequest.getNotify_url());
parameters.put("trade_type", payRequest.getTrade_type());
parameters.put("openid", payRequest.getOpenid());
String sign = WXPayUtil.createSign("UTF-8", parameters);
payRequest.setSign(sign);
try{
Map<String, Object> map = ConvertMapBean.bean2map(payRequest);
String xmlStr = WXPayUtil.map2Xmlstring(map);
String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
String result = HTTPSClient.sendPostXml(url, xmlStr);
System.out.println(result);
Map<String, Object> resultMap = WXPayUtil.xmlString2Map(result);
long timeStamp = System.currentTimeMillis();
nonceStr = Sha1Util.getNonceStr();
// 加密参数
String packages = "prepay_id=" + resultMap.get("prepay_id").toString();
SortedMap<Object,Object> secretParams = new TreeMap<Object,Object>();
secretParams.put("timeStamp", timeStamp);
secretParams.put("nonceStr", nonceStr);
secretParams.put("package", packages);
secretParams.put("appId", WxConfig.APPID);
secretParams.put("signType", "MD5");
String secretSign = WXPayUtil.createSign("UTF-8", secretParams);
// 获取签名
// String params = "appid=wxfc18f5186b729d15&timestamp="+timeStamp+"&noncestr="+nonceStr+"&package="+resultMap.get("prepay_id")+"&signtype=MD5";
// MessageDigest crypt = MessageDigest.getInstance("MD5");
// crypt.reset();
// crypt.update(params.getBytes("UTF-8"));
// String signature = WxInterfacesUtil.byteToHex(crypt.digest());
Map<String,Object> jsonObject = new Hashtable<>();
jsonObject.put("appId", WxConfig.APPID);
jsonObject.put("timeStamp", timeStamp);
jsonObject.put("nonceStr", nonceStr);
jsonObject.put("package", packages);
jsonObject.put("signType", "MD5");
jsonObject.put("sign", secretSign);
return ResponseData.success(jsonObject);
}catch(Exception e){
e.printStackTrace();
}
return ResponseData.error("");
}
/**
* 半个小时后取消订单
* @param orderNum
* @return
*/
@RequestMapping("cancelOrder")
public ResponseData<Map<String,Object>> cancelOrder(@RequestParam("orderNum")String orderNum){
try{
Wrapper<YxtOrder> orderWrapper = new EntityWrapper<>();
orderWrapper.eq("order_num",orderNum);
YxtOrder yxtOrder = new YxtOrder();
yxtOrder.setDelFlag(1);
yxtOrder.setState(1);
int result = yxtOrderMapper.update(yxtOrder,orderWrapper);
if(result>0){
Wrapper<YxtOrderDetail> detailWrapper = new EntityWrapper<>();
detailWrapper.eq("order_id",orderNum);
List<YxtOrderDetail> list = yxtOrderDetailMapper.selectList(detailWrapper);
List<Integer> couponIds = null;
List<Integer> ids = null;
if(list.size()>0){
for (YxtOrderDetail detail : list) {
couponIds.add(detail.getYxtId());
ids.add(detail.getId());
}
}
YxtOrderDetail orderDetail = new YxtOrderDetail();
orderDetail.setIsDel(1);
Wrapper<YxtOrderDetail> orderDetailWrapper = new EntityWrapper<>();
orderDetailWrapper.in("id",ids);
yxtOrderDetailMapper.update(orderDetail,orderDetailWrapper);
//修改院线通卡的状态
YxtCoupon coupon = new YxtCoupon();
coupon.setState(1);
Wrapper<YxtCoupon> couponWrapper = new EntityWrapper<>();
couponWrapper.eq("state",3);
couponWrapper.in("id",couponIds);
yxtCouponMapper.update(coupon,couponWrapper);
}
}catch(Exception e){
e.printStackTrace();
return ResponseData.error("取消订单失败!!!");
}
return ResponseData.success();
}
/**
* 进入付款成功界面
* @return
*/
@RequestMapping("enterPaySuccess")
public ResponseData<Map<String,Object>> enterPaySuccess(@RequestParam("orderNum")String orderNum,@RequestParam("totalPrice")Double totalPrice){
Map<String,Object> objectMap = new HashMap<>();
Wrapper<YxtOrder> orderWrapper = new EntityWrapper<>();
orderWrapper.eq("order_num",orderNum);
List<YxtOrder> orderList = yxtOrderMapper.selectList(orderWrapper);
List<Integer> couponIds = null;
if(orderList.size()>0){
Wrapper<YxtOrderDetail> detailWrapper = new EntityWrapper<>();
detailWrapper.eq("order_id",orderList.get(0).getId());
List<YxtOrderDetail> detailList = yxtOrderDetailMapper.selectList(detailWrapper);
for (YxtOrderDetail orderDetail : detailList) {
couponIds.add(orderDetail.getYxtId());
}
}
Wrapper<YxtCoupon> couponWrapper = new EntityWrapper<>();
couponWrapper.in("id",couponIds);
List<YxtCoupon> cardList = yxtCouponMapper.selectList(couponWrapper);
objectMap.put("orderNum", orderNum);
objectMap.put("totalPrice", totalPrice);
objectMap.put("cardList", cardList);
return ResponseData.success(objectMap);
}
// 返回目前可购买兑换券数量
public int returnCardNum(){
Wrapper<YxtCoupon> couponWrapper = new EntityWrapper<>();
couponWrapper.eq("state", "1");
couponWrapper.eq("shelf_state", "1");
List<YxtCoupon> list = yxtCouponMapper.selectList(couponWrapper);
return list.size() > 0 ? list.size() : 0;
}
//返回院线通订单信息
public YxtOrder getYxtOrder(String userId,String orderNum){
Wrapper<YxtOrder> orderWrapper1 = new EntityWrapper<>();
orderWrapper1.eq("user_id",userId);
orderWrapper1.eq("order_num",orderNum);
orderWrapper1.orderBy("id",false);
YxtOrder order1 = yxtOrderMapper.selectList(orderWrapper1).get(0);
return order1;
}
}
......@@ -92,5 +92,20 @@
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20190722</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.winsun.bean;
import java.io.Serializable;
import java.util.Date;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.IdType;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@SuppressWarnings("serial")
@TableName("hhr_bill")
@Data
......@@ -63,17 +62,17 @@ public class Bill implements Serializable{
/**
* 不含税金额
*/
private double amount;
private Double amount;
/**
* 含税金额
*/
private double taxAmount;
private Double taxAmount;
/**
* 税点
*/
private double taxPoint;
private Double taxPoint;
/**
* 创建时间
......@@ -83,5 +82,5 @@ public class Bill implements Serializable{
/**
* 删除标记
*/
private int delFlag;
private Integer delFlag;
}
package com.winsun.bean;
import java.io.Serializable;
/**
* 〈微信统一下单参数〉
*
* @author PXL
* @create 2020/5/12 15:17
*/
public class PayRequest implements Serializable {
private static final long serialVersionUID = -7878937183538920548L;
private String appid;
private String mch_id;
private String nonce_str;
private String sign;
private String body;
private String out_trade_no;
private String total_fee;
private String spbill_create_ip;
private String notify_url;
private String openid;
private String trade_type;
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 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;
}
}
......@@ -55,7 +55,7 @@ public class YxtOrder implements Serializable {
@TableField("update_date")
private Date updateDate;
/**
*是否删除(1.已删除,2.不删除)
*是否删除(1.已删除,0.不删除)
*/
@TableField("del_flag")
private Integer delFlag;
......@@ -70,7 +70,7 @@ public class YxtOrder implements Serializable {
@TableField("unit_price")
private Double unitPrice;
/**
*订单类型
*订单类型(1.电子订单,2.实体订单)
*/
@TableField("order_type")
private String orderType;
......@@ -80,7 +80,7 @@ public class YxtOrder implements Serializable {
@TableField("address_id")
private Integer addressId;
/**
* 快递状态(0:无须快递,1:寄出,2:已寄出)
* 快递状态(0:无须快递,1待寄出:,2:寄出,3:已寄出)
*/
@TableField("express_state")
private Integer expressState;
......
......@@ -32,4 +32,10 @@ public class YxtOrderDetail implements Serializable {
*/
@TableField("yxt_id")
private Integer yxtId;
/**
*
*/
@TableField("is_del")
private Integer isDel;
}
package com.winsun.bean;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.IdType;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* 〈用户购买记录表〉
*
* @author PXL
* @create 2020/5/12 10:43
*/
@Data
@TableName("hhr_yxt_sales_limit")
public class YxtSalesLimit implements Serializable {
private static final long serialVersionUID = 8980324270129957305L;
/**
*
*/
@TableId(value = "id",type = IdType.AUTO)
private Integer id;
/**
*购买人id
*/
@TableField("open_id")
private String openId;
/**
*购买数量
*/
@TableField("sales_num")
private Integer salesNum;
/**
*
*/
@TableField("update_date")
private Date updateDate;
}
package com.winsun.mapper;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.winsun.bean.YxtSalesLimit;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
/**
* 〈用户购买记录〉
*
* @author PXL
* @create 2020/5/12 10:48
*/
@Mapper
@Component
public interface YxtSalesLimitMapper extends BaseMapper<YxtSalesLimit> {
}
package com.winsun.utils;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
/**
* .properties文件解析工具
*
*
*
*/
@Slf4j
public class CommonPropertiesUtil {
private static CommonPropertiesUtil instance = null;
private CommonPropertiesUtil() {
}
public static CommonPropertiesUtil getInstance() {
if (instance == null) {
instance = new CommonPropertiesUtil();
}
return instance;
}
/**
* 解析传入的文件
*
* @param ls
* @return
*/
public static Properties parseProp(String ls) {
Properties properties = new Properties();
// 20081105 直接使用getInstance()取得文件的路径
InputStream is = getInstance().getClass().getResourceAsStream(ls);
try {
properties.load(is);
} catch (IOException e) {
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
}
}
return properties;
}
/**
* 直接解析.properties文件返回文件的数据结构
*
* @param ls
* @return
*/
public static Set<java.util.Map.Entry<Object, Object>> getEntrySet(String ls) {
return parseProp(ls).entrySet();
}
public static void main(String[] args) {
Set<java.util.Map.Entry<Object, Object>> set = getEntrySet("/log4j.properties");
Iterator<java.util.Map.Entry<Object, Object>> itr = set.iterator();
while(itr.hasNext()){
java.util.Map.Entry<Object, Object> obj = itr.next();
log.info(obj.getValue().toString());
}
}
}
package com.winsun.utils;
import com.winsun.bean.PayRequest;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* Map与JavaBean相互转化
* @author 董有沛
* @date 2018年1月19日
*
*/
public class ConvertMapBean {
//JavaBean转换为Map
public static Map<String,Object> bean2map(Object bean) throws Exception{
Map<String,Object> map = new HashMap<>();
//获取指定类(Person)的BeanInfo 对象
BeanInfo beanInfo = Introspector.getBeanInfo(PayRequest.class, Object.class);
//获取所有的属性描述器
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for(PropertyDescriptor pd:pds){
String key = pd.getName();
Method getter = pd.getReadMethod();
Object value = getter.invoke(bean);
map.put(key, value);
}
return map;
}
//Map转换为JavaBean
public static <T> T map2bean(Map<String,Object> map,Class<T> clz) throws Exception{
//创建JavaBean对象
T obj = clz.newInstance();
//获取指定类的BeanInfo对象
BeanInfo beanInfo = Introspector.getBeanInfo(clz, Object.class);
//获取所有的属性描述器
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for(PropertyDescriptor pd:pds){
Object value = map.get(pd.getName());
Method setter = pd.getWriteMethod();
setter.invoke(obj, value);
}
return obj;
}
}
package com.winsun.utils;
import com.alibaba.fastjson.JSONException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
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 org.json.JSONTokener;
import javax.net.ssl.SSLContext;
import javax.security.cert.CertificateException;
import javax.security.cert.X509Certificate;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
public class HTTPSClient {
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
// 不走代理
public static String sendPost(String url, String param) {
String result = "";
CloseableHttpClient httpClient = HTTPSClient.createSSLClientDefault();
HttpPost post = new HttpPost(url);
StringEntity s = new StringEntity(param, "UTF-8"); // 中文乱码在此解决
s.setContentType("application/json");
post.setEntity(s);
HttpResponse res;
try {
res = httpClient.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = res.getEntity();
if (entity.getContentLength() > 0) {
String charset = EntityUtils.getContentCharSet(entity);
org.json.JSONObject response = new org.json.JSONObject(new JSONTokener(new InputStreamReader(entity.getContent(), charset)));
result = response.toString();
System.out.println(result);
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}finally {
try {
httpClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
// 走代理
public static String sendPostAgent(String url, String param) {
String string = "";
CloseableHttpClient httpClient = HTTPSClient.createSSLClientDefault();
HttpPost httpPost = new HttpPost(url);
StringEntity s = new StringEntity(param, "UTF-8"); // 中文乱码在此解决
s.setContentType("application/json");
httpPost.setEntity(s);
HttpResponse res;
try {
HttpHost proxy = new HttpHost("172.18.101.170", 3128);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(200000).setConnectTimeout(200000).setProxy(proxy).build();
httpPost.setConfig(requestConfig);
CloseableHttpResponse result = httpClient.execute(httpPost);
string = EntityUtils.toString(result.getEntity(), "utf-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}finally {
try {
httpClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return string;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendCodePost(String url, String param) {
String string = "";
CloseableHttpClient httpClient = HTTPSClient.createSSLClientDefault();
HttpPost httpPost = new HttpPost(url);
StringEntity s = new StringEntity(param, "UTF-8"); // 中文乱码在此解决
//s.setContentEncoding("UTF-8");
s.setContentType("application/json");
httpPost.setEntity(s);
HttpResponse res;
try {
HttpHost proxy = new HttpHost("172.18.101.170", 3128);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(200000).setConnectTimeout(200000).setProxy(proxy).build();
httpPost.setConfig(requestConfig);
CloseableHttpResponse result = httpClient.execute(httpPost);
string = EntityUtils.toString(result.getEntity(), "utf-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}finally {
try {
httpClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return string;
}
// public static String sendCodePost(String url, String param) {
// String result = "";
//
// CloseableHttpClient httpClient = HTTPSClient.createSSLClientDefault();
// HttpPost post = new HttpPost(url);
// StringEntity s = new StringEntity(param, "UTF-8"); // 中文乱码在此解决
// //s.setContentEncoding("UTF-8");
//
//
// s.setContentType("application/json");
// post.setEntity(s);
// HttpResponse res;
// try {
// res = httpClient.execute(post);
// if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// HttpEntity entity = res.getEntity();
// if (entity.getContentLength() > 0) {
// String charset = EntityUtils.getContentCharSet(entity);
// org.json.JSONObject response = new org.json.JSONObject(new JSONTokener(new InputStreamReader(entity.getContent(), charset)));
// result = response.toString();
// System.out.println(result);
// }
// }
//
// } catch (ClientProtocolException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// } catch (IllegalStateException e) {
// e.printStackTrace();
// } catch (JSONException e) {
// e.printStackTrace();
// }finally {
// try {
// httpClient.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
//
// return result;
// }
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPosts(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
/// conn.setRequestProperty("accept", "*/*");
// conn.setRequestProperty("connection", "Keep-Alive");
// conn.setRequestProperty("user-agent",
// "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
// 原方法 不走代理
// public static String sendGet(String url) {
// String result = "";
// HttpClient client = new HttpClient();
// GetMethod getMethod = new GetMethod(url);
// getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 25000);
// try {
// int statusCode = client.executeMethod(getMethod);
// if (statusCode == HttpStatus.SC_OK) {
// result = getMethod.getResponseBodyAsString(); // 出现中文乱码
// // result = new String(getMethod.getResponseBody(),"utf-8");
// }
//
// } catch (ClientProtocolException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// } catch (IllegalStateException e) {
// e.printStackTrace();
// }
//
// return result;
// }
// 新方法 走代理
public static String sendGet(String url) {
String string = "";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
try {
HttpHost proxy = new HttpHost("172.18.101.170", 3128);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(200000).setConnectTimeout(200000).setProxy(proxy).build();
httpPost.setConfig(requestConfig);
CloseableHttpResponse result = httpClient.execute(httpPost);
string = EntityUtils.toString(result.getEntity(), "utf-8"); ;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
return string;
}
/**
* 发送xml请求到server端
* @param url xml请求数据地址
* @param xmlString 发送的xml数据流
* @return null发送失败,否则返回响应内容
* @throws IOException
*/
public static String sendPostXml(String url,String xmlString) throws IOException{
//创建httpclient工具对象
HttpClient client = new HttpClient();
//创建post请求方法
PostMethod myPost = new PostMethod(url);
//设置请求超时时间
client.setConnectionTimeout(3000*1000);
String responseString = null;
InputStream inputStream = null;
BufferedReader br = null;
try{
//设置请求头部类型
myPost.setRequestHeader("Content-Type","text/xml");
myPost.setRequestHeader("charset","utf-8");
//设置请求体,即xml文本内容,一种是直接获取xml内容字符串,一种是读取xml文件以流的形式
myPost.setRequestBody(xmlString);
int statusCode = client.executeMethod(myPost);
//只有请求成功200了,才做处理
if(statusCode == HttpStatus.SC_OK){
inputStream = myPost.getResponseBodyAsStream();
br = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
StringBuffer stringBuffer = new StringBuffer();
String str = "";
while ((str = br.readLine()) != null) {
stringBuffer.append(str);
}
responseString = stringBuffer.toString();
}
}catch (Exception e) {
e.printStackTrace();
}finally{
myPost.releaseConnection();
if(null != inputStream)
inputStream.close();
if(null != br)
br.close();
}
return responseString;
}
public static void main(String[] args) throws ClientProtocolException,
IOException, IllegalStateException, JSONException {
// String test = "{"
// + "\"articles\": ["
// + "{"
// + "\"thumb_media_id\":\"rmuGybyc35bNvEADz__r_GCnKpu0NNRvFi7wG-4MgiT1B171IgbyJKaeNS95Pi-Y\","
// + "\"author\":\"xxx\","
// + "\"title\":\"Happy Day\","
// + "\"content_source_url\":\"www.qq.com\","
// + "\"content\":\"content\","
// + "\"digest\":\"digest\","
// + "\"show_cover_pic\":1"
// + "},"
// + "{"
// + "\"thumb_media_id\":\"rmuGybyc35bNvEADz__r_GCnKpu0NNRvFi7wG-4MgiT1B171IgbyJKaeNS95Pi-Y\","
// + "\"author\":\"xxx\","
// + "\"title\":\"Happy Day\","
// + "\"content_source_url\":\"www.qq.com\","
// + "\"content\":\"content\","
// + "\"digest\":\"digest\","
// + "\"show_cover_pic\":0"
// + "}"
// + "]"
// +"}";
// String test = "{"
// + "\"filter\":{"
// + "\"is_to_all\":true"
// + "},"
// + "\"mpnews\":{"
// + "\"media_id\":\"jOhPKihXdmEfo2VXsf1w4mv-eDz2cQl1DyOHrQaHw2srrEFFHuzb8w2aJZyMIE_5\""
// + "},"
// + "\"msgtype\":\"mpnews\""
// +"}";
// String test = "{"
// + "\"filter\":{"
// + "\"is_to_all\":true"
// + "},"
// + "\"text\":{"
// + "\"content\":\"啊哈哈(30+70)哈哈\""
// + "},"
// + "\"msgtype\":\"text\""
// +"}";
//
// String id = "{"
// + "\"msg_id\":1000000019"
// + "}";
//
// String access = WxInterfacesUtil.getToken("client_credential", WxConfig.APPID, WxConfig.APPSECRET);
String url = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=63jVygxyIkK6oUCeM2YuzZHYLuzrkhSf6eDwmdd2HkXvIxnbfYIzQNMnt7deEWugUUobmyxNrZZa4gEMx1G0wtEJFqofT1sA3yvm9ZVctGPEG0B9DO0L8c3j3cnCC5XtZYRhAEATSL";
// String urldel = "https://api.weixin.qq.com/cgi-bin/message/mass/delete?access_token=" + access;
// String urlup = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=" + access;
//
////
// String result = sendPosts(url, test);
// String reul = "";
// WxInterfacesUtil.sendMessage_text("dd","dd","dd");
PropertiesInit pinit = new PropertiesInit();
pinit.initProperties();
returnMenu(pinit);
}
public static String returnMenu(PropertiesInit ppp) {
// WxInterfacesUtil.sendGroupMessage_text("", "", "");
JSONObject button = new JSONObject();
try {
String Weixin = ppp.getProperties("Weixin");
// part1
String menu_tdhd = ppp.getProperties("wx_menu_tdhd");
String menu_grhd = ppp.getProperties("wx_menu_grhd");
String menu_lshd = ppp.getProperties("wx_menu_lshd");
String menu_ywdj = ppp.getProperties("wx_menu_ywdj");
String menu_xscx = ppp.getProperties("wx_menu_xscx");
String menu_xsgj = ppp.getProperties("wx_menu_xsgj");
String menu_fhdj = ppp.getProperties("wx_menu_fhdj");
String menu_userInfo = ppp.getProperties("wx_menu_userInfo");
String menu_register = ppp.getProperties("wx_menu_register");
String menu_czzj = ppp.getProperties("wx_menu_czzj");
String menu_twzf = ppp.getProperties("wx_menu_twzf");
String menu_yrym = ppp.getProperties("wx_menu_yrym");
//String menu_blzc = ppp.getProperties("wx_menu_blzc");
// part2
menu_tdhd = URLEncoder.encode(menu_tdhd, "UTF-8");
menu_grhd = URLEncoder.encode(menu_grhd, "UTF-8");
menu_lshd = URLEncoder.encode(menu_lshd, "UTF-8");
menu_ywdj = URLEncoder.encode(menu_ywdj, "UTF-8");
menu_xscx = URLEncoder.encode(menu_xscx, "UTF-8");
menu_xsgj = URLEncoder.encode(menu_xsgj, "UTF-8");
menu_fhdj = URLEncoder.encode(menu_fhdj, "UTF-8");
menu_userInfo = URLEncoder.encode(menu_userInfo,"UTF-8");
menu_register = URLEncoder.encode(menu_register, "UTF-8");
menu_czzj = URLEncoder.encode(menu_czzj,"UTF-8");
menu_twzf = URLEncoder.encode(menu_twzf,"UTF-8");
menu_yrym = URLEncoder.encode(menu_yrym,"UTF-8");
//menu_blzc = URLEncoder.encode(menu_blzc, "UTF-8");
//part3
menu_tdhd = Weixin.replace("redirect_uri=","redirect_uri=" + menu_tdhd);
menu_grhd = Weixin.replace("redirect_uri=","redirect_uri=" + menu_grhd);
menu_lshd = Weixin.replace("redirect_uri=","redirect_uri=" + menu_lshd);
menu_xsgj = Weixin.replace("redirect_uri=", "redirect_uri="+ menu_xsgj);
menu_fhdj = Weixin.replace("redirect_uri=", "redirect_uri="+ menu_fhdj);
menu_ywdj = Weixin.replace("redirect_uri=", "redirect_uri="+ menu_ywdj);
menu_xscx = Weixin.replace("redirect_uri=", "redirect_uri="+ menu_xscx);
menu_register = Weixin.replace("redirect_uri=", "redirect_uri="+ menu_register);
menu_userInfo = Weixin.replace("redirect_uri=","redirect_uri=" + menu_userInfo);
menu_czzj = Weixin.replace("redirect_uri=", "redirect_uri="+ menu_czzj);
menu_twzf = Weixin.replace("redirect_uri=", "redirect_uri="+ menu_twzf);
menu_yrym = Weixin.replace("redirect_uri=", "redirect_uri="+ menu_yrym);
//menu_blzc = Weixin.replace("redirect_uri=", "redirect_uri="+ menu_blzc);
JSONArray menu = new JSONArray();
JSONArray menuList1 = new JSONArray();
JSONObject menu1 = new JSONObject();
menu1.put("name", "活动参与");
menu1.put("type", "click");
JSONObject btn11 = new JSONObject();
btn11.put("name", "个人活动参与");
btn11.put("key", "m11");
btn11.put("type", "view");
btn11.put("url", menu_grhd);
JSONObject btn12 = new JSONObject();
btn12.put("name", "团队活动参与");
btn12.put("key", "m12");
btn12.put("type", "view");
btn12.put("url", menu_tdhd);
JSONObject btn13 = new JSONObject();
btn13.put("name", "历史活动查询");
btn13.put("key", "m13");
btn13.put("type", "view");
btn13.put("url", menu_lshd);
JSONObject btn14 = new JSONObject();
btn14.put("name", "飞行考试");
btn14.put("key", "m14");
btn14.put("type", "view");
btn14.put("url", "https://ks.sojump.hk/jq/15330543.aspx");
JSONObject btn15 = new JSONObject();
btn15.put("name", "训练营报名");
btn15.put("key", "m15");
btn15.put("type", "view");
btn15.put("url", "https://jinshuju.net/f/wTrBil");
menuList1.add(btn11);
menuList1.add(btn12);
menuList1.add(btn13);
menuList1.add(btn14);
menuList1.add(btn15);
menu1.put("sub_button", menuList1);
menu.add(menu1);
/*********************/
JSONArray menuList2 = new JSONArray();
JSONObject menu2 = new JSONObject();
menu2.put("name", "业务销售");
menu2.put("key", "m20");
JSONObject btn21 = new JSONObject();
btn21.put("name", "业务登记");
btn21.put("key", "m21");
btn21.put("type", "view");
btn21.put("url", menu_ywdj);
// JSONObject btn22 = new JSONObject();
// btn22.put("name", "历史销量查询");
// btn22.put("key", "m22");
// btn22.put("type", "view");
// btn22.put("url", menu_xscx);
JSONObject btn22 = new JSONObject();
btn22.put("name", "放号登记");
btn22.put("key", "m22");
btn22.put("type", "view");
btn22.put("url", menu_fhdj);
JSONObject btn23 = new JSONObject();
btn23.put("name", "网络测速");
btn23.put("key", "m23");
btn23.put("type", "view");
btn23.put("url", "http://tool.cncn.com/cewangsu/");
JSONObject btn24 = new JSONObject();
btn24.put("name", "小白卡销售"); // 即销售工具
btn24.put("key", "m24");
btn24.put("type", "view");
btn24.put("url", menu_xsgj);
JSONObject btn25 = new JSONObject();
btn25.put("name", "电子传单");
btn25.put("key", "m25");
btn25.put("type", "view");
btn25.put("url", "http://a.xiumi.us/stage/v5/2Zq72/44772355");
menuList2.add(btn21);
menuList2.add(btn22);
menuList2.add(btn23);
menuList2.add(btn24);
menuList2.add(btn25);
menu2.put("sub_button", menuList2);
/***********************/
JSONArray menuList3 = new JSONArray();
JSONObject menu3 = new JSONObject();
menu3.put("name", "用户管理");
menu3.put("key", "m30");
JSONObject btn31 = new JSONObject();
btn31.put("name", "报名加入");
btn31.put("key", "m31");
btn31.put("type", "view");
btn31.put("url", menu_register);
// JSONObject btn32 = new JSONObject();
// btn32.put("name", "部落成员注册");
// btn32.put("key", "m32");
// btn32.put("type", "view");
// btn32.put("url", menu_blzc);
JSONObject btn32 = new JSONObject();
btn32.put("name", "个人信息");
btn32.put("key", "m32");
btn32.put("type", "view");
btn32.put("url", menu_userInfo);
JSONObject btn33 = new JSONObject();
btn33.put("name", "成长足迹");
btn33.put("key", "m33");
btn33.put("type", "view");
btn33.put("url", menu_czzj);
JSONObject btn34 = new JSONObject();
btn34.put("name", "推文转发");
btn34.put("key", "m34");
btn34.put("type", "view");
btn34.put("url", menu_twzf);
JSONObject btn35 = new JSONObject();
btn35.put("name", "一人一码");
btn35.put("key", "m35");
btn35.put("type", "view");
btn35.put("url", menu_yrym);
menuList3.add(btn31);
menuList3.add(btn32);
menuList3.add(btn33);
menuList3.add(btn34);
menuList3.add(btn35);
menu3.put("sub_button", menuList3);
menu.add(menu2);
menu.add(menu3);
button.put("button", menu);
System.out.println(button.toString());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String formateURL(String url) {
if (url != null) {
url = "http://open.plus.yixin.im/connect/oauth2/authorize?appid=9e65cdacfb9e4f3b820031d7af01fceb&redirect_uri="
+ url
+ "&response_type=code&scope=snsapi_base&state=from_menu";
return url;
} else {
return null;
}
}
public static CloseableHttpClient createSSLClientDefault() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
return true;
}
@Override
public boolean isTrusted(
java.security.cert.X509Certificate[] arg0,
String arg1)
throws java.security.cert.CertificateException {
// TODO Auto-generated method stub
return false;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
}
\ No newline at end of file
package com.winsun.utils;
import java.security.MessageDigest;
public class MD5Util
{
private static String byteArrayToHexString(byte[] b)
{
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++) {
resultSb.append(byteToHexString(b[i]));
}
return resultSb.toString();
}
private static String byteToHexString(byte b)
{
int n = b;
if (n < 0) {
n += 256;
}
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
public static String MD5Encode(String origin, String charsetname)
{
String resultString = null;
try
{
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if ((charsetname == null) || ("".equals(charsetname))) {
resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
} else {
resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
}
}
catch (Exception localException) {}
return resultString;
}
private static final String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
"e", "f" };
}
package com.winsun.utils;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import lombok.extern.slf4j.Slf4j;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
@Slf4j
public class MD5Utils {
......@@ -23,7 +22,7 @@ public class MD5Utils {
* 循环次数
*/
public final static int hashIterations = 1024;
/**
* shiro密码加密工具类
*
......
package com.winsun.utils;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* 加载系统配置
* @author czl
* @date 2014-3-21
*/
@Slf4j
public class PropertiesInit {
private static boolean initFlag = false;
/**
* 系统配置保存集合
*/
private static Map<String, String> propertiesMap = null;
/**
* 初始化系统配置
*/
public static synchronized void initProperties(){
if(initFlag){
return;
}
log.info("initProperties..");
initFlag = true;
propertiesMap = new HashMap<String, String>();
String[] pros = new String[]{"/META-INF/config/application.properties", "/META-INF/config/zjinfoDetail.properties"};
Set<Map.Entry<Object, Object>> set = null;
Iterator<Map.Entry<Object, Object>> itr = null;
Map.Entry<Object, Object> obj = null;
String tempkey = null;
String tempValue = null;
for (int i = 0; i < pros.length; i++) {
set = CommonPropertiesUtil.getEntrySet(pros[i]);
itr = set.iterator();
while(itr.hasNext()){
obj = itr.next();
tempkey = (String)obj.getKey();
tempValue = (String)obj.getValue();
propertiesMap.put(tempkey, tempValue);
}
}
}
/**
* 获取系统配置值
* @param key
* @return
*/
public static String getProperties(String key){
return propertiesMap.get(key);
}
public static void main(String[] args) {
initProperties();
log.info(getProperties("cookieMaxAge"));
}
}
package com.winsun.utils;
import java.security.MessageDigest;
import java.util.Random;
public class Sha1Util {
// 生成微信签名
public static String getSha1(String str) {
if ((str == null) || (str.length() == 0)) {
return null;
}
char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
try {
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes());
byte[] md = mdTemp.digest();
int j = md.length;
char[] buf = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
buf[(k++)] = hexDigits[(byte0 >>> 4 & 0xF)];
buf[(k++)] = hexDigits[(byte0 & 0xF)];
}
return new String(buf);
} catch (Exception e) {
}
return null;
}
// 获取随机字符串
public static String getNonceStr() {
Random random = new Random();
return MD5Util.MD5Encode(String.valueOf(random.nextInt(10000)), "UTF-8");
}
// 获取时间戳
public static String getTimeStamp() {
return String.valueOf(System.currentTimeMillis() / 1000);
}
}
package com.winsun.utils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;
import java.util.*;
public class WXPayUtil {
/**
* 将Map转换为XML格式的字符串
*
* @param data Map类型数据
* @return XML格式的字符串
* @throws Exception
*/
public static String mapToXml(Map<String, Object> data) throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
org.w3c.dom.Document document = documentBuilder.newDocument();
org.w3c.dom.Element root = document.createElement("xml");
document.appendChild(root);
for (String key: data.keySet()) {
String value = data.get(key).toString();
if (value == null) {
value = "";
}
value = value.trim();
org.w3c.dom.Element filed = document.createElement(key);
filed.appendChild(document.createTextNode(value));
root.appendChild(filed);
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
try {
writer.close();
}
catch (Exception ex) {
}
return output;
}
/**
* Map转换成Xml
* @param map
* @return
*/
public static String map2Xmlstring(Map<String,Object> map){
StringBuffer sb = new StringBuffer("");
sb.append("<xml>");
Set<String> set = map.keySet();
for(Iterator<String> it=set.iterator(); it.hasNext();){
String key = it.next();
Object value = map.get(key);
sb.append("<").append(key).append(">");
sb.append(value);
sb.append("</").append(key).append(">");
// sb.append("\n");
}
sb.append("</xml>");
return sb.toString();
}
/**
* Xml string转换成Map
* @param xmlStr
* @return
*/
public static Map<String,Object> xmlString2Map(String xmlStr){
Map<String,Object> map = new HashMap<String,Object>();
Document doc;
try {
doc = DocumentHelper.parseText(xmlStr);
Element el = doc.getRootElement();
map = recGetXmlElementValue(el,map);
} catch (DocumentException e) {
e.printStackTrace();
}
return map;
}
/**
* 循环解析xml
* @param ele
* @param map
* @return
*/
@SuppressWarnings({ "unchecked" })
private static Map<String, Object> recGetXmlElementValue(Element ele, Map<String, Object> map){
List<Element> eleList = ele.elements();
if (eleList.size() == 0) {
map.put(ele.getName(), ele.getTextTrim());
return map;
} else {
for (Iterator<Element> iter = eleList.iterator(); iter.hasNext();) {
Element innerEle = iter.next();
recGetXmlElementValue(innerEle, map);
}
return map;
}
}
/**
* 微信支付签名算法sign
* @param characterEncoding
* @param parameters
* @return
*/
@SuppressWarnings("unchecked")
public static String createSign(String characterEncoding,SortedMap<Object,Object> parameters){
StringBuffer sb = new StringBuffer();
Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序(升序)
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
Object v = entry.getValue();
if(null != v && !"".equals(v)
&& !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + WxConfig.KEY);
// sb.append("key=" + "WINSUN123456xyjl987654wxpay55555");
System.out.println(sb.toString());
String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase(Locale.ENGLISH);
System.out.println(sign);
return sign;
}
/**
* 微信支付签名算法sign
* @param characterEncoding
* @param parameters
* @return
*/
@SuppressWarnings("unchecked")
public static String createSignNoKey(String characterEncoding,SortedMap<Object,Object> parameters){
StringBuffer sb = new StringBuffer();
Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序(升序)
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
Object v = entry.getValue();
if(null != v && !"".equals(v)
&& !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
return sign;
}
}
package com.winsun.utils;
/**
* 微信请求地址配置及微信参数类
* @author 董有沛
* @date 2017-03-31
*/
public class WxConfig {
/**************公众号参数信息*************/
// 公众号appid 校园服务号
public static final String APPID = "wx0641dc1dc4d34384";
// 公众号秘钥 secret 校园服务号
public static final String APPSECRET = "3b43b46fc94d4e98588ee6ad992fa5c7";
public static final String headUrl = "http://dianyuanjiangli.com";
public static final String KEY = "WINSUN123456xyjl987654wxpay88888";
public static final String MAC_ID = "1498149672";
public static final String NOTIFY_URL = "http://dianyuanjiangli.com/xyjl/yx/wxpay/yxt!payNotify.action";
// // 公众号appid 网讯测试服务号
// public static final String APPID = "wxfc18f5186b729d15";
//
// // 公众号秘钥 secret 网讯测试服务号
// public static final String APPSECRET = "122278f3fb555468848ff040620505ad";
//
// public static final String headUrl = "http://167460x6b0.51mypc.cn";
//
// public static final String KEY = "WINSUN123456xyjl987654wxpay55555";
//
// public static final String MAC_ID = "1346602601";
//
// public static final String NOTIFY_URL = "http://167460x6b0.51mypc.cn/xyjl/yx/wxpay/yxt!payNotify.action";
/**************消息类型**************/
// 文本类型
public static final String MSG_TEXT = "text";
// 图片类型
public static final String MSG_IMAGE = "image";
// 语音类型
public static final String MSG_VOICE = "voice";
// 视频类型
public static final String MSG_VIDEO = "video";
// 小视频类型
public static final String MSG_SHORT_VIDEO = "shortvideo";
// 位置类型
public static final String MSG_LOCATION = "location";
// 链接类型
public static final String MSG_LINK = "link";
// 事件类型
public static final String MSG_EVENT = "event";
/****************事件类型******************/
// 订阅事件
public static final String EVENT_SUBSCRIBE = "subscribe";
// 取消订阅事件
public static final String EVENT_UNSUBSCRIBE = "unsubscribe";
// 扫带参数的二维码事件 ps: 只有用户已关注了公众号,事件类型才是scan,未关注时,事件类型是subscribe
public static final String EVENT_SCAN = "SCAN";
// 上报位置事件
public static final String EVENT_LOCATION = "LOCATION";
// 自定义菜单的拉取消息事件
public static final String EVENT_CLICK = "CLICK";
// 自定义菜单的链接跳转事件
public static final String EVENT_VIEW = "VIEW";
/****************微信接口地址******************/
// accessToken生成
public static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ APPID +"&secret=" + APPSECRET;
// 临时二维码
public static String TEMPORARY_CODE_URL = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=";
// 永久二维码生成
public static String PERMANENT_CODE_URL = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=";
// 使用请求二维码返回ticket换取二维码图片 ps:(ticket需UrlEncode)
public static String TICKET_CODE_URL = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=";
// 授权地址
public static String OAuth = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APPID + "&redirect_uri=&response_type=code&scope=&state=#wechat_redirect";
/***********************/
public static String commonUrl = "http://open.weixin.qq.com/connect/oauth2/authorize?appid="+ APPID +"&redirect_uri=&response_type=code&scope=snsapi_base&state=frommenu#wechat_redirect";
}
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