电商平台-支付模块的设计与架构

开源生鲜电商平台支付目前支持支付宝与微信。针对的是APP端(android or IOS)

1. 数据库表设计

说明:

无论是支付宝还是微信支付,都会有一个服务端的回调,业务根据回调的结果处理相应的业务逻辑。

pay_logs这个表主要是记录相关的用户支付信息。是一个日志记录。

比如:谁付款的,什么时候付款的,订单号多少,是支付宝还是微信,支付状态是支付成功还是支付失败,还是未支付。

特别注意:订单主表也有类似的回调信息。这样用多张表记录相应的信息,可以统计相应的业务指标,包括用户的行为分析等。

 关于表的设计,我的经验分享是:如果可以,核心业务表一定要有一个日志记录表,如果可以,可以用时间轴等方式进行数据的插入,与时间轴的显示。时间轴可以清楚的知道用户的行为点,帮助更加清晰的设计业务流程与系统架构。           

相应的支付宝回调代码如下:(注意,这个业务模块属于买家。)

APP调用后端的业务代码

  1. /***
  2. * APP端调用请求支付宝
  3. */
  4. @RestController
  5. @RequestMapping( "/buyer")
  6. public class AlipayController extends BaseController
  7. {
  8. private static final Logger logger = LoggerFactory.getLogger(AlipayController.class);
  9. /**
  10. * 服务器通知地址
  11. */
  12. private static final String NOTIFY_URL= "";
  13. /**待支付*/
  14. private static final int PAY_LOGS_READY= 0;
  15. @Autowired
  16. private OrderInfoService orderInfoService;
  17. @Autowired
  18. private BuyerService buyerService;
  19. @Autowired
  20. private PayLogsService payLogsService; /**
  21. * APP端请求调用支付宝
  22. * @param request
  23. * @param response
  24. * @return
  25. */
  26. @RequestMapping(value= "/alipay/invoke",method={RequestMethod.GET,RequestMethod.POST})
  27. public JsonResult alipayInvoke(HttpServletRequest req, HttpServletResponse resp)
  28. {
  29. String result= "";
  30. try
  31. {
  32. /**订单号*/
  33. String orderNumber= this.getNotNull( "orderNumber", req);
  34. /**金额*/
  35. String money= this.getNotNull( "money", req);
  36. /**优惠券id*/
  37. String couponReceiveId = req.getParameter( "couponReceiveId");
  38. if(StringUtils.isBlank(orderNumber) || StringUtils.isBlank(money))
  39. {
  40. return new JsonResult(JsonResultCode.FAILURE, "请求参数有误,请稍后重试", "");
  41. }
  42. //对比金额
  43. OrderInfo orderInfo= this.orderInfoService.getOrderInfoByOrderNumber(orderNumber);
  44. if(orderInfo== null)
  45. {
  46. return new JsonResult(JsonResultCode.FAILURE, "订单号不存在,请稍后重试", "");
  47. }
  48. //获取订单的金额
  49. BigDecimal orderAmount=orderInfo.getOrderAmount();
  50. //减余额
  51. Long buyerId=orderInfo.getBuyerId();
  52. Buyer buyer= this.buyerService.getBuyerById(buyerId);
  53. //用户余额
  54. BigDecimal balanceMoney=buyer.getBalanceMoney();
  55. //计算最终需要给支付宝的金额
  56. BigDecimal payAmount=orderAmount.subtract(balanceMoney);
  57. //买家支付时抵扣优惠券
  58. if(StringUtils.isNotBlank(couponReceiveId)){
  59. Long id = Long.parseLong(couponReceiveId);
  60. payAmount = couponReceiveService.deductionCouponMoney(id, orderNumber, payAmount);
  61. }
  62. logger.info( "[AlipayController][alipayInvoke] orderNumber:" +orderNumber + " money:" +money+ " orderAmount:"+orderAmount+ " balanceMoney:"+balanceMoney+ " payAmount:" +payAmount);
  63. //考虑重复订单的问题,会产生重复日志
  64. PayLogs payLogs= this.payLogsService.getPayLogsByOrderNumber(orderNumber);
  65. if(payLogs== null)
  66. {
  67. //创建订单日志
  68. PayLogs logs= new PayLogs();
  69. logs.setUserId(buyerId);
  70. logs.setOrderId(orderInfo.getOrderId());
  71. logs.setOrderNumber(orderNumber);
  72. logs.setOrderAmount(payAmount);
  73. logs.setStatus(PAY_LOGS_READY);
  74. logs.setCreateTime( new Date());
  75. int payLogsResult=payLogsService.addPayLogs(logs);
  76. logger.info( "[AlipayController][alipayInvoke] 创建订单日志结果:" + (payLogsResult> 0));
  77. } else
  78. {
  79. logger.info( "[AlipayController][alipayInvoke] 创建重复订单");
  80. }
  81. AlipayClient alipayClient = new DefaultAlipayClient( "https://openapi.alipay.com/gateway.do", "", "", "json", "UTF-8", "", "RSA2");
  82. AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
  83. AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
  84. model.setBody( "");
  85. model.setSubject( "xxx");
  86. model.setOutTradeNo(orderNumber);
  87. model.setTimeoutExpress( "15m");
  88. model.setTotalAmount(payAmount.toString());
  89. model.setProductCode( "QUICK_MSECURITY_PAY");
  90. request.setBizModel(model);
  91. request.setNotifyUrl(NOTIFY_URL);
  92. AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
  93. result=response.getBody();
  94. logger.info( "[AlipayController][alipayNotify] result: " +result);
  95. } catch (AlipayApiException ex)
  96. {
  97. logger.error( "[AlipayController][alipayNotify] exception:",ex);
  98. return new JsonResult(JsonResultCode.FAILURE, "系统错误,请稍后重试", "");
  99. }
  100. return new JsonResult(JsonResultCode.SUCCESS, "操作成功",result);
  101. }
  102. }

支付宝服务端回调代码

  1. import java.io.IOException;
  2. import java.math.BigDecimal;
  3. import java.util.Date;
  4. import java.util.Enumeration;
  5. import java.util.HashMap;
  6. import java.util.Iterator;
  7. import java.util.Map;
  8. import javax.servlet.ServletOutputStream;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import org.apache.commons.lang3.StringUtils;
  12. import org.slf4j.Logger;
  13. import org.slf4j.LoggerFactory;
  14. import org.springframework.beans.factory.annotation.Autowired;
  15. import org.springframework.stereotype.Controller;
  16. import org.springframework.web.bind.annotation.RequestMapping;
  17. import org.springframework.web.bind.annotation.RequestMethod;
  18. import com.alipay.api.AlipayApiException;
  19. import com.alipay.api.internal.util.AlipaySignature;
  20. /**
  21. * alipay 支付宝服务端回调
  22. * 参考文档:https://docs.open.alipay.com/204/105301/
  23. * 对于App支付产生的交易,支付宝会根据原始支付API中传入的异步通知地址notify_url,通过POST请求的形式将支付结果作为参数通知到商户系统。
  24. */
  25. @Controller
  26. @RequestMapping( "/buyer")
  27. public class AlipayNotifyController extends BaseController {
  28. private static final Logger logger = LoggerFactory.getLogger(AlipayNotifyController.class);
  29. private static final String ALIPAYPUBLICKEY = "";
  30. private static final String CHARSET = "UTF-8";
  31. /**支付成功*/
  32. private static final int PAY_LOGS_SUCCESS= 1;
  33. @Autowired
  34. private OrderInfoService orderInfoService;
  35. @RequestMapping(value = "/alipay/notify", method = { RequestMethod.GET, RequestMethod.POST })
  36. public void alipayNotify(HttpServletRequest request, HttpServletResponse response) throws IOException
  37. {
  38. String url=request.getRequestURL().toString();
  39. logger.info( "AlipayNotifyController.alipayNotify.s+tart");
  40. logger.info( "[AlipayNotifyController][alipayNotify] url:" +url);
  41. ServletOutputStream out = response.getOutputStream();
  42. //支付宝交易号
  43. String alipayTradeNo= this.getNotNull( "trade_no", request);
  44. //商户订单号
  45. String outerTradeNo= this.getNotNull( "out_trade_no", request);
  46. //买家支付宝用户号
  47. String buyerId= this.getNotNull( "buyer_id", request);
  48. //买家支付宝账号
  49. String buyerLogonId= this.getNotNull( "buyer_logon_id", request);
  50. //交易状态
  51. String tradeStatus= this.getNotNull( "trade_status", request);
  52. //订单金额,精确到小数点后2位
  53. String money=getNotNull( "total_amount", request);
  54. logger.info( "[AlipayNotifyController][alipayNotify] tradeStatus:" +tradeStatus+ " money:"+money);
  55. StringBuffer buf = new StringBuffer();
  56. if (request.getMethod().equalsIgnoreCase( "POST"))
  57. {
  58. Enumeration em = request.getParameterNames();
  59. for (; em.hasMoreElements();)
  60. {
  61. Object o = em.nextElement();
  62. buf.append(o).append( "=").append(request.getParameter(o.toString())).append( ",");
  63. }
  64. logger.info( "回调 method:post]http://" + request.getServerName() + request.getServletPath() + " [ + buf + ">]");
  65. } else
  66. {
  67. buf.append(request.getQueryString());
  68. logger.info( "回调 method:get]http://" + request.getServerName() + request.getServletPath() + "?" + request.getQueryString());
  69. }
  70. //检验支付宝参数
  71. if(!verifyAlipay(request))
  72. {
  73. out.print( "fail");
  74. return;
  75. }
  76. //交易成功
  77. if( "TRADE_SUCCESS".equalsIgnoreCase(tradeStatus))
  78. {
  79. try
  80. {
  81. if(StringUtils.isNotBlank(outerTradeNo))
  82. {
  83. //查询当前订单信息
  84. OrderInfo info= this.orderInfoService.getOrderInfoByOrderNumber(outerTradeNo);
  85. if(info== null)
  86. {
  87. logger.error( "[AlipayNotifyController][alipayNotify] info:" +info);
  88. out.print( "fail");
  89. return;
  90. }
  91. //订单信息
  92. OrderInfo orderInfo= new OrderInfo();
  93. orderInfo.setOrderNumber(outerTradeNo);
  94. orderInfo.setCardCode( "alipay");
  95. orderInfo.setCardName( "支付宝");
  96. orderInfo.setCardNumber(buyerLogonId);
  97. orderInfo.setCardOwner(buyerId);
  98. orderInfo.setPayTime( new Date());
  99. orderInfo.setOuterTradeNo(alipayTradeNo);
  100. orderInfo.setPayStatus(PayStatus.PAY_SUCCESS);
  101. orderInfo.setTradeStatus(TradeStatus.TRADE_PROGRESS);
  102. orderInfo.setPayAmount( new BigDecimal(money));
  103. orderInfo.setBuyerId(info.getBuyerId());
  104. //付款日志
  105. PayLogs payLogs= new PayLogs();
  106. payLogs.setOrderNumber(outerTradeNo);
  107. payLogs.setOuterTradeNo(alipayTradeNo);
  108. payLogs.setStatus(PAY_LOGS_SUCCESS);
  109. orderInfoService.payReturn(orderInfo,payLogs);
  110. out.print( "success");
  111. return;
  112. }
  113. } catch(Exception ex)
  114. {
  115. logger.error( "[AlipayNotifyController][payReturn] 出现了异常:",ex);
  116. out.print( "success");
  117. return;
  118. }
  119. } else
  120. {
  121. out.print( "fail");
  122. return;
  123. }
  124. }
  125. /**
  126. * 检验支付宝
  127. * @param request
  128. * @return
  129. */
  130. @SuppressWarnings( "rawtypes")
  131. public boolean verifyAlipay(HttpServletRequest request)
  132. {
  133. boolean flag= true;
  134. // 获取支付宝POST过来反馈信息
  135. Map params = new HashMap();
  136. Map requestParams = request.getParameterMap();
  137. for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
  138. String name = (String) iter.next();
  139. String[] values = (String[]) requestParams.get(name);
  140. String valueStr = "";
  141. for ( int i = 0; i < values.length; i++) {
  142. valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
  143. }
  144. params.put(name, valueStr);
  145. }
  146. try
  147. {
  148. flag= AlipaySignature.rsaCheckV1(params, ALIPAYPUBLICKEY, CHARSET, "RSA2");
  149. } catch (AlipayApiException e) {
  150. e.printStackTrace();
  151. flag= false;
  152. }
  153. return flag;
  154. }
  155. }

APP支付成功后,其实支付宝或者微信都会告诉你是否成功,只是这种通知是不可靠的,最可靠的的一种方式是支付宝或者微信的服务端回调。

根据回调处理相关的业务。

相应的微信回调代码如下:(注意,这个业务模块属于买家。)

APP调用微信:

  1. /***
  2. * APP端调用请求微信
  3. */
  4. @RestController
  5. @RequestMapping( "/buyer")
  6. public class WeiXinController extends BaseController
  7. {
  8. private static final Logger logger = LoggerFactory.getLogger(WeiXinController.class);
  9. /**待支付*/
  10. private static final int PAY_LOGS_READY= 0;
  11. @Autowired
  12. private OrderInfoService orderInfoService;
  13. @Autowired
  14. private BuyerService buyerService;
  15. @Autowired
  16. private PayLogsService payLogsService;
  17. @Autowired
  18. private CouponReceiveService couponReceiveService;
  19. /**
  20. * APP端请求调用微信
  21. * @param request
  22. * @param response
  23. * @return
  24. */
  25. @RequestMapping(value= "/weixin/invoke",method={RequestMethod.GET,RequestMethod.POST})
  26. public JsonResult weixinInvoke(HttpServletRequest req, HttpServletResponse resp)
  27. {
  28. try
  29. {
  30. /**订单号*/
  31. String orderNumber= this.getNotNull( "orderNumber", req);
  32. /**金额*/
  33. String money= this.getNotNull( "money", req);
  34. /**优惠券id*/
  35. String couponReceiveId = req.getParameter( "couponReceiveId");
  36. if(StringUtils.isBlank(orderNumber) || StringUtils.isBlank(money))
  37. {
  38. return new JsonResult(JsonResultCode.FAILURE, "请求参数有误,请稍后重试", "");
  39. }
  40. //对比金额
  41. OrderInfo orderInfo= this.orderInfoService.getOrderInfoByOrderNumber(orderNumber);
  42. if(orderInfo== null)
  43. {
  44. return new JsonResult(JsonResultCode.FAILURE, "订单号不存在,请稍后重试", "");
  45. }
  46. //获取订单的金额
  47. BigDecimal orderAmount=orderInfo.getOrderAmount();
  48. //减余额
  49. Long buyerId=orderInfo.getBuyerId();
  50. Buyer buyer= this.buyerService.getBuyerById(buyerId);
  51. //用户余额
  52. BigDecimal balanceMoney=buyer.getBalanceMoney();
  53. //计算最终需要给微信的金额
  54. BigDecimal payAmount=orderAmount.subtract(balanceMoney);
  55. //买家支付时抵扣优惠券
  56. if(StringUtils.isNotBlank(couponReceiveId)){
  57. Long id = Long.parseLong(couponReceiveId);
  58. payAmount = couponReceiveService.deductionCouponMoney(id, orderNumber, payAmount);
  59. }
  60. logger.info( "[WeiXinController][weixinInvoke] orderNumber:" +orderNumber + " money:" +money+ " orderAmount:"+orderAmount+ " balanceMoney:"+balanceMoney+ " payAmount:" +payAmount);
  61. //考虑重复订单的问题,会产生重复日志
  62. PayLogs payLogs= this.payLogsService.getPayLogsByOrderNumber(orderNumber);
  63. if(payLogs== null)
  64. {
  65. //创建订单日志
  66. PayLogs logs= new PayLogs();
  67. logs.setUserId(buyerId);
  68. logs.setOrderId(orderInfo.getOrderId());
  69. logs.setOrderNumber(orderNumber);
  70. logs.setOrderAmount(payAmount);
  71. logs.setStatus(PAY_LOGS_READY);
  72. logs.setCreateTime( new Date());
  73. int payLogsResult=payLogsService.addPayLogs(logs);
  74. logger.info( "[WeiXinController][weixinInvoke] 创建订单日志结果:" + (payLogsResult> 0));
  75. } else
  76. {
  77. logger.info( "[WeiXinController][weixinInvoke] 创建重复订单");
  78. }
  79. //微信开始
  80. SortedMap paramMap = new TreeMap();
  81. paramMap.put( "appid", WeiXinUtil.APPID);
  82. paramMap.put( "mch_id", WeiXinUtil.MCHID);
  83. String nonceStr=RandomUtil.generateString( 8);
  84. // 随机字符串
  85. paramMap.put( "nonce_str", nonceStr);
  86. paramMap.put( "body", "魔笛食材"); // 商品描述
  87. paramMap.put( "out_trade_no", orderNumber); // 商户订单编号
  88. paramMap.put( "total_fee",Math.round(payAmount.doubleValue()* 100));
  89. //IP地址
  90. String ip=IpUtils.getIpAddr(req);
  91. paramMap.put( "spbill_create_ip",ip);
  92. paramMap.put( "notify_url", WeiXinUtil.NOTIFYURL); // 回调地址
  93. paramMap.put( "trade_type",WeiXinUtil.TRADETYPE); // 交易类型APP
  94. String sign=createSign(paramMap);
  95. paramMap.put( "sign", sign); // 数字签证
  96. logger.info( "weixin支付请求IP:" +ip+ " sign:" +sign);
  97. String xml = getRequestXML(paramMap);
  98. String content = HttpClientUtil.getInstance().sendHttpPost(WeiXinUtil.URL,xml, "UTF-8");
  99. logger.info( "weixin支付请求的内容content:" +content);
  100. JSONObject jsonObject = JSONObject.fromObject(XmltoJsonUtil.xml2JSON(content));
  101. JSONObject resultXml = jsonObject.getJSONObject( "xml");
  102. //返回的编码
  103. JSONArray returnCodeArray =resultXml.getJSONArray( "return_code");
  104. //返回的消息
  105. JSONArray returnMsgArray =resultXml.getJSONArray( "return_msg");
  106. //结果编码
  107. JSONArray resultCodeArray =resultXml.getJSONArray( "result_code");
  108. String returnCode= (String)returnCodeArray.get( 0);
  109. String returnMsg= (String)returnMsgArray.get( 0);
  110. String resultCode = (String)resultCodeArray.get( 0);
  111. logger.info( "[WeiXinController][weixinInvoke] returnCode: " +returnCode+ " returnMsg:"+returnMsg + " resultCode:"+resultCode);
  112. if(resultCode.equalsIgnoreCase( "FAIL"))
  113. {
  114. return new JsonResult(JsonResultCode.FAILURE, "微信统一订单下单失败", "");
  115. }
  116. if(resultCode.equalsIgnoreCase( "SUCCESS"))
  117. {
  118. JSONArray prepayIdArray =resultXml.getJSONArray( "prepay_id");
  119. String prepayId= (String)prepayIdArray.get( 0);
  120. WeiXinBean weixin= new WeiXinBean();
  121. weixin.setAppid(WeiXinUtil.APPID);
  122. weixin.setPartnerid(WeiXinUtil.MCHID);
  123. weixin.setNoncestr(nonceStr);
  124. weixin.setPrepayid(prepayId);
  125. String timestamp=System.currentTimeMillis()/ 1000+ "";
  126. weixin.setTimestamp(timestamp);
  127. //最终返回签名
  128. SortedMap apiMap = new TreeMap();
  129. apiMap.put( "appid", WeiXinUtil.APPID);
  130. apiMap.put( "partnerid", WeiXinUtil.MCHID);
  131. apiMap.put( "prepayid", prepayId);
  132. apiMap.put( "package", "Sign=WXPay");
  133. apiMap.put( "noncestr",nonceStr);
  134. apiMap.put( "timestamp", timestamp);
  135. //再次签名
  136. weixin.setSign(createSign(apiMap));
  137. return new JsonResult(JsonResultCode.SUCCESS, "微信统一订单下单成功",weixin);
  138. }
  139. return new JsonResult(JsonResultCode.FAILURE, "操作失败", "");
  140. } catch (Exception ex)
  141. {
  142. logger.error( "[WeiXinController][weixinInvoke] exception:",ex);
  143. return new JsonResult(JsonResultCode.FAILURE, "系统错误,请稍后重试", "");
  144. }
  145. }
  146. //拼接xml 请求路径
  147. @SuppressWarnings({ "rawtypes"})
  148. private String getRequestXML(SortedMap parame){
  149. StringBuffer buffer = new StringBuffer();
  150. buffer.append( "");
  151. Set set = parame.entrySet();
  152. Iterator iterator = set.iterator();
  153. while(iterator.hasNext()){
  154. Map.Entry entry = (Map.Entry) iterator.next();
  155. String key =String.valueOf(entry.getKey());
  156. String value = String.valueOf(entry.getValue());
  157. //过滤相关字段sign
  158. if( "sign".equalsIgnoreCase(key)){
  159. buffer.append( "<"+key+ ">"+ "+value+ "]]>"+ "+key+ ">");
  160. } else{
  161. buffer.append( "<"+key+ ">"+value+ "+key+ ">");
  162. }
  163. }
  164. buffer.append( "");
  165. return buffer.toString();
  166. }
  167. //创建md5 数字签证
  168. @SuppressWarnings({ "rawtypes"})
  169. private String createSign(SortedMap param){
  170. StringBuffer buffer = new StringBuffer();
  171. Set set = param.entrySet();
  172. Iterator iterator = set.iterator();
  173. while(iterator.hasNext()){
  174. Map.Entry entry = (Map.Entry) iterator.next();
  175. String key = String.valueOf(entry.getKey());
  176. Object value =String.valueOf(entry.getValue());
  177. if( null != value && ! "".equals(value) && ! "sign".equals(key) && ! "key".equals(key)){
  178. buffer.append(key+ "="+value+ "&");
  179. }
  180. }
  181. buffer.append( "key="+WeiXinUtil.APIKEY);
  182. String sign =EncryptUtil.getMD5(buffer.toString()).toUpperCase();
  183. return sign;
  184. }
  185. }

微信回调接口:

  1. /**
  2. * weixin 微信服务端回调
  3. */
  4. @Controller
  5. @RequestMapping( "/buyer")
  6. public class WeiXinNotifyController extends BaseController {
  7. private static final Logger logger = LoggerFactory.getLogger(WeiXinNotifyController.class);
  8. /**支付成功*/
  9. private static final int PAY_LOGS_SUCCESS= 1;
  10. @Autowired
  11. private OrderInfoService orderInfoService;
  12. @Autowired
  13. private CouponReceiveService couponReceiveService;
  14. @Autowired
  15. private GroupsService groupsService;
  16. @RequestMapping(value = "/weixin/notify", method = { RequestMethod.GET, RequestMethod.POST })
  17. public void weixinNotify(HttpServletRequest request, HttpServletResponse response) throws IOException
  18. {
  19. String url=request.getRequestURL().toString();
  20. logger.info( "WeiXinNotifyController.weixinNotify.start-->url:" +url);
  21. try
  22. {
  23. StringBuffer buf = new StringBuffer();
  24. if (request.getMethod().equalsIgnoreCase( "POST"))
  25. {
  26. Enumeration em = request.getParameterNames();
  27. for (; em.hasMoreElements();)
  28. {
  29. Object o = em.nextElement();
  30. buf.append(o).append( "=").append(request.getParameter(o.toString())).append( ",");
  31. }
  32. logger.info( "回调 method:post]http://" + request.getServerName() + request.getServletPath() + " [ + buf + ">]");
  33. } else
  34. {
  35. buf.append(request.getQueryString());
  36. logger.info( "回调 method:get]http://" + request.getServerName() + request.getServletPath() + "?" + request.getQueryString());
  37. }
  38. request.setCharacterEncoding( "UTF-8");
  39. response.setCharacterEncoding( "UTF-8");
  40. response.setContentType( "text/html;charset=UTF-8");
  41. response.setHeader( "Access-Control-Allow-Origin", "*");
  42. InputStream in=request.getInputStream();
  43. ByteArrayOutputStream out= new ByteArrayOutputStream();
  44. byte[] buffer = new byte[ 1024];
  45. int len= 0;
  46. while((len=in.read(buffer))!=- 1){
  47. out.write(buffer, 0, len);
  48. }
  49. out.close();
  50. in.close();
  51. String content= new String(out.toByteArray(), "utf-8"); //xml数据
  52. logger.info( "[WeiXinNotifyController][weixinNotify] content:" +content);
  53. //日志显示,存在为空的情况.
  54. if(StringUtils.isBlank(content))
  55. {
  56. logger.error( "[WeiXinNotifyController][weixinNotify] content is blank,please check it");
  57. response.getWriter().write(setXml( "FAIL", "ERROR"));
  58. return;
  59. }
  60. JSONObject jsonObject = JSONObject.fromObject(XmltoJsonUtil.xml2JSON(content));
  61. JSONObject resultXml = jsonObject.getJSONObject( "xml");
  62. JSONArray returnCode = resultXml.getJSONArray( "return_code");
  63. String code = (String)returnCode.get( 0);
  64. if(code.equalsIgnoreCase( "FAIL"))
  65. {
  66. response.getWriter().write(setXml( "SUCCESS", "OK"));
  67. return;
  68. } else if(code.equalsIgnoreCase( "SUCCESS"))
  69. {
  70. //商户订单号即订单编号
  71. String outerTradeNo =String.valueOf(resultXml.getJSONArray( "out_trade_no").get( 0));
  72. //微信交易订单号
  73. String tradeNo = String.valueOf(resultXml.getJSONArray( "transaction_id").get( 0));
  74. //交易状态
  75. String resultCode = String.valueOf(resultXml.getJSONArray( "result_code").get( 0));
  76. //金额
  77. String money =String.valueOf(resultXml.getJSONArray( "total_fee").get( 0));
  78. //微信的用户ID
  79. String openId =String.valueOf(resultXml.getJSONArray( "openid").get( 0));
  80. logger.info( "[WeiXinNotifyController][weixinNotify] resultCode:" +resultCode+ " money:"+money);
  81. //根据这个判断来获取订单交易是否OK
  82. if(!resultCode.equalsIgnoreCase( "SUCCESS"))
  83. {
  84. response.getWriter().write(setXml( "FAIL", "ERROR"));
  85. return;
  86. }
  87. try
  88. {
  89. if(StringUtils.isNotBlank(outerTradeNo))
  90. {
  91. //查询当前订单信息
  92. OrderInfo info= this.orderInfoService.getOrderInfoByOrderNumber(outerTradeNo);
  93. if(info== null)
  94. {
  95. logger.error( "[WeiXinNotifyController][weixinNotify] info:" +info);
  96. response.getWriter().write(setXml( "FAIL", "ERROR"));
  97. return;
  98. }
  99. //订单信息
  100. OrderInfo orderInfo= new OrderInfo();
  101. orderInfo.setOrderNumber(outerTradeNo);
  102. orderInfo.setCardCode( "weixin");
  103. orderInfo.setCardName( "微信支付");
  104. orderInfo.setCardNumber(openId);
  105. orderInfo.setCardOwner(openId);
  106. orderInfo.setPayTime( new Date());
  107. orderInfo.setOuterTradeNo(tradeNo);
  108. orderInfo.setPayStatus(PayStatus.PAY_SUCCESS);
  109. orderInfo.setTradeStatus(TradeStatus.TRADE_PROGRESS);
  110. orderInfo.setPayAmount( new BigDecimal(money).divide( new BigDecimal( 100)));
  111. orderInfo.setBuyerId(info.getBuyerId());
  112. //付款日志
  113. PayLogs payLogs= new PayLogs();
  114. payLogs.setOrderNumber(outerTradeNo);
  115. payLogs.setOuterTradeNo(tradeNo);
  116. payLogs.setStatus(PAY_LOGS_SUCCESS);
  117. orderInfoService.payReturn(orderInfo,payLogs);
  118. //回写团购成功状态
  119. groupsService.updateGbStatusByOrderNumber(outerTradeNo);
  120. response.getWriter().write(setXml( "SUCCESS", "OK"));
  121. try
  122. {
  123. //更新优惠券状态为已用
  124. couponReceiveService.updateStatus(outerTradeNo);
  125. } catch(Exception ex){
  126. logger.error( "[AlipayNotifyController][payReturn] 更新优惠券状态异常:",ex);
  127. }
  128. return;
  129. }
  130. } catch(Exception ex)
  131. {
  132. logger.error( "[WeiXinNotifyController][payReturn] 出现了异常:",ex);
  133. response.getWriter().write(setXml( "SUCCESS", "OK"));
  134. return;
  135. }
  136. }
  137. } catch(Exception e){
  138. logger.error( "[WeiXinNotifyController][weixinNotify] exception:" ,e);
  139. response.getWriter().write(setXml( "SUCCESS", "OK"));
  140. return;
  141. }
  142. }
  143. //返回微信服务
  144. private String setXml(String returnCode,String returnMsg)
  145. {
  146. return "+returnCode+ "]]>+returnMsg+ "]]>";
  147. }
  148. }

Java开源生鲜电商平台-支付表的设计与架构(源码可下载),如果需要下载的话,可以在我的github下面进行下载。 

相关的运营截图如下:

 

 


你可能感兴趣的:(电商平台)