private static final String wechatPay = "https://api.mch.weixin.qq.com/pay/unifiedorder";
// 沙箱
// private static final String wechatPay = "https://api.mch.weixin.qq.com/sandboxnew/pay/unifiedorder";
/**
* 微信支付创建支付订单
*/
@Override
public ResultMsg preparePayment(BaseController ctrl, TblOrder pay) {
logger.info("启动微信支付:" + pay.getPayNo());
// 生成参数
HashMap<String, String> params = new HashMap<>();
params.put("appid", PropKit.get("wechat.appId"));
params.put("body", "M币");
params.put("mch_id", PropKit.get("wechat.mchId"));
params.put("nonce_str", StringUtils.getRandomTimeString("WXPAY"));
params.put("notify_url", PropKit.get("wechat.notifyUrl"));
logger.info("notify_url:" + params.get("notify_url"));
params.put("out_trade_no", pay.getPayNo());
params.put("spbill_create_ip", PropKit.get("server-ip"));
// params.put("fee_type", "CNY");
params.put("total_fee", String.valueOf(pay.getAmount().multiply(BigDecimal.valueOf(100)).intValue()));
// params.put("total_fee", "1");
params.put("trade_type", "APP");
// 微信支付封装XML格式
String xml = null;
try {
// 封装微信支付所需参数进行加密支付
xml = WeChatPayUtils.generateSignedXml(params, PropKit.get("wechat.appSecret"));
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// 请求预付单id
OkHttpClient client = new OkHttpClient();
// 微信支付回调地址
Request requestOkhttp = new Request.Builder().url(wechatPay)
.post(RequestBody.create(MediaType.parse("application/xml"), xml)).build();
Call call = client.newCall(requestOkhttp);
String result = null;
try {
result = call.execute().body().string();
} catch (IOException e) {
e.printStackTrace();
}
// XML转String格式
Map<String, String> resultMap = null;
try {
resultMap = WeChatPayUtils.xmlToMap(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 创建返回信息
ResultMsg msg = null;
// 取得预付单id
if (resultMap.containsKey("result_code") && resultMap.containsKey("return_code")
&& resultMap.containsKey("prepay_id")) {
String return_code = resultMap.get("return_code");
String result_code = resultMap.get("result_code");
if ("SUCCESS".equals(result_code) && "SUCCESS".equals(return_code)) {
// 取得prepare_id
String prepay_id = resultMap.get("prepay_id");
logger.info("prepay_id:{}", prepay_id);
SortedMap<String, String> orderInfoMap = new TreeMap<>();
orderInfoMap.put("appid", PropKit.get("wechat.appId"));
orderInfoMap.put("partnerid", PropKit.get("wechat.mchId"));
orderInfoMap.put("prepayid", prepay_id);
orderInfoMap.put("noncestr", System.currentTimeMillis() + "");
orderInfoMap.put("package", "Sign=WXPay");
orderInfoMap.put("timestamp", System.currentTimeMillis() / 1000 + "");
// 生成订单信息签名
String signUpdate = null;
try {
// 订单签名生成加密
signUpdate = WeChatPayUtils.generateSignature(orderInfoMap, PropKit.get("wechat.appSecret"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
orderInfoMap.put("sign", signUpdate);
// 预支付订单信息返回
String reJson = JSON.toJSONString(orderInfoMap);
msg = ResultMsg.success(reJson);
// return JSON.toJSONString(orderInfoMap);
} else {
String error = resultMap.get("return_msg");
msg = ResultMsg.error(error);
}
} else {
// 微信支付错误
msg = ResultMsg.error("no result");
logger.info("微信支付预支付失败:" + "no result");
}
// if (result.containsKey("return_code") == false || !"SUCCESS".equals(result.get("return_code"))){
// String error = result.get("return_msg");
// msg = ResultMsg.error(error);
// logger.info("微信支付预支付失败:" + error);
// }
// // 生成APP调用信息
// String prepay_id = result.get("prepay_id");
// //封装调起微信支付的参数 https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_12
// Map<String, String> packageParams = new HashMap<String, String>();
// packageParams.put("appid", PropKit.get("wechat.appId"));
// packageParams.put("partnerid", PropKit.get("wechat.mchId"));
// packageParams.put("prepayid", prepay_id);
// packageParams.put("package", "Sign=WXPay");
// packageParams.put("noncestr", System.currentTimeMillis() + "");
// packageParams.put("timestamp", System.currentTimeMillis() / 1000 + "");
// String packageSign = PaymentKit.createSign(packageParams, PropKit.get("wechat.mchSecret"));
// packageParams.put("sign", packageSign);
// msg = ResultMsg.success(packageParams);
// 返回
return msg;
}
/**
* 微信查询支付状态
*/
@Override
public ResultMsg checkPaymentResult(TblOrder pay) {
String appid = PropKit.get("wechat.appId");
String mch_id = PropKit.get("wechat.mchId");
String paternerKey = PropKit.get("wechat.appSecret");
String out_trade_no = pay.getPayNo();
//根据商户订单号查询信息
Map<String, String> map = PaymentApi.queryByOutTradeNo(appid, mch_id, paternerKey, out_trade_no);
//根据微信状态码进行订单判断处理
if (map.containsKey("return_code") && "SUCCESS".equals(map.get("return_code"))) {
if (map.containsKey("result_code") && "SUCCESS".equals(map.get("result_code"))) {
if (map.containsKey("trade_state") && "SUCCESS".equals(map.get("trade_state"))) {
String totalFee = map.get("total_fee");
// 取得价格
BigDecimal realFee = new BigDecimal(totalFee);
realFee = realFee.divide(new BigDecimal(100));
realFee = realFee.setScale(2, BigDecimal.ROUND_FLOOR);
// 取得订单好
String bussinessNo = map.get("transaction_id");
String openId = map.get("openid");
// 保存
pay.setRealAmount(realFee);
pay.setBussinessNo(bussinessNo);
pay.setOpenId(openId);
pay.setState(1);
// pay.setBussinessNo(map.get("transaction_id"));
pay.setNotifyJson(JSONObject.toJSONString(map));
pay.update();
return ResultMsg.success(pay);
} else {
// 没有成功
pay.setState(-1);
pay.update();
return ResultMsg.error(map.get("trade_state_desc"));
}
}
}
return ResultMsg.error("查询订单失败,请稍后再试");
}
/**
* 微信支付回调
*/
@SkipJWTCheck
public void wxPayNotify() {
String xmlMsg = HttpKit.readData(getRequest());
logger.info("xmlMsg=============================" + xmlMsg);
Map<String, String> params = PaymentKit.xmlToMap(xmlMsg);
logger.info("params=============================" + params);
logger.info("out_trade_no==================================" + params.get("out_trade_no"));
String payNo = params.get("out_trade_no");
int channelType = 2;
TblOrder pay = TblOrder.dao.findById(payNo);
// 回调重复判断
if (pay.getState() == 1) {
renderJson(ResultMsg.error("订单已完成"));
return;
}
IPayChannel channel = getPayChannel(channelType);
if (channel != null) {
// 回调校验
if (!PaymentKit.verifyNotify(params, PropKit.get("wechat.appSecret"))) {
logger.info("支付回调校验失败==>{}", JSONObject.toJSONString(params));
return;
}
// 判断是否成功
if (params.containsKey("return_code") && "SUCCESS".equals(params.get("return_code"))) {
String totalFee = params.get("total_fee");
// 取得价格
BigDecimal realFee = new BigDecimal(totalFee);
realFee = realFee.divide(new BigDecimal(100));
realFee = realFee.setScale(2, BigDecimal.ROUND_FLOOR);
// 取得订单好
String bussinessNo = params.get("transaction_id");
String openId = params.get("openid");
// 保存
pay.setRealAmount(realFee);
pay.setBussinessNo(bussinessNo);
pay.setOpenId(openId);
pay.setNotifyJson(JSONObject.toJSONString(params));
pay.setState(1);
pay.update();
renderJson(
"<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
}
} else {
renderJson(ResultMsg.error("支付渠道不存在"));
}
}