IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 游戏开发 -> java版商城源码之聚合支付Spring Cloud+Spring Boot+mybatis+security+uniapp+Redis+MQ+VR全景+b2b2c多商家入驻前后端分离 -> 正文阅读

[游戏开发]java版商城源码之聚合支付Spring Cloud+Spring Boot+mybatis+security+uniapp+Redis+MQ+VR全景+b2b2c多商家入驻前后端分离

@源码地址来源: https://minglisoft.cn/honghu/business.html
package com.honghu.cloud.controller;
 
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.lang.StringUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
 
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.honghu.cloud.bean.GoldLog;
import com.honghu.cloud.bean.GoldRecord;
import com.honghu.cloud.bean.Payment;
import com.honghu.cloud.bean.PlatformPay;
import com.honghu.cloud.bean.PlatformPayFlow;
import com.honghu.cloud.code.ResponseCode;
import com.honghu.cloud.dto.CloudPurchaseOrderDto;
import com.honghu.cloud.dto.DistributionSettingDto;
import com.honghu.cloud.dto.IntegralGoodsDto;
import com.honghu.cloud.dto.IntegralGoodsOrderDto;
import com.honghu.cloud.dto.MessageDto;
import com.honghu.cloud.dto.OrderFormDto;
import com.honghu.cloud.dto.PredepositDto;
import com.honghu.cloud.dto.PredepositLogDto;
import com.honghu.cloud.dto.RushOrderformDto;
import com.honghu.cloud.dto.StoreDto;
import com.honghu.cloud.dto.SysConfigDto;
import com.honghu.cloud.dto.SysConfigExtendDto;
import com.honghu.cloud.dto.UserDto;
import com.honghu.cloud.feign.AgentProfitFeignClient;
import com.honghu.cloud.feign.CloudPurchaseOrderFeignClient;
import com.honghu.cloud.feign.DistributionOrderFeignClient;
import com.honghu.cloud.feign.DistributionProfitFeignClient;
import com.honghu.cloud.feign.DistributionSettingFeignClient;
import com.honghu.cloud.feign.HandleOrderFormFeignClient;
import com.honghu.cloud.feign.IntegralGoodsFeignClient;
import com.honghu.cloud.feign.IntegralGoodsOrderFeignClient;
import com.honghu.cloud.feign.JiguangPushFeignClient;
import com.honghu.cloud.feign.LiveOrderFeignClient;
import com.honghu.cloud.feign.MessageFeignClient;
import com.honghu.cloud.feign.OrderFormFeignClient;
import com.honghu.cloud.feign.OrderFormToolsFeignClient;
import com.honghu.cloud.feign.PinPayRecordFeignClient;
import com.honghu.cloud.feign.PredepositFeignClient;
import com.honghu.cloud.feign.PredepositLogFeignClient;
import com.honghu.cloud.feign.RushOrderFormFeignClient;
import com.honghu.cloud.feign.StoreFeignClient;
import com.honghu.cloud.feign.SysConfigFeignClient;
import com.honghu.cloud.feign.SysconrigExtendFeignClient;
import com.honghu.cloud.feign.TXTemplateFeignClient;
import com.honghu.cloud.feign.UserFeignClient;
import com.honghu.cloud.pay.alipay.services.AlipayService;
import com.honghu.cloud.pay.alipay.util.AlipayUtil;
import com.honghu.cloud.pay.bill.util.MD5Util;
import com.honghu.cloud.pay.tenpay.RequestHandler;
import com.honghu.cloud.pay.tenpay.ResponseHandler;
import com.honghu.cloud.pay.tenpay.util.Sha1Util;
import com.honghu.cloud.pay.tenpay.util.TenpayUtil;
import com.honghu.cloud.pay.unionpay.acp.sdk.SDKUtil;
import com.honghu.cloud.service.IGoldLogService;
import com.honghu.cloud.service.IGoldRecordService;
import com.honghu.cloud.service.IPaymentService;
import com.honghu.cloud.service.IPlatformPayFlowService;
import com.honghu.cloud.service.IPlatformPayService;
import com.honghu.cloud.tools.AccessTokenTools;
import com.honghu.cloud.tools.SecurityUserHolder;
import com.honghu.cloud.tools.qrcode.QRCodeUtil;
import com.honghu.cloud.utils.CommUtil;
import com.honghu.cloud.utils.tools.Md5Encrypt;
 
import lombok.extern.log4j.Log4j;
import net.sf.json.JSONObject;
 
/**
 * 
 * <p>
 * Title: HongHuPayViewAction.java
 * </p>
 * 
 * <p>
 * Description:在线支付回调控制器,处理系统支持的所有支付方式回调业务处理,包括支付宝、财付通、快钱、paypal、网银在线
 * </p>
 * 
 * <p>
 * Copyright: Copyright (c) 2015
 * </p>
 * 
 * <p>
 * Company: www.minglisoft.cn
 * </p>
 * 
 * @author honghu
 * 
 * @date 2014-5-25
 * 
 * @version honghu_b2b2c v8.0 2016版
 */
@SuppressWarnings({ "unchecked", "rawtypes", "unused" })
@RestController
@Log4j
@RequestMapping(value = "/pay")
public class PayController {
 
	private static final Logger logger = LoggerFactory.getLogger(PayController.class);
	
	@Autowired
	private SysConfigFeignClient sysConfigFeignClient;
	@Autowired
	private OrderFormFeignClient orderFormFeignClient;
	@Autowired
	private PredepositLogFeignClient predepositLogFeignClient;
	@Autowired
	private PredepositFeignClient predepositFeignClient;
	@Autowired
	private IPaymentService paymentService;
	@Autowired
	private CloudPurchaseOrderFeignClient cloudPurchaseOrderFeignClient;
	@Autowired
	private IntegralGoodsOrderFeignClient integralGoodsOrderFeignClient;
	@Autowired
	private RushOrderFormFeignClient rushOrderFormFeignClient;
 
	@Autowired
	private UserFeignClient userFeignClient;
	@Autowired
	private IGoldRecordService goldRecordService;
	@Autowired
	private IGoldLogService goldLogService;
	@Autowired
	private HandleOrderFormFeignClient handleOrderFormFeignClient;
	@Autowired
	private OrderFormToolsFeignClient orderFormToolsFeignClient;
	@Autowired
	private IntegralGoodsFeignClient integralGoodsFeignClient;
	@Autowired
	private PinPayRecordFeignClient pinPayRecordFeignClient;
	@Autowired
	private DistributionOrderFeignClient distributionOrderFeignClient;
	@Autowired
	private SysconrigExtendFeignClient sysconrigExtendFeignClient;
	@Autowired
	private IPlatformPayService platformPayService;
	@Autowired
	private IPlatformPayFlowService platformPayFlowService;
	@Autowired
	private StoreFeignClient storeFeignClient;
	@Autowired
	private LiveOrderFeignClient liveOrderFeignClient;
	@Autowired
	private MessageFeignClient messageFeignClient;
	@Autowired
	private DistributionProfitFeignClient distributionProfitFeignClient;
	@Autowired
	private DistributionSettingFeignClient distributionSettingFeignClient;
	@Autowired
	private AgentProfitFeignClient agentProfitFeignClient;
	@Autowired
	private TXTemplateFeignClient tXTemplateFeignClient;
	@Autowired
	private JiguangPushFeignClient jiguangPushFeignClient;
	@Autowired
	private AccessTokenTools accessTokenTools;
 
	@Autowired
	private AlipayService alipayService;
 
/*	@Value("${notify.url}")
	private String notify_url;
	*/
	/**
	 * 移动端订单支付详情
	 * 
	 * @param request
	 * @param response
	 * @param payType
	 * @param order_id
	 * @param order_type
	 * @param pay_password
	 * @return
	 */
	@RequestMapping(value = "/order_pay", method = RequestMethod.POST)
	public Map<String, Object> order_pay(HttpServletRequest request, HttpServletResponse response,@RequestBody JSONObject json) {
		String order_type = json.optString("order_type");
		String payType = json.optString("payType");
		Long order_id = json.optLong("order_id");
		
		UserDto user = SecurityUserHolder.getCurrentUser(request);
 
		Map<String, Object> result = new HashMap<String, Object>();
		if ("cloudpurchase".equals(order_type)) {
			CloudPurchaseOrderDto order = cloudPurchaseOrderFeignClient
					.selectByPrimaryKey(CommUtil.null2Long(order_id));
			if (order != null) {
				if ((order.getUser_id().equals(user.getId())) && (order.getStatus() == 0)) {
					if ("wx_pay".equals(payType)) {
						try {
							// TODO
							// 微信支付
							return ResponseCode
									.buildSuccessMap(wx_pay1(request, response, order_id, payType, order_type));
						} catch (Exception e) {
							log.error(e.toString());
							return ResponseCode.buildCodeMap("20008", "支付方式错误!", null);
						}
					}
					if ("wxh5_pay".equals(payType)) {
						try {
							// TODO
							// 微信支付
							return ResponseCode
									.buildSuccessMap(wxh5_pay(request, response, order_id, payType, order_type));
						} catch (Exception e) {
							log.error(e.toString());
							return ResponseCode.buildCodeMap("20008", "支付方式错误!", null);
						}
					}
					if (payType.equals("balance")) {
						double order_total_price = CommUtil.null2Double(Integer.valueOf(order.getPrice()));
						result.put("order_total_price", Double.valueOf(order_total_price));
						result.put("type", order_type);
						result.put("order_id", order_id);
						return ResponseCode.buildCodeMap("20009", "余额支付!", null);
					}
					result.put("type", "cloudpurchase");
					result.put("order_id", order.getId());
					result.put("url", CommUtil.getURL(request));
 
					Map<String, Object> params = Maps.newHashMap();
					params.put("mark", payType);
					List<Payment> payments = paymentService.queryPageList(params);
 
					if (payments.size() > 0) {
						Payment payment = payments.get(0);
						result.put("payment_id", payment.getId());
					}
					return ResponseCode.buildSuccessMap(result);
				}
			}
			return ResponseCode.buildCodeMap("20010", "订单中商品已被删除,请重新下单", null);
		}
		OrderFormDto order = orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_id));
 
		Map<Boolean, Object> map_verify = orderFormToolsFeignClient.orderForm_verify(order, user.getId());
		Iterator iterator = map_verify.keySet().iterator();
		while (iterator.hasNext()) {
			Boolean verify_result = (Boolean) iterator.next();
			if (!verify_result.booleanValue()) {
				return ResponseCode.buildFailMap("", map_verify.get(verify_result));
			}
		}
 
		int order_status = orderFormToolsFeignClient.query_order_status(CommUtil.null2String(order_id));
		if (order_status == 10) {
			if ((payType == null) || ("".equals(CommUtil.null2String(payType)))) {
				return ResponseCode.buildCodeMap("20011", "支付方式错误", null);
			}
 
			Map<String, Object> params = Maps.newHashMap();
			params.put("mark", payType);
 
			List<Payment> payments = paymentService.queryPageList(params);
 
			if (payments.size() > 0) {
				Payment payment = payments.get(0);
				order.setPayment_id(payment.getId());
				order.setPayment_mark(payment.getMark());
				order.setPayment_name(payment.getName());
			}
			order.setPayType("online");
			orderFormFeignClient.updateById(order);
 
			if (payType.equals("balance")) {
				double order_total_price = orderFormToolsFeignClient
						.query_order_pay_price(CommUtil.null2String(order_id));
				result.put("order_total_price", order_total_price);
				result.put("user", user);
			} else {
				result.put("payType", payType);
				result.put("url", CommUtil.getURL(request));
				// mv.addObject("payTools", this.payTools);
				String type = "goods";
				if (order.getOrder_cat() == 2) {
					type = "group";
				}
				result.put("type", type);
				result.put("payment_id", order.getPayment_id());
				if ("wx_pay".equals(payType)) {
					try {
						// TODO
						// 微信支付
						return ResponseCode.buildSuccessMap(wx_pay1(request, response, order_id, payType, order_type));
					} catch (Exception e) {
						log.error(e.toString());
						return ResponseCode.buildCodeMap("20011", "支付方式错误", null);
					}
				}
			}
			result.put("order", order);
			result.put("order_id", order.getId());
			result.put("user", user);
		}
		if (order_status == 11) {
			if (payType.equals("balance")) {
				double order_total_price = orderFormToolsFeignClient
						.query_order_pay_price(CommUtil.null2String(order_id));
				result.put("order_total_price", order_total_price);
				result.put("user", user);
			} else {
				result.put("payType", payType);
				result.put("url", CommUtil.getURL(request));
				// mv.addObject("payTools", this.payTools);
				String type = "goods";
				result.put("type", type);
				result.put("payment_id", order.getPayment_id());
				if ("wx_pay".equals(payType)) {
					try {
						// TODO
						// 微信支付
						return ResponseCode.buildSuccessMap(wx_pay1(request, response, order_id, payType, order_type));
					} catch (Exception e) {
						log.error(e.toString());
						return ResponseCode.buildCodeMap("20011", "支付方式错误", null);
					}
				}
			}
			result.put("order", order);
			result.put("order_id", order.getId());
			result.put("user", user);
		}
		return ResponseCode.buildSuccessMap(result);
	}
 
	/**
	 * 手机订单货到付款
	 * 
	 * @param request
	 * @param response
	 * @param order_id
	 * @param pay_msg
	 * @param pay_session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping({ "/order_pay_payafter" })
	public Map<String, Object> order_pay_payafter(HttpServletRequest request, HttpServletResponse response,
			 @RequestBody JSONObject json) throws Exception {
		String pay_session = json.optString("pay_session");
		String pay_msg = json.optString("pay_msg");
		String order_id = json.optString("order_id");
		
		Map<String, Object> result = new HashMap<String, Object>();
		String pay_session1 = CommUtil.null2String(request.getSession(false).getAttribute("pay_session"));
		if (pay_session1.equals(pay_session)) {
			OrderFormDto order = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_id));
			boolean exist = orderFormToolsFeignClient.verify_goods_exist(order);
			if (!exist) {
				return ResponseCode.buildFailMap("订单中商品已被删除,请重新下单", null);
			}
			boolean inventory_very = orderFormToolsFeignClient.verify_goods_Inventory(order);
			if (!inventory_very) {
				return ResponseCode.buildFailMap("订单中商品库存不足,请重新下单", null);
			}
			boolean ret = handleOrderFormFeignClient.payByPayafter(order, CommUtil.getURL(request), pay_msg);
			if (ret) {
				orderFormToolsFeignClient.updateGoodsInventory(order);
			}
			request.getSession(false).removeAttribute("pay_session");
			result.put("op_title", "货到付款提交成功,等待发货");
			result.put("url", CommUtil.getURL(request) + "/buyer/order_list");
		} else {
			return ResponseCode.buildFailMap("订单已经支付,禁止重复支付", null);
		}
		return ResponseCode.buildSuccessMap(result);
	}
 
	/**
	 * 支付宝在线支付成功回调控制
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 *//*
	@RequestMapping({ "/aplipay_return" })
	public Map<String, Object> aplipay_return(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		System.out.println("pc_alipay_return");
		String trade_no = request.getParameter("trade_no");
		String[] order_nos = request.getParameter("out_trade_no").split("-");
		String total_fee = request.getParameter("price");
		String subject = request.getParameter("subject");
		String order_no = order_nos[2];
		String type = CommUtil.null2String(request.getParameter("body")).trim();
		String trade_status = request.getParameter("trade_status");
		OrderFormDto main_order = null;
		PredepositDto obj = null;
		GoldRecord gold = null;
		IntegralGoodsOrderDto ig_order = null;
		CloudPurchaseOrderDto cp_order = null;
		if (type.equals("goods")) {
			main_order = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_no));
		}
		if (type.equals("cash")) {
			obj = predepositFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_no));
		}
		if (type.equals("gold")) {
			gold = this.goldRecordService.selectByPrimaryKey(CommUtil.null2Long(order_no));
		}
		if (type.equals("integral")) {
			ig_order = this.integralGoodsOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_no));
		}
		if (type.equals("group")) {
			main_order = orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_no));
		}
		if (type.equals("cloudpurchase")) {
			cp_order = this.cloudPurchaseOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_no));
		}
		Map<String, String> params = Maps.newHashMap();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}
		AlipayConfig config = new AlipayConfig();
		Payment payment = null;
		if ((type.equals("goods")) || (type.equals("group"))) {
			payment = this.paymentService.selectByPrimaryKey(main_order.getPayment_id());
			config.setKey(payment.getSafeKey());
			config.setPartner(payment.getPartner());
			config.setSeller_email(payment.getSeller_email());
		}
		if ((type.equals("cash")) || (type.equals("gold")) || (type.equals("integral"))
				|| (type.equals("cloudpurchase"))) {
			Map q_params = Maps.newHashMap();
			q_params.put("install", Boolean.valueOf(true));
			if (type.equals("cash")) {
				q_params.put("mark", obj.getPd_payment());
			}
			if (type.equals("gold")) {
				q_params.put("mark", gold.getGold_payment());
			}
			if (type.equals("integral")) {
				q_params.put("mark", ig_order.getIgo_payment());
			}
			if (type.equals("cloudpurchase")) {
				q_params.put("mark", cp_order.getPayment());
			}
			List<Payment> payments = this.paymentService.queryPageList(q_params);
			config.setKey(((Payment) payments.get(0)).getSafeKey());
			config.setPartner(((Payment) payments.get(0)).getPartner());
			config.setSeller_email(((Payment) payments.get(0)).getSeller_email());
		}
		config.setNotify_url(CommUtil.getURL(request) + "/alipay_notify");
		config.setReturn_url(CommUtil.getURL(request) + "/aplipay_return");
		boolean verify_result = AlipayNotify.verify(config, params);
		if (verify_result) {
			if (((type.equals("goods")) || (type.equals("group"))) && ((trade_status.equals("WAIT_SELLER_SEND_GOODS"))
					|| (trade_status.equals("TRADE_FINISHED")) || (trade_status.equals("TRADE_SUCCESS")))) {
				boolean flag = this.handleOrderFormFeignClient.payByOnline(main_order, trade_no,
						CommUtil.getURL(request));
				if (flag) {
					this.orderFormToolsFeignClient.updateGoodsInventory(main_order);
				}
				this.orderFormToolsFeignClient.sendMsgWhenHandleOrder(CommUtil.getURL(request), main_order,
						"tobuyer_online_pay_ok_notify", "toseller_online_pay_ok_notify");
				resultMap.put("all_price", Double.valueOf(this.orderFormToolsFeignClient
						.query_order_pay_price(CommUtil.null2String(main_order.getId()))));
				resultMap.put("obj", main_order);
			}
			if ((type.equals("cash")) && ((trade_status.equals("WAIT_SELLER_SEND_GOODS"))
					|| (trade_status.equals("TRADE_FINISHED")) || (trade_status.equals("TRADE_SUCCESS")))) {
				if (obj.getPd_pay_status() != 2) {
					obj.setPd_status(1);
					obj.setPd_pay_status(2);
					this.predepositFeignClient.updateById(obj);
					UserDto user = userFeignClient.selectByPrimaryKey(obj.getPd_user().getId());
					user.setAvailableBalance(
							BigDecimal.valueOf(CommUtil.add(user.getAvailableBalance(), obj.getPd_amount())));
					userFeignClient.updateById(user);
					PredepositLogDto log = new PredepositLogDto();
					log.setAddTime(new Date());
					log.setPd_log_amount(obj.getPd_amount());
					log.setPd_log_user(obj.getPd_user());
					log.setPd_op_type("充值");
					log.setPd_type("可用预存款");
					log.setPd_log_info("支付宝在线支付");
					this.predepositLogFeignClient.saveEntity(log);
				}
				resultMap.put("op_title", "恭喜您,成功充值" + obj.getPd_amount() + "元");
				resultMap.put("url", CommUtil.getURL(request) + "/buyer/predeposit_list");
			}
			if ((type.equals("gold")) && ((trade_status.equals("WAIT_SELLER_SEND_GOODS"))
					|| (trade_status.equals("TRADE_FINISHED")) || (trade_status.equals("TRADE_SUCCESS")))) {
				if (gold.getGold_pay_status() != 2) {
					gold.setGold_status(1);
					gold.setGold_pay_status(2);
					this.goldRecordService.updateById(gold);
					UserDto user = this.userFeignClient.selectByPrimaryKey(gold.getGold_user().getId());
					user.setGold(user.getGold() + gold.getGold_count());
					this.userFeignClient.updateById(user);
					GoldLog log = new GoldLog();
					log.setAddTime(new Date());
					log.setGl_payment(gold.getGold_payment());
					log.setGl_content("支付宝在线支付");
					log.setGl_money(gold.getGold_money());
					log.setGl_count(gold.getGold_count());
					log.setGl_type(0);
					log.setGl_user(gold.getGold_user());
					log.setGr(gold);
					this.goldLogService.saveEntity(log);
				}
				resultMap.put("op_title", "兑换" + gold.getGold_count() + "金币成功");
				resultMap.put("url", CommUtil.getURL(request) + "/seller/gold_record_list");
			}
			if ((type.equals("integral")) && ((trade_status.equals("WAIT_SELLER_SEND_GOODS"))
					|| (trade_status.equals("TRADE_FINISHED")) || (trade_status.equals("TRADE_SUCCESS")))) {
				if (ig_order.getIgo_status() < 20) {
					ig_order.setIgo_status(20);
					ig_order.setIgo_pay_time(new Date());
					ig_order.setIgo_payment("alipay");
					this.integralGoodsOrderFeignClient.updateById(ig_order);
					List<Map> ig_maps = this.orderFormToolsFeignClient
							.query_integral_goodsinfo(ig_order.getGoods_info());
					for (Map map : ig_maps) {
						IntegralGoodsDto goods = this.integralGoodsFeignClient
								.selectByPrimaryKey(CommUtil.null2Long(map.get("id")));
						goods.setIg_goods_count(
								goods.getIg_goods_count() - CommUtil.null2Int(map.get("ig_goods_count")));
						goods.setIg_exchange_count(
								goods.getIg_exchange_count() + CommUtil.null2Int(map.get("ig_goods_count")));
						this.integralGoodsFeignClient.updateById(goods);
					}
				}
				resultMap.put("obj", ig_order);
			}
			if (type.equals("cloudpurchase")) {
				if (cp_order.getStatus() < 5) {
					cp_order.setStatus(5);
					cp_order.setPayTime(new Date());
					this.cloudPurchaseOrderFeignClient.updateById(cp_order);
					this.cloudPurchaseOrderFeignClient.reduce_inventory(cp_order, request);
				}
				resultMap.put("op_title", "预付款支付成功!");
				resultMap.put("url", CommUtil.getURL(request) + "/buyer/cloudbuy_order");
			}
		} else {
			resultMap.put("op_title", "支付回调失败");
			resultMap.put("url", CommUtil.getURL(request) + "/index");
		}
		return resultMap;
	}*/
 
	/**
	 * 支付宝异步通知
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping({ "/alipay_notify" })
	public void alipay_notify(HttpServletRequest request, HttpServletResponse response) throws Exception {
		 /*
        https://xx/receive_notify.htm?notify_type=trade_status_sync&notify_id=91722adff935e8cfa58b3aabf4dead6ibe
        &notify_time=2017-02-16 21:46:15&sign_type=RSA2
        &sign=xxxxxxxxxxxxxxx&app_id=2088102146225135&trade_no=2013112011001004330000121536&out_trade_no=6823789339978248&out_biz_no=85478536823789339978248
        &buyer_logon_id=159****5620&seller_id=2088102146225135&trans_currency=USD&seller_email=aa@mail.sa.com&total_amount=120.88
        &buyer_id=2088202954065786&settle_currency=USD&settle_amount=88.88&pay_currency=CNY&pay_amount=580.04&settle_trans_rate=1
        &trans_pay_rate=6.5261&trade_status=TRADE_SUCCESS&invoice_amount=88.88&receipt_amount=88.88&point_amount=88.88&refund_fee=10.23
        &buyer_pay_amount=88.88&subject=Iphone6 16G&body=Iphone6 16G&gmt_create=2014-11-27 15:45:57&gmt_payment=2014-11-27 15:45:57
        &gmt_refund=2014-11-27 14:15:57&gmt_close=2014-11-27 17:45:57&fund_bill_list="[{\"amount\":\"10000.00\",\"fundChannel\":\"ALIPAYACCOUNT\"}]"&voucher_detail_list="[{\"id\":\"20170307000730026487005X1M6V\",\"name\":\"全仓5折优惠券\"}]"
        &discount_goods_detail="[{\"goodsId\":\"STANDARD1026181538\",\"goodsName\":\"雪碧\",\"discountAmount\":\"10.00\"}]"
        &refund_preset_paytool_list=[{"amount":"1.00","assert_type_code":"HEMA"}]&charge_amount=8.88&charge_flags=bluesea_1
        &settlement_id=2018101610032004620239146945&advance_amount=11.11&current_seller_received_amount=88.88&seller_received_total_amount=88.88
        &total_from_seller_fee=88.88&ff_current_period=1&notify_action_type=payByAccountAction/closeTradeAction/reverseAction/finishFPAction/confirmDisburseAction/financingReceiptAction
        &discount_amount=88.88&mdiscount_amount=88.88&unfreeze_amount=18.18&auth_trade_pay_mode=CREDIT_PREAUTH_PAY
        &passback_params=merchantBizType%3d3C%26merchantBizNo%3d2016010101111&hb_fq_pay_info={"USER_INSTALL_NUM":"3"}&receipt_currency_type=DC
         */
 
 
		//获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			//乱码解决,这段代码在出现乱码时使用。
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
 
 
		//String sign = request.getParameter("sign");
		String passbackParamsUnCode = request.getParameter("passback_params");
		String passbackParams = java.net.URLDecoder.decode(passbackParamsUnCode);
 
		String[] attachs = passbackParams.split("_");
		String type = attachs[3];
		//支付方式  因为付方式是"alipay_app" 形式 故pay_type为attachs[4]+"_"+attachs[5]
		String pay_type = attachs[4] + "_" + attachs[5];
		System.out.println("返回的pay_type:" + pay_type);
 
 
 
		Map<String, Object> pay_type_params = Maps.newHashMap();
		pay_type_params.put("mark", pay_type);
		List<Payment> payments =   this.paymentService.queryPageList(pay_type_params);
 
		log.info("----异步通知参数 开始 ------");
		log.info(params.toString());
		log.info("----异步通知参数 结束 ------");
		if (null == payments || payments.size() < 1) {
			log.error("支付异步通知失败");
 
			response.setContentType("text/plain");
			response.setHeader("Cache-Control", "no-cache");
			response.setCharacterEncoding("UTF-8");
			try {
				PrintWriter writer = response.getWriter();
				writer.print("fail");
			} catch (IOException e) {
				log.error(e.toString());
			}
 
			return;
		}
		Payment payment = payments.get(0);
 
		//
		if (AlipayUtil.validateSign(params, payment.getApp_public_key())) {
			log.info("回調验签成功");
			afterNotifyOrderHandling_alipay(request, payment, type, attachs);
 
			response.setContentType("text/plain");
			response.setHeader("Cache-Control", "no-cache");
			response.setCharacterEncoding("UTF-8");
			try {
				PrintWriter writer = response.getWriter();
				writer.print("success");
			} catch (IOException e) {
				log.error(e.toString());
			}
 
		} else {
			log.info("回調验签失败");
			response.setContentType("text/plain");
			response.setHeader("Cache-Control", "no-cache");
			response.setCharacterEncoding("UTF-8");
			try {
				PrintWriter writer = response.getWriter();
				writer.print("fail");
			} catch (IOException e) {
				log.error(e.toString());
			}
		}
	}
 
	/**
	 * 快钱在线支付回调处理控制
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping({ "/bill_return" })
	public Map<String, Object> bill_return(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String ext1 = request.getParameter("ext1").trim();
		String ext2 = CommUtil.null2String(request.getParameter("ext2").trim());
		OrderFormDto order = null;
		PredepositDto obj = null;
		GoldRecord gold = null;
		IntegralGoodsOrderDto ig_order = null;
		CloudPurchaseOrderDto cp_order = null;
		if ((ext2.equals("goods")) || (ext2.equals("group"))) {
			order = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(ext1));
		}
		if (ext2.equals("cash")) {
			obj = this.predepositFeignClient.selectByPrimaryKey(CommUtil.null2Long(ext1));
		}
		if (ext2.equals("gold")) {
			gold = this.goldRecordService.selectByPrimaryKey(CommUtil.null2Long(ext1));
		}
		if (ext2.equals("integral")) {
			ig_order = this.integralGoodsOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(ext1));
		}
		if (ext2.equals("cloudpurchase")) {
			cp_order = this.cloudPurchaseOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(ext1));
		}
		String merchantAcctId = request.getParameter("merchantAcctId").trim();
 
		String key = "";
		Payment payment = null;
		if ((ext2.equals("goods")) || (ext2.equals("group"))) {
			payment = this.paymentService.selectByPrimaryKey(order.getPayment_id());
			key = payment.getRmbKey();
		}
		if ((ext2.equals("cash")) || (ext2.equals("gold")) || (ext2.equals("integral"))
				|| (ext2.equals("cloudpurchase"))) {
			Map q_params = Maps.newHashMap();
			q_params.put("install", Boolean.valueOf(true));
			if (ext2.equals("cash")) {
				q_params.put("mark", obj.getPd_payment());
			}
			if (ext2.equals("gold")) {
				q_params.put("mark", gold.getGold_payment());
			}
			if (ext2.equals("integral")) {
				q_params.put("mark", ig_order.getIgo_payment());
			}
			if (ext2.equals("cloudpurchase")) {
				q_params.put("mark", cp_order.getPayment());
			}
 
			List<Payment> payments = this.paymentService.queryPageList(q_params);
 
			key = ((Payment) payments.get(0)).getRmbKey();
		}
		String version = request.getParameter("version").trim();
 
		String language = request.getParameter("language").trim();
 
		String signType = request.getParameter("signType").trim();
 
		String payType = request.getParameter("payType").trim();
 
		String bankId = request.getParameter("bankId").trim();
 
		String orderId = request.getParameter("orderId").trim();
 
		String orderTime = request.getParameter("orderTime").trim();
 
		String orderAmount = request.getParameter("orderAmount").trim();
 
		String dealId = request.getParameter("dealId").trim();
 
		String bankDealId = request.getParameter("bankDealId").trim();
 
		String dealTime = request.getParameter("dealTime").trim();
 
		String payAmount = request.getParameter("payAmount").trim();
 
		String fee = request.getParameter("fee").trim();
 
		String payResult = request.getParameter("payResult").trim();
 
		String errCode = request.getParameter("errCode").trim();
 
		String signMsg = request.getParameter("signMsg").trim();
 
		String merchantSignMsgVal = "";
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "merchantAcctId", merchantAcctId);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "version", version);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "language", language);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "signType", signType);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "payType", payType);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "bankId", bankId);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderId", orderId);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderTime", orderTime);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderAmount", orderAmount);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "dealId", dealId);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "bankDealId", bankDealId);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "dealTime", dealTime);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "payAmount", payAmount);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "fee", fee);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "ext1", ext1);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "ext2", ext2);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "payResult", payResult);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "errCode", errCode);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "key", key);
 
		String merchantSignMsg = MD5Util.md5Hex(merchantSignMsgVal.getBytes("utf-8")).toUpperCase();
		if (signMsg.toUpperCase().equals(merchantSignMsg.toUpperCase())) {
			switch (Integer.parseInt(payResult)) {
			case 10:
				if ((ext2.equals("goods")) || (ext2.equals("group"))) {
					boolean flag = this.handleOrderFormFeignClient.payByOnline(order, "", CommUtil.getURL(request));
					if (flag) {
						this.orderFormToolsFeignClient.updateGoodsInventory(order);
					}
					this.orderFormToolsFeignClient.sendMsgWhenHandleOrder(CommUtil.getURL(request), order,
							"tobuyer_online_pay_ok_notify", "toseller_online_pay_ok_notify");
					resultMap.put("all_price", Double.valueOf(
							this.orderFormToolsFeignClient.query_order_pay_price(CommUtil.null2String(order.getId()))));
					resultMap.put("obj", order);
				}
				if (ext2.equals("cash")) {
					if (obj.getPd_pay_status() < 2) {
						obj.setPd_status(1);
						obj.setPd_pay_status(2);
						this.predepositFeignClient.updateById(obj);
						UserDto user = this.userFeignClient.selectByPrimaryKey(obj.getPd_user().getId());
						user.setAvailableBalance(
								BigDecimal.valueOf(CommUtil.add(user.getAvailableBalance(), obj.getPd_amount())));
						this.userFeignClient.updateById(user);
						PredepositLogDto log = new PredepositLogDto();
						log.setAddTime(new Date());
						log.setPd_log_amount(obj.getPd_amount());
						log.setPd_log_user(obj.getPd_user());
						log.setPd_op_type("充值");
						log.setPd_type("可用预存款");
						log.setPd_log_info("快钱在线支付");
						this.predepositLogFeignClient.saveEntity(log);
					}
 
					resultMap.put("op_title", "充值" + obj.getPd_amount() + "成功");
					resultMap.put("url", CommUtil.getURL(request) + "/buyer/predeposit_list");
				}
				if (ext2.equals("gold")) {
					if (gold.getGold_pay_status() < 2) {
						gold.setGold_status(1);
						gold.setGold_pay_status(2);
						this.goldRecordService.updateById(gold);
						UserDto user = this.userFeignClient.selectByPrimaryKey(gold.getGold_user().getId());
						user.setGold(user.getGold() + gold.getGold_count());
						this.userFeignClient.updateById(user);
						GoldLog log = new GoldLog();
						log.setAddTime(new Date());
						log.setGl_payment(gold.getGold_payment());
						log.setGl_content("快钱在线支付");
						log.setGl_money(gold.getGold_money());
						log.setGl_count(gold.getGold_count());
						log.setGl_type(0);
						log.setGl_user(gold.getGold_user());
						log.setGr(gold);
						this.goldLogService.saveEntity(log);
					}
 
					resultMap.put("op_title", "兑换" + gold.getGold_count() + "金币成功");
					resultMap.put("url", CommUtil.getURL(request) + "/seller/gold_record_list");
				}
				if (ext2.equals("integral")) {
					if (ig_order.getIgo_status() < 20) {
						ig_order.setIgo_status(20);
						ig_order.setIgo_pay_time(new Date());
						ig_order.setIgo_payment("bill");
						this.integralGoodsOrderFeignClient.updateById(ig_order);
						List<Map> ig_maps = this.orderFormToolsFeignClient
								.query_integral_goodsinfo(ig_order.getGoods_info());
						for (Map map : ig_maps) {
							IntegralGoodsDto goods = this.integralGoodsFeignClient
									.selectByPrimaryKey(CommUtil.null2Long(map.get("id")));
							goods.setIg_goods_count(
									goods.getIg_goods_count() - CommUtil.null2Int(map.get("ig_goods_count")));
							goods.setIg_exchange_count(
									goods.getIg_exchange_count() + CommUtil.null2Int(map.get("ig_goods_count")));
							this.integralGoodsFeignClient.updateById(goods);
						}
					}
 
					resultMap.put("obj", ig_order);
				}
				if (!ext2.equals("cloudpurchase")) {
					break;
				}
				if (cp_order.getStatus() < 5) {
					cp_order.setStatus(5);
					cp_order.setPayTime(new Date());
					this.cloudPurchaseOrderFeignClient.updateById(cp_order);
					this.cloudPurchaseOrderFeignClient.reduce_inventory(cp_order, request);
				}
				resultMap.put("op_title", "预付款支付成功!");
				resultMap.put("url", CommUtil.getURL(request) + "/buyer/cloudbuy_order");
 
				break;
			default:
				resultMap.put("op_title", "快钱支付失败!");
				resultMap.put("url", CommUtil.getURL(request) + "/index");
 
				break;
			}
		} else {
 
			resultMap.put("op_title", "快钱支付失败!");
			resultMap.put("url", CommUtil.getURL(request) + "/index");
		}
		return resultMap;
	}
 
	public String appendParam(String returnStr, String paramId, String paramValue) {
		if (!returnStr.equals("")) {
			if (!paramValue.equals("")) {
				returnStr = returnStr + "&" + paramId + "=" + paramValue;
			}
		} else if (!paramValue.equals("")) {
			returnStr = paramId + "=" + paramValue;
		}
		return returnStr;
	}
 
	/**
	 * 快钱异步回调处理,如果同步回调出错,异步回调会弥补该功能
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping({ "/bill_notify_return" })
	public void bill_notify_return(HttpServletRequest request, HttpServletResponse response) throws Exception {
		int rtnOK = 0;
 
		String ext1 = request.getParameter("ext1").trim();
		String ext2 = CommUtil.null2String(request.getParameter("ext2").trim());
		OrderFormDto order = null;
		PredepositDto obj = null;
		GoldRecord gold = null;
		IntegralGoodsOrderDto ig_order = null;
		CloudPurchaseOrderDto cp_order = null;
		if ((ext2.equals("goods")) || (ext2.equals("group"))) {
			order = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(ext1));
		}
		if (ext2.equals("cash")) {
			obj = this.predepositFeignClient.selectByPrimaryKey(CommUtil.null2Long(ext1));
		}
		if (ext2.equals("gold")) {
			gold = this.goldRecordService.selectByPrimaryKey(CommUtil.null2Long(ext1));
		}
		if (ext2.equals("integral")) {
			ig_order = this.integralGoodsOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(ext1));
		}
		if (ext2.equals("cloudpurchase")) {
			cp_order = this.cloudPurchaseOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(ext1));
		}
		String merchantAcctId = request.getParameter("merchantAcctId").trim();
 
		String key = "";
		Payment payment = null;
		if ((ext2.equals("goods")) || (ext2.equals("group"))) {
			payment = this.paymentService.selectByPrimaryKey(order.getPayment_id());
			key = payment.getRmbKey();
		}
		if ((ext2.equals("cash")) || (ext2.equals("gold")) || (ext2.equals("integral"))
				|| (ext2.equals("cloudpurchase"))) {
			Map q_params = Maps.newHashMap();
			q_params.put("install", Boolean.valueOf(true));
			if (ext2.equals("cash")) {
				q_params.put("mark", obj.getPd_payment());
			}
			if (ext2.equals("gold")) {
				q_params.put("mark", gold.getGold_payment());
			}
			if (ext2.equals("integral")) {
				q_params.put("mark", ig_order.getIgo_payment());
			}
			if (ext2.equals("cloudpurchase")) {
				q_params.put("mark", cp_order.getPayment());
			}
 
			List<Payment> payments = this.paymentService.queryPageList(q_params);
 
			key = ((Payment) payments.get(0)).getRmbKey();
		}
		String version = request.getParameter("version").trim();
 
		String language = request.getParameter("language").trim();
 
		String signType = request.getParameter("signType").trim();
 
		String payType = request.getParameter("payType").trim();
 
		String bankId = request.getParameter("bankId").trim();
 
		String orderId = request.getParameter("orderId").trim();
 
		String orderTime = request.getParameter("orderTime").trim();
 
		String orderAmount = request.getParameter("orderAmount").trim();
 
		String dealId = request.getParameter("dealId").trim();
 
		String bankDealId = request.getParameter("bankDealId").trim();
 
		String dealTime = request.getParameter("dealTime").trim();
 
		String payAmount = request.getParameter("payAmount").trim();
 
		String fee = request.getParameter("fee").trim();
 
		String payResult = request.getParameter("payResult").trim();
 
		String errCode = request.getParameter("errCode").trim();
 
		String signMsg = request.getParameter("signMsg").trim();
 
		String merchantSignMsgVal = "";
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "merchantAcctId", merchantAcctId);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "version", version);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "language", language);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "signType", signType);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "payType", payType);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "bankId", bankId);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderId", orderId);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderTime", orderTime);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderAmount", orderAmount);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "dealId", dealId);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "bankDealId", bankDealId);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "dealTime", dealTime);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "payAmount", payAmount);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "fee", fee);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "ext1", ext1);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "ext2", ext2);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "payResult", payResult);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "errCode", errCode);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "key", key);
 
		String merchantSignMsg = MD5Util.md5Hex(merchantSignMsgVal.getBytes("utf-8")).toUpperCase();
		if (signMsg.toUpperCase().equals(merchantSignMsg.toUpperCase())) {
			switch (Integer.parseInt(payResult)) {
			case 10:
				if ((ext2.equals("goods")) || (ext2.equals("group"))) {
					boolean flag = this.handleOrderFormFeignClient.payByOnline(order, dealId, CommUtil.getURL(request));
					if (flag) {
						this.orderFormToolsFeignClient.updateGoodsInventory(order);
					}
					this.orderFormToolsFeignClient.sendMsgWhenHandleOrder(CommUtil.getURL(request), order,
							"tobuyer_online_pay_ok_notify", "toseller_online_pay_ok_notify");
					rtnOK = 1;
				}
				if (ext2.equals("cash")) {
					if (obj.getPd_pay_status() < 2) {
						obj.setPd_status(1);
						obj.setPd_pay_status(2);
						this.predepositFeignClient.updateById(obj);
						UserDto user = this.userFeignClient.selectByPrimaryKey(obj.getPd_user().getId());
						user.setAvailableBalance(
								BigDecimal.valueOf(CommUtil.add(user.getAvailableBalance(), obj.getPd_amount())));
						this.userFeignClient.updateById(user);
						PredepositLogDto log = new PredepositLogDto();
						log.setAddTime(new Date());
						log.setPd_log_amount(obj.getPd_amount());
						log.setPd_log_user(obj.getPd_user());
						log.setPd_op_type("充值");
						log.setPd_type("可用预存款");
						log.setPd_log_info("快钱在线支付");
						this.predepositLogFeignClient.saveEntity(log);
					}
					rtnOK = 1;
				}
				if (ext2.equals("gold")) {
					if (gold.getGold_pay_status() < 2) {
						gold.setGold_status(1);
						gold.setGold_pay_status(2);
						this.goldRecordService.updateById(gold);
						UserDto user = this.userFeignClient.selectByPrimaryKey(gold.getGold_user().getId());
						user.setGold(user.getGold() + gold.getGold_count());
						this.userFeignClient.updateById(user);
						GoldLog log = new GoldLog();
						log.setAddTime(new Date());
						log.setGl_payment(gold.getGold_payment());
						log.setGl_content("快钱在线支付");
						log.setGl_money(gold.getGold_money());
						log.setGl_count(gold.getGold_count());
						log.setGl_type(0);
						log.setGl_user(gold.getGold_user());
						log.setGr(gold);
						this.goldLogService.saveEntity(log);
					}
					rtnOK = 1;
				}
				if (ext2.equals("integral")) {
					if (ig_order.getIgo_status() < 20) {
						ig_order.setIgo_status(20);
						ig_order.setIgo_pay_time(new Date());
						ig_order.setIgo_payment("bill");
						this.integralGoodsOrderFeignClient.updateById(ig_order);
						List<Map> ig_maps = this.orderFormToolsFeignClient
								.query_integral_goodsinfo(ig_order.getGoods_info());
						for (Map map : ig_maps) {
							IntegralGoodsDto goods = this.integralGoodsFeignClient
									.selectByPrimaryKey(CommUtil.null2Long(map.get("id")));
							goods.setIg_goods_count(
									goods.getIg_goods_count() - CommUtil.null2Int(map.get("ig_goods_count")));
							goods.setIg_exchange_count(
									goods.getIg_exchange_count() + CommUtil.null2Int(map.get("ig_goods_count")));
							this.integralGoodsFeignClient.updateById(goods);
						}
					}
					rtnOK = 1;
				}
				if (ext2.equals("cloudpurchase")) {
					if (cp_order.getStatus() < 5) {
						cp_order.setStatus(5);
						cp_order.setPayTime(new Date());
						this.cloudPurchaseOrderFeignClient.updateById(cp_order);
						this.cloudPurchaseOrderFeignClient.reduce_inventory(cp_order, request);
					}
					rtnOK = 1;
				}
				break;
			}
		}
		response.setContentType("text/plain");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		try {
			PrintWriter writer = response.getWriter();
			writer.print(rtnOK);
		} catch (IOException e) {
			log.error(e.toString());
		}
	}
 
	/**
	 * 财付通支付
	 * 
	 * @param request
	 * @param response
	 * @param id
	 * @param type
	 * @param payment_id
	 * @throws IOException
	 */
	@RequestMapping({ "/tenpay" })
	public void tenpay(HttpServletRequest request, HttpServletResponse response,@RequestBody JSONObject json) throws IOException {
		String payment_id = json.optString("payment_id");
		String type = json.optString("type");
		String id = json.optString("id");
		
		boolean submit = true;
		OrderFormDto of = null;
		PredepositDto obj = null;
		GoldRecord gold = null;
		IntegralGoodsOrderDto ig_order = null;
		CloudPurchaseOrderDto cp_order = null;
		if ((type.equals("goods")) || (type.equals("group"))) {
			of = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
			if (of.getOrder_status() >= 20) {
				submit = false;
			}
		}
		if (type.equals("cash")) {
			obj = this.predepositFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
			if (obj.getPd_pay_status() >= 2) {
				submit = false;
			}
		}
		if (type.equals("gold")) {
			gold = this.goldRecordService.selectByPrimaryKey(CommUtil.null2Long(id));
			if (gold.getGold_pay_status() >= 2) {
				submit = false;
			}
		}
		if (type.equals("integral")) {
			ig_order = this.integralGoodsOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
			if (ig_order.getIgo_status() >= 20) {
				submit = false;
			}
		}
		if (type.equals("cloudpurchase")) {
			cp_order = this.cloudPurchaseOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
		}
		if (submit) {
			String order_price = "";
			if ((type.equals("goods")) || (type.equals("gruop"))) {
				order_price = CommUtil.null2String(of.getTotalPrice());
			}
			if (type.equals("cash")) {
				order_price = CommUtil.null2String(obj.getPd_amount());
			}
			if (type.equals("gold")) {
				order_price = CommUtil.null2String(Integer.valueOf(gold.getGold_money()));
			}
			if (type.equals("integral")) {
				order_price = CommUtil.null2String(ig_order.getIgo_trans_fee());
			}
			if (type.equals("cloudpurchase")) {
				order_price = CommUtil.null2String(Integer.valueOf(cp_order.getPrice()));
			}
			double total_fee = CommUtil.null2Double(order_price) * 100.0D;
			int fee = (int) total_fee;
 
			String product_name = "";
			if ((type.equals("goods")) || (type.equals("group"))) {
				product_name = of.getOrder_id();
			}
			if (type.equals("cash")) {
				product_name = obj.getPd_sn();
			}
			if (type.equals("gold")) {
				product_name = gold.getGold_sn();
			}
			if (type.equals("integral")) {
				product_name = ig_order.getIgo_order_sn();
			}
			if (type.equals("cloudpurchase")) {
				product_name = cp_order.getOdrdersn();
			}
			String remarkexplain = "";
			if ((type.equals("goods")) || (type.equals("group"))) {
				remarkexplain = of.getMsg();
			}
			if (type.equals("cash")) {
				remarkexplain = obj.getPd_remittance_info();
			}
			if (type.equals("gold")) {
				remarkexplain = gold.getGold_exchange_info();
			}
			if (type.equals("integral")) {
				remarkexplain = ig_order.getIgo_msg();
			}
			if (type.equals("cloudpurchase")) {
				product_name = cp_order.getIgo_order_sn();
			}
			String attach = "";
			if ((type.equals("goods")) || (type.equals("group"))) {
				attach = type + "," + of.getId().toString();
			}
			if (type.equals("cash")) {
				attach = type + "," + obj.getId().toString();
			}
			if (type.equals("gold")) {
				attach = type + "," + gold.getId().toString();
			}
			if (type.equals("integral")) {
				attach = type + "," + ig_order.getId().toString();
			}
			if (type.equals("cloudpurchase")) {
				attach = type + "," + cp_order.getId().toString();
			}
			String desc = "商品:" + product_name;
 
			String out_trade_no = "";
			if ((type.equals("goods")) || (type.equals("group"))) {
				out_trade_no = of.getOrder_id();
			}
			if (type.endsWith("cash")) {
				out_trade_no = obj.getPd_sn();
			}
			if (type.endsWith("gold")) {
				out_trade_no = gold.getGold_sn();
			}
			if (type.equals("integral")) {
				out_trade_no = ig_order.getIgo_order_sn();
			}
			if (type.equals("cloudpurchase")) {
				out_trade_no = cp_order.getOdrdersn();
			}
			Payment payment = this.paymentService.selectByPrimaryKey(CommUtil.null2Long(payment_id));
			if (payment == null) {
				payment = new Payment();
			}
			String trade_mode = CommUtil.null2String(Integer.valueOf(payment.getTrade_mode()));
			String currTime = TenpayUtil.getCurrTime();
 
			RequestHandler reqHandler = new RequestHandler(request, response);
			reqHandler.init();
 
			reqHandler.setKey(payment.getTenpay_key());
 
			reqHandler.setGateUrl("https://gw.tenpay.com/gateway/pay");
 
			reqHandler.setParameter("partner", payment.getTenpay_partner());
			reqHandler.setParameter("out_trade_no", out_trade_no);
			reqHandler.setParameter("total_fee", String.valueOf(fee));
			reqHandler.setParameter("return_url", CommUtil.getURL(request) + "/tenpay_return");
			reqHandler.setParameter("notify_url", CommUtil.getURL(request) + "/tenpay_notify");
			reqHandler.setParameter("body", desc);
			reqHandler.setParameter("bank_type", "DEFAULT");
			reqHandler.setParameter("spbill_create_ip", request.getRemoteAddr());
			reqHandler.setParameter("fee_type", "1");
			reqHandler.setParameter("subject", desc);
 
			reqHandler.setParameter("sign_type", "MD5");
			reqHandler.setParameter("service_version", "1.0");
			reqHandler.setParameter("input_charset", "UTF-8");
			reqHandler.setParameter("sign_key_index", "1");
 
			reqHandler.setParameter("attach", attach);
			reqHandler.setParameter("product_fee", "");
 
			reqHandler.setParameter("transport_fee", "0");
			reqHandler.setParameter("time_start", currTime);
			reqHandler.setParameter("time_expire", "");
			reqHandler.setParameter("buyer_id", "");
			reqHandler.setParameter("goods_tag", "");
			reqHandler.setParameter("trade_mode", trade_mode);
			reqHandler.setParameter("transport_desc", "");
			reqHandler.setParameter("trans_type", "1");
			reqHandler.setParameter("agentid", "");
			reqHandler.setParameter("agent_type", "");
			reqHandler.setParameter("seller_id", "");
 
			String requestUrl = reqHandler.getRequestURL();
			response.sendRedirect(requestUrl);
		} else {
			response.getWriter().write("该订单已经完成支付!");
		}
	}
 
	/**
	 * 财付通在线支付回调控制
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping({ "/tenpay_return" })
	public Map<String, Object> tenpay_return(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
 
		ResponseHandler resHandler = new ResponseHandler(request, response);
		String[] attachs = request.getParameter("attach").split(",");
 
		String out_trade_no = resHandler.getParameter("out_trade_no");
		OrderFormDto order = null;
		PredepositDto obj = null;
		GoldRecord gold = null;
		IntegralGoodsOrderDto ig_order = null;
		CloudPurchaseOrderDto cp_order = null;
		if (attachs[0].equals("cloudpurchase")) {
			cp_order = this.cloudPurchaseOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(attachs[1]));
			Map q_params = Maps.newHashMap();
			q_params.put("install", Boolean.valueOf(true));
			q_params.put("mark", cp_order.getPayment());
 
			List<Payment> payments = this.paymentService.queryPageList(q_params);
 
			resHandler.setKey(((Payment) payments.get(0)).getTenpay_key());
		}
		if (attachs[0].equals("integral")) {
			ig_order = this.integralGoodsOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(attachs[1]));
			Map q_params = Maps.newHashMap();
			q_params.put("install", Boolean.valueOf(true));
			q_params.put("mark", ig_order.getIgo_payment());
			List<Payment> payments = this.paymentService.queryPageList(q_params);
 
			resHandler.setKey(((Payment) payments.get(0)).getTenpay_key());
		}
		if (attachs[0].equals("cash")) {
			obj = this.predepositFeignClient.selectByPrimaryKey(CommUtil.null2Long(attachs[1]));
			Map q_params = Maps.newHashMap();
			q_params.put("install", Boolean.valueOf(true));
			q_params.put("mark", obj.getPd_payment());
			List<Payment> payments = this.paymentService.queryPageList(q_params);
 
			resHandler.setKey(((Payment) payments.get(0)).getTenpay_key());
		}
		if (attachs[0].equals("gold")) {
			gold = this.goldRecordService.selectByPrimaryKey(CommUtil.null2Long(attachs[1]));
			Map q_params = Maps.newHashMap();
			q_params.put("install", Boolean.valueOf(true));
			q_params.put("mark", gold.getGold_payment());
			List<Payment> payments = this.paymentService.queryPageList(q_params);
 
			resHandler.setKey(((Payment) payments.get(0)).getTenpay_key());
		}
		Payment payment = null;
		if ((attachs[0].equals("goods")) || (attachs[0].equals("group"))) {
			order = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(attachs[1]));
			payment = this.paymentService.selectByPrimaryKey(order.getPayment_id());
			resHandler.setKey(payment.getTenpay_key());
		}
		if (resHandler.isTenpaySign()) {
			String notify_id = resHandler.getParameter("notify_id");
 
			String transaction_id = resHandler.getParameter("transaction_id");
 
			String total_fee = resHandler.getParameter("total_fee");
 
			String discount = resHandler.getParameter("discount");
 
			String trade_state = resHandler.getParameter("trade_state");
 
			String trade_mode = resHandler.getParameter("trade_mode");
			if ("1".equals(trade_mode)) {
				if ("0".equals(trade_state)) {
					if (attachs[0].equals("cash")) {
						obj.setPd_status(1);
						obj.setPd_pay_status(2);
						this.predepositFeignClient.updateById(obj);
						UserDto user = this.userFeignClient.selectByPrimaryKey(obj.getPd_user().getId());
						user.setAvailableBalance(
								BigDecimal.valueOf(CommUtil.add(user.getAvailableBalance(), obj.getPd_amount())));
						this.userFeignClient.updateById(user);
						resultMap.put("op_title", "充值" + obj.getPd_amount() + "成功");
						resultMap.put("url", CommUtil.getURL(request) + "/buyer/predeposit_list");
					}
					if ((attachs[0].equals("goods")) || (attachs[0].equals("group"))) {
						boolean flag = this.handleOrderFormFeignClient.payByOnline(order, transaction_id,
								CommUtil.getURL(request));
						if (flag) {
							this.orderFormToolsFeignClient.updateGoodsInventory(order);
						}
						this.orderFormToolsFeignClient.sendMsgWhenHandleOrder(CommUtil.getURL(request), order,
								"tobuyer_online_pay_ok_notify", "toseller_online_pay_ok_notify");
						resultMap.put("all_price", Double.valueOf(this.orderFormToolsFeignClient
								.query_order_pay_price(CommUtil.null2String(order.getId()))));
						resultMap.put("obj", order);
					}
					if (attachs[0].equals("gold")) {
						gold.setGold_status(1);
						gold.setGold_pay_status(2);
						this.goldRecordService.updateById(gold);
						UserDto user = this.userFeignClient.selectByPrimaryKey(gold.getGold_user().getId());
						user.setGold(user.getGold() + gold.getGold_count());
						this.userFeignClient.updateById(user);
						GoldLog log = new GoldLog();
						log.setAddTime(new Date());
						log.setGl_payment(gold.getGold_payment());
						log.setGl_content("财付通及时到账支付");
						log.setGl_money(gold.getGold_money());
						log.setGl_count(gold.getGold_count());
						log.setGl_type(0);
						log.setGl_user(gold.getGold_user());
						log.setGr(gold);
						this.goldLogService.saveEntity(log);
						resultMap.put("op_title", "兑换" + gold.getGold_count() + "金币成功");
						resultMap.put("url", CommUtil.getURL(request) + "/seller/gold_record_list");
					}
					if (attachs[0].equals("integral")) {
						ig_order.setIgo_status(20);
						ig_order.setIgo_pay_time(new Date());
						ig_order.setIgo_payment("bill");
						this.integralGoodsOrderFeignClient.updateById(ig_order);
						List<Map> ig_maps = this.orderFormToolsFeignClient
								.query_integral_goodsinfo(ig_order.getGoods_info());
						for (Map map : ig_maps) {
							IntegralGoodsDto goods = this.integralGoodsFeignClient
									.selectByPrimaryKey(CommUtil.null2Long(map.get("id")));
							goods.setIg_goods_count(
									goods.getIg_goods_count() - CommUtil.null2Int(map.get("ig_goods_count")));
							goods.setIg_exchange_count(
									goods.getIg_exchange_count() + CommUtil.null2Int(map.get("ig_goods_count")));
							this.integralGoodsFeignClient.updateById(goods);
						}
						resultMap.put("obj", ig_order);
					}
					if (attachs[0].equals("cloudpurchase")) {
						if (cp_order.getStatus() < 5) {
							cp_order.setStatus(5);
							cp_order.setPayTime(new Date());
							this.cloudPurchaseOrderFeignClient.updateById(cp_order);
							this.cloudPurchaseOrderFeignClient.reduce_inventory(cp_order, request);
						}
						resultMap.put("op_title", "预付款支付成功!");
						resultMap.put("url", CommUtil.getURL(request) + "/buyer/cloudbuy_order");
					}
				} else {
					resultMap.put("op_title", "财付通支付失败!");
					resultMap.put("url", CommUtil.getURL(request) + "/index");
				}
			} else if ("2".equals(trade_mode)) {
				if ("0".equals(trade_state)) {
					if (attachs[0].equals("cash")) {
						obj.setPd_status(1);
						obj.setPd_pay_status(2);
						this.predepositFeignClient.updateById(obj);
						UserDto user = this.userFeignClient.selectByPrimaryKey(obj.getPd_user().getId());
						user.setAvailableBalance(
								BigDecimal.valueOf(CommUtil.add(user.getAvailableBalance(), obj.getPd_amount())));
						this.userFeignClient.updateById(user);
						PredepositLogDto log = new PredepositLogDto();
						log.setAddTime(new Date());
						log.setPd_log_amount(obj.getPd_amount());
						log.setPd_log_user(obj.getPd_user());
						log.setPd_op_type("充值");
						log.setPd_type("可用预存款");
						log.setPd_log_info("财付通中介担保付款");
						this.predepositLogFeignClient.saveEntity(log);
						resultMap.put("op_title", "充值" + obj.getPd_amount() + "成功");
						resultMap.put("url", CommUtil.getURL(request) + "/buyer/predeposit_list");
					}
					if (attachs[0].equals("goods")) {
						boolean flag = this.handleOrderFormFeignClient.payByOnline(order, transaction_id,
								CommUtil.getURL(request));
						if (flag) {
							this.orderFormToolsFeignClient.updateGoodsInventory(order);
						}
						this.orderFormToolsFeignClient.sendMsgWhenHandleOrder(CommUtil.getURL(request), order,
								"tobuyer_online_pay_ok_notify", "toseller_online_pay_ok_notify");
						resultMap.put("all_price", Double.valueOf(this.orderFormToolsFeignClient
								.query_order_pay_price(CommUtil.null2String(order.getId()))));
						resultMap.put("obj", order);
					}
					if (attachs[0].equals("gold")) {
						gold.setGold_status(1);
						gold.setGold_pay_status(2);
						this.goldRecordService.updateById(gold);
						UserDto user = this.userFeignClient.selectByPrimaryKey(gold.getGold_user().getId());
						user.setGold(user.getGold() + gold.getGold_count());
						this.userFeignClient.updateById(user);
						GoldLog log = new GoldLog();
						log.setAddTime(new Date());
						log.setGl_payment(gold.getGold_payment());
						log.setGl_content("财付通中介担保付款成功");
						log.setGl_money(gold.getGold_money());
						log.setGl_count(gold.getGold_count());
						log.setGl_type(0);
						log.setGl_user(gold.getGold_user());
						log.setGr(gold);
						this.goldLogService.saveEntity(log);
						resultMap.put("op_title", "兑换" + gold.getGold_count() + "金币成功");
						resultMap.put("url", CommUtil.getURL(request) + "/seller/gold_record_list");
					}
					if (attachs[0].equals("integral")) {
						ig_order.setIgo_status(20);
						ig_order.setIgo_pay_time(new Date());
						ig_order.setIgo_payment("bill");
						this.integralGoodsOrderFeignClient.updateById(ig_order);
						List<Map> ig_maps = this.orderFormToolsFeignClient
								.query_integral_goodsinfo(ig_order.getGoods_info());
						for (Map map : ig_maps) {
							IntegralGoodsDto goods = this.integralGoodsFeignClient
									.selectByPrimaryKey(CommUtil.null2Long(map.get("id")));
							goods.setIg_goods_count(
									goods.getIg_goods_count() - CommUtil.null2Int(map.get("ig_goods_count")));
							goods.setIg_exchange_count(
									goods.getIg_exchange_count() + CommUtil.null2Int(map.get("ig_goods_count")));
							this.integralGoodsFeignClient.updateById(goods);
						}
						resultMap.put("obj", ig_order);
					}
					if (attachs[0].equals("cloudpurchase")) {
						if (cp_order.getStatus() < 5) {
							cp_order.setStatus(5);
							cp_order.setPayTime(new Date());
							this.cloudPurchaseOrderFeignClient.updateById(cp_order);
							this.cloudPurchaseOrderFeignClient.reduce_inventory(cp_order, request);
						}
						resultMap.put("op_title", "预付款支付成功!");
						resultMap.put("url", CommUtil.getURL(request) + "/buyer/cloudbuy_order");
					}
				} else {
					resultMap.put("op_title", "财付通支付失败!");
					resultMap.put("url", CommUtil.getURL(request) + "/index");
				}
			}
		} else {
			resultMap.put("op_title", "财付通认证签名失败!");
			resultMap.put("url", CommUtil.getURL(request) + "/index");
		}
		return resultMap;
	}
 
	/**
	 * 网银在线回调函数
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping({ "/chinabank_return" })
	public Map<String, Object> chinabank_return(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
 
		String remark1 = request.getParameter("remark1");
		String remark2 = CommUtil.null2String(request.getParameter("remark2"));
		OrderFormDto order = null;
		PredepositDto obj = null;
		GoldRecord gold = null;
		IntegralGoodsOrderDto ig_order = null;
		CloudPurchaseOrderDto cp_order = null;
		if ((remark2.equals("goods")) || (remark2.equals("group"))) {
			order = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(remark1.trim()));
		}
		if (remark2.equals("cash")) {
			obj = this.predepositFeignClient.selectByPrimaryKey(CommUtil.null2Long(remark1));
		}
		if (remark2.equals("gold")) {
			gold = this.goldRecordService.selectByPrimaryKey(CommUtil.null2Long(remark1));
		}
		if (remark2.equals("integral")) {
			ig_order = this.integralGoodsOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(remark1));
		}
		if (remark2.equals("cloudpurchase")) {
			cp_order = this.cloudPurchaseOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(remark1));
		}
		String key = "";
		Payment payment = null;
		if ((remark2.equals("goods")) || (remark2.equals("group"))) {
			payment = this.paymentService.selectByPrimaryKey(order.getPayment_id());
			key = payment.getChinabank_key();
		}
		if ((remark2.equals("cash")) || (remark2.equals("gold")) || (remark2.equals("integral"))
				|| (remark2.equals("cloudpurchase"))) {
			Map q_params = Maps.newHashMap();
			q_params.put("install", Boolean.valueOf(true));
			if (remark2.equals("cash")) {
				q_params.put("mark", obj.getPd_payment());
			}
			if (remark2.equals("gold")) {
				q_params.put("mark", gold.getGold_payment());
			}
			if (remark2.equals("integral")) {
				q_params.put("mark", ig_order.getIgo_payment());
			}
			if (remark2.equals("cloudpurchase")) {
				q_params.put("mark", cp_order.getPayment());
			}
			List<Payment> payments = this.paymentService.queryPageList(q_params);
 
			key = ((Payment) payments.get(0)).getChinabank_key();
		}
		String v_oid = request.getParameter("v_oid");
		String v_pmode = request.getParameter("v_pmode");
 
		String v_pstatus = request.getParameter("v_pstatus");
		String v_pstring = request.getParameter("v_pstring");
 
		String v_amount = request.getParameter("v_amount");
		String v_moneytype = request.getParameter("v_moneytype");
		String v_md5str = request.getParameter("v_md5str");
		String text = v_oid + v_pstatus + v_amount + v_moneytype + key;
		String v_md5text = Md5Encrypt.md5(text).toUpperCase();
		if (v_md5str.equals(v_md5text)) {
			if ("20".equals(v_pstatus)) {
				if ((remark2.equals("goods")) || (remark2.equals("group"))) {
					boolean flag = this.handleOrderFormFeignClient.payByOnline(order, v_oid, CommUtil.getURL(request));
					if (flag) {
						this.orderFormToolsFeignClient.updateGoodsInventory(order);
					}
					this.orderFormToolsFeignClient.sendMsgWhenHandleOrder(CommUtil.getURL(request), order,
							"tobuyer_online_pay_ok_notify", "toseller_online_pay_ok_notify");
					resultMap.put("all_price", Double.valueOf(
							this.orderFormToolsFeignClient.query_order_pay_price(CommUtil.null2String(order.getId()))));
					resultMap.put("obj", order);
				}
				if (remark2.endsWith("cash")) {
					obj.setPd_status(1);
					obj.setPd_pay_status(2);
					this.predepositFeignClient.updateById(obj);
					UserDto user = this.userFeignClient.selectByPrimaryKey(obj.getPd_user().getId());
					user.setAvailableBalance(
							BigDecimal.valueOf(CommUtil.add(user.getAvailableBalance(), obj.getPd_amount())));
					this.userFeignClient.updateById(user);
					PredepositLogDto log = new PredepositLogDto();
					log.setAddTime(new Date());
					log.setPd_log_amount(obj.getPd_amount());
					log.setPd_log_user(obj.getPd_user());
					log.setPd_op_type("充值");
					log.setPd_type("可用预存款");
					log.setPd_log_info("网银在线支付");
					this.predepositLogFeignClient.saveEntity(log);
					resultMap.put("op_title", "充值" + obj.getPd_amount() + "成功");
					resultMap.put("url", CommUtil.getURL(request) + "/buyer/predeposit_list");
				}
				if (remark2.equals("gold")) {
					gold.setGold_status(1);
					gold.setGold_pay_status(2);
					this.goldRecordService.updateById(gold);
					UserDto user = this.userFeignClient.selectByPrimaryKey(gold.getGold_user().getId());
					user.setGold(user.getGold() + gold.getGold_count());
					this.userFeignClient.updateById(user);
					GoldLog log = new GoldLog();
					log.setAddTime(new Date());
					log.setGl_payment(gold.getGold_payment());
					log.setGl_content("网银在线支付");
					log.setGl_money(gold.getGold_money());
					log.setGl_count(gold.getGold_count());
					log.setGl_type(0);
					log.setGl_user(gold.getGold_user());
					log.setGr(gold);
					this.goldLogService.saveEntity(log);
					resultMap.put("op_title", "兑换" + gold.getGold_count() + "金币成功");
					resultMap.put("url", CommUtil.getURL(request) + "/seller/gold_record_list");
				}
				if (remark2.equals("integral")) {
					ig_order.setIgo_status(20);
					ig_order.setIgo_pay_time(new Date());
					ig_order.setIgo_payment("bill");
					this.integralGoodsOrderFeignClient.updateById(ig_order);
					List<Map> ig_maps = this.orderFormToolsFeignClient
							.query_integral_goodsinfo(ig_order.getGoods_info());
					for (Map map : ig_maps) {
						IntegralGoodsDto goods = this.integralGoodsFeignClient
								.selectByPrimaryKey(CommUtil.null2Long(map.get("id")));
						goods.setIg_goods_count(
								goods.getIg_goods_count() - CommUtil.null2Int(map.get("ig_goods_count")));
						goods.setIg_exchange_count(
								goods.getIg_exchange_count() + CommUtil.null2Int(map.get("ig_goods_count")));
						this.integralGoodsFeignClient.updateById(goods);
					}
					resultMap.put("obj", ig_order);
				}
				if (remark2.equals("cloudpurchase")) {
					if (cp_order.getStatus() < 5) {
						cp_order.setStatus(5);
						cp_order.setPayTime(new Date());
						this.cloudPurchaseOrderFeignClient.updateById(cp_order);
						this.cloudPurchaseOrderFeignClient.reduce_inventory(cp_order, request);
					}
					resultMap.put("op_title", "预付款支付成功!");
					resultMap.put("url", CommUtil.getURL(request) + "/buyer/cloudbuy_order");
				}
			}
		} else {
			resultMap.put("op_title", "网银在线支付失败!");
			resultMap.put("url", CommUtil.getURL(request) + "/index");
		}
		return resultMap;
	}
 
	/**
	 * paypal回调方法,paypal支付成功了后,调用该方法进行后续处理
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	@RequestMapping({ "/paypal_return" })
	public Map<String, Object> paypal_return(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
 
		Enumeration en = request.getParameterNames();
		String str = "cmd=_notify-validate";
		while (en.hasMoreElements()) {
			String paramName = (String) en.nextElement();
			String paramValue = request.getParameter(paramName);
			str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue);
		}
		String[] customs = request.getParameter("custom").split(",");
		String remark1 = customs[0];
		String remark2 = customs[1];
		String item_name = request.getParameter("item_name");
		String txnId = request.getParameter("txn_id");
		OrderFormDto order = null;
		PredepositDto obj = null;
		GoldRecord gold = null;
		IntegralGoodsOrderDto ig_order = null;
		CloudPurchaseOrderDto cp_order = null;
		Payment payment = null;
		if ((remark2.equals("goods")) || (remark2.equals("group"))) {
			order = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(remark1.trim()));
			payment = this.paymentService.selectByPrimaryKey(order.getPayment_id());
		}
		if (remark2.equals("cash")) {
			obj = this.predepositFeignClient.selectByPrimaryKey(CommUtil.null2Long(remark1));
		}
		if (remark2.equals("gold")) {
			gold = this.goldRecordService.selectByPrimaryKey(CommUtil.null2Long(remark1));
		}
		if (remark2.equals("integral")) {
			ig_order = this.integralGoodsOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(remark1));
		}
		if (remark2.equals("cloudpurchase")) {
			cp_order = this.cloudPurchaseOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(remark1));
		}
		String txn_id = request.getParameter("txn_id");
 
		String itemName = request.getParameter("item_name");
		String paymentStatus = request.getParameter("payment_status");
		String paymentAmount = request.getParameter("mc_gross");
		String paymentCurrency = request.getParameter("mc_currency");
		String receiverEmail = request.getParameter("receiver_email");
		String payerEmail = request.getParameter("payer_email");
		if ((paymentStatus.equals("Completed")) || (paymentStatus.equals("Pending"))) {
			if (((remark2.equals("goods")) || (remark2.equals("group"))) && (order.getOrder_status() < 20)) {
				if (CommUtil.null2String(order.getTotalPrice()).equals(paymentAmount)) {
					boolean flag = this.handleOrderFormFeignClient.payByOnline(order, txnId, CommUtil.getURL(request));
					if (flag) {
						this.orderFormToolsFeignClient.updateGoodsInventory(order);
					}
					this.orderFormToolsFeignClient.sendMsgWhenHandleOrder(CommUtil.getURL(request), order,
							"tobuyer_online_pay_ok_notify", "toseller_online_pay_ok_notify");
					resultMap.put("all_price", Double.valueOf(
							this.orderFormToolsFeignClient.query_order_pay_price(CommUtil.null2String(order.getId()))));
					resultMap.put("obj", order);
				}
			}
			if (remark2.endsWith("cash")) {
				if (obj.getPd_pay_status() < 2) {
					obj.setPd_status(1);
					obj.setPd_pay_status(2);
					this.predepositFeignClient.updateById(obj);
					UserDto user = this.userFeignClient.selectByPrimaryKey(obj.getPd_user().getId());
					user.setAvailableBalance(
							BigDecimal.valueOf(CommUtil.add(user.getAvailableBalance(), obj.getPd_amount())));
					this.userFeignClient.updateById(user);
					PredepositLogDto log = new PredepositLogDto();
					log.setAddTime(new Date());
					log.setPd_log_amount(obj.getPd_amount());
					log.setPd_log_user(obj.getPd_user());
					log.setPd_op_type("充值");
					log.setPd_type("可用预存款");
					log.setPd_log_info("Paypal在线支付");
					this.predepositLogFeignClient.saveEntity(log);
				}
				resultMap.put("op_title", "成功充值:" + obj.getPd_amount());
				resultMap.put("url", CommUtil.getURL(request) + "/buyer/predeposit_list");
			}
			if (remark2.equals("gold")) {
				if (gold.getGold_pay_status() < 2) {
					gold.setGold_status(1);
					gold.setGold_pay_status(2);
					this.goldRecordService.updateById(gold);
					UserDto user = this.userFeignClient.selectByPrimaryKey(gold.getGold_user().getId());
					user.setGold(user.getGold() + gold.getGold_count());
					this.userFeignClient.updateById(user);
					GoldLog log = new GoldLog();
					log.setAddTime(new Date());
					log.setGl_payment(gold.getGold_payment());
					log.setGl_content("Paypal");
					log.setGl_money(gold.getGold_money());
					log.setGl_count(gold.getGold_count());
					log.setGl_type(0);
					log.setGl_user(gold.getGold_user());
					log.setGr(gold);
					this.goldLogService.saveEntity(log);
				}
				resultMap.put("op_title", "成功充值金币:" + gold.getGold_count());
				resultMap.put("url", CommUtil.getURL(request) + "/seller/gold_record_list");
			}
			if (remark2.equals("integral")) {
				if (ig_order.getIgo_status() < 20) {
					ig_order.setIgo_status(20);
					ig_order.setIgo_pay_time(new Date());
					ig_order.setIgo_payment("paypal");
					this.integralGoodsOrderFeignClient.updateById(ig_order);
					List<Map> ig_maps = this.orderFormToolsFeignClient
							.query_integral_goodsinfo(ig_order.getGoods_info());
					for (Map map : ig_maps) {
						IntegralGoodsDto goods = this.integralGoodsFeignClient
								.selectByPrimaryKey(CommUtil.null2Long(map.get("id")));
						goods.setIg_goods_count(
								goods.getIg_goods_count() - CommUtil.null2Int(map.get("ig_goods_count")));
						goods.setIg_exchange_count(
								goods.getIg_exchange_count() + CommUtil.null2Int(map.get("ig_goods_count")));
						this.integralGoodsFeignClient.updateById(goods);
					}
				}
				resultMap.put("obj", ig_order);
			}
			if (remark2.equals("cloudpurchase")) {
				if (cp_order.getStatus() < 5) {
					cp_order.setStatus(5);
					cp_order.setPayTime(new Date());
					this.cloudPurchaseOrderFeignClient.updateById(cp_order);
					this.cloudPurchaseOrderFeignClient.reduce_inventory(cp_order, request);
				}
				resultMap.put("op_title", "预付款支付成功!");
				resultMap.put("url", CommUtil.getURL(request) + "/buyer/cloudbuy_order");
			}
		} else {
			resultMap.put("op_title", "Paypal支付失败");
			resultMap.put("url", CommUtil.getURL(request) + "/index");
		}
		return resultMap;
	}
 
	public Map<String, Object> wx_pay1(HttpServletRequest request, HttpServletResponse response, Long id,
			String pay_type, String order_type) throws Exception {
		
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
 
		RequestHandler reqHandler = new RequestHandler(request, response);
 
		List<Payment> payments = Lists.newArrayList();
		Map<String, Object> params = Maps.newHashMap();
 
		//TODO
		pay_type="wx_miniprogram";
		params.put("mark", pay_type);
		payments = this.paymentService.queryPageList(params);
 
		Payment payment = null;
		if (payments.size() > 0) {
			payment = (Payment) payments.get(0);
		}
		String body = "";
		String attach = "";
		String out_trade_no = "";
		double total_fee = 0.0D;
		boolean submit = true;
		OrderFormDto of = null;
		PredepositDto pd = null;
		GoldRecord gold = null;
		IntegralGoodsOrderDto ig_order = null;
		CloudPurchaseOrderDto cp_order = null;
		if ((order_type.equals("goods")) || (order_type.equals("group"))) {
			of = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
			if (of.getOrder_status() >= 20) {
				submit = false;
			} else {
				body = of.getOrder_id();
				attach = of.getId() + "_" + of.getOrder_id() + "_" + of.getUser_id() + "_" + order_type +"_"+pay_type;
				out_trade_no = of.getOrder_id();
				total_fee = Double.valueOf(of.getTotalPrice().toString()).doubleValue() * 100.0D;
				resultMap.put("obj", of);
			}
		}
		if (order_type.equals("cash")) {
			pd = this.predepositFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
			if (pd.getPd_pay_status() >= 2) {
				submit = false;
			} else {
				body = pd.getPd_sn();
				attach = pd.getId() + "_" + pd.getPd_sn() + "_" + pd.getPd_user().getId() + "_" + order_type+"_"+pay_type;
				out_trade_no = pd.getPd_sn();
				total_fee = Double.valueOf(pd.getPd_amount().toString()).doubleValue() * 100.0D;
				resultMap.put("obj", pd);
			}
		}
		if (order_type.equals("gold")) {
			gold = this.goldRecordService.selectByPrimaryKey(CommUtil.null2Long(id));
			if (gold.getGold_pay_status() >= 2) {
				submit = false;
			} else {
				body = gold.getGold_sn();
				attach = gold.getId() + "_" + gold.getGold_sn() + "_" + gold.getGold_user().getId() + "_" + order_type+"_"+pay_type;
				out_trade_no = gold.getGold_sn();
				total_fee = Double.valueOf(of.getTotalPrice().toString()).doubleValue() * 100.0D;
				resultMap.put("obj", gold);
			}
		}
		if (order_type.equals("integral")) {
			ig_order = this.integralGoodsOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
			if (ig_order.getIgo_status() >= 20) {
				submit = false;
			} else {
				body = ig_order.getIgo_order_sn();
				attach = ig_order.getId() + "_" + ig_order.getIgo_order_sn() + "_" + ig_order.getIgo_user().getId()
						+ "_" + order_type+"_"+pay_type;
				out_trade_no = ig_order.getIgo_order_sn();
				total_fee = Double.valueOf(ig_order.getIgo_trans_fee().toString()).doubleValue() * 100.0D;
				resultMap.put("obj", ig_order);
			}
		}
		if (order_type.equals("cloudpurchase")) {
			cp_order = this.cloudPurchaseOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
			if (cp_order.getStatus() == 5) {
				submit = false;
			} else {
				body = cp_order.getIgo_order_sn();
				attach = cp_order.getId() + "_" + cp_order.getIgo_order_sn() + "_" + cp_order.getUser_id() + "_"
						+ order_type+"_"+pay_type;
				out_trade_no = cp_order.getIgo_order_sn();
				total_fee = Double.valueOf(cp_order.getPrice()).doubleValue() * 100.0D;
				resultMap.put("obj", cp_order);
			}
		}
		if ((submit) && (payment != null)) {
			if (payment != null) {
				String app_id = payment.getWx_appid();
				String app_key = payment.getWx_paySignKey();
				String partner = payment.getTenpay_partner();
				String notify_url = payment.getTenpay_partner();
				String noncestr = Sha1Util.getNonceStr();
				String timestamp = Sha1Util.getTimeStamp();
				String path = request.getContextPath();
				String basePath = notify_url + "/";
				reqHandler.setParameter("appid", app_id);
				reqHandler.setParameter("mch_id", partner);
				reqHandler.setParameter("nonce_str", noncestr);
				reqHandler.setParameter("device_info", "wechat_mini_program");
				reqHandler.setParameter("body", body);
				reqHandler.setParameter("attach", attach);
				reqHandler.setParameter("out_trade_no", out_trade_no);
				BigDecimal total_feeBig = new BigDecimal(total_fee);
				reqHandler.setParameter("total_fee", total_feeBig.setScale(0, BigDecimal.ROUND_UP)+"");
				reqHandler.setParameter("spbill_create_ip", CommUtil.getIpAddr(request));
				reqHandler.setParameter("notify_url", basePath + "weixin_return");
				reqHandler.setParameter("trade_type", "JSAPI");
				// trade_type=JSAPI时,必须传入openid
				UserDto user = userFeignClient.selectByPrimaryKey(CommUtil.null2Long(of.getUser_id()));
				reqHandler.setParameter("openid", user.getOpenId());
 
				String requestUrl = reqHandler.reqToXml(app_key);
				HttpURLConnection conn = creatConnection(requestUrl);
				String result = getInput(conn);
				Map<String, String> map = doXMLParse(result);
				String return_code = ((String) map.get("return_code")).toString();
				String prepay_id = "";
				String code_url = "";
				if ("SUCCESS".equals(return_code)) {
					String result_code = ((String) map.get("result_code")).toString();
					if ("SUCCESS".equals(result_code)) {
						prepay_id = (String) map.get("prepay_id");
						code_url = (String) map.get("code_url");
					} else {
						// 预下单异常信息显示
						log.error(map.toString());
					}
				} else {
					// 预下单异常信息显示
					log.error(map.toString());
				}
				
				reqHandler.getAllParameters().clear();
				String newPackage = "prepay_id=" + prepay_id;
				
				reqHandler.setParameter("appId", app_id);
				reqHandler.setParameter("nonceStr", noncestr);  
				reqHandler.setParameter("package", newPackage);
				reqHandler.setParameter("signType", "MD5");
				reqHandler.setParameter("timeStamp", timestamp+"");
				reqHandler.genSign(app_key);
		
				String order_sign = reqHandler.getParameter("sign");
				resultMap.put("app_id", app_id);
				resultMap.put("timestamp", timestamp+"");
				resultMap.put("noncestr", noncestr);
				resultMap.put("packageValue", newPackage);
				resultMap.put("sign", order_sign);
				resultMap.put("code_url", code_url);
				resultMap.put("signType", "MD5");
				
				System.out.print("返回给前端---------------------------");
				System.out.print(resultMap.toString());
				System.out.print("返回给前端---------------------------");
				reqHandler.getAllParameters().clear();
				reqHandler.setParameter("appId", app_id);
				reqHandler.setParameter("nonceStr", noncestr);
				reqHandler.genSign(app_key);
				order_sign=reqHandler.getParameter("sign");
				
				if ((order_type.equals("goods")) || (order_type.equals("group"))) {
					of.setOrder_sign(order_sign);
					this.orderFormFeignClient.updateById(of);
				}
				if (order_type.equals("cash")) {
					pd.setOrder_sign(order_sign);
					this.predepositFeignClient.updateById(pd);
				}
				if (order_type.equals("gold")) {
					gold.setOrder_sign(order_sign);
					this.goldRecordService.updateById(gold);
				}
				if (order_type.equals("integral")) {
					ig_order.setOrder_sign(order_sign);
					this.integralGoodsOrderFeignClient.updateById(ig_order);
				}
				if (order_type.equals("cloudpurchase")) {
					cp_order.setOrder_sign(order_sign);
					this.cloudPurchaseOrderFeignClient.updateById(cp_order);
				}
			} else {
				return ResponseCode.buildCodeMap("20001", "支付方式错误!", null);
			}
		} else {
			return ResponseCode.buildCodeMap("20001", "支付方式错误!", null);
		}
		
		
		return ResponseCode.buildSuccessMap(resultMap) ;
		
		
	}
	/**
	 * 微信支付
	 * 
	 * @param request
	 * @param response
	 * @param id 订单id
	 * @param pay_type  支付方式 小程序端写死为wx_pay
	 * @param order_type  订单类型
	 * @return
	 * @throws Exception
	 */
	@RequestMapping({ "/pay/wx_pay" })
	public Map<String, Object> wx_pay(HttpServletRequest request, HttpServletResponse response,
			@RequestBody JSONObject json) throws Exception {
		Long id = json.optLong("id");
		String pay_type = json.optString("pay_type");
		String order_type = json.optString("order_type");
 
		Map<String, Object> resultMap = new HashMap<String, Object>();
 
		RequestHandler reqHandler = new RequestHandler(request, response);
 
		List<Payment> payments = Lists.newArrayList();
		Map<String, Object> params = Maps.newHashMap();
 
		if (StringUtils.isEmpty(pay_type)) {
			pay_type = "wx_miniprogram";
		}
		params.put("mark", pay_type);
		payments = this.paymentService.queryPageList(params);
 
		Payment payment = null;
		if (payments.size() > 0) {
			payment = (Payment) payments.get(0);
		}
		String body = "";
		String attach = "";
		String out_trade_no = "";
		String order_sign = "";
		double total_fee = 0.0D;
		boolean submit = true;
		OrderFormDto of = null;
		PredepositDto pd = null;
		GoldRecord gold = null;
		PlatformPay platformpay = null;
		RushOrderformDto  rushOrderformDto =null;
		Date time = new Date();
		IntegralGoodsOrderDto ig_order = null;
		CloudPurchaseOrderDto cp_order = null;
		UserDto user = null;
		if ((order_type.equals("goods")) || (order_type.equals("group"))) {
			of = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
			if (of.getOrder_status() >= 20) {
				submit = false;
			} else {
				body = of.getOrder_id();
				attach = of.getId() + "_" + of.getOrder_id() + "_" + of.getUser_id() + "_" + order_type + "_"
						+ pay_type;
				// out_trade_no = of.getOrder_id();
				out_trade_no = of.getId() + "" + time.getTime();
				total_fee = Double.valueOf(of.getTotalPrice().toString()).doubleValue() * 100.0D;
				resultMap.put("obj", of);
			}
		} // 第一次付款, 带上子订单信息
		if ((order_type.equals("goodsfirst")) || (order_type.equals("groupfirst"))) {
			of = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
			if (of.getOrder_status() >= 20) {
				submit = false;
			} else {
				body = of.getOrder_id();
				attach = of.getId() + "_" + of.getOrder_id() + "_" + of.getUser_id() + "_" + order_type + "_"
						+ pay_type;
				// out_trade_no = of.getOrder_id();
				out_trade_no = of.getId() + "" + time.getTime();
				// 第一次付款取子订单总价格
				total_fee = Double.valueOf(
						orderFormToolsFeignClient.query_order_pay_price(CommUtil.null2String(of.getId()))) * 100.0D;
				resultMap.put("obj", of);
			}
		}
		if (order_type.equals("cash")) {
			pd = this.predepositFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
			if (pd.getPd_pay_status() >= 2) {
				submit = false;
			} else {
				body = pd.getPd_sn();
				attach = pd.getId() + "_" + pd.getPd_sn() + "_" + pd.getPd_user().getId() + "_" + order_type + "_"
						+ pay_type;
				out_trade_no = pd.getPd_sn();
				total_fee = Double.valueOf(pd.getPd_amount().toString()).doubleValue() * 100.0D;
				resultMap.put("obj", pd);
			}
		}
		if (order_type.equals("gold")) {
			gold = this.goldRecordService.selectByPrimaryKey(CommUtil.null2Long(id));
			if (gold.getGold_pay_status() >= 2) {
				submit = false;
			} else {
				body = gold.getGold_sn();
				attach = gold.getId() + "_" + gold.getGold_sn() + "_" + gold.getGold_user().getId() + "_" + order_type
						+ "_" + pay_type;
				out_trade_no = gold.getGold_sn();
				total_fee = Double.valueOf(of.getTotalPrice().toString()).doubleValue() * 100.0D;
				resultMap.put("obj", gold);
			}
		}
		if (order_type.equals("integral")) {
			ig_order = this.integralGoodsOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
			if (ig_order.getIgo_status() >= 20) {
				submit = false;
			} else {
				body = ig_order.getIgo_order_sn();
				attach = ig_order.getId() + "_" + ig_order.getIgo_order_sn() + "_" + ig_order.getIgo_user().getId()
						+ "_" + order_type + "_" + pay_type;
				out_trade_no = ig_order.getIgo_order_sn();
				//积分订单  支付金额    =   运费  加   付款金额
				total_fee = Double.valueOf(ig_order.getIgo_pay_amount().toString()).doubleValue() * 100.0D;
				resultMap.put("obj", ig_order);
			}
		
		
			
			
		
		}
		if (order_type.equals("cloudpurchase")) {
			cp_order = this.cloudPurchaseOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
			if (cp_order.getStatus() == 5) {
				submit = false;
			} else {
				body = cp_order.getIgo_order_sn();
				attach = cp_order.getId() + "_" + cp_order.getIgo_order_sn() + "_" + cp_order.getUser_id() + "_"
						+ order_type + "_" + pay_type;
				out_trade_no = cp_order.getIgo_order_sn();
				total_fee = Double.valueOf(cp_order.getPrice()).doubleValue() * 100.0D;
				resultMap.put("obj", cp_order);
			}
		}
		if (order_type.equals("platformpay")) { // 保证金
			platformpay = this.platformPayService.selectByPrimaryKey(CommUtil.null2Long(id));
			if (platformpay.getPay_status() == 1) { // 已支付
				submit = false;
			} else {
				body = platformpay.getPay_no();
				attach = platformpay.getId() + "_" + platformpay.getPay_no() + "_" + platformpay.getUser_id() + "_"
						+ order_type + "_" + pay_type;
				out_trade_no = platformpay.getPay_no();
				total_fee = platformpay.getAmount().doubleValue() * 100.0D;
				resultMap.put("obj", platformpay);
				user = userFeignClient.selectByPrimaryKey(CommUtil.null2Long(platformpay.getUser_id()));
			}
		}
		if (order_type.equals("rushorder")) { // 抢购单
			rushOrderformDto = rushOrderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
			if (rushOrderformDto.getPay_time()!=null) { // 已支付
				submit = false;
			} else {
				body = rushOrderformDto.getOrder_no(); //订单号id
				attach = rushOrderformDto.getId() + "_" + rushOrderformDto.getOrder_no() + "_" + rushOrderformDto.getRush_id() + "_"
						+ order_type + "_" + pay_type;
				out_trade_no = rushOrderformDto.getId() + "" + time.getTime();  //流水号
				total_fee = rushOrderformDto.getBond_money().doubleValue() * 100.0D;  //上架费
				resultMap.put("obj", rushOrderformDto);
				user = userFeignClient.selectByPrimaryKey(CommUtil.null2Long(rushOrderformDto.getRush_id()));
			}
		}
		
		if ((submit) && (payment != null)) {
			if (payment != null) {
				String app_id = payment.getWx_appid();
				String app_key = payment.getWx_paySignKey();
				String partner = payment.getTenpay_partner();
				String notify_url = payment.getNotify_url();
				
				String noncestr = Sha1Util.getNonceStr();
				String timestamp = Sha1Util.getTimeStamp();
				String path = request.getContextPath();
				String basePath = notify_url + "/";
				if (pay_type.equals("wx_pay")) {
					reqHandler.setParameter("appid", app_id);
					reqHandler.setParameter("mch_id", partner);
					reqHandler.setParameter("nonce_str", noncestr);
					reqHandler.setParameter("device_info", "WEB");
					reqHandler.setParameter("body", body);
					reqHandler.setParameter("attach", attach);
					reqHandler.setParameter("out_trade_no", out_trade_no);
					BigDecimal total_feeBig = new BigDecimal(total_fee);
					reqHandler.setParameter("total_fee", total_feeBig.setScale(0, BigDecimal.ROUND_UP)+"");
					reqHandler.setParameter("spbill_create_ip", CommUtil.getIpAddr(request));
					reqHandler.setParameter("notify_url", basePath + "weixin_return");
					reqHandler.setParameter("scene_info", "'h5_info':{'type':'Wap','wap_url':'http://haiwah5.minglisoft.cn/','wap_name': '海哇'}");
					reqHandler.setParameter("trade_type", "MWEB");
					
					if (of != null) {
						// trade_type=JSAPI时,必须传入openid
					//	user = userFeignClient.selectByPrimaryKey(CommUtil.null2Long(of.getUser_id()));
					}
					/*reqHandler.setParameter("openid", user.getOpenId());*/
 
					String requestUrl = reqHandler.reqToXml(app_key);
					HttpURLConnection conn = creatConnection(requestUrl);
					String result = getInput(conn);
					Map<String, String> map = doXMLParse(result);
					String return_code = ((String) map.get("return_code")).toString();
					String prepay_id = "";
					String code_url = "";
					if ("SUCCESS".equals(return_code)) {
						System.out.println("mapppp==="+map);
						String result_code = ((String) map.get("result_code")).toString();
						if ("SUCCESS".equals(result_code)) {
							prepay_id = (String) map.get("prepay_id");
							code_url = (String) map.get("mweb_url");
						} else {
							// 预下单异常信息显示
							log.error(map.toString());
						}
					} else {
						// 预下单异常信息显示
						log.error(map.toString());
					}
 
					reqHandler.getAllParameters().clear();
					String newPackage = "prepay_id=" + prepay_id;
 
					reqHandler.setParameter("appId", app_id);
					reqHandler.setParameter("nonceStr", noncestr);
					reqHandler.setParameter("package", newPackage);
					reqHandler.setParameter("signType", "MD5");
					reqHandler.setParameter("timeStamp", timestamp + "");
					reqHandler.genSign(app_key);
 
					order_sign = reqHandler.getParameter("sign");
					resultMap.put("app_id", app_id);
					resultMap.put("timestamp", timestamp + "");
					resultMap.put("noncestr", noncestr);
					resultMap.put("packageValue", newPackage);
					resultMap.put("sign", order_sign);		//   http://haiwah5.minglisoft.cn/#/pagesA/order/index/index?type=order_nopay 
					resultMap.put("code_url", code_url+"&redirect_url="+"http://haiwah5.minglisoft.cn/%23/pagesA/order/index/index?type=order_nopay");
					resultMap.put("signType", "MD5");
 
					System.out.print("返回给前端-new1--------------------------");
					System.out.print(resultMap.toString());
					System.out.print("返回给前端---------------------------");
					reqHandler.getAllParameters().clear();
					reqHandler.setParameter("appId", app_id);
					reqHandler.setParameter("nonceStr", noncestr);
					reqHandler.genSign(app_key);
					order_sign = reqHandler.getParameter("sign");
				} else {
 
					reqHandler.setParameter("appid", app_id);
					reqHandler.setParameter("mch_id", partner);
					reqHandler.setParameter("nonce_str", noncestr);
					reqHandler.setParameter("device_info", "wechat_mini_program");
					reqHandler.setParameter("body", body);
					reqHandler.setParameter("attach", attach);
					reqHandler.setParameter("out_trade_no", out_trade_no);
					BigDecimal total_feeBig = new BigDecimal(total_fee);
					reqHandler.setParameter("total_fee", total_feeBig.setScale(0, BigDecimal.ROUND_UP) + "");
					reqHandler.setParameter("spbill_create_ip", CommUtil.getIpAddr(request));
					reqHandler.setParameter("notify_url", basePath + "weixin_return");
					reqHandler.setParameter("trade_type", "JSAPI");
					if (of != null) {
						// trade_type=JSAPI时,必须传入openid
						user = userFeignClient.selectByPrimaryKey(CommUtil.null2Long(of.getUser_id()));
					}
					reqHandler.setParameter("openid", user.getOpenId());
 
					String requestUrl = reqHandler.reqToXml(app_key);
					HttpURLConnection conn = creatConnection(requestUrl);
					String result = getInput(conn);
					Map<String, String> map = doXMLParse(result);
					String return_code = ((String) map.get("return_code")).toString();
					String prepay_id = "";
					String code_url = "";
					if ("SUCCESS".equals(return_code)) {
						String result_code = ((String) map.get("result_code")).toString();
						if ("SUCCESS".equals(result_code)) {
							prepay_id = (String) map.get("prepay_id");
							code_url = (String) map.get("code_url");
						} else {
							// 预下单异常信息显示
							log.error(map.toString());
						}
					} else {
						// 预下单异常信息显示
						log.error(map.toString());
					}
 
					reqHandler.getAllParameters().clear();
					String newPackage = "prepay_id=" + prepay_id;
 
					reqHandler.setParameter("appId", app_id);
					reqHandler.setParameter("nonceStr", noncestr);
					reqHandler.setParameter("package", newPackage);
					reqHandler.setParameter("signType", "MD5");
					reqHandler.setParameter("timeStamp", timestamp + "");
					reqHandler.genSign(app_key);
 
					order_sign = reqHandler.getParameter("sign");
					resultMap.put("app_id", app_id);
					resultMap.put("timestamp", timestamp + "");
					resultMap.put("noncestr", noncestr);
					resultMap.put("packageValue", newPackage);
					resultMap.put("sign", order_sign);
					resultMap.put("code_url", code_url);
					resultMap.put("signType", "MD5");
 
					System.out.print("返回给前端---------------------------");
					System.out.print(resultMap.toString());
					System.out.print("返回给前端---------------------------");
					reqHandler.getAllParameters().clear();
					reqHandler.setParameter("appId", app_id);
					reqHandler.setParameter("nonceStr", noncestr);
					reqHandler.genSign(app_key);
					order_sign = reqHandler.getParameter("sign");
 
				}
 
				if ((order_type.equals("goods")) || (order_type.equals("group")) || (order_type.equals("goodsfirst"))
						|| (order_type.equals("goodsfirst"))) {
					of.setOrder_sign(order_sign);
					of.setTrade_no(out_trade_no);
					this.orderFormFeignClient.updateById(of);
				}
				if (order_type.equals("cash")) {
					pd.setOrder_sign(order_sign);
					this.predepositFeignClient.updateById(pd);
				}
				if (order_type.equals("gold")) {
					gold.setOrder_sign(order_sign);
					this.goldRecordService.updateById(gold);
				}
				if (order_type.equals("integral")) {
					ig_order.setOrder_sign(order_sign);
					this.integralGoodsOrderFeignClient.updateById(ig_order);
				}
				if (order_type.equals("cloudpurchase")) {
					cp_order.setOrder_sign(order_sign);
					this.cloudPurchaseOrderFeignClient.updateById(cp_order);
				}
				if (order_type.equals("platformpay")) {
					platformpay.setTrade_no(order_sign);
					platformpay.setSign(order_sign);
					this.platformPayService.updateById(platformpay);
				}
				if (order_type.equals("rushorder")) {
					rushOrderformDto.setSign(order_sign);
					rushOrderformDto.setTrade_no(out_trade_no);
					this.rushOrderFormFeignClient.updateById(rushOrderformDto);
				}
				
			} else {
				return ResponseCode.buildCodeMap("20001", "支付方式错误!", null);
			}
		} else {
			return ResponseCode.buildCodeMap("20001", "支付方式错误!", null);
		}
 
		return ResponseCode.buildSuccessMap(resultMap);
 
	}
	
	public void disAgentProfit(OrderFormDto orderformDto){
		//分销收益
		try{
			// 拓展配置信息
			DistributionSettingDto distributionSetting = distributionSettingFeignClient.getDistributionSetting();
			// 下单成功后调用分销的处理逻辑
			if (null != distributionSetting && "1".equals(distributionSetting.getIsOpen()) && 4 != orderformDto.getOrder_cat()) {
				distributionProfitFeignClient.profitInsert(orderformDto);
				agentProfitFeignClient.profitInsert(orderformDto);
				// 计算分销的佣金
				//BigDecimal disProfit = distributionProfitFeignClient.totalProfitByOrderId(orderformDto.getId());
				//BigDecimal agentProfit = agentProfitFeignClient.totalProfitByOrderId(orderformDto.getId());
				List<Map> goods_list = JSON.parseArray(orderformDto.getGoods_info(), Map.class);
				BigDecimal goods_distribution_price = BigDecimal.ZERO;
				for (Map<String, Object> map : goods_list) {
					goods_distribution_price = goods_distribution_price.add(CommUtil.toBigDecimal(map.get("goods_distribution_price")));
				}
				// 平台的分佣+分销的佣金
				BigDecimal commission_amount = goods_distribution_price.add(orderformDto.getCommission_amount());
				orderformDto.setCommission_amount(commission_amount);
				orderFormFeignClient.updateById(orderformDto);
			}
			
		}catch (Exception e) {
			logger.error("PayController >> disAgentProfit(distribution&agentProfit) >> Exception:"+ e.getMessage());
		}
	}
	
	
	public void sendOrderMessage(OrderFormDto orderformDto){
		//分销收益
		try{
			MessageDto msg = new MessageDto();
			msg.setAddTime(new Date());
			msg.setDeleteStatus(0);
			msg.setContent("订单编号:"+orderformDto.getOrder_id()+"已付款。下单人:"+orderformDto.getUser_name()+",订单金额:"+orderformDto.getTotalPrice()+"。");
			msg.setMsg_cat(0);
			msg.setReply_status(0);
			msg.setStatus(0);
			msg.setTitle("用户付款");
			msg.setType(2);
			msg.setFromUser_id(1L);
			UserDto seller = userFeignClient.getUserByStoreId(Long.parseLong(orderformDto.getStore_id()));
			msg.setToUser_id(seller.getId());
			messageFeignClient.saveEntity(msg);
		}catch (Exception e) {
			logger.error("PayController >> sendOrderMessage >> Exception:"+ e.getMessage());
		}
	}
	
	public void sendTxMessage(OrderFormDto orderformDto){
		UserDto saler = userFeignClient.getUserByStoreId(Long.parseLong(orderformDto.getStore_id()));
		try{
			Map<String, Object> params2 = new HashMap<String, Object>();
			params2.put("order_id", orderformDto.getOrder_id());
			params2.put("orderMoney", orderformDto.getTotalPrice()+"");
			params2.put("nickname", orderformDto.getUser_name());
			params2.put("user_id", saler.getId().toString());
			logger.info("params2[{}]",params2);
			tXTemplateFeignClient.delivereMsg(params2);
			tXTemplateFeignClient.paySuccessMsg(orderformDto);
		}catch (Exception e) {
			logger.error("PayController >> sendTxMessage >> Exception:"+ e.getMessage());
		}
		try{
			jiguangPushFeignClient.deliveryReminder(saler.getId());
		}catch (Exception e) {
			logger.error("PayController >> jiGuangMessage >> Exception:"+ e.getMessage());
		}
	}
	
	//发送酒店消息
	public void sendHotelMessage(OrderFormDto orderformDto){
		UserDto saler = userFeignClient.getUserByStoreId(Long.parseLong(orderformDto.getStore_id()));
		UserDto buyer = userFeignClient.selectByPrimaryKey(Long.parseLong(orderformDto.getUser_id()));
		try{
			Map<String, Object> params2 = new HashMap<String, Object>();
			params2.put("user_id", saler.getId().toString());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日"); 
			params2.put("check_in_time", sdf.format(orderformDto.getCheck_in_time()));
			params2.put("departure_time", sdf.format(orderformDto.getDeparture_time()));
			List<Map> goods_list = JSON.parseArray(orderformDto.getGoods_info(), Map.class);
			for (Map<String, Object> map : goods_list) {
				params2.put("days", map.get("days").toString());
				params2.put("goods_name", map.get("goods_name").toString());
				params2.put("count", map.get("goods_count").toString());
			}
			params2.put("goods_price", orderformDto.getTotalPrice().toString());
			params2.put("receiver_name", orderformDto.getReceiver_Name());
			params2.put("receiver_mobile", orderformDto.getReceiver_mobile());
			logger.info("params2[{}]",params2);
			tXTemplateFeignClient.shotelOrderMsg(params2);
			
			params2.put("store_name", orderformDto.getStore_name());
			params2.put("wx_open_id", buyer.getWx_open_id());
			logger.info("params2[{}]",params2);
			tXTemplateFeignClient.uhotelOrderMsg(params2);
		}catch (Exception e) {
			logger.error("PayController >> sendHotelMessage >> Exception:"+ e.getMessage());
		}
	}
	/**
	 * 微信回调
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping({ "/weixin_return" })
	public void weixin_return(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType("text/plain");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
		String line = "";
		StringBuffer strBuf = new StringBuffer();
		while ((line = in.readLine()) != null) {
			strBuf.append(line).append("\n");
		}
		in.close();
		Map<String, String> xml = doXMLParse(strBuf.toString().trim());
 
		//扩展信息表
		SysConfigExtendDto  sysConfigExtendDto=sysconrigExtendFeignClient.getSysConfigExtend();
		String appid = ((String) xml.get("appid")).toString();
		
		if ("SUCCESS".equals(((String) xml.get("return_code")).toString())) {
			if ("SUCCESS".equals(((String) xml.get("result_code")).toString())) {
				String total_fee = (String) xml.get("total_fee");
				String out_trade_no = (String) xml.get("out_trade_no");
				String[] attachs = ((String) xml.get("attach")).split("_");
				String type = attachs[3];
				//支付方式  因为微信支付方式是"wx_miniprogram" 形式故pay_type为attachs[4]+"_"+attachs[5]
				String pay_type = attachs[4]+"_"+attachs[5];
				System.out.println("返回的pay_type:"+pay_type);
				OrderFormDto main_order = null;
				PredepositDto obj = null;
				GoldRecord gold = null;
				IntegralGoodsOrderDto ig_order = null;
				CloudPurchaseOrderDto cp_order = null;
				
				
				List<Payment> payments = Lists.newArrayList();
				Map<String, Object> params = Maps.newHashMap();
				params.put("mark",pay_type);
				payments = this.paymentService.queryPageList(params);
				Payment payment = null;
				if (payments.size() > 0) {
					payment = (Payment) payments.get(0);
				}
				
				
				RequestHandler reqHandler = new RequestHandler(request, response);
				reqHandler.setParameter("appId", payment.getWx_appid());
				reqHandler.setParameter("nonceStr", ((String) xml.get("nonce_str")).toString());
				reqHandler.genSign(payment.getWx_paySignKey());
				String sign = reqHandler.getParameter("sign");
				if (("goodsfirst".equals(type)) || ("groupfirst".equals(type))) {
					main_order = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(attachs[0]));
					if (sign.equals(main_order.getOrder_sign())) {
						main_order.setPayTime(new Date());
						main_order.setPayment_mark(payment.getMark());
						main_order.setPayment_name(payment.getName());
						main_order.setOut_order_id(out_trade_no);
						boolean flag = false;
						//查询修改相关子订单
						main_order.setOrder_first(0);
						flag = this.handleOrderFormFeignClient.payByOnline(main_order, "", CommUtil.getURL(request));
						if (flag) {
							main_order.setOrder_status(20);
							
							//分销收益
							try{
								disAgentProfit(main_order);
								sendOrderMessage(main_order);
								if(main_order.getChild_order_detail() != null){
									List<Map> datalist = com.alibaba.fastjson.JSONObject.parseArray(main_order.getChild_order_detail(), Map.class);
									for (Map map : datalist) {
										Integer order_id = (Integer) map.get("order_id");
										OrderFormDto order = orderFormFeignClient.selectByPrimaryKey(order_id.longValue());
										if(order != null){
											disAgentProfit(order);
											sendOrderMessage(order);
										}
									}
								}
								
							}catch (Exception e) {
								logger.error("PayController >> weixin_return(distribution&agentProfit【goods_first】) >> Exception:"+ e.getMessage());
							}
							//更新库存
							this.orderFormToolsFeignClient.updateGoodsInventory(main_order);	
							//该订单存在直播商品
							if (main_order.getLiveorder_type() != null && main_order.getLiveorder_type()==1) {
								liveOrderFeignClient.updateLiveOrder(main_order);
							}	
							
							//如果订单是增值服务,修改用户   审核状态
							if (main_order.getOrder_cat() != null && main_order.getOrder_cat()==4) {
								userFeignClient.updateLiveById(CommUtil.null2Long(main_order.getUser_id()));
							}
							//如果订单是拉新用户订单  ,  添加
							if (main_order.getOrder_cat() != null && main_order.getOrder_cat()==5) {
								main_order.setOrder_status(14);
								orderFormFeignClient.updateById(main_order);
							}else{
							if(main_order.getCheck_in_time() != null){
								sendHotelMessage(main_order);
							}else if(main_order.getOrder_offline()==1){
								//TODO 待修改 , 验证码消息
							}else{
								try{
									sendTxMessage(main_order);
									if(main_order.getChild_order_detail() != null){
										List<Map> datalist = com.alibaba.fastjson.JSONObject.parseArray(main_order.getChild_order_detail(), Map.class);
										for (Map map : datalist) {
											Integer order_id = (Integer) map.get("order_id");
											OrderFormDto order = orderFormFeignClient.selectByPrimaryKey(order_id.longValue());
											if(order != null){
												sendTxMessage(main_order);
											}
										}
									}
									
								}catch (Exception e) {
									logger.error("PayController >> weixin_return(sendTxMessage【goods_first】) >> Exception:"+ e.getMessage());
								}
							}
							}
							//发站内消息
							/*//拓展配置中分销为开启
							if(null !=sysConfigExtendDto && sysConfigExtendDto.isDistribution_open() && main_order.getOrder_cat()==0){
								OrderFormDto updateorder=main_order;
								//更新分销订单状态
								updateorder.setOrder_status(20);
								distributionOrderFeignClient.updateOrderStatus(updateorder);
							}*/
							
						}
						this.orderFormToolsFeignClient.sendMsgWhenHandleOrder(CommUtil.getURL(request), main_order,
								"tobuyer_online_pay_ok_notify", "toseller_online_pay_ok_notify");
					}
					
				}
				if (("goods".equals(type)) || ("group".equals(type))) {
					main_order = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(attachs[0]));
					if (sign.equals(main_order.getOrder_sign())) {
						main_order.setPayTime(new Date());
						main_order.setPayment_mark(payment.getMark());
						main_order.setPayment_name(payment.getName());
						main_order.setOut_order_id(out_trade_no);
						boolean flag = false;
						//不查询相关子订单
						main_order.setOrder_first(1);
						flag = this.handleOrderFormFeignClient.payByOnline(main_order, "", CommUtil.getURL(request));
						if (flag) {
							main_order.setOrder_status(20);
							try{
								disAgentProfit(main_order);
								sendOrderMessage(main_order);
							}catch (Exception e) {
								logger.error("PayController >> weixin_return(distribution&agentProfit【goods】) >> Exception:"+ e.getMessage());
							}
							if (main_order.getOrder_cat() != null && main_order.getOrder_cat() != 5) {
								if (main_order.getCheck_in_time() != null) {
									sendHotelMessage(main_order);
								} else if(main_order.getOrder_offline()==1){
									//TODO 待修改 , 验证码消息
								}else {
									try {
										sendTxMessage(main_order);
									} catch (Exception e) {
										logger.error(
												"PayController >> weixin_return(sendTxMessage【goods】) >> Exception:"
														+ e.getMessage());
									}
								}
							}
							//更新库存
							this.orderFormToolsFeignClient.updateGoodsInventory(main_order);	
							//该订单存在直播商品
							if (main_order.getLiveorder_type() != null && main_order.getLiveorder_type()==1) {
								liveOrderFeignClient.updateLiveOrder(main_order);
							}	
							
							//如果订单是增值服务,修改用户   审核状态
							if (main_order.getOrder_cat() != null && main_order.getOrder_cat()==4) {
								userFeignClient.updateLiveById(CommUtil.null2Long(main_order.getUser_id()));
							}
							//如果订单是拉新用户订单  ,  添加
							if (main_order.getOrder_cat() != null && main_order.getOrder_cat()==5) {
								main_order.setOrder_status(14);
								orderFormFeignClient.updateById(main_order);
							}
							
						}
						this.orderFormToolsFeignClient.sendMsgWhenHandleOrder(CommUtil.getURL(request), main_order,
								"tobuyer_online_pay_ok_notify", "toseller_online_pay_ok_notify");
					}
					
				}
				if ("integral".equals(type)) {
					ig_order = this.integralGoodsOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(attachs[0]));
					if ((ig_order != null) && (ig_order.getIgo_status() < 20)
							&& (sign.equals(ig_order.getOrder_sign()))) {
					 
						
						ig_order.setIgo_status(20);
						ig_order.setIgo_order_sn(out_trade_no);
						ig_order.setIgo_pay_time(new Date());
						ig_order.setIgo_payment(payment.getMark()); 
						this.integralGoodsOrderFeignClient.updateById(ig_order);
						List<Map> ig_maps = this.orderFormToolsFeignClient
								.query_integral_goodsinfo(ig_order.getGoods_info());
						for (Map map : ig_maps) {
							IntegralGoodsDto goods = this.integralGoodsFeignClient
									.selectByPrimaryKey(CommUtil.null2Long(map.get("id")));
							goods.setIg_goods_count(
									goods.getIg_goods_count() - CommUtil.null2Int(map.get("ig_goods_count")));
							goods.setIg_exchange_count(
									goods.getIg_exchange_count() + CommUtil.null2Int(map.get("ig_goods_count")));
							this.integralGoodsFeignClient.updateById(goods);
						}
					}
				}
				if ("cash".equals(type)) {
					obj = this.predepositFeignClient.selectByPrimaryKey(CommUtil.null2Long(attachs[0]));
					if ((obj != null) && (obj.getPd_pay_status() != 2) && (sign.equals(obj.getOrder_sign()))) {
						 
						obj.setPd_payment(payment.getMark());
						obj.setPd_status(1);
						obj.setPd_pay_status(2);
						this.predepositFeignClient.updateById(obj);
						UserDto user = this.userFeignClient.selectByPrimaryKey(obj.getPd_user().getId());
						user.setAvailableBalance(
								BigDecimal.valueOf(CommUtil.add(user.getAvailableBalance(), obj.getPd_amount())));
						this.userFeignClient.updateById(user);
						PredepositLogDto log = new PredepositLogDto();
						log.setAddTime(new Date());
						log.setPd_log_amount(obj.getPd_amount());
						log.setPd_log_user(obj.getPd_user());
						log.setPd_op_type("充值");
						log.setPd_type("可用预存款");
						log.setPd_log_info(payment.getName());
						this.predepositLogFeignClient.saveEntity(log);
					}
				}
				if ("gold".equals(type)) {
					gold = this.goldRecordService.selectByPrimaryKey(CommUtil.null2Long(attachs[0]));
					if ((gold != null) && (gold.getGold_pay_status() != 2) && (sign.equals(gold.getOrder_sign()))) {
						gold.setGold_status(1);
						gold.setGold_pay_status(2);
						gold.setGold_payment(payment.getMark());
						this.goldRecordService.updateById(gold);
						UserDto user = this.userFeignClient.selectByPrimaryKey(gold.getGold_user().getId());
						user.setGold(user.getGold() + gold.getGold_count());
						this.userFeignClient.updateById(user);
						GoldLog log = new GoldLog();
						log.setAddTime(new Date());
						log.setGl_payment(gold.getGold_payment());
						log.setGl_content(payment.getName());
						log.setGl_money(gold.getGold_money());
						log.setGl_count(gold.getGold_count());
						log.setGl_type(0);
						log.setGl_user(gold.getGold_user());
						log.setGr(gold);
						this.goldLogService.saveEntity(log);
					}
				}
				if (type.equals("cloudpurchase")) {
					cp_order = this.cloudPurchaseOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(attachs[0]));
					if (cp_order.getStatus() < 5) {
						cp_order.setStatus(5);
						cp_order.setPayTime(new Date());
						cp_order.setPayment(payment.getMark());
						this.cloudPurchaseOrderFeignClient.updateById(cp_order);
						this.cloudPurchaseOrderFeignClient.reduce_inventory(cp_order, request);
					}
				}
				if (type.equals("platformpay")) {
					PlatformPay pf = this.platformPayService.selectByPrimaryKey(CommUtil.null2Long(attachs[0]));
					if (pf.getPay_status() == 0 && StringUtils.equals(sign, pf.getSign())) {
						pf.setPay_status(1);
						pf.setUpdate_date(new Date());
						pf.setPay_type(payment.getMark());
						this.platformPayService.updateById(pf);
						
						PlatformPayFlow platformpayflow = new PlatformPayFlow();
						platformpayflow.setPlatform_pay_id(pf.getId());
						platformpayflow.setInfo("编号["+pf.getPay_no()+"]店铺保证金,支付成功");
						platformpayflow.setCreate_date(new Date());
						this.platformPayFlowService.saveEntity(platformpayflow);
						UserDto user = userFeignClient.selectByPrimaryKey(pf.getUser_id());
						
						StoreDto store = this.storeFeignClient.selectByPrimaryKey(user.getStore_id());
						store.setDeposit(pf.getAmount());
						this.storeFeignClient.updateById(store);
					}
				}
				//支付抢购订单上架费
				if (type.equals("rushorder")) {
					RushOrderformDto rushorderformdto = rushOrderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(attachs[0]));
					if (rushorderformdto.getOrder_status()==5 && StringUtils.equals(sign, rushorderformdto.getSign())) {
						rushorderformdto.setPay_mark(payment.getMark());
						rushorderformdto.setPayment_id(payment.getId());
						rushorderformdto.setPayment_name(payment.getName());
						rushorderformdto.setOut_order_id(out_trade_no);
						rushorderformdto.setPay_time(new Date());
						rushOrderFormFeignClient.completePayment(rushorderformdto);
						//2022 支付流水待写入
						/*PlatformPayFlow platformpayflow = new PlatformPayFlow();
						platformpayflow.setPlatform_pay_id(pf.getId());
						platformpayflow.setInfo("编号["+pf.getPay_no()+"]店铺保证金,支付成功");
						platformpayflow.setCreate_date(new Date());
						this.platformPayFlowService.saveEntity(platformpayflow);
						UserDto user = userFeignClient.selectByPrimaryKey(pf.getUser_id());*/
						
					}
				}
				
				
				
				PrintWriter write = response.getWriter();
				write.print(
						"<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
			} else {
				PrintWriter write = response.getWriter();
				write.print(
						"<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>");
			}
		} else {
			PrintWriter write = response.getWriter();
			write.print(
					"<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>");
		}
	}
 
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping({ "/unionpay_return" })
	public Map<String, Object> unionpay_return(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
 
		Map<String, Object> resultMap = new HashMap<String, Object>();
		request.setCharacterEncoding("ISO-8859-1");
		String encoding = request.getParameter("encoding");
 
		Map<String, String> reqParam = getAllRequestParam(request);
		Map<String, String> valideData = null;
		if ((reqParam != null) && (!reqParam.isEmpty())) {
			Iterator<Map.Entry<String, String>> it = reqParam.entrySet().iterator();
			valideData = new HashMap(reqParam.size());
			while (it.hasNext()) {
				Map.Entry<String, String> e = (Map.Entry) it.next();
				String key = (String) e.getKey();
				String value = (String) e.getValue();
				value = new String(value.getBytes("ISO-8859-1"), encoding);
				valideData.put(key, value);
			}
		}
		if (!SDKUtil.validate(valideData, encoding)) {
			resultMap.put("op_title", "支付回调失败");
			resultMap.put("url", CommUtil.getURL(request) + "/index");
		} else {
			String orderId = (String) valideData.get("orderId");
			String respCode = (String) valideData.get("respCode");
			String txtAmt = (String) valideData.get("txtAmt");
			String reqReserved = (String) valideData.get("reqReserved");
			String[] infos = reqReserved.split("_");
			String type = infos[0];
			String order_no = infos[1];
			OrderFormDto main_order = null;
			PredepositDto obj = null;
			GoldRecord gold = null;
			IntegralGoodsOrderDto ig_order = null;
			CloudPurchaseOrderDto cp_order = null;
			if (type.equals("goods")) {
				main_order = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_no));
			}
			if (type.equals("cash")) {
				obj = this.predepositFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_no));
			}
			if (type.equals("gold")) {
				gold = this.goldRecordService.selectByPrimaryKey(CommUtil.null2Long(order_no));
			}
			if (type.equals("integral")) {
				ig_order = this.integralGoodsOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_no));
			}
			if (type.equals("group")) {
				main_order = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_no));
			}
			if (type.equals("cloudpurchase")) {
				cp_order = this.cloudPurchaseOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_no));
			}
			Payment payment = null;
			if ((type.equals("goods")) || (type.equals("group"))) {
				payment = this.paymentService.selectByPrimaryKey(main_order.getPayment_id());
			}
			if ((type.equals("goods")) || (type.equals("group"))) {
				boolean flag = this.handleOrderFormFeignClient.payByOnline(main_order, main_order.getTrade_no(),
						CommUtil.getURL(request));
				if (flag) {
					this.orderFormToolsFeignClient.updateGoodsInventory(main_order);
				}
				resultMap.put("all_price", Double.valueOf(this.orderFormToolsFeignClient
						.query_order_pay_price(CommUtil.null2String(main_order.getId()))));
				resultMap.put("obj", main_order);
			}
			if (type.equals("cash")) {
				if (obj.getPd_pay_status() != 2) {
					obj.setPd_status(1);
					obj.setPd_pay_status(2);
					this.predepositFeignClient.updateById(obj);
					UserDto user = this.userFeignClient.selectByPrimaryKey(obj.getPd_user().getId());
					user.setAvailableBalance(
							BigDecimal.valueOf(CommUtil.add(user.getAvailableBalance(), obj.getPd_amount())));
					this.userFeignClient.updateById(user);
					PredepositLogDto log = new PredepositLogDto();
					log.setAddTime(new Date());
					log.setPd_log_amount(obj.getPd_amount());
					log.setPd_log_user(obj.getPd_user());
					log.setPd_op_type("充值");
					log.setPd_type("可用预存款");
					log.setPd_log_info("银联在线支付");
					this.predepositLogFeignClient.saveEntity(log);
				}
				resultMap.put("op_title", "恭喜您,成功充值" + obj.getPd_amount() + "元");
				resultMap.put("url", CommUtil.getURL(request) + "/buyer/predeposit_list");
			}
			if (type.equals("gold")) {
				if (gold.getGold_pay_status() != 2) {
					gold.setGold_status(1);
					gold.setGold_pay_status(2);
					this.goldRecordService.updateById(gold);
					UserDto user = this.userFeignClient.selectByPrimaryKey(gold.getGold_user().getId());
					user.setGold(user.getGold() + gold.getGold_count());
					this.userFeignClient.updateById(user);
					GoldLog log = new GoldLog();
					log.setAddTime(new Date());
					log.setGl_payment(gold.getGold_payment());
					log.setGl_content("银联支付");
					log.setGl_money(gold.getGold_money());
					log.setGl_count(gold.getGold_count());
					log.setGl_type(0);
					log.setGl_user(gold.getGold_user());
					log.setGr(gold);
					this.goldLogService.saveEntity(log);
				}
				resultMap.put("op_title", "兑换" + gold.getGold_count() + "金币成功");
				resultMap.put("url", CommUtil.getURL(request) + "/seller/gold_record_list");
			}
			if (type.equals("integral")) {
				if (ig_order.getIgo_status() < 20) {
					ig_order.setIgo_status(20);
					ig_order.setIgo_pay_time(new Date());
					ig_order.setIgo_payment("unionpay");
					this.integralGoodsOrderFeignClient.updateById(ig_order);
					List<Map> ig_maps = this.orderFormToolsFeignClient
							.query_integral_goodsinfo(ig_order.getGoods_info());
					for (Map map : ig_maps) {
						IntegralGoodsDto goods = this.integralGoodsFeignClient
								.selectByPrimaryKey(CommUtil.null2Long(map.get("id")));
						goods.setIg_goods_count(
								goods.getIg_goods_count() - CommUtil.null2Int(map.get("ig_goods_count")));
						goods.setIg_exchange_count(
								goods.getIg_exchange_count() + CommUtil.null2Int(map.get("ig_goods_count")));
						this.integralGoodsFeignClient.updateById(goods);
					}
				}
				resultMap.put("obj", ig_order);
			}
			if (type.equals("cloudpurchase")) {
				if (cp_order.getStatus() < 5) {
					cp_order.setStatus(5);
					cp_order.setPayTime(new Date());
					this.cloudPurchaseOrderFeignClient.updateById(cp_order);
					this.cloudPurchaseOrderFeignClient.reduce_inventory(cp_order, request);
				}
 
				resultMap.put("op_title", "预付款支付成功!");
				resultMap.put("url", CommUtil.getURL(request) + "/buyer/cloudbuy_order");
			}
		}
		return resultMap;
	}
 
	@RequestMapping({ "/unionpay_notify" })
	public void unionpay_notify(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String result = "ok";
		request.setCharacterEncoding("ISO-8859-1");
		String encoding = request.getParameter("encoding");
 
		Map<String, String> reqParam = getAllRequestParam(request);
		Map<String, String> valideData = null;
		if ((reqParam != null) && (!reqParam.isEmpty())) {
			Iterator<Map.Entry<String, String>> it = reqParam.entrySet().iterator();
			valideData = new HashMap(reqParam.size());
			while (it.hasNext()) {
				Map.Entry<String, String> e = (Map.Entry) it.next();
				String key = (String) e.getKey();
				String value = (String) e.getValue();
				value = new String(value.getBytes("ISO-8859-1"), encoding);
				valideData.put(key, value);
			}
		}
		if (!SDKUtil.validate(valideData, encoding)) {
			result = "no";
		} else {
			String orderId = (String) valideData.get("orderId");
			String respCode = (String) valideData.get("respCode");
			String txtAmt = (String) valideData.get("txtAmt");
			String reqReserved = (String) valideData.get("reqReserved");
			String[] infos = reqReserved.split("_");
			String type = infos[0];
			String order_no = infos[1];
			OrderFormDto main_order = null;
			PredepositDto obj = null;
			GoldRecord gold = null;
			IntegralGoodsOrderDto ig_order = null;
			CloudPurchaseOrderDto cp_order = null;
			if (type.equals("goods")) {
				main_order = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_no));
			}
			if (type.equals("cash")) {
				obj = this.predepositFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_no));
			}
			if (type.equals("gold")) {
				gold = this.goldRecordService.selectByPrimaryKey(CommUtil.null2Long(order_no));
			}
			if (type.equals("integral")) {
				ig_order = this.integralGoodsOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_no));
			}
			if (type.equals("group")) {
				main_order = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_no));
			}
			if (type.equals("cloudpurchase")) {
				cp_order = this.cloudPurchaseOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_no));
			}
			Payment payment = null;
			if ((type.equals("goods")) || (type.equals("group"))) {
				payment = this.paymentService.selectByPrimaryKey(main_order.getPayment_id());
			}
			if ((type.equals("goods")) || (type.equals("group"))) {
				boolean flag = this.handleOrderFormFeignClient.payByOnline(main_order, main_order.getTrade_no(),
						CommUtil.getURL(request));
				if (flag) {
					this.orderFormToolsFeignClient.updateGoodsInventory(main_order);
				}
				this.orderFormToolsFeignClient.sendMsgWhenHandleOrder(CommUtil.getURL(request), main_order,
						"tobuyer_online_pay_ok_notify", "toseller_online_pay_ok_notify");
			}
			if ((type.equals("cash")) && (obj.getPd_pay_status() != 2)) {
				obj.setPd_status(1);
				obj.setPd_pay_status(2);
				this.predepositFeignClient.updateById(obj);
				UserDto user = this.userFeignClient.selectByPrimaryKey(obj.getPd_user().getId());
				user.setAvailableBalance(
						BigDecimal.valueOf(CommUtil.add(user.getAvailableBalance(), obj.getPd_amount())));
				this.userFeignClient.updateById(user);
				PredepositLogDto log = new PredepositLogDto();
				log.setAddTime(new Date());
				log.setPd_log_amount(obj.getPd_amount());
				log.setPd_log_user(obj.getPd_user());
				log.setPd_op_type("充值");
				log.setPd_type("可用预存款");
				log.setPd_log_info("银联在线支付");
				this.predepositLogFeignClient.saveEntity(log);
			}
			if ((type.equals("gold")) && (gold.getGold_pay_status() != 2)) {
				gold.setGold_status(1);
				gold.setGold_pay_status(2);
				this.goldRecordService.updateById(gold);
				UserDto user = this.userFeignClient.selectByPrimaryKey(gold.getGold_user().getId());
				user.setGold(user.getGold() + gold.getGold_count());
				this.userFeignClient.updateById(user);
				GoldLog log = new GoldLog();
				log.setAddTime(new Date());
				log.setGl_payment(gold.getGold_payment());
				log.setGl_content("银联支付");
				log.setGl_money(gold.getGold_money());
				log.setGl_count(gold.getGold_count());
				log.setGl_type(0);
				log.setGl_user(gold.getGold_user());
				log.setGr(gold);
				this.goldLogService.saveEntity(log);
			}
			if ((type.equals("integral")) && (ig_order.getIgo_status() < 20)) {
				ig_order.setIgo_status(20);
				ig_order.setIgo_pay_time(new Date());
				ig_order.setIgo_payment("unionpay");
				this.integralGoodsOrderFeignClient.updateById(ig_order);
				List<Map> ig_maps = this.orderFormToolsFeignClient.query_integral_goodsinfo(ig_order.getGoods_info());
				for (Map map : ig_maps) {
					IntegralGoodsDto goods = this.integralGoodsFeignClient
							.selectByPrimaryKey(CommUtil.null2Long(map.get("id")));
					goods.setIg_goods_count(goods.getIg_goods_count() - CommUtil.null2Int(map.get("ig_goods_count")));
					goods.setIg_exchange_count(
							goods.getIg_exchange_count() + CommUtil.null2Int(map.get("ig_goods_count")));
					this.integralGoodsFeignClient.updateById(goods);
				}
			}
			if ((type.equals("cloudpurchase")) && (cp_order.getStatus() < 5)) {
				cp_order.setStatus(5);
				cp_order.setPayTime(new Date());
				this.cloudPurchaseOrderFeignClient.updateById(cp_order);
				this.cloudPurchaseOrderFeignClient.reduce_inventory(cp_order, request);
			}
		}
		response.setContentType("text/plain");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		try {
			PrintWriter writer = response.getWriter();
			writer.print(result);
		} catch (IOException e) {
			log.error(e.toString());
		}
	}
 
	public static Map<String, String> getAllRequestParam(HttpServletRequest request) {
		Map<String, String> res = Maps.newHashMap();
		Enumeration<?> temp = request.getParameterNames();
		if (temp != null) {
			while (temp.hasMoreElements()) {
				String en = (String) temp.nextElement();
				String value = request.getParameter(en);
				res.put(en, value);
				if ((res.get(en) == null) || ("".equals(res.get(en)))) {
					res.remove(en);
				}
			}
		}
		return res;
	}
 
	
	/**
	 * 移动端订单预付款支付
	 * @param request
	 * @param response
	 * @param order_id
	 * @param pay_msg
	 * @param type
	 * @return
	 * @throws Exception
	 */
	@RequestMapping({ "/order_pay_balance" })
	public Map<String,Object> order_pay_balance(HttpServletRequest request,
			HttpServletResponse response, @RequestBody JSONObject json) throws Exception {
		String order_id = json.optString("order_id");
		String pay_msg = json.optString("pay_msg");
		String type = json.optString("type");
		
		
		Map<String,Object> result=Maps.newHashMap();
		OrderFormDto order = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_id));
		
		//余额支付信息
		Payment balance_payment=paymentService.selectByPrimaryKey(1L);
		order.setPayment_id(balance_payment.getId());
		order.setPayment_mark(balance_payment.getMark());
		order.setPayment_name(balance_payment.getName());
		
		//扩展信息表
		SysConfigExtendDto  sysConfigExtendDto=sysconrigExtendFeignClient.getSysConfigExtend();
				
		UserDto user = SecurityUserHolder.getCurrentUser(request);
		user=userFeignClient.selectByPrimaryKey(user.getId());
		Map<Boolean, Object>  map_verify = this.orderFormToolsFeignClient.orderForm_verify( order, user.getId());
		Iterator iterator = map_verify.keySet().iterator();
		while (iterator.hasNext()) {
			Boolean verify_result = (Boolean) iterator.next();
			if (!verify_result.booleanValue()) {
				return ResponseCode.buildFailMap("", map_verify.get(verify_result));
			}
		}
		double order_total_price = this.orderFormToolsFeignClient.query_order_pay_price(order_id);
		if (CommUtil.null2Double(user.getAvailableBalance()) >= order_total_price) {
			boolean ret = this.handleOrderFormFeignClient.payByBalance(order,CommUtil.getURL(request), pay_msg);
			if(ret){
				
				//调用拼一拼更新拼团状态服务
				if(null !=sysConfigExtendDto && sysConfigExtendDto.isPin_open() && order.getOrder_cat()==3){
					//调用拼一拼更新拼团状态服务
					pinPayRecordFeignClient.updateStatusByOrderId(order.getId(),0);
				}
				
				if(null !=sysConfigExtendDto && sysConfigExtendDto.isDistribution_open() && order.getOrder_cat()==0){
					//更新分销订单状态
					order.setOrder_status(20);
					distributionOrderFeignClient.updateOrderStatus(order);
				}
				result.put("op_title", "预付款支付成功");
			}else{
				result.put("op_title", "预付款支付成功");
			}
		
		} else {			
			result.put("op_title", "可用余额不足,支付失败");
		}
		return result;
	}
	
	
	
	/**
	 * 移动端订单预付款支付
	 * @param request
	 * @param response
	 * @param order_id
	 * @param pay_msg
	 * @param type
	 * @return
	 * @throws Exception
	 */
	@RequestMapping({ "/rushorder_pay_balance" })
	public Map<String,Object> rushorder_pay_balance(HttpServletRequest request,
			HttpServletResponse response, @RequestBody JSONObject json) {
		String id = json.optString("id");
		String pay_password = json.optString("pay_password");
 
		UserDto user = SecurityUserHolder.getCurrentUser(request);
 
		// 用户密码是否匹配
		if (!StringUtils.equals(Md5Encrypt.md5(pay_password), user.getPassword())) {
			return ResponseCode.buildFailMap("支付密码错误", null);
		}
 
		Map<String, Object> result = Maps.newHashMap();
		RushOrderformDto rushorder = rushOrderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
		
		if(rushorder==null||rushorder.getOrder_status()!=5){
			return ResponseCode.buildFailMap("订单数据错误", null);
		}
		user = userFeignClient.selectByPrimaryKey(user.getId());
		if (CommUtil.null2Double(user.getAvailableBalance()) >= CommUtil.null2Double(rushorder.getBond_money())) {
			// 余额
			// 买家减去余额
			user.setAvailableBalance(
					BigDecimal.valueOf(CommUtil.subtract(user.getAvailableBalance(), rushorder.getBond_money())));
			
			userFeignClient.updateById(user);
			PredepositLogDto log = new PredepositLogDto();
			log.setAddTime(new Date());
			//log.setPd_log_user(buyer);
			log.setPd_log_user_id(user.getId());
			log.setPd_op_type("消费");
			log.setPd_log_amount(BigDecimal.valueOf(-CommUtil.null2Double(rushorder.getBond_money())));
			log.setPd_log_info(rushorder.getOrder_no() + "抢购订单支付上架费减少可用预存款");
			log.setPd_type("可用预存款");
			predepositLogFeignClient.saveEntity(log);
			
			rushorder.setPay_mark("balance");
			rushorder.setPayment_id(1L);
			rushorder.setPayment_name("余额支付");
			rushorder.setPay_time(new Date());
			rushOrderFormFeignClient.completePayment(rushorder);
			
			return ResponseCode.buildSuccessMap(result);//支付成功
		} else {
			return ResponseCode.buildFailMap("可用余额不足,支付失败", null);
		}
 
	}
	
	
	
	@RequestMapping({ "/pay_code/generate" })
	public void pay_code_generate(HttpServletRequest request, HttpServletResponse response, @RequestBody JSONObject json)
			throws IOException {
		String url = json.optString("url");
		String logoPath = "";
		SysConfigDto sysconfig = sysConfigFeignClient.getSysConfig();
 
		if (sysconfig.getQr_logo() != null) {
			logoPath =
 
					request.getSession().getServletContext().getRealPath("/") + sysconfig.getQr_logo().getPath()
							+ File.separator + sysconfig.getQr_logo().getName();
		}
		QRCodeUtil.encode(url, logoPath, response, true);
	}
 
	private HttpURLConnection creatConnection(String requestUrl) throws IOException {
		URL url = new URL("https://api.mch.weixin.qq.com/pay/unifiedorder");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(30000);
		conn.setReadTimeout(30000);
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setUseCaches(false);
 
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Length", requestUrl.length() + "");
		String encode = "utf-8";
		OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), encode);
		out.write(requestUrl.toString());
		out.flush();
		out.close();
		return conn;
	}
 
	private String getInput(HttpURLConnection conn) throws IOException {
		if (conn.getResponseCode() != 200) {
			return null;
		}
		BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
		String line = "";
		StringBuffer strBuf = new StringBuffer();
		while ((line = in.readLine()) != null) {
			strBuf.append(line).append("\n");
		}
		in.close();
		return strBuf.toString().trim();
	}
 
	public Map doXMLParse(String strxml) throws JDOMException, IOException {
		strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
		if ((strxml == null) || ("".equals(strxml))) {
			return null;
		}
		Map m = Maps.newHashMap();
 
		InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
 
		SAXBuilder builder = new SAXBuilder();
 
		Document doc = builder.build(in);
 
		Element root = doc.getRootElement();
 
		List list = root.getChildren();
 
		Iterator it = list.iterator();
		while (it.hasNext()) {
			Element e = (Element) it.next();
 
			String k = e.getName();
 
			String v = "";
 
			List children = e.getChildren();
			if (children.isEmpty()) {
				v = e.getTextNormalize();
			} else {
				v = getChildrenText(children);
			}
			m.put(k, v);
		}
		in.close();
 
		return m;
	}
 
	public String getChildrenText(List children) {
		StringBuffer sb = new StringBuffer();
		if (!children.isEmpty()) {
			Iterator it = children.iterator();
			while (it.hasNext()) {
				Element e = (Element) it.next();
				String name = e.getName();
				String value = e.getTextNormalize();
				List list = e.getChildren();
				sb.append("<" + name + ">");
				if (!list.isEmpty()) {
					sb.append(getChildrenText(list));
				}
				sb.append(value);
				sb.append("</" + name + ">");
			}
		}
		return sb.toString();
	}
	/**
	 * 微信回调
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/weixin_returntest2636dd", method = RequestMethod.POST)
	public void weixin_returntest2636dd(HttpServletRequest request, HttpServletResponse response,@RequestBody JSONObject json) throws Exception {
		String type = json.optString("type");
		String pay_type = json.optString("pay_type");
		String order_id = json.optString("order_id");
		//扩展信息表
		
		if (true) {
			if (true) {
				//支付方式  因为微信支付方式是"wx_miniprogram" 形式故pay_type为attachs[4]+"_"+attachs[5]
				OrderFormDto main_order = null;
				PredepositDto obj = null;
				GoldRecord gold = null;
				IntegralGoodsOrderDto ig_order = null;
				CloudPurchaseOrderDto cp_order = null;
				
				
				List<Payment> payments = Lists.newArrayList();
				Map<String, Object> params = Maps.newHashMap();
				params.put("mark",pay_type);
				payments = this.paymentService.queryPageList(params);
 
				Payment payment = null;
				if (payments.size() > 0) {
					payment = (Payment) payments.get(0);
				}
				
 
				
				if (("goods_first".equals(type)) || ("group_first".equals(type))) {
					main_order = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_id));
					if (true) {
						main_order.setPayment_mark(payment.getMark());
						main_order.setPayment_name(payment.getName());
						boolean flag = false;
						//查询修改相关子订单
						main_order.setOrder_first(0);
						flag = this.handleOrderFormFeignClient.payByOnline(main_order, "", CommUtil.getURL(request));
						if (flag) {
							main_order.setOrder_status(20);
							//分销收益
							try{
								disAgentProfit(main_order);
								sendOrderMessage(main_order);
								if(main_order.getChild_order_detail() != null){
									List<Map> datalist = com.alibaba.fastjson.JSONObject.parseArray(main_order.getChild_order_detail(), Map.class);
									for (Map map : datalist) {
										Integer order_id1 = (Integer) map.get("order_id");
										OrderFormDto order = orderFormFeignClient.selectByPrimaryKey(order_id1.longValue());
										if(order != null){
											disAgentProfit(order);
											sendOrderMessage(order);
										}
									}
								}
							}catch (Exception e) {
								logger.error("PayController >> weixin_returntest2636dd(distribution) >> Exception:"+ e.getMessage());
							}
							
							//更新库存
							this.orderFormToolsFeignClient.updateGoodsInventory(main_order);	
							//该订单存在直播商品
							if (main_order.getLiveorder_type() != null && main_order.getLiveorder_type()==1) {
								liveOrderFeignClient.updateLiveOrder(main_order);
							}	
							
							//如果订单是增值服务,修改用户   审核状态
							if (main_order.getOrder_cat() != null && main_order.getOrder_cat()==4) {
								userFeignClient.updateLiveById(CommUtil.null2Long(main_order.getUser_id()));
							}
							
							//调用拼一拼更新拼团状态服务
							if(true && main_order.getOrder_cat()==3){
								//调用拼一拼更新拼团状态服务
								orderFormToolsFeignClient.updateStatusByOrderId(main_order.getId(),0);
							}
							
							//拓展配置中分销为开启
							if(true && main_order.getOrder_cat()==0){
								OrderFormDto updateorder=main_order;
								//更新分销订单状态
								updateorder.setOrder_status(20);
								distributionOrderFeignClient.updateOrderStatus(updateorder);
							}
							
						}
						this.orderFormToolsFeignClient.sendMsgWhenHandleOrder(CommUtil.getURL(request), main_order,
								"tobuyer_online_pay_ok_notify", "toseller_online_pay_ok_notify");
					}
					
				}
				if (("goods".equals(type)) || ("group".equals(type))) {
					main_order = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_id));
					if (true) {
						main_order.setPayment_mark(payment.getMark());
						main_order.setPayment_name(payment.getName());
						boolean flag = false;
						//不查询相关子订单
						main_order.setOrder_first(1);
						flag = this.handleOrderFormFeignClient.payByOnline(main_order, "", CommUtil.getURL(request));
						if (flag) {
							main_order.setOrder_status(20);
							//分销收益
							try{
								disAgentProfit(main_order);
								sendOrderMessage(main_order);
							}catch (Exception e) {
								logger.error("PayController >> weixin_returntest2636dd(distribution) >> Exception:"+ e.getMessage());
							}
							//更新库存
							this.orderFormToolsFeignClient.updateGoodsInventory(main_order);	
							//该订单存在直播商品
							if (main_order.getLiveorder_type() != null && main_order.getLiveorder_type()==1) {
								liveOrderFeignClient.updateLiveOrder(main_order);
							}	
							
							//如果订单是增值服务,修改用户   审核状态
							if (main_order.getOrder_cat() != null && main_order.getOrder_cat()==4) {
								userFeignClient.updateLiveById(CommUtil.null2Long(main_order.getUser_id()));
							}
							
						}
						this.orderFormToolsFeignClient.sendMsgWhenHandleOrder(CommUtil.getURL(request), main_order,
								"tobuyer_online_pay_ok_notify", "toseller_online_pay_ok_notify");
					}
					
				}
				if ("integral".equals(type)) {
					ig_order = this.integralGoodsOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_id));
					if ((ig_order != null) && (ig_order.getIgo_status() < 20)
							&& (true)) {
					 
						
						ig_order.setIgo_status(20);
						ig_order.setIgo_pay_time(new Date());
						ig_order.setIgo_payment(payment.getMark()); 
						this.integralGoodsOrderFeignClient.updateById(ig_order);
						List<Map> ig_maps = this.orderFormToolsFeignClient
								.query_integral_goodsinfo(ig_order.getGoods_info());
						for (Map map : ig_maps) {
							IntegralGoodsDto goods = this.integralGoodsFeignClient
									.selectByPrimaryKey(CommUtil.null2Long(map.get("id")));
							goods.setIg_goods_count(
									goods.getIg_goods_count() - CommUtil.null2Int(map.get("ig_goods_count")));
							goods.setIg_exchange_count(
									goods.getIg_exchange_count() + CommUtil.null2Int(map.get("ig_goods_count")));
							this.integralGoodsFeignClient.updateById(goods);
						}
					}
				}
				if ("cash".equals(type)) {
					obj = this.predepositFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_id));
					if ((obj != null) && (obj.getPd_pay_status() != 2) && (true)) {
						 
						obj.setPd_payment(payment.getMark());
						obj.setPd_status(1);
						obj.setPd_pay_status(2);
						this.predepositFeignClient.updateById(obj);
						UserDto user = this.userFeignClient.selectByPrimaryKey(obj.getPd_user().getId());
						user.setAvailableBalance(
								BigDecimal.valueOf(CommUtil.add(user.getAvailableBalance(), obj.getPd_amount())));
						this.userFeignClient.updateById(user);
						PredepositLogDto log = new PredepositLogDto();
						log.setAddTime(new Date());
						log.setPd_log_amount(obj.getPd_amount());
						log.setPd_log_user(obj.getPd_user());
						log.setPd_op_type("充值");
						log.setPd_type("可用预存款");
						log.setPd_log_info(payment.getName());
						this.predepositLogFeignClient.saveEntity(log);
					}
				}
				if ("gold".equals(type)) {
					gold = this.goldRecordService.selectByPrimaryKey(CommUtil.null2Long(order_id));
					if ((gold != null) && (gold.getGold_pay_status() != 2) && (true)) {
						gold.setGold_status(1);
						gold.setGold_pay_status(2);
						gold.setGold_payment(payment.getMark());
						this.goldRecordService.updateById(gold);
						UserDto user = this.userFeignClient.selectByPrimaryKey(gold.getGold_user().getId());
						user.setGold(user.getGold() + gold.getGold_count());
						this.userFeignClient.updateById(user);
						GoldLog log = new GoldLog();
						log.setAddTime(new Date());
						log.setGl_payment(gold.getGold_payment());
						log.setGl_content(payment.getName());
						log.setGl_money(gold.getGold_money());
						log.setGl_count(gold.getGold_count());
						log.setGl_type(0);
						log.setGl_user(gold.getGold_user());
						log.setGr(gold);
						this.goldLogService.saveEntity(log);
					}
				}
				if (type.equals("cloudpurchase")) {
					cp_order = this.cloudPurchaseOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(order_id));
					if (cp_order.getStatus() < 5) {
						cp_order.setStatus(5);
						cp_order.setPayTime(new Date());
						cp_order.setPayment(payment.getMark());
						this.cloudPurchaseOrderFeignClient.updateById(cp_order);
						this.cloudPurchaseOrderFeignClient.reduce_inventory(cp_order, request);
					}
				}
				if (type.equals("platformpay")) {
					PlatformPay pf = this.platformPayService.selectByPrimaryKey(CommUtil.null2Long(order_id));
					if (pf.getPay_status() == 0 && true) {
						pf.setPay_status(1);
						pf.setUpdate_date(new Date());
						pf.setPay_type(payment.getMark());
						this.platformPayService.updateById(pf);
						
						PlatformPayFlow platformpayflow = new PlatformPayFlow();
						platformpayflow.setPlatform_pay_id(pf.getId());
						platformpayflow.setInfo("编号["+pf.getPay_no()+"]店铺保证金,支付成功");
						platformpayflow.setCreate_date(new Date());
						this.platformPayFlowService.saveEntity(platformpayflow);
						UserDto user = userFeignClient.selectByPrimaryKey(pf.getUser_id());
						
						StoreDto store = this.storeFeignClient.selectByPrimaryKey(user.getStore_id());
						store.setDeposit(pf.getAmount());
						this.storeFeignClient.updateById(store);
					}
				}
				PrintWriter write = response.getWriter();
				write.print(
						"<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
			} else {
				PrintWriter write = response.getWriter();
				write.print(
						"<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>");
			}
		} else {
			PrintWriter write = response.getWriter();
			write.print(
					"<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>");
		}
	}
 
	/**
	 * 移动端订单支付
	 * @param request
	 * @param response
	 * @param payType
	 * @param order_id
	 * @param order_type
	 * @param pay_password
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping({ "/order_unifiedorder" })
	public Object order_unifiedorder(HttpServletRequest request,HttpServletResponse response,@RequestBody JSONObject json) throws Exception {
		Long id = json.optLong("id");
		String pay_type =json.optString("pay_type");
		String order_type =json.optString("order_type");
		
		Map<String,Object> resultMap=new HashMap<String,Object>();
		
		
		
		//TODO 
		try{
			//检查支付方式
			if(pay_type.equals("wx_app")){
				return this.weixin_unifiedorder(request, response,pay_type,  id,
						order_type);
			}else if(pay_type.equals("alipay_app")){
				return alipayService.app_alipay_unifiedorder(request, response,pay_type,  id,
						order_type);
			}else{
				resultMap.put("60001", "支付方式错误");
			}	
			}catch(Exception e){
				logger.error(e.toString());
			}
			
		return resultMap;
	}
	
	
	/**
	 * 移动端移动端预下单
	 * @param request
	 * @param response
	 * @param payType
	 * @param order_id 订单id
	 * @param type 订单类型
	 * @return
	 * @throws Exception 
	 */
	private  Map<String,Object> weixin_unifiedorder(HttpServletRequest request,
			HttpServletResponse response,String  pay_type,Long  id,
			String order_type) throws Exception {
		
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
 
		RequestHandler reqHandler = new RequestHandler(request, response);
 
		List<Payment> payments = Lists.newArrayList();
		Map<String, Object> params = Maps.newHashMap();
 
		// TODO
		//pay_type = "wx_app";
		params.put("mark", pay_type);
		payments = this.paymentService.queryPageList(params);
 
		Payment payment = null;
		if (payments.size() > 0) {
			payment = (Payment) payments.get(0);
		}
		String body = "";
		String attach = "";
		String out_trade_no = "";
		double total_fee = 0.0D;
		boolean submit = true;
		OrderFormDto of = null;
		PredepositDto pd = null;
		GoldRecord gold = null;
		PlatformPay platformpay=null;
		IntegralGoodsOrderDto ig_order = null;
		CloudPurchaseOrderDto cp_order = null;
		UserDto user=null;
		if ((order_type.equals("goods")) || (order_type.equals("group"))) {
			of = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
			if (of.getOrder_status() >= 20) {
				submit = false;
			} else {
				body = of.getOrder_id();
				attach = of.getId() + "_" + of.getOrder_id() + "_" + of.getUser_id() + "_" + order_type + "_"
						+ pay_type;
				out_trade_no = of.getOrder_id();
				total_fee = Double.valueOf(of.getTotalPrice().toString()).doubleValue() * 100.0D;
				resultMap.put("obj", of);
			}
		}//第一次付款, 带上子订单信息
		if ((order_type.equals("goodsfirst")) || (order_type.equals("groupfirst"))) {
			of = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
			if (of.getOrder_status() >= 20) {
				submit = false;
			} else {
				body = of.getOrder_id();
				attach = of.getId() + "_" + of.getOrder_id() + "_" + of.getUser_id() + "_" + order_type + "_"
						+ pay_type;
				out_trade_no = of.getOrder_id();
				//第一次付款取子订单总价格
				total_fee = Double
						.valueOf(orderFormToolsFeignClient.query_order_pay_price(CommUtil.null2String(of.getId())))* 100.0D;
				resultMap.put("obj", of);
			}
		}
		if (order_type.equals("cash")) {
			pd = this.predepositFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
			if (pd.getPd_pay_status() >= 2) {
				submit = false;
			} else {
				body = pd.getPd_sn();
				attach = pd.getId() + "_" + pd.getPd_sn() + "_" + pd.getPd_user().getId() + "_" + order_type + "_"
						+ pay_type;
				out_trade_no = pd.getPd_sn();
				total_fee = Double.valueOf(pd.getPd_amount().toString()).doubleValue() * 100.0D;
				resultMap.put("obj", pd);
			}
		}
		if (order_type.equals("gold")) {
			gold = this.goldRecordService.selectByPrimaryKey(CommUtil.null2Long(id));
			if (gold.getGold_pay_status() >= 2) {
				submit = false;
			} else {
				body = gold.getGold_sn();
				attach = gold.getId() + "_" + gold.getGold_sn() + "_" + gold.getGold_user().getId() + "_" + order_type
						+ "_" + pay_type;
				out_trade_no = gold.getGold_sn();
				total_fee = Double.valueOf(of.getTotalPrice().toString()).doubleValue() * 100.0D;
				resultMap.put("obj", gold);
			}
		}
		if (order_type.equals("integral")) {
			ig_order = this.integralGoodsOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
			if (ig_order.getIgo_status() >= 20) {
				submit = false;
			} else {
				body = ig_order.getIgo_order_sn();
				attach = ig_order.getId() + "_" + ig_order.getIgo_order_sn() + "_" + ig_order.getIgo_user().getId()
						+ "_" + order_type + "_" + pay_type;
				out_trade_no = ig_order.getIgo_order_sn();
				total_fee = Double.valueOf(ig_order.getIgo_trans_fee().toString()).doubleValue() * 100.0D;
				resultMap.put("obj", ig_order);
			}
		}
		if (order_type.equals("cloudpurchase")) {
			cp_order = this.cloudPurchaseOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
			if (cp_order.getStatus() == 5) {
				submit = false;
			} else {
				body = cp_order.getIgo_order_sn();
				attach = cp_order.getId() + "_" + cp_order.getIgo_order_sn() + "_" + cp_order.getUser_id() + "_"
						+ order_type + "_" + pay_type;
				out_trade_no = cp_order.getIgo_order_sn();
				total_fee = Double.valueOf(cp_order.getPrice()).doubleValue() * 100.0D;
				resultMap.put("obj", cp_order);
			}
		}
		if (order_type.equals("platformpay")) {   //保证金
			  platformpay = this.platformPayService.selectByPrimaryKey(CommUtil.null2Long(id));
			if (platformpay.getPay_status() == 1) { //已支付 
				submit = false;
			} else {
				body = platformpay.getPay_no();
				attach = platformpay.getId() + "_" + platformpay.getPay_no() + "_" + platformpay.getUser_id() + "_"
						+ order_type + "_" + pay_type;
				out_trade_no = platformpay.getPay_no();
				total_fee = platformpay.getAmount().doubleValue() * 100.0D;
				resultMap.put("obj", platformpay);
			  user = userFeignClient.selectByPrimaryKey(CommUtil.null2Long(platformpay.getUser_id()));
			}
		}
		if ((submit) && (payment != null)) {
			if (payment != null) {
				String app_id = payment.getWx_appid();
				String app_key = payment.getWx_paySignKey();
				String partner = payment.getTenpay_partner();
				String notify_url = payment.getNotify_url();
				String noncestr = Sha1Util.getNonceStr();
				String timestamp = Sha1Util.getTimeStamp();
				String path = request.getContextPath();
				String basePath = notify_url+ "/";
				reqHandler.setParameter("appid", app_id);
				reqHandler.setParameter("mch_id", partner);
				reqHandler.setParameter("nonce_str", noncestr);
				reqHandler.setParameter("body", body);
				reqHandler.setParameter("attach", attach);
				reqHandler.setParameter("out_trade_no", out_trade_no);
				BigDecimal total_feeBig = new BigDecimal(total_fee);
				reqHandler.setParameter("total_fee", total_feeBig.setScale(0, BigDecimal.ROUND_UP) + "");
				reqHandler.setParameter("notify_url", basePath + "weixin_return");
				reqHandler.setParameter("trade_type", "APP");
		
				String requestUrl = reqHandler.reqToXml(app_key);
				HttpURLConnection conn = creatConnection(requestUrl);
				String result = getInput(conn);
				Map<String, String> map = doXMLParse(result);
				String return_code = ((String) map.get("return_code")).toString();
				String prepay_id = "";
				String code_url = "";
				if ("SUCCESS".equals(return_code)) {
					String result_code = ((String) map.get("result_code")).toString();
					if ("SUCCESS".equals(result_code)) {
						prepay_id = (String) map.get("prepay_id");
						code_url = (String) map.get("code_url");
					} else {
						// 预下单异常信息显示
						log.error(map.toString());
					}
				} else {
					// 预下单异常信息显示
					log.error(map.toString());
				}
 
				reqHandler.getAllParameters().clear();
				reqHandler.setParameter("appid", app_id);
				reqHandler.setParameter("partnerid", payment.getTenpay_partner());	
				reqHandler.setParameter("prepayid", prepay_id);
				reqHandler.setParameter("package", "Sign=WXPay");
				reqHandler.setParameter("noncestr", noncestr);
				reqHandler.setParameter("timestamp", timestamp);
				reqHandler.genSign(app_key);
				
				resultMap.put("appid", app_id);
				resultMap.put("partnerid", payment.getTenpay_partner());
				resultMap.put("prepayid", prepay_id);
				resultMap.put("package", "Sign=WXPay");
				resultMap.put("noncestr", noncestr);		
				resultMap.put("timestamp", timestamp);
				resultMap.put("sign", reqHandler.getParameter("sign"));
				
 
				System.out.print("返回给前端---------------------------");
				System.out.print(resultMap.toString());
				System.out.print("返回给前端---------------------------");
				reqHandler.getAllParameters().clear();
				reqHandler.setParameter("appId", app_id);
				reqHandler.setParameter("nonceStr", noncestr);
				reqHandler.genSign(app_key);
				String order_sign = reqHandler.getParameter("sign");
				
				if ((order_type.equals("goods")) || (order_type.equals("group"))
						||(order_type.equals("goodsfirst")) || (order_type.equals("goodsfirst"))) {
					of.setOrder_sign(order_sign);
					this.orderFormFeignClient.updateById(of);
				}
				if (order_type.equals("cash")) {
					pd.setOrder_sign(order_sign);
					this.predepositFeignClient.updateById(pd);
				}
				if (order_type.equals("gold")) {
					gold.setOrder_sign(order_sign);
					this.goldRecordService.updateById(gold);
				}
				if (order_type.equals("integral")) {
					ig_order.setOrder_sign(order_sign);
					this.integralGoodsOrderFeignClient.updateById(ig_order);
				}
				if (order_type.equals("cloudpurchase")) {
					cp_order.setOrder_sign(order_sign);
					this.cloudPurchaseOrderFeignClient.updateById(cp_order);
				}
				if (order_type.equals("platformpay")) {
					platformpay.setTrade_no(order_sign);
					platformpay.setSign(order_sign);
					this.platformPayService.updateById(platformpay);
				}
				
				
				
			} else {
				return ResponseCode.buildCodeMap("20001", "支付方式错误!", null);
			}
		} else {
			return ResponseCode.buildCodeMap("20001", "支付方式错误!", null);
		}
 
		return ResponseCode.buildSuccessMap(resultMap);
 
	}
	/**
	 * 微信app支付回调
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping({ "/weixin_return_app" })
	public void weixin_return_app(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		response.setContentType("text/plain");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
		String line = "";
		StringBuffer strBuf = new StringBuffer();
		while ((line = in.readLine()) != null) {
			strBuf.append(line).append("\n");
		}
		in.close();
		Map<String, String> xml = doXMLParse(strBuf.toString().trim());
 
		//扩展信息表
		SysConfigExtendDto  sysConfigExtendDto=sysconrigExtendFeignClient.getSysConfigExtend();
		String appid = ((String) xml.get("appid")).toString();
		
		if ("SUCCESS".equals(((String) xml.get("return_code")).toString())) {
			if ("SUCCESS".equals(((String) xml.get("result_code")).toString())) {
				String total_fee = (String) xml.get("total_fee");
				String[] attachs = ((String) xml.get("attach")).split("_");
				String type = attachs[3];
				//支付方式  因为微信支付方式是"wx_miniprogram" 形式故pay_type为attachs[4]+"_"+attachs[5]
				String pay_type = attachs[4]+"_"+attachs[5];
				System.out.println("返回的pay_type:"+pay_type);
				OrderFormDto main_order = null;
				PredepositDto obj = null;
				GoldRecord gold = null;
				IntegralGoodsOrderDto ig_order = null;
				CloudPurchaseOrderDto cp_order = null;
				
				
				List<Payment> payments = Lists.newArrayList();
				Map<String, Object> params = Maps.newHashMap();
				params.put("mark",pay_type);
				payments = this.paymentService.queryPageList(params);
				Payment payment = null;
				if (payments.size() > 0) {
					payment = (Payment) payments.get(0);
				}
				
				
				RequestHandler reqHandler = new RequestHandler(request, response);
				reqHandler.setParameter("appId", payment.getWx_appid());
				reqHandler.setParameter("nonceStr", ((String) xml.get("nonce_str")).toString());
				reqHandler.genSign(payment.getWx_paySignKey());
				String sign = reqHandler.getParameter("sign");
				if (("goodsfirst".equals(type)) || ("groupfirst".equals(type))) {
					main_order = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(attachs[0]));
					if (sign.equals(main_order.getOrder_sign())) {
						main_order.setPayTime(new Date());
						main_order.setPayment_mark(payment.getMark());
						main_order.setPayment_name(payment.getName());
						boolean flag = false;
						//查询修改相关子订单
						main_order.setOrder_first(0);
						flag = this.handleOrderFormFeignClient.payByOnline(main_order, "", CommUtil.getURL(request));
						if (flag) {
							main_order.setOrder_status(20);
							//分销收益
							try{
								disAgentProfit(main_order);
								sendOrderMessage(main_order);
								if(main_order.getChild_order_detail() != null){
									List<Map> datalist = com.alibaba.fastjson.JSONObject.parseArray(main_order.getChild_order_detail(), Map.class);
									for (Map map : datalist) {
										Integer order_id = (Integer) map.get("order_id");
										OrderFormDto order = orderFormFeignClient.selectByPrimaryKey(order_id.longValue());
										if(order != null){
											disAgentProfit(order);
											sendOrderMessage(order);
										}
									}
								}
								
							}catch (Exception e) {
								logger.error("PayController >> weixin_return(distribution&agentProfit【goods_first】) >> Exception:"+ e.getMessage());
							}
							//更新库存
							this.orderFormToolsFeignClient.updateGoodsInventory(main_order);	
							//该订单存在直播商品
							if (main_order.getLiveorder_type() != null && main_order.getLiveorder_type()==1) {
								liveOrderFeignClient.updateLiveOrder(main_order);
							}	
							
							//如果订单是增值服务,修改用户   审核状态
							if (main_order.getOrder_cat() != null && main_order.getOrder_cat()==4) {
								userFeignClient.updateLiveById(CommUtil.null2Long(main_order.getUser_id()));
							}
							
							try{
								sendTxMessage(main_order);
								if(main_order.getChild_order_detail() != null){
									List<Map> datalist = com.alibaba.fastjson.JSONObject.parseArray(main_order.getChild_order_detail(), Map.class);
									for (Map map : datalist) {
										Integer order_id = (Integer) map.get("order_id");
										OrderFormDto order = orderFormFeignClient.selectByPrimaryKey(order_id.longValue());
										if(order != null){
											sendTxMessage(main_order);
										}
									}
								}
								
							}catch (Exception e) {
								logger.error("PayController >> weixin_return(sendTxMessage【goods_first】) >> Exception:"+ e.getMessage());
							}
							
							//发站内消息
							/*//拓展配置中分销为开启
							if(null !=sysConfigExtendDto && sysConfigExtendDto.isDistribution_open() && main_order.getOrder_cat()==0){
								OrderFormDto updateorder=main_order;
								//更新分销订单状态
								updateorder.setOrder_status(20);
								distributionOrderFeignClient.updateOrderStatus(updateorder);
							}*/
							
						}
						this.orderFormToolsFeignClient.sendMsgWhenHandleOrder(CommUtil.getURL(request), main_order,
								"tobuyer_online_pay_ok_notify", "toseller_online_pay_ok_notify");
					}
					
				}
				if (("goods".equals(type)) || ("group".equals(type))) {
					main_order = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(attachs[0]));
					if (sign.equals(main_order.getOrder_sign())) {
						main_order.setPayment_mark(payment.getMark());
						main_order.setPayment_name(payment.getName());
						boolean flag = false;
						//不查询相关子订单
						main_order.setOrder_first(1);
						flag = this.handleOrderFormFeignClient.payByOnline(main_order, "", CommUtil.getURL(request));
						if (flag) {
							main_order.setOrder_status(20);
							try{
								disAgentProfit(main_order);
								sendOrderMessage(main_order);
							}catch (Exception e) {
								logger.error("PayController >> weixin_return(distribution&agentProfit【goods】) >> Exception:"+ e.getMessage());
							}
							
							try{
								sendTxMessage(main_order);
							}catch (Exception e) {
								logger.error("PayController >> weixin_return(sendTxMessage【goods】) >> Exception:"+ e.getMessage());
							}
							//更新库存
							this.orderFormToolsFeignClient.updateGoodsInventory(main_order);	
							//该订单存在直播商品
							if (main_order.getLiveorder_type() != null && main_order.getLiveorder_type()==1) {
								liveOrderFeignClient.updateLiveOrder(main_order);
							}	
							
							//如果订单是增值服务,修改用户   审核状态
							if (main_order.getOrder_cat() != null && main_order.getOrder_cat()==4) {
								userFeignClient.updateLiveById(CommUtil.null2Long(main_order.getUser_id()));
							}
							
						}
						this.orderFormToolsFeignClient.sendMsgWhenHandleOrder(CommUtil.getURL(request), main_order,
								"tobuyer_online_pay_ok_notify", "toseller_online_pay_ok_notify");
					}
					
				}
				if ("integral".equals(type)) {
					ig_order = this.integralGoodsOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(attachs[0]));
					if ((ig_order != null) && (ig_order.getIgo_status() < 20)
							&& (sign.equals(ig_order.getOrder_sign()))) {
					 
						
						ig_order.setIgo_status(20);
						ig_order.setIgo_pay_time(new Date());
						ig_order.setIgo_payment(payment.getMark()); 
						this.integralGoodsOrderFeignClient.updateById(ig_order);
						List<Map> ig_maps = this.orderFormToolsFeignClient
								.query_integral_goodsinfo(ig_order.getGoods_info());
						for (Map map : ig_maps) {
							IntegralGoodsDto goods = this.integralGoodsFeignClient
									.selectByPrimaryKey(CommUtil.null2Long(map.get("id")));
							goods.setIg_goods_count(
									goods.getIg_goods_count() - CommUtil.null2Int(map.get("ig_goods_count")));
							goods.setIg_exchange_count(
									goods.getIg_exchange_count() + CommUtil.null2Int(map.get("ig_goods_count")));
							this.integralGoodsFeignClient.updateById(goods);
						}
					}
				}
				if ("cash".equals(type)) {
					obj = this.predepositFeignClient.selectByPrimaryKey(CommUtil.null2Long(attachs[0]));
					if ((obj != null) && (obj.getPd_pay_status() != 2) && (sign.equals(obj.getOrder_sign()))) {
						 
						obj.setPd_payment(payment.getMark());
						obj.setPd_status(1);
						obj.setPd_pay_status(2);
						this.predepositFeignClient.updateById(obj);
						UserDto user = this.userFeignClient.selectByPrimaryKey(obj.getPd_user().getId());
						user.setAvailableBalance(
								BigDecimal.valueOf(CommUtil.add(user.getAvailableBalance(), obj.getPd_amount())));
						this.userFeignClient.updateById(user);
						PredepositLogDto log = new PredepositLogDto();
						log.setAddTime(new Date());
						log.setPd_log_amount(obj.getPd_amount());
						log.setPd_log_user(obj.getPd_user());
						log.setPd_op_type("充值");
						log.setPd_type("可用预存款");
						log.setPd_log_info(payment.getName());
						this.predepositLogFeignClient.saveEntity(log);
					}
				}
				if ("gold".equals(type)) {
					gold = this.goldRecordService.selectByPrimaryKey(CommUtil.null2Long(attachs[0]));
					if ((gold != null) && (gold.getGold_pay_status() != 2) && (sign.equals(gold.getOrder_sign()))) {
						gold.setGold_status(1);
						gold.setGold_pay_status(2);
						gold.setGold_payment(payment.getMark());
						this.goldRecordService.updateById(gold);
						UserDto user = this.userFeignClient.selectByPrimaryKey(gold.getGold_user().getId());
						user.setGold(user.getGold() + gold.getGold_count());
						this.userFeignClient.updateById(user);
						GoldLog log = new GoldLog();
						log.setAddTime(new Date());
						log.setGl_payment(gold.getGold_payment());
						log.setGl_content(payment.getName());
						log.setGl_money(gold.getGold_money());
						log.setGl_count(gold.getGold_count());
						log.setGl_type(0);
						log.setGl_user(gold.getGold_user());
						log.setGr(gold);
						this.goldLogService.saveEntity(log);
					}
				}
				if (type.equals("cloudpurchase")) {
					cp_order = this.cloudPurchaseOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(attachs[0]));
					if (cp_order.getStatus() < 5) {
						cp_order.setStatus(5);
						cp_order.setPayTime(new Date());
						cp_order.setPayment(payment.getMark());
						this.cloudPurchaseOrderFeignClient.updateById(cp_order);
						this.cloudPurchaseOrderFeignClient.reduce_inventory(cp_order, request);
					}
				}
				if (type.equals("platformpay")) {
					PlatformPay pf = this.platformPayService.selectByPrimaryKey(CommUtil.null2Long(attachs[0]));
					if (pf.getPay_status() == 0 && StringUtils.equals(sign, pf.getSign())) {
						pf.setPay_status(1);
						pf.setUpdate_date(new Date());
						pf.setPay_type(payment.getMark());
						this.platformPayService.updateById(pf);
						
						PlatformPayFlow platformpayflow = new PlatformPayFlow();
						platformpayflow.setPlatform_pay_id(pf.getId());
						platformpayflow.setInfo("编号["+pf.getPay_no()+"]店铺保证金,支付成功");
						platformpayflow.setCreate_date(new Date());
						this.platformPayFlowService.saveEntity(platformpayflow);
						UserDto user = userFeignClient.selectByPrimaryKey(pf.getUser_id());
						
						StoreDto store = this.storeFeignClient.selectByPrimaryKey(user.getStore_id());
						store.setDeposit(pf.getAmount());
						this.storeFeignClient.updateById(store);
					}
				}
				PrintWriter write = response.getWriter();
				write.print(
						"<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
			} else {
				PrintWriter write = response.getWriter();
				write.print(
						"<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>");
			}
		} else {
			PrintWriter write = response.getWriter();
			write.print(
					"<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>");
		}
	}
	public Map<String, Object> wxh5_pay(HttpServletRequest request, HttpServletResponse response, Long id,
			String pay_type, String order_type) throws Exception {
		
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
 
		RequestHandler reqHandler = new RequestHandler(request, response);
 
		List<Payment> payments = Lists.newArrayList();
		Map<String, Object> params = Maps.newHashMap();
 
		//TODO
		pay_type="wx_pay";
		params.put("mark", pay_type);
		payments = this.paymentService.queryPageList(params);
 
		Payment payment = null;
		if (payments.size() > 0) {
			payment = (Payment) payments.get(0);
		}
		String body = "";
		String attach = "";
		String out_trade_no = "";
		double total_fee = 0.0D;
		boolean submit = true;
		OrderFormDto of = null;
		PredepositDto pd = null;
		GoldRecord gold = null;
		IntegralGoodsOrderDto ig_order = null;
		CloudPurchaseOrderDto cp_order = null;
		if ((order_type.equals("goods")) || (order_type.equals("group"))) {
			of = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
			if (of.getOrder_status() >= 20) {
				submit = false;
			} else {
				body = of.getOrder_id();
				attach = of.getId() + "_" + of.getOrder_id() + "_" + of.getUser_id() + "_" + order_type +"_"+pay_type;
				out_trade_no = of.getOrder_id();
				total_fee = Double.valueOf(of.getTotalPrice().toString()).doubleValue() * 100.0D;
				resultMap.put("obj", of);
			}
		}
		if (order_type.equals("cash")) {
			pd = this.predepositFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
			if (pd.getPd_pay_status() >= 2) {
				submit = false;
			} else {
				body = pd.getPd_sn();
				attach = pd.getId() + "_" + pd.getPd_sn() + "_" + pd.getPd_user().getId() + "_" + order_type+"_"+pay_type;
				out_trade_no = pd.getPd_sn();
				total_fee = Double.valueOf(pd.getPd_amount().toString()).doubleValue() * 100.0D;
				resultMap.put("obj", pd);
			}
		}
		if (order_type.equals("gold")) {
			gold = this.goldRecordService.selectByPrimaryKey(CommUtil.null2Long(id));
			if (gold.getGold_pay_status() >= 2) {
				submit = false;
			} else {
				body = gold.getGold_sn();
				attach = gold.getId() + "_" + gold.getGold_sn() + "_" + gold.getGold_user().getId() + "_" + order_type+"_"+pay_type;
				out_trade_no = gold.getGold_sn();
				total_fee = Double.valueOf(of.getTotalPrice().toString()).doubleValue() * 100.0D;
				resultMap.put("obj", gold);
			}
		}
		if (order_type.equals("integral")) {
			ig_order = this.integralGoodsOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
			if (ig_order.getIgo_status() >= 20) {
				submit = false;
			} else {
				body = ig_order.getIgo_order_sn();
				attach = ig_order.getId() + "_" + ig_order.getIgo_order_sn() + "_" + ig_order.getIgo_user().getId()
						+ "_" + order_type+"_"+pay_type;
				out_trade_no = ig_order.getIgo_order_sn();
				total_fee = Double.valueOf(ig_order.getIgo_trans_fee().toString()).doubleValue() * 100.0D;
				resultMap.put("obj", ig_order);
			}
		}
		if (order_type.equals("cloudpurchase")) {
			cp_order = this.cloudPurchaseOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(id));
			if (cp_order.getStatus() == 5) {
				submit = false;
			} else {
				body = cp_order.getIgo_order_sn();
				attach = cp_order.getId() + "_" + cp_order.getIgo_order_sn() + "_" + cp_order.getUser_id() + "_"
						+ order_type+"_"+pay_type;
				out_trade_no = cp_order.getIgo_order_sn();
				total_fee = Double.valueOf(cp_order.getPrice()).doubleValue() * 100.0D;
				resultMap.put("obj", cp_order);
			}
		}
		if ((submit) && (payment != null)) {
			if (payment != null) {
				String app_id = payment.getWx_appid();
				String app_key = payment.getWx_paySignKey();
				String partner = payment.getTenpay_partner();
				String notify_url = payment.getNotify_url();
				String noncestr = Sha1Util.getNonceStr();
				String timestamp = Sha1Util.getTimeStamp();
				String path = request.getContextPath();
				String basePath = notify_url + "/";
				reqHandler.setParameter("appid", app_id);
				reqHandler.setParameter("mch_id", partner);
				reqHandler.setParameter("nonce_str", noncestr);
				/*reqHandler.setParameter("device_info", "wechat_mini_program");*/
				reqHandler.setParameter("body", body);
				reqHandler.setParameter("attach", attach);
				reqHandler.setParameter("out_trade_no", out_trade_no);
				BigDecimal total_feeBig = new BigDecimal(total_fee);
				reqHandler.setParameter("total_fee", total_feeBig.setScale(0, BigDecimal.ROUND_UP)+"");
				reqHandler.setParameter("spbill_create_ip", CommUtil.getIpAddr(request));
				reqHandler.setParameter("notify_url", basePath + "weixin_return");
				reqHandler.setParameter("scene_info", "'h5_info':{'type':'Wap','wap_url':'http://haiwah5.minglisoft.cn/','wap_name': '海哇'}");
				reqHandler.setParameter("trade_type", "MWEB");
				// trade_type=JSAPI时,必须传入openid
				UserDto user = userFeignClient.selectByPrimaryKey(CommUtil.null2Long(of.getUser_id()));
				reqHandler.setParameter("openid", user.getOpenId());
 
				String requestUrl = reqHandler.reqToXml(app_key);
				HttpURLConnection conn = creatConnection(requestUrl);
				String result = getInput(conn);
				Map<String, String> map = doXMLParse(result);
				String return_code = ((String) map.get("return_code")).toString();
				String prepay_id = "";
				String code_url = "";
				if ("SUCCESS".equals(return_code)) {
					String result_code = ((String) map.get("result_code")).toString();
					if ("SUCCESS".equals(result_code)) {
						prepay_id = (String) map.get("prepay_id");
						code_url = (String) map.get("code_url");
					} else {
						// 预下单异常信息显示
						log.error(map.toString());
					}
				} else {
					// 预下单异常信息显示
					log.error(map.toString());
				}
				
				reqHandler.getAllParameters().clear();
				String newPackage = "prepay_id=" + prepay_id;
				
				reqHandler.setParameter("appId", app_id);
				reqHandler.setParameter("nonceStr", noncestr);  
				reqHandler.setParameter("package", newPackage);
				reqHandler.setParameter("signType", "MD5");
				reqHandler.setParameter("timeStamp", timestamp+"");
				reqHandler.genSign(app_key);
		
				String order_sign = reqHandler.getParameter("sign");
				resultMap.put("app_id", app_id);
				resultMap.put("timestamp", timestamp+"");
				resultMap.put("noncestr", noncestr);
				resultMap.put("packageValue", newPackage);
				resultMap.put("sign", order_sign);
				resultMap.put("code_url", code_url);
				resultMap.put("signType", "MD5");
				
				System.out.print("返回给前端---------------------------");
				System.out.print(resultMap.toString());
				System.out.print("返回给前端---------------------------");
				reqHandler.getAllParameters().clear();
				reqHandler.setParameter("appId", app_id);
				reqHandler.setParameter("nonceStr", noncestr);
				reqHandler.genSign(app_key);
				order_sign=reqHandler.getParameter("sign");
				
				if ((order_type.equals("goods")) || (order_type.equals("group"))) {
					of.setOrder_sign(order_sign);
					this.orderFormFeignClient.updateById(of);
				}
				if (order_type.equals("cash")) {
					pd.setOrder_sign(order_sign);
					this.predepositFeignClient.updateById(pd);
				}
				if (order_type.equals("gold")) {
					gold.setOrder_sign(order_sign);
					this.goldRecordService.updateById(gold);
				}
				if (order_type.equals("integral")) {
					ig_order.setOrder_sign(order_sign);
					this.integralGoodsOrderFeignClient.updateById(ig_order);
				}
				if (order_type.equals("cloudpurchase")) {
					cp_order.setOrder_sign(order_sign);
					this.cloudPurchaseOrderFeignClient.updateById(cp_order);
				}
			} else {
				return ResponseCode.buildCodeMap("20001", "支付方式错误!", null);
			}
		} else {
			return ResponseCode.buildCodeMap("20001", "支付方式错误!", null);
		}
		
		
		return ResponseCode.buildSuccessMap(resultMap) ;
		
	}
	@RequestMapping({ "/pay/ditu" })
	public Map<String, Object> ditu(HttpServletRequest request, HttpServletResponse response,
			@RequestBody JSONObject json) throws Exception {
		List<Payment> payments = Lists.newArrayList();
		Map<String, Object> params = Maps.newHashMap();
 
		params.put("mark", "wx_pay");
		payments = this.paymentService.queryPageList(params);
 
		Payment payment = null;
		if (payments.size() > 0) {
			payment = (Payment) payments.get(0);
		}
		String app_id = payment.getWx_appid();
		String app_key = payment.getWx_paySignKey();
		String noncestr = Sha1Util.getNonceStr();
		String timestamp = Sha1Util.getTimeStamp();
		
		
		//String accessToken = accessTokenTools.getAccessTokenOld(app_id, payment.getWx_appSecret());
		String accessToken = accessTokenTools.getAccessToken(app_id, payment.getWx_appSecret());
		System.out.println("accessToken===="+accessToken);
		Map<String, String> jsapiTicket = accessTokenTools.JsapiTicket(accessToken);
		String str = "jsapi_ticket="+jsapiTicket.get("ticket")+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+"http://haiwah5.minglisoft.cn/";
		String signature = Sha1Util.getSha1(str);
		//String signature = SHA1.SHA1(str);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("app_id", payment.getWx_appid());
		resultMap.put("timestamp", timestamp + "");
		resultMap.put("nonceStr", noncestr);
		resultMap.put("jsapiTicket", jsapiTicket.get("ticket"));
		resultMap.put("sign", signature);
		
		return ResponseCode.buildSuccessMap(resultMap);
	}
	/**
	 * 支付宝app 支付成功 处理订单
	 * @param request
	 * @param payment 支付方式
	 * @param type 类型
	 * @param attachs 附加参数
	 */
	private  void afterNotifyOrderHandling_alipay(HttpServletRequest request,Payment payment,String type,String[] attachs ){
		OrderFormDto main_order = null;
		PredepositDto obj = null;
		GoldRecord gold = null;
		IntegralGoodsOrderDto ig_order = null;
		CloudPurchaseOrderDto cp_order = null;
 
		if (("goodsfirst".equals(type)) || ("groupfirst".equals(type))) {
			main_order = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(attachs[0]));
			if(main_order==null||main_order.getOrder_status()!=10){
				return;
			}
			main_order.setPayTime(new Date());
			main_order.setPayment_mark(payment.getMark());
			main_order.setPayment_name(payment.getName());
			boolean flag = false;
			//查询修改相关子订单
			main_order.setOrder_first(0);
			flag = this.handleOrderFormFeignClient.payByOnline(main_order, "", CommUtil.getURL(request));
			if (flag) {
				main_order.setOrder_status(20);
 
				//分销收益
				try{
					disAgentProfit(main_order);
					sendOrderMessage(main_order);
					if(main_order.getChild_order_detail() != null){
						List<Map> datalist = com.alibaba.fastjson.JSONObject.parseArray(main_order.getChild_order_detail(), Map.class);
						for (Map map : datalist) {
							Integer order_id = (Integer) map.get("order_id");
							OrderFormDto order = orderFormFeignClient.selectByPrimaryKey(order_id.longValue());
							if(order != null){
								disAgentProfit(order);
								sendOrderMessage(order);
							}
						}
					}
 
				}catch (Exception e) {
					logger.error("PayController >> weixin_return(distribution&agentProfit【goods_first】) >> Exception:"+ e.getMessage());
				}
				//更新库存
				this.orderFormToolsFeignClient.updateGoodsInventory(main_order);
				//该订单存在直播商品
				if (main_order.getLiveorder_type() != null && main_order.getLiveorder_type()==1) {
					liveOrderFeignClient.updateLiveOrder(main_order);
				}
 
				//如果订单是增值服务,修改用户   审核状态
				if (main_order.getOrder_cat() != null && main_order.getOrder_cat()==4) {
					userFeignClient.updateLiveById(CommUtil.null2Long(main_order.getUser_id()));
				}
				//如果订单是拉新用户订单  ,  添加
				if (main_order.getOrder_cat() != null && main_order.getOrder_cat()==5) {
					main_order.setOrder_status(14);
					orderFormFeignClient.updateById(main_order);
				}else{
					if(main_order.getCheck_in_time() != null){
						sendHotelMessage(main_order);
					}else if(main_order.getOrder_offline()==1){
						//TODO 待修改 , 验证码消息
					}else{
						try{
							sendTxMessage(main_order);
							if(main_order.getChild_order_detail() != null){
								List<Map> datalist = com.alibaba.fastjson.JSONObject.parseArray(main_order.getChild_order_detail(), Map.class);
								for (Map map : datalist) {
									Integer order_id = (Integer) map.get("order_id");
									OrderFormDto order = orderFormFeignClient.selectByPrimaryKey(order_id.longValue());
									if(order != null){
										sendTxMessage(main_order);
									}
								}
							}
 
						}catch (Exception e) {
							logger.error("PayController >> weixin_return(sendTxMessage【goods_first】) >> Exception:"+ e.getMessage());
						}
					}
				}
				//发站内消息
							/*//拓展配置中分销为开启
							if(null !=sysConfigExtendDto && sysConfigExtendDto.isDistribution_open() && main_order.getOrder_cat()==0){
								OrderFormDto updateorder=main_order;
								//更新分销订单状态
								updateorder.setOrder_status(20);
								distributionOrderFeignClient.updateOrderStatus(updateorder);
							}*/
 
			}
			this.orderFormToolsFeignClient.sendMsgWhenHandleOrder(CommUtil.getURL(request), main_order,
					"tobuyer_online_pay_ok_notify", "toseller_online_pay_ok_notify");
 
 
		}
		if (("goods".equals(type)) || ("group".equals(type))) {
			main_order = this.orderFormFeignClient.selectByPrimaryKey(CommUtil.null2Long(attachs[0]));
			if(main_order==null||main_order.getOrder_status()!=10){
				return;
			}
			main_order.setPayTime(new Date());
			main_order.setPayment_mark(payment.getMark());
			main_order.setPayment_name(payment.getName());
			boolean flag = false;
			//不查询相关子订单
			main_order.setOrder_first(1);
			flag = this.handleOrderFormFeignClient.payByOnline(main_order, "", CommUtil.getURL(request));
			if (flag) {
				main_order.setOrder_status(20);
				try{
					disAgentProfit(main_order);
					sendOrderMessage(main_order);
				}catch (Exception e) {
					logger.error("PayController >> weixin_return(distribution&agentProfit【goods】) >> Exception:"+ e.getMessage());
				}
				if (main_order.getOrder_cat() != null && main_order.getOrder_cat() != 5) {
					if (main_order.getCheck_in_time() != null) {
						sendHotelMessage(main_order);
					} else if(main_order.getOrder_offline()==1){
						//TODO 待修改 , 验证码消息
					}else {
						try {
							sendTxMessage(main_order);
						} catch (Exception e) {
							logger.error(
									"PayController >> weixin_return(sendTxMessage【goods】) >> Exception:"
											+ e.getMessage());
						}
					}
				}
				//更新库存
				this.orderFormToolsFeignClient.updateGoodsInventory(main_order);
				//该订单存在直播商品
				if (main_order.getLiveorder_type() != null && main_order.getLiveorder_type()==1) {
					liveOrderFeignClient.updateLiveOrder(main_order);
				}
 
				//如果订单是增值服务,修改用户   审核状态
				if (main_order.getOrder_cat() != null && main_order.getOrder_cat()==4) {
					userFeignClient.updateLiveById(CommUtil.null2Long(main_order.getUser_id()));
				}
				//如果订单是拉新用户订单  ,  添加
				if (main_order.getOrder_cat() != null && main_order.getOrder_cat()==5) {
					main_order.setOrder_status(14);
					orderFormFeignClient.updateById(main_order);
				}
 
			}
			this.orderFormToolsFeignClient.sendMsgWhenHandleOrder(CommUtil.getURL(request), main_order,
					"tobuyer_online_pay_ok_notify", "toseller_online_pay_ok_notify");
 
 
		}
		if ("integral".equals(type)) {
			ig_order = this.integralGoodsOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(attachs[0]));
			if (ig_order != null && ig_order.getIgo_status() < 20) {
 
 
				ig_order.setIgo_status(20);
				ig_order.setIgo_pay_time(new Date());
				ig_order.setIgo_payment(payment.getMark());
				this.integralGoodsOrderFeignClient.updateById(ig_order);
				List<Map> ig_maps = this.orderFormToolsFeignClient
						.query_integral_goodsinfo(ig_order.getGoods_info());
				for (Map map : ig_maps) {
					IntegralGoodsDto goods = this.integralGoodsFeignClient
							.selectByPrimaryKey(CommUtil.null2Long(map.get("id")));
					goods.setIg_goods_count(
							goods.getIg_goods_count() - CommUtil.null2Int(map.get("ig_goods_count")));
					goods.setIg_exchange_count(
							goods.getIg_exchange_count() + CommUtil.null2Int(map.get("ig_goods_count")));
					this.integralGoodsFeignClient.updateById(goods);
				}
			}
		}
		if ("cash".equals(type)) {
			obj = this.predepositFeignClient.selectByPrimaryKey(CommUtil.null2Long(attachs[0]));
			if (obj != null && obj.getPd_pay_status() != 2) {
 
				obj.setPd_payment(payment.getMark());
				obj.setPd_status(1);
				obj.setPd_pay_status(2);
				this.predepositFeignClient.updateById(obj);
				UserDto user = this.userFeignClient.selectByPrimaryKey(obj.getPd_user().getId());
				user.setAvailableBalance(
						BigDecimal.valueOf(CommUtil.add(user.getAvailableBalance(), obj.getPd_amount())));
				this.userFeignClient.updateById(user);
				PredepositLogDto log = new PredepositLogDto();
				log.setAddTime(new Date());
				log.setPd_log_amount(obj.getPd_amount());
				log.setPd_log_user(obj.getPd_user());
				log.setPd_op_type("充值");
				log.setPd_type("可用预存款");
				log.setPd_log_info(payment.getName());
				this.predepositLogFeignClient.saveEntity(log);
			}
		}
		if ("gold".equals(type)) {
			gold = this.goldRecordService.selectByPrimaryKey(CommUtil.null2Long(attachs[0]));
			if (gold != null && gold.getGold_pay_status() != 2) {
				gold.setGold_status(1);
				gold.setGold_pay_status(2);
				gold.setGold_payment(payment.getMark());
				this.goldRecordService.updateById(gold);
				UserDto user = this.userFeignClient.selectByPrimaryKey(gold.getGold_user().getId());
				user.setGold(user.getGold() + gold.getGold_count());
				this.userFeignClient.updateById(user);
				GoldLog log = new GoldLog();
				log.setAddTime(new Date());
				log.setGl_payment(gold.getGold_payment());
				log.setGl_content(payment.getName());
				log.setGl_money(gold.getGold_money());
				log.setGl_count(gold.getGold_count());
				log.setGl_type(0);
				log.setGl_user(gold.getGold_user());
				log.setGr(gold);
				this.goldLogService.saveEntity(log);
			}
		}
		if (type.equals("cloudpurchase")) {
			cp_order = this.cloudPurchaseOrderFeignClient.selectByPrimaryKey(CommUtil.null2Long(attachs[0]));
			if (cp_order.getStatus() < 5) {
				cp_order.setStatus(5);
				cp_order.setPayTime(new Date());
				cp_order.setPayment(payment.getMark());
				this.cloudPurchaseOrderFeignClient.updateById(cp_order);
				this.cloudPurchaseOrderFeignClient.reduce_inventory(cp_order, request);
			}
		}
		if (type.equals("platformpay")) {
			PlatformPay pf = this.platformPayService.selectByPrimaryKey(CommUtil.null2Long(attachs[0]));
			if (pf.getPay_status() == 0 ) {
				pf.setPay_status(1);
				pf.setUpdate_date(new Date());
				pf.setPay_type(payment.getMark());
				this.platformPayService.updateById(pf);
 
				PlatformPayFlow platformpayflow = new PlatformPayFlow();
				platformpayflow.setPlatform_pay_id(pf.getId());
				platformpayflow.setInfo("编号["+pf.getPay_no()+"]店铺保证金,支付成功");
				platformpayflow.setCreate_date(new Date());
				this.platformPayFlowService.saveEntity(platformpayflow);
				UserDto user = userFeignClient.selectByPrimaryKey(pf.getUser_id());
 
				StoreDto store = this.storeFeignClient.selectByPrimaryKey(user.getStore_id());
				store.setDeposit(pf.getAmount());
				this.storeFeignClient.updateById(store);
			}
		}
	}
}

支持支付宝、微信APP支付、H5、公众号、小程序支付

  游戏开发 最新文章
6、英飞凌-AURIX-TC3XX: PWM实验之使用 GT
泛型自动装箱
CubeMax添加Rtthread操作系统 组件STM32F10
python多线程编程:如何优雅地关闭线程
数据类型隐式转换导致的阻塞
WebAPi实现多文件上传,并附带参数
from origin ‘null‘ has been blocked by
UE4 蓝图调用C++函数(附带项目工程)
Unity学习笔记(一)结构体的简单理解与应用
【Memory As a Programming Concept in C a
上一篇文章      下一篇文章      查看所有文章
加:2022-02-09 21:02:32  更:2022-02-09 21:03:48 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/27 16:39:55-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码