嗨森逛服务
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hai-server/hai-cweb/src/main/java/com/cweb/controller/pay/OrderController.java

693 lines
37 KiB

package com.cweb.controller.pay;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cweb.config.SysConst;
import com.cweb.config.WxMsgConfig;
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.OrderType;
import com.hai.common.pay.entity.WeChatPayReqInfo;
import com.hai.common.pay.util.MD5Util;
import com.hai.common.security.AESEncodeUtil;
import com.hai.common.security.Base64Util;
import com.hai.common.security.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.*;
import com.hai.config.*;
import com.hai.entity.*;
import com.hai.enum_type.GoodsType;
import com.hai.enum_type.PayType;
import com.hai.model.HighCouponModel;
import com.hai.model.HighUserModel;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.*;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
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;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.math.BigDecimal;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
/**
*
* @Title:
* @Description: 对订单的操作
* @author: 魏真峰
* @param:
* @return:
* @throws
*/
@Controller
@RequestMapping("/order")
@Api(value = "对订单的操作")
public class OrderController {
private static Logger log = LoggerFactory.getLogger(OrderController.class);
@Autowired
private UserCenter userCenter;
@Resource
private WechatPayUtil wechatPayUtil;
@Resource
private HighOrderService highOrderService;
@Resource
private HighCouponService highCouponService;
@Resource
private HighQzOrderService highQzOrderService;
@Resource
private HighUserPayPasswordService highUserPayPasswordService;
@Resource
private HighUserCardService highUserCardService;
@Resource
private HighUserService highUserService;
@Resource
private UnionPayConfig unionPayConfig;
@Resource
private UnionStagingPayConfig unionStagingPayConfig;
/**
*
* @Title: orderToPay
* @Description: 订单支付发起支付
* @author: 魏真峰
* @param: [pageNum, pageSize]
* @return: com.shinwoten.haj.common.model.ResponseData
* @throws
*/
@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");
Integer openIdType = jsonObject.getInteger("openIdType"); // openId类型 1:小程序 2:公众号
String orderScene = jsonObject.getString("orderScene"); // 订单类型
String openId = jsonObject.getString("openId"); // openId
if ( orderId == null || StringUtils.isBlank(orderScene) || StringUtils.isBlank(openId)) {
log.error("orderToPay error!", "参数错误");
throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
}
HighOrder order = highOrderService.getOrderById(orderId);
if(order == null) {
log.error("OrderController --> orderToPay() ERROR", "未找到订单信息");
throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_ORDER, "");
}
//校验订单状态 订单状态:1 待支付 2 已支付 3.已完成 4. 已退款 5.已取消
if(order.getOrderStatus() != 1) {
log.error("OrderController --> orderToPay() ERROR", "订单不处于待支付状态");
throw ErrorHelp.genException(SysCode.System, ErrorCode.ORDER_NO_STAY_PAY, "");
}
// 商品类型 1:卡卷 2:金币充值 3:加油站
for (HighChildOrder childOrder : order.getHighChildOrderList()) {
if (childOrder.getGiveawayType() == false && childOrder.getGoodsType() == 1) {
HighCoupon coupon = highCouponService.getCouponById(childOrder.getGoodsId());
// 支付类型:1.微信支付 2.金币支付
if (coupon.getPayType() != 1) {
log.error("OrderController --> orderToPay() ERROR", "只支持微信支持");
throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, coupon.getCouponName() + ",只支持微信支付");
}
}
if (childOrder.getGoodsType() == 3) {
// 查询账号余额
JSONObject accountInfo2JD = TuanYouConfig.queryCompanyAccountInfo2JD();
JSONArray result = accountInfo2JD.getJSONArray("result");
for (Object accountObject : result) {
JSONObject account = (JSONObject)accountObject;
// 1:汽油:2:柴油;3:天然气
if (account.getInteger("energyType") == childOrder.getGasOilType()) {
// 支付金额 大于 团油账号余额
if(order.getPayPrice().compareTo(account.getBigDecimal("accountBalance")) == 1){
log.error("OrderController --> 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", orderScene);
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()); //商户号
if (openIdType != null && openIdType.equals(2)) {
weChatPayReqInfo.setSub_appid("wxa075e8509802f826"); //商户号公众号
} else {
weChatPayReqInfo.setSub_appid(SysConst.getSysConfig().getWxSubAppId());//商户号
}
if (order.getHighChildOrderList().get(0).getGoodsType() == 8) {
weChatPayReqInfo.setSub_mch_id(SysConst.getSysConfig().getWxGzSubMchId());//商户号
} else {
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("122.9.135.148"); //终端ip
weChatPayReqInfo.setNotify_url(SysConst.getSysConfig().getNotifyUrl()); //通知url
weChatPayReqInfo.setTrade_type("JSAPI"); //交易类型
weChatPayReqInfo.setAttach(map.get("orderScene").toString());
weChatPayReqInfo.setProfit_sharing("N");
//附加数据,区分订单类型
Map<String,String> payMap = new HashMap<>();
payMap.put("app_id", weChatPayReqInfo.getSub_appid());
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="/orderToGoldPay",method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "订单支付发起金币支付")
public ResponseData orderToGoldPay(@RequestBody String reqBodyStr,HttpServletRequest request) {
try {
// 用户
SessionObject sessionObject = userCenter.getSessionObject(request);
HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();
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 password = jsonObject.getString("password");
if (orderId == null) {
log.error("orderToPay error!", "参数错误");
throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
}
// 查询用户支付密码
HighUserPayPassword userPayPassword = highUserPayPasswordService.getDetailByUser(userInfoModel.getHighUser().getId());
if (userPayPassword == null) {
log.error("orderToPay error!", "未设置支付密码");
throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_SET_USER_PAY_PWD, "");
}
if (StringUtils.isBlank(password)) {
log.error("orderToPay error!", "未输入支付密码");
throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_ENTER_USER_PAY_PWD, "");
}
// 校验支付密码是否一直
if (!AESEncodeUtil.aesEncrypt(password).equals(userPayPassword.getPassword())) {
log.error("orderToPay error!", "");
throw ErrorHelp.genException(SysCode.System, ErrorCode.USER_PAY_PWD_ERROR, "");
}
HighOrder order = highOrderService.getOrderById(orderId);
if(order == null) {
log.error("OrderController --> orderToPay() ERROR", "未找到订单信息");
throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_ORDER, "");
}
//校验订单状态 订单状态:1 待支付 2 已支付 3.已完成 4. 已退款 5.已取消
if(order.getOrderStatus() != 1) {
log.error("OrderController --> orderToPay() ERROR", "订单不处于待支付状态");
throw ErrorHelp.genException(SysCode.System, ErrorCode.ORDER_NO_STAY_PAY, "");
}
// 商品类型 1:卡卷 2:金币充值
for (HighChildOrder childOrder : order.getHighChildOrderList()) {
if (childOrder.getGoodsType() == 2) {
HighCoupon coupon = highCouponService.getCouponById(childOrder.getGoodsId());
// 支付类型:1.微信支付 2.金币支付
if (coupon.getPayType() != 2) {
log.error("OrderController --> orderToPay() ERROR", "只支持积分支付");
throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, coupon.getCouponName() + ",只支持积分支付");
}
}
}
highOrderService.goldPayOrder(order.getMemId(), order.getId());
new Thread(() -> {
// 查询订单信息
if (order == null) {
throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_ORDER, "");
}
HighUser highUser = highUserService.findByUserId(order.getMemId());
HighChildOrder presentation = highOrderService.getChildOrderByPresentation(order.getId());
WxMsgConfig.pushOneUser(
presentation.getGoodsName() + "(" + GoodsType.getNameByType(presentation.getGoodsType()) + ")",
String.valueOf(order.getPayPrice()),
order.getOrderNo(),
order.getPayTime(),
PayType.getNameByType(order.getPayType()), order.getId(),
highUser.getOpenId());
}).start();
return ResponseMsgUtil.success("支付成功");
} catch (Exception e) {
log.error("orderToPay error!", e);
return ResponseMsgUtil.exception(e);
}
}
@RequestMapping(value="/hltUnionCardPay",method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "汇联通工会卡支付")
public ResponseData hltUnionCardPay(@RequestBody String reqBodyStr,HttpServletRequest request) {
try {
// 用户
SessionObject sessionObject = userCenter.getSessionObject(request);
HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();
if (StringUtils.isBlank(reqBodyStr)) {
log.error("orderToPay error!", "参数错误");
throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
}
JSONObject jsonObject = JSONObject.parseObject(reqBodyStr);
String cardNo = jsonObject.getString("cardNo");
Long orderId = jsonObject.getLong("orderId");
String password = jsonObject.getString("password");
if (StringUtils.isBlank(cardNo) || orderId == null) {
log.error("orderToPay error!", "参数错误");
throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
}
// 查询用户支付密码
HighUserPayPassword userPayPassword = highUserPayPasswordService.getDetailByUser(userInfoModel.getHighUser().getId());
if (userPayPassword == null) {
log.error("orderToPay error!", "未设置支付密码");
throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_SET_USER_PAY_PWD, "");
}
if (StringUtils.isBlank(password)) {
log.error("orderToPay error!", "未输入支付密码");
throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_ENTER_USER_PAY_PWD, "");
}
// 校验支付密码是否一直
if (!AESEncodeUtil.aesEncrypt(password).equals(userPayPassword.getPassword())) {
log.error("orderToPay error!", "");
throw ErrorHelp.genException(SysCode.System, ErrorCode.USER_PAY_PWD_ERROR, "");
}
// 查询用户与卡号的关系
HighUserCard userCard = highUserCardService.getDetailByUserCardNo(userInfoModel.getHighUser().getId(), cardNo);
if (userCard == null) {
log.error("OrderController --> orderToPay() ERROR", "未绑定卡号");
throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未绑定卡号");
}
HighOrder order = highOrderService.getOrderById(orderId);
if(order == null) {
log.error("OrderController --> orderToPay() ERROR", "未找到订单信息");
throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_ORDER, "");
}
//校验订单状态 订单状态:1 待支付 2 已支付 3.已完成 4. 已退款 5.已取消
if(order.getOrderStatus() != 1) {
log.error("OrderController --> orderToPay() ERROR", "订单不处于待支付状态");
throw ErrorHelp.genException(SysCode.System, ErrorCode.ORDER_NO_STAY_PAY, "");
}
/* // 商品类型 1:卡卷 2:金币充值
for (HighChildOrder childOrder : order.getHighChildOrderList()) {
if (childOrder.getGoodsType() == 2) {
HighCoupon coupon = highCouponService.getCouponById(childOrder.getGoodsId());
// 支付类型:1.微信支付 2.金币支付
if (coupon.getPayType() != 2) {
log.error("OrderController --> orderToPay() ERROR", "只支持积分支付");
throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, coupon.getCouponName() + ",只支持积分支付");
}
}
}*/
highOrderService.hltUnionCardPay(userCard.getId(), order.getId());
new Thread(() -> {
// 查询订单信息
if (order == null) {
throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_ORDER, "");
}
HighUser highUser = highUserService.findByUserId(order.getMemId());
HighChildOrder presentation = highOrderService.getChildOrderByPresentation(order.getId());
WxMsgConfig.pushOneUser(
presentation.getGoodsName() + "(" + GoodsType.getNameByType(presentation.getGoodsType()) + ")",
String.valueOf(order.getPayPrice()),
order.getOrderNo(),
order.getPayTime(),
PayType.getNameByType(order.getPayType()), order.getId(),
highUser.getOpenId());
}).start();
return ResponseMsgUtil.success("支付成功");
} catch (Exception e) {
log.error("orderToPay error!", e);
return ResponseMsgUtil.exception(e);
}
}
@RequestMapping(value="/unionPay",method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "银联支付")
public ResponseData unionPay(@RequestBody String reqBodyStr,HttpServletRequest request) {
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");
if ( orderId == null) {
log.error("orderToPay error!", "参数错误");
throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
}
HighOrder order = highOrderService.getOrderById(orderId);
if(order == null) {
log.error("OrderController --> orderToPay() ERROR", "未找到订单信息");
throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_ORDER, "");
}
//校验订单状态 订单状态:1 待支付 2 已支付 3.已完成 4. 已退款 5.已取消
if(order.getOrderStatus() != 1) {
log.error("OrderController --> orderToPay() ERROR", "订单不处于待支付状态");
throw ErrorHelp.genException(SysCode.System, ErrorCode.ORDER_NO_STAY_PAY, "");
}
// 商品类型 1:卡卷 2:金币充值 3:加油站
for (HighChildOrder childOrder : order.getHighChildOrderList()) {
if (childOrder.getGiveawayType() == false && childOrder.getGoodsType() == 1) {
HighCoupon coupon = highCouponService.getCouponById(childOrder.getGoodsId());
// 支付类型:1.微信支付 2.金币支付
// if (coupon.getPayType() != 1) {
// log.error("OrderController --> orderToPay() ERROR", "只支持微信支持");
// throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, coupon.getCouponName() + ",只支持微信支付");
// }
}
if (childOrder.getGoodsType() == 3) {
// 查询账号余额
JSONObject accountInfo2JD = TuanYouConfig.queryCompanyAccountInfo2JD();
JSONArray result = accountInfo2JD.getJSONArray("result");
for (Object accountObject : result) {
JSONObject account = (JSONObject)accountObject;
// 1:汽油:2:柴油;3:天然气
if (account.getInteger("energyType") == childOrder.getGasOilType()) {
// 支付金额 大于 团油账号余额
if(order.getPayPrice().compareTo(account.getBigDecimal("accountBalance")) == 1){
log.error("OrderController --> orderToPay() ERROR", "无法进行支付,请联系平台客服");
throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "无法进行支付,请联系平台客服");
}
}
}
}
}
return ResponseMsgUtil.success(unionPayConfig.upPreOrder(UnionPayConfig.MER_ID3, UnionPayConfig.TERM_ID3, order.getOrderNo(), order.getPayPrice(), "购买商品", CommonSysConst.getSysConfig().getUnionPayNotifyUrl(), request));
} catch (Exception e) {
log.error("orderToPay error!", e);
return ResponseMsgUtil.exception(e);
}
}
@RequestMapping(value="/unionStagingPay",method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "银联分期支付")
public ResponseData unionStagingPay(@RequestBody String reqBodyStr,HttpServletRequest request) {
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");
if ( orderId == null) {
log.error("orderToPay error!", "参数错误");
throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
}
HighOrder order = highOrderService.getOrderById(orderId);
if(order == null) {
log.error("OrderController --> orderToPay() ERROR", "未找到订单信息");
throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_ORDER, "");
}
//校验订单状态 订单状态:1 待支付 2 已支付 3.已完成 4. 已退款 5.已取消
if(order.getOrderStatus() != 1) {
log.error("OrderController --> orderToPay() ERROR", "订单不处于待支付状态");
throw ErrorHelp.genException(SysCode.System, ErrorCode.ORDER_NO_STAY_PAY, "");
}
// 商品类型 1:卡卷 2:金币充值 3:加油站
for (HighChildOrder childOrder : order.getHighChildOrderList()) {
if (childOrder.getGiveawayType() == false && childOrder.getGoodsType() == 1) {
// 卡券详情
HighCoupon coupon = highCouponService.getCouponById(childOrder.getGoodsId());
if (coupon == null) {
log.error("OrderController --> orderToPay() ERROR", "只支持微信支持");
throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, coupon.getCouponName() + ",只支持微信支付");
}
}
}
String orgTrace = CommonSysConst.getSysConfig().getUnionStagingPayOrgId().substring(0,4)
+CommonSysConst.getSysConfig().getUnionStagingPayOrgId().substring(CommonSysConst.getSysConfig().getUnionStagingPayOrgId().length() - 4,CommonSysConst.getSysConfig().getUnionStagingPayOrgId().length())
+ DateUtil.format(new Date(), DateUtil.YMDHMS)
+ IDGenerator.nextId(6);
order.setPaySerialNo(orgTrace);
highOrderService.updateOrderDetail(order);
return ResponseMsgUtil.success(unionStagingPayConfig.advancePay(order.getPaySerialNo(),order.getPaySerialNo(),order.getPayPrice(), "",request));
} catch (Exception e) {
log.error("orderToPay error!", e);
return ResponseMsgUtil.exception(e);
}
}
@RequestMapping(value="/qzOrderToPay",method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "千猪订单支付发起支付")
public ResponseData qzOrderToPay(@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);
String orderNo = jsonObject.getString("orderNo");
String source = jsonObject.getString("source");
String openId = jsonObject.getString("openId");
if (StringUtils.isBlank(orderNo) || StringUtils.isBlank(source) || StringUtils.isBlank(openId)) {
log.error("orderToPay error!", "参数错误");
throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
}
// 组装千猪订单
HighOrder qzOrder = highQzOrderService.assemblyQzOrder(orderNo, source);
if (qzOrder != null) {
Map<String,Object> map = new HashMap<>();
map.put("orderNo", qzOrder.getOrderNo());
map.put("payPrice", qzOrder.getPayPrice());
map.put("orderScene", source);
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();
// int total_fee = 1;
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("N");
//附加数据,区分订单类型
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);
}
throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的订单号");
} catch (Exception e) {
log.error("orderToPay error!", e);
return ResponseMsgUtil.exception(e);
}
}
@RequestMapping(value="/orderToH5Pay",method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "H5订单下单")
public ResponseData orderToH5Pay(@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");
if ( orderId == null) {
log.error("orderToPay error!", "参数错误");
throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
}*/
//微信支付
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();
int total_fee = MathUtils.objectConvertBigDecimal(1).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.setNonce_str(nonce_str); //随机字符串
weChatPayReqInfo.setBody("购买商品"); //商品描述
weChatPayReqInfo.setOut_trade_no(String.valueOf(new Date().getTime())); //商户订单号
weChatPayReqInfo.setTotal_fee(total_fee); //总金额
weChatPayReqInfo.setSpbill_create_ip("139.159.177.244"); //终端ip
weChatPayReqInfo.setNotify_url(SysConst.getSysConfig().getNotifyUrl()); //通知url
weChatPayReqInfo.setTrade_type("MWEB"); //交易类型
//weChatPayReqInfo.setAttach(map.get("orderScene").toString()); //附加数据,区分订单类型
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);
/*1·
Map<String,Object> param = new HashMap<>();
param.put("appid", SysConst.getSysConfig().getWxMchAppId());
param.put("mchid", SysConst.getSysConfig().getWxSubMchId());
param.put("description", "购买商品");
param.put("out_trade_no", String.valueOf(new Date().getTime()));
param.put("notify_url", SysConst.getSysConfig().getNotifyUrl());
Map<String,Object> amountMap = new HashMap<>();
amountMap.put("total", 1);
param.put("amount", amountMap);
Map<String,Object> sceneInfoMap = new HashMap<>();
sceneInfoMap.put("payer_client_ip", "127.0.0.1");
Map<String,Object> h5InfoMap = new HashMap<>();
h5InfoMap.put("type", "Wap");
sceneInfoMap.put("h5_info", h5InfoMap);
param.put("scene_info", sceneInfoMap);
Map<String,Object> header = new HashMap<>();
String post = getToken("POST", "/v3/pay/transactions/h5", JSONObject.toJSONString(param));
header.put("Accept","application/json");
header.put("Authorization", "WECHATPAY2-SHA256-RSA2048 " + post);
JSONObject object = HttpsUtils.doPost("https://api.mch.weixin.qq.com/v3/pay/transactions/h5", param, header);
return ResponseMsgUtil.success(object);*/
} catch (Exception e) {
log.error("orderToPay error!", e);
return ResponseMsgUtil.exception(e);
}
}
String getToken(String method, String url, String body) throws UnsupportedEncodingException, SignatureException, NoSuchAlgorithmException, InvalidKeyException, FileNotFoundException {
long timeMillis = System.currentTimeMillis();
String nonceStr = String.valueOf(timeMillis);
long timestamp = System.currentTimeMillis() / 1000;
String message = buildMessage(method, url, timestamp, nonceStr, body);
PrivateKey privateKey = PemUtil.loadPrivateKey(new FileInputStream("G:/hurui-project/hai-parent/hai-cweb/src/main/resources/privatekey/apiclient_key.pem"));
String signature = sign(privateKey,message.getBytes("utf-8"));
return "mchid=\"" + SysConst.getSysConfig().getWxSubMchId() + "\","
+ "nonce_str=\"" + nonceStr + "\","
+ "timestamp=\"" + timestamp + "\","
+ "serial_no=\"" + "1B08DC2A078B0B1F77A65C97C445AAD545B5EAA6" + "\","
+ "signature=\"" + signature + "\"";
}
String sign(PrivateKey privateKey,byte[] message) throws SignatureException, NoSuchAlgorithmException, InvalidKeyException {
Signature sign = Signature.getInstance("SHA256withRSA");
sign.initSign(privateKey);
sign.update(message);
return Base64.getEncoder().encodeToString(sign.sign());
}
String buildMessage(String method, String url, long timestamp, String nonceStr, String body) {
return method + ""
+ url + ""
+ timestamp + ""
+ nonceStr + ""
+ body + "";
}
}