'充值订单支付'

dev-discount
= 4 years ago
parent b0aaa698f6
commit 60326d842d
  1. 2
      hai-cweb/src/main/java/com/cweb/config/AuthConfig.java
  2. 75
      hai-cweb/src/main/java/com/cweb/controller/HighTestController.java
  3. 157
      hai-cweb/src/main/java/com/cweb/controller/OutRechargeOrderController.java
  4. 3
      hai-service/src/main/java/com/hai/common/pay/entity/OrderType.java
  5. 36
      hai-service/src/main/java/com/hai/common/utils/WxUtils.java
  6. 2
      hai-service/src/main/java/com/hai/entity/OutRechargeOrder.java
  7. 6
      hai-service/src/main/java/com/hai/service/pay/impl/GoodsOrderServiceImpl.java
  8. 73
      hai-service/src/main/java/com/hai/service/pay/impl/rechargeOrderServiceImpl.java
  9. BIN
      hai-service/src/main/java/privatekey/1289663601_apiclient_cert.p12

@ -108,6 +108,8 @@ public class AuthConfig implements WebMvcConfigurer {
.excludePathPatterns("/user/getUnionId")
.excludePathPatterns("/order/orderToH5Pay")
.excludePathPatterns("/order/orderToPay")
.excludePathPatterns("/test/*")
.excludePathPatterns("/outRechargeOrder/refundOrder")
.excludePathPatterns("/wechat/*")
;
}

@ -0,0 +1,75 @@
package com.cweb.controller;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.*;
import com.hai.entity.*;
import com.hai.model.HighUserModel;
import com.hai.model.ResponseData;
import com.hai.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @Auther: 胡锐
* @Description:
* @Date: 2021/3/26 23:08
*/
@Controller
@RequestMapping(value = "/test")
@Api(value = "订单接口")
public class HighTestController {
private static Logger log = LoggerFactory.getLogger(HighTestController.class);
@RequestMapping(value = "/getOrderById", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "根据id查询订单详情")
public ResponseData getOrderById() {
try {
Map<String,Object> map = new HashMap<>();
map.put("app_key", "208241666939552");
//map.put("app_secret", "adecc3cff077834cb8632c8ab3bec0e6");
map.put("timestamp", new Date().getTime());
map.put("pageIndex", 1);
map.put("pageSize", 10);
String signStr = "adecc3cff077834cb8632c8ab3bec0e6" + WxUtils.generateSignature(map,"adecc3cff077834cb8632c8ab3bec0e6") + "adecc3cff077834cb8632c8ab3bec0e6";
System.out.println("加密前:" + signStr);
String sign = MD5Util.encode(signStr.getBytes()).toLowerCase();
System.out.println("加密后:" + sign);
map.put("sign", sign);
return ResponseMsgUtil.success(HttpsUtils.doPost("https://test02-motorcade-hcs.czb365.com/services/vp/openapi/queryGasInfoListByPage", JSON.toJSONString(map)));
} catch (Exception e) {
log.error("HighOrderController --> getOrderById() error!", e);
return ResponseMsgUtil.exception(e);
}
}
}

@ -1,25 +1,37 @@
package com.cweb.controller;
import com.alibaba.fastjson.JSONObject;
import com.cweb.config.SysConst;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.pay.WechatPayUtil;
import com.hai.common.pay.entity.WeChatPayReqInfo;
import com.hai.common.pay.util.MD5Util;
import com.hai.common.pay.util.sdk.WXPayConstants;
import com.hai.common.security.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.IDGenerator;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.common.utils.*;
import com.hai.entity.HighChildOrder;
import com.hai.entity.HighCoupon;
import com.hai.entity.HighOrder;
import com.hai.entity.OutRechargeOrder;
import com.hai.model.HighUserModel;
import com.hai.model.ResponseData;
import com.hai.service.OutRechargeOrderService;
import com.hai.service.TelApiService;
import com.hai.service.pay.impl.GoodsOrderServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@ -28,9 +40,12 @@ import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.concurrent.ThreadLocalRandom;
@Controller
@RequestMapping(value = "/outRechargeOrder")
@ -47,6 +62,12 @@ public class OutRechargeOrderController {
@Resource
private TelApiService telApiService;
@Resource
private WechatPayUtil wechatPayUtil;
@Resource
private GoodsOrderServiceImpl goodsOrderService;
@RequestMapping(value="/addOrder",method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "增加订单")
@ -160,4 +181,134 @@ public class OutRechargeOrderController {
return ResponseMsgUtil.exception(e);
}
}
@RequestMapping(value="/orderToPay",method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "订单支付发起支付")
public ResponseData orderToPay(@RequestBody String reqBodyStr) {
try {
if (StringUtils.isBlank(reqBodyStr)) {
log.error("orderToPay error!", "参数错误");
throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
}
JSONObject jsonObject = JSONObject.parseObject(reqBodyStr);
Long orderId = jsonObject.getLong("orderId");
String openId = jsonObject.getString("openId"); // openId
if (orderId == null || StringUtils.isBlank(openId)) {
log.error("orderToPay error!", "参数错误");
throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
}
// 订单
OutRechargeOrder order = outRechargeOrderService.findByOrderId(orderId);
if (order == null) {
log.error("orderToPay error!", "未找到订单信息");
throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到订单信息");
}
// 订单状态 : 1.待支付 2.已支付 3.已完成 4.已退款 5.已取消
if (order.getStatus() != 1) {
log.error("orderToPay error!", "无法支付,订单不处于待支付状态");
throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "无法支付,订单不处于待支付状态");
}
Map<String,Object> map = new HashMap<>();
map.put("orderNo", order.getOrderNo());
map.put("payPrice", order.getPayPrice());
map.put("orderScene", "RECHARGE_ORDER");
map.put("body","购买产品");
map.put("subject","购买产品");
//微信支付
String nonce_str = MD5Util.MD5Encode(String.valueOf(ThreadLocalRandom.current().nextInt(10000)), "UTF-8");
int total_fee = MathUtils.objectConvertBigDecimal(map.get("payPrice")).multiply(new BigDecimal("100")).intValue();
WeChatPayReqInfo weChatPayReqInfo = new WeChatPayReqInfo();
weChatPayReqInfo.setAppid(SysConst.getSysConfig().getWxMchAppId()); //公众号id
weChatPayReqInfo.setMch_id(SysConst.getSysConfig().getWxMchId()); //商户号
weChatPayReqInfo.setSub_appid(SysConst.getSysConfig().getWxSubAppId()); //商户号
weChatPayReqInfo.setSub_mch_id(SysConst.getSysConfig().getWxSubMchId()); //子商户号
// weChatPayReqInfo.setOpenid(openId);
weChatPayReqInfo.setSub_openid(openId);
weChatPayReqInfo.setNonce_str(nonce_str); //随机字符串
weChatPayReqInfo.setBody(map.get("body").toString()); //商品描述
weChatPayReqInfo.setOut_trade_no(map.get("orderNo").toString()); //商户订单号
weChatPayReqInfo.setTotal_fee(total_fee); //总金额
weChatPayReqInfo.setSpbill_create_ip("139.159.177.244"); //终端ip
weChatPayReqInfo.setNotify_url(SysConst.getSysConfig().getNotifyUrl()); //通知url
weChatPayReqInfo.setTrade_type("JSAPI"); //交易类型
weChatPayReqInfo.setAttach(map.get("orderScene").toString());
weChatPayReqInfo.setProfit_sharing("Y");
//附加数据,区分订单类型
Map<String,String> payMap = new HashMap<>();
payMap.put("app_id",SysConst.getSysConfig().getWxSubAppId());
payMap.put("api_key",SysConst.getSysConfig().getWxApiKey());
payMap.put("unified_order_url",SysConst.getSysConfig().getWxUnifiedOrderUrl());
SortedMap<Object, Object> sortedMap = wechatPayUtil.goWechatPay(weChatPayReqInfo,payMap);
return ResponseMsgUtil.success(sortedMap);
} catch (Exception e) {
log.error("orderToPay error!", e);
return ResponseMsgUtil.exception(e);
}
}
@RequestMapping(value = "/orderToRefund", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "订单退款")
public ResponseData orderToRefund(HttpServletRequest request) {
try {
Map<String,String> param = new HashMap<>();
param.put("appid", "wx637bd6f7314daa46");
param.put("mch_id", "1289663601");
param.put("sub_mch_id" , "1609882817");
param.put("nonce_str", WxUtils.makeNonStr());
param.put("transaction_id", "4200001165202106112686446080");
param.put("out_refund_no", "HFR"+new Date().getTime());
param.put("total_fee", "1");
param.put("refund_fee", "1");
param.put("sign_type", "HMAC-SHA256");
String signStr = WxUtils.generateSignature(param, "Skufk5oi85wDFGl888i6wsRSTkdd5df5" , WXPayConstants.SignType.HMACSHA256);
param.put("sign", signStr);
return ResponseMsgUtil.success(doRefundRequest(param.get("mch_id"),null,WxUtils.mapToXml(param)));
} catch (Exception e) {
log.error("HighOrderController --> getUserOrderList() error!", e);
return ResponseMsgUtil.exception(e);
}
}
public String doRefundRequest(String mchId, String url, String data) throws Exception {
//小程序退款需要调用双向证书的认证
CloseableHttpClient httpClient = goodsOrderService.readCertificate(mchId);
try {
HttpPost httpost = new HttpPost("https://api.mch.weixin.qq.com/secapi/pay/refund"); // 设置响应头信息
httpost.addHeader("Connection", "keep-alive");
httpost.addHeader("Accept", "*/*");
httpost.addHeader("Content-Type", "text/xml");
httpost.addHeader("Host", "api.mch.weixin.qq.com");
httpost.addHeader("X-Requested-With", "XMLHttpRequest");
httpost.addHeader("Cache-Control", "max-age=0");
httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
httpost.setEntity(new StringEntity(data, "UTF-8"));
CloseableHttpResponse response = httpClient.execute(httpost);
try {
HttpEntity entity = response.getEntity();
String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
EntityUtils.consume(entity);
return jsonStr;
} finally {
response.close();
}
} catch (Exception e){
throw new RuntimeException(e);
} finally {
httpClient.close();
}
}
}

@ -3,7 +3,8 @@ package com.hai.common.pay.entity;
public enum OrderType {
// 建议将支付频率高的模块放在前面
GOODS_ORDER("GOODS_ORDER", "goodsOrderService", "购买商品"),
TEST("TEST", "testPayService", "支付测试")
RECHARGE_ORDER("RECHARGE_ORDER", "rechargeOrderService", "充值订单"),
TEST("TEST", "testPayService", "支付测试"),
;
private String moduleCode;

@ -247,6 +247,42 @@ public class WxUtils {
}
}
public static String generateSignature(final Map<String, Object> data, String key) throws Exception {
Set<String> keySet = data.keySet();
String[] keyArray = keySet.toArray(new String[keySet.size()]);
Arrays.sort(keyArray);
StringBuilder sb = new StringBuilder();
for (String k : keyArray) {
if (k.equals(WXPayConstants.FIELD_SIGN)) {
continue;
}
if (data.get(k) != null) // 参数值为空,则不参与签名
sb.append(k).append("").append(data.get(k)).append("");
}
if (key != null) {
//sb.append("app_secret=").append(key);
}
return sb.toString();
}
public static String generateSignature2(final Map<String, Object> data, String sign, String key) throws Exception {
Set<String> keySet = data.keySet();
String[] keyArray = keySet.toArray(new String[keySet.size()]);
Arrays.sort(keyArray);
StringBuilder sb = new StringBuilder();
for (String k : keyArray) {
if (k.equals(WXPayConstants.FIELD_SIGN)) {
continue;
}
if (data.get(k) != null) // 参数值为空,则不参与签名
sb.append(k).append("=").append(data.get(k)).append("&");
}
if (key != null) {
sb.append("app_secret=").append(key);
}
return sb.toString();
}
/**
* 生成 MD5
*

@ -12,7 +12,7 @@ import java.util.Date;
* 代码由工具生成
*
**/
public class OutRechargeOrder implements Serializable {
public class OutRechargeOrder extends HighOrder implements Serializable {
/**
* 主键
*/

@ -187,14 +187,14 @@ public class GoodsOrderServiceImpl implements PayService {
}
}
//微信小程序读取双向证书
private static CloseableHttpClient readCertificate(String mchId) throws Exception{
public CloseableHttpClient readCertificate(String mchId) throws Exception{
/**
* 注意PKCS12证书 是从微信商户平台-账户设置- API安全 中下载的
*/
KeyStore keyStore = KeyStore.getInstance("PKCS12");
//P12文件目录 证书路径,这里需要你自己修改,linux下还是windows下的根路径
FileInputStream instream = new FileInputStream("/home/project/wx_cert/1289663601_apiclient_cert.p12");
FileInputStream instream = new FileInputStream("G:\\hurui-project/hai-parent/hai-service/src/main/java/privatekey/1289663601_apiclient_cert.p12");
try {
keyStore.load(instream, "1289663601".toCharArray());//这里写密码..默认是你的MCHID
} finally {

@ -0,0 +1,73 @@
package com.hai.service.pay.impl;
import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.pay.util.XmlUtil;
import com.hai.common.pay.util.sdk.WXPayConstants;
import com.hai.common.utils.WxUtils;
import com.hai.dao.HighUserCouponMapper;
import com.hai.entity.*;
import com.hai.model.ResultProfitSharing;
import com.hai.service.*;
import com.hai.service.pay.PayService;
import org.apache.http.HttpEntity;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import javax.net.ssl.SSLContext;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.security.KeyStore;
import java.util.*;
/**
* @Auther: 胡锐
* @Description:
* @Date: 2021/3/27 00:35
*/
@Service("rechargeOrderService")
public class rechargeOrderServiceImpl implements PayService {
private static Logger log = LoggerFactory.getLogger(rechargeOrderServiceImpl.class);
@Resource
private OutRechargeOrderService outRechargeOrderService;
@Override
@Transactional(propagation= Propagation.REQUIRES_NEW)
public void paySuccess(Map<String, String> map, String payType) throws Exception {
if (payType.equals("Alipay")) {
// 支付宝支付 todo 暂未开发
return;
}
if (payType.equals("WechatPay")) {
// 查询订单信息
OutRechargeOrder order = outRechargeOrderService.findByOrderNo(map.get("out_trade_no"));
if (order == null) {
throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_ORDER, "");
}
if (order.getOrderStatus() == 1) {
order.setPaySerialNo(map.get("transaction_id")); // 支付流水号
order.setPayRealPrice(new BigDecimal(map.get("total_fee")).divide(new BigDecimal("100"))); // 实付金额
order.setPayTime(new Date()); // 支付时间
order.setOrderStatus(2); // 订单状态:1 待支付 2 已支付 3.已完成 4. 已退款 5.已取消
outRechargeOrderService.updateOrder(order);
}
}
}
}
Loading…
Cancel
Save