Package com.lgx8.common.payment.service

Source Code of com.lgx8.common.payment.service.PaymentController

package com.lgx8.common.payment.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.lgx8.common.payment.util.AlipayNotify;
import com.lgx8.common.servlet.BaseController;
import com.lgx8.gateway.dao.IFareWayDao;
import com.lgx8.gateway.entities.Orders;
import com.lgx8.gateway.service.IOrderService;
import com.lgx8.right.entities.User;
import com.lgx8.right.service.IUserCardService;

@Controller
public class PaymentController extends BaseController{
 
  @Resource(name="orderService")
  private IOrderService orderService;
 
  @Resource(name="userCardService")
  public IUserCardService userCardService;
 
  @Resource(name="farewayDao")
  IFareWayDao farewayDao;
 
  private Logger logger = Logger.getLogger("payment");
  @RequestMapping(value="/payment.do")
  public ModelAndView payment(HttpServletRequest request,HttpServletResponse response){
    Orders order = (Orders)request.getAttribute("order");
    String xml = alipayto(order);
    request.setAttribute("reqHtmlText", xml);
    return new ModelAndView("payment/alipayto");
  }

  @RequestMapping(value="/payment/notify_url.do")
  public ModelAndView notifyURL(HttpServletRequest request,HttpServletResponse response){
    PrintWriter out = null;
    try {
      out = response.getWriter();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    //获取支付宝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] + ",";
      }
      //乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
      try {
        valueStr = new String(valueStr.getBytes("ISO-8859-1"), "UTF-8");
      } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      params.put(name, valueStr);
    }


   
    //获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//

    String trade_no = request.getParameter("trade_no");        //支付宝交易号
    String order_no = request.getParameter("out_trade_no");          //获取订单号
    String total_fee = request.getParameter("price");            //获取总金额
    try {
      String subject = new String(request.getParameter("subject").getBytes("ISO-8859-1"),"UTF-8");
    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }//商品名称、订单名称

    String buyer_email = request.getParameter("buyer_email");    //买家支付宝账号

    String trade_status = request.getParameter("trade_status");    //交易状态
   
    //获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//

    String is_success = request.getParameter("is_success");
   
    if(is_success.equals("T")){//验证成功
      //////////////////////////////////////////////////////////////////////////////////////////
      //请在这里加上商户的业务逻辑程序代码
     
      if(trade_status.equals("WAIT_BUYER_PAY")){
        //该判断表示买家已在支付宝交易管理中产生了交易记录,但没有付款
        //判断该笔订单是否在商户网站中已经做过处理(可参考“集成教程”中“3.4返回数据处理”)
        //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
        //如果有做过处理,不执行商户的业务程序
        logger.debug("notify WAIT_BUYER_PAY[orderID:"+order_no+"]");
        if(order_no==null)order_no="-1";
        Orders o = orderService.queryOrderById(Long.parseLong(order_no.trim()));
        if(null!=o){
          if(o.getStatus()<Orders.STATUS_DEAL){
            logger.debug("notify WAIT_BUYER_PAY[update orderID:"+order_no+"]");
            o.setStatus(Orders.STATUS_DEAL);
            orderService.updateOrder(o);
          }
        }
          out.println("success")//请不要修改或删除
      } else if(trade_status.equals("WAIT_SELLER_SEND_GOODS")){
        //该判断表示买家已在支付宝交易管理中产生了交易记录且付款成功,但卖家没有发货
        //判断该笔订单是否在商户网站中已经做过处理(可参考“集成教程”中“3.4返回数据处理”)
        //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
        //如果有做过处理,不执行商户的业务程序
        logger.debug("notify WAIT_SELLER_SEND_GOODS[orderID:"+order_no+"]");
          if(order_no==null)order_no="-1";
          Orders o = orderService.queryOrderById(Long.parseLong(order_no.trim()));
          if(null!=o){
            if(o.getStatus()<Orders.STATUS_PAID){
              logger.debug("notify WAIT_SELLER_SEND_GOODS[update orderID:"+order_no+"]");
              User user = userCardService.findUserById(o.getUser().getId() );
              double balance = user.getCard().getScore();
              o.setStatus(Orders.STATUS_PAID);
              o.setPaytime(new Date());
              orderService.updateOrder(o);
              user.getCard().setScore(balance-o.getScore());
              userCardService.updateUser(user);
            }
          }
          out.println("success")//请不要修改或删除
        } else if(trade_status.equals("WAIT_BUYER_CONFIRM_GOODS")){
        //该判断表示卖家已经发了货,但买家还没有做确认收货的操作
        //判断该笔订单是否在商户网站中已经做过处理(可参考“集成教程”中“3.4返回数据处理”)
        //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
        //如果有做过处理,不执行商户的业务程序   
          logger.debug("notify WAIT_BUYER_CONFIRM_GOODS[orderID:"+order_no+"]");
          if(order_no==null)order_no="-1";
          Orders o = orderService.queryOrderById(Long.parseLong(order_no.trim()));
          if(null!=o){
            if(o.getStatus()<Orders.STATUS_SENDED){
              logger.debug("notify WAIT_BUYER_CONFIRM_GOODS[update orderID:"+order_no+"]");
              o.setStatus(Orders.STATUS_SENDED);
              orderService.updateOrder(o);
            }
          }
         
          out.println("success")//请不要修改或删除
        } else if(trade_status.equals("TRADE_FINISHED")){
        //该判断表示买家已经确认收货,这笔交易完成
        //判断该笔订单是否在商户网站中已经做过处理(可参考“集成教程”中“3.4返回数据处理”)
        //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
        //如果有做过处理,不执行商户的业务程序
          logger.debug("notify TRADE_FINISHED[orderID:"+order_no+"]");
          if(order_no==null)order_no="-1";
          Orders o = orderService.queryOrderById(Long.parseLong(order_no.trim()));
          if(null!=o){
            if(o.getStatus()<Orders.STATUS_CONFIRM){
              logger.debug("notify TRADE_FINISHED[update orderID:"+order_no+"]");
              o.setStatus(Orders.STATUS_CONFIRM);
              orderService.updateOrder(o);
             
            }
          }
          out.println("success")//请不要修改或删除
        }
        else {
          logger.debug("notify else[orderID:"+order_no+"]");
          out.println("success")//请不要修改或删除
        }

      //——请根据您的业务逻辑来编写程序(以上代码仅作参考)——

      //////////////////////////////////////////////////////////////////////////////////////////
    }else{//验证失败
      out.println("fail");
    }
    return null;
  }
 
  @RequestMapping(value="/payment/return_url.do")
  public ModelAndView returnURL(HttpServletRequest request,HttpServletResponse response){
    PrintWriter out = null;
    response.setContentType("text/html;charset=UTF-8");
    try {
      out = response.getWriter();
    } catch (IOException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    //获取支付宝GET过来反馈信息
    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] + ",";
      }
      //乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
      try {
        valueStr = new String(valueStr.getBytes("ISO-8859-1"), "UTF-8");
      } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      params.put(name, valueStr);
    }
    //获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
    String trade_no = request.getParameter("trade_no");        //支付宝交易号
    String order_no = request.getParameter("out_trade_no");          //获取订单号
    String total_fee = request.getParameter("price");              //获取总金额
    try {
      String subject = new String(request.getParameter("subject").getBytes("ISO-8859-1"),"UTF-8");
    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }//商品名称、订单名称

    String buyer_email = request.getParameter("buyer_email");    //买家支付宝账号

    String trade_status = request.getParameter("trade_status");    //交易状态
   
    //获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
   
    //计算得出通知验证结果
    String is_success = request.getParameter("is_success");
   
    boolean verify_result = AlipayNotify.verify(params);
   
    if(is_success.equals("T")){//验证成功
      //////////////////////////////////////////////////////////////////////////////////////////
      //请在这里加上商户的业务逻辑程序代码

      //——请根据您的业务逻辑来编写程序(以下代码仅作参考)——

      if(trade_status.equals("WAIT_SELLER_SEND_GOODS")){
        //判断该笔订单是否在商户网站中已经做过处理(可参考“集成教程”中“3.4返回数据处理”)
        //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
        //如果有做过处理,不执行商户的业务程序
        logger.debug("return WAIT_SELLER_SEND_GOODS[orderID:"+order_no+"]");
        if(order_no==null)order_no="-1";
        Orders o = orderService.queryOrderById(Long.parseLong(order_no.trim()));
        if(null!=o){
          if(o.getStatus()<Orders.STATUS_PAID){
            logger.debug("return WAIT_SELLER_SEND_GOODS[update orderID:"+order_no+"]");
            User user = userCardService.findUserById(o.getUser().getId() );
            double balance = user.getCard().getScore();
            o.setStatus(Orders.STATUS_PAID);
            o.setPaytime(new Date());
            orderService.updateOrder(o);
            user.getCard().setScore(balance-o.getScore());
            userCardService.updateUser(user);
          }
        }
      }
   
      if(trade_status.equals("TRADE_FINISHED")){
        //判断该笔订单是否在商户网站中已经做过处理(可参考“集成教程”中“3.4返回数据处理”)
        //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
        //如果有做过处理,不执行商户的业务程序
        if(order_no==null)order_no="-1";
        Orders o = orderService.queryOrderById(Long.parseLong(order_no.trim()));
        logger.debug("return TRADE_FINISHED[orderID:"+order_no+"]");
        if(null!=o){
          if(o.getStatus()<Orders.STATUS_CONFIRM){
            logger.debug("return TRADE_FINISHED[update orderID:"+order_no+"]");
            o.setStatus(Orders.STATUS_CONFIRM);
            orderService.updateOrder(o);
          }
        }
      }
 
      /*RunTimeUser.getRunTimeUser(request).updateUser(user);
      FareWay farway = farewayDao.getFareWayById(Integer.parseInt(deliveryId.trim()));
      request.setAttribute("farway", farway);
      request.setAttribute("order", order);
      request.setAttribute("url", MemberURLConst.URL_ORDER_DETAIL);
      return new ModelAndView(MemberURLConst.URL_BASE);*/
      //——请根据您的业务逻辑来编写程序(以上代码仅作参考)——
//      out.println("支付成功");
//      out.println("trade_no=" + trade_no);
     
      out.print("<script type=\"text/javascript\">alert('支付成功');window.close();</script>");
      //////////////////////////////////////////////////////////////////////////////////////////
    }else{
      logger.debug("return verify failed[orderID:"+order_no+"]");
      //该页面可做页面美工编辑
      out.print("<script type=\"text/javascript\">alert('支付失败');window.close();</script>");
    }
    return null;
  }
  public String alipayto(Orders order){
    //必填参数//
    //请与贵网站订单系统中的唯一订单号匹配
    String out_trade_no = order.getId()+"";
    //订单名称,显示在支付宝收银台里的“商品名称”里,显示在支付宝的交易管理的“商品名称”的列表里。
    String subject = "订单号"+out_trade_no;
    //订单描述、订单详细、订单备注,显示在支付宝收银台里的“商品描述”里
    String body = "";
    //订单总金额,显示在支付宝收银台里的“应付总额”里
    String price = order.getFare()+"";
   
    //物流费用,即运费。
    String logistics_fee = "0.00";
    //物流类型,三个值可选:EXPRESS(快递)、POST(平邮)、EMS(EMS)
    String logistics_type = "EXPRESS";
    //物流支付方式,两个值可选:SELLER_PAY(卖家承担运费)、BUYER_PAY(买家承担运费)
    String logistics_payment = "BUYER_PAY";
   
    //商品数量,建议默认为1,不改变值,把一次交易看成是一次下订单而非购买一件商品。
    String quantity = "1";

    //////////////////////////////////////////////////////////////////////////////////
    logger.debug("send payment request[Order ID:"+order.getId()+" "+order.getFare()+"]");
    //把请求参数打包成数组
    Map<String, String> sParaTemp = new HashMap<String, String>();
    sParaTemp.put("payment_type","1");
    sParaTemp.put("show_url", "");
    sParaTemp.put("out_trade_no", out_trade_no);
    sParaTemp.put("subject", subject);
    sParaTemp.put("body", body);
    sParaTemp.put("price", price);
    sParaTemp.put("logistics_fee", logistics_fee);
    sParaTemp.put("logistics_type", logistics_type);
    sParaTemp.put("logistics_payment", logistics_payment);
    sParaTemp.put("quantity", quantity);
    sParaTemp.put("receive_name", order.getAdrreessname());
    sParaTemp.put("receive_address", order.getAddressprovince()+order.getAddresscity()+order.getAddressregion()+order.getAddressname());
    sParaTemp.put("receive_zip", order.getAddresszipcode());
    sParaTemp.put("receive_phone", "");
    sParaTemp.put("receive_mobile", order.getAddresstel());
   
    //构造函数,生成请求URL
    String sHtmlText = AlipayService.trade_create_by_buyer(sParaTemp);
    return sHtmlText;
  }
}
TOP

Related Classes of com.lgx8.common.payment.service.PaymentController

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.