com.greenline.guahao.web.module.home.controllers.mobile.reservation.MobilePaymentController.java Source code

Java tutorial

Introduction

Here is the source code for com.greenline.guahao.web.module.home.controllers.mobile.reservation.MobilePaymentController.java

Source

/* controller
 * Project: guahao-portal-web-home
 * 
 * File Created at 2012-5-16
 * 
 * Copyright 2012 Greenline.com Corporation Limited.
 * All rights reserved.
 * 
 * This software is the confidential and proprietary information of
 * Greenline Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Greenline.com.
 */
package com.greenline.guahao.web.module.home.controllers.mobile.reservation;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
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.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.greenline.common.util.FenToYuan;
import com.greenline.guahao.biz.manager.hrs.ExpertManager;
import com.greenline.guahao.biz.manager.hrs.dataobject.ExpertDO;
import com.greenline.guahao.biz.manager.order.OrderManager;
import com.greenline.guahao.biz.manager.order.dataobject.OrderDO;
import com.greenline.guahao.biz.manager.payment.PaymentManager;
import com.greenline.guahao.biz.manager.payment.config.MobileAlipayConstant;
import com.greenline.guahao.biz.manager.payment.dataobject.MobilePayMentDO;
import com.greenline.guahao.biz.manager.payment.util.AlipayCore;
import com.greenline.guahao.web.module.common.annotation.MethodRemark;
import com.greenline.guahao.web.module.common.constants.MobileConstants;
import com.greenline.guahao.web.module.common.constants.ReservationMsgConstants;
import com.greenline.guahao.web.module.common.utils.CommonUtils;
import com.greenline.guahao.web.module.home.controllers.my.reservation.ReservationDOBuilder;
import com.greenline.guahao.web.module.home.vo.reservation.ShiftCaseVO;
import com.greenline.hrs.biz.service.dto.ResponseCode;
import com.greenline.hrs.biz.service.dto.ResponseDTO;
import com.greenline.hrs.biz.service.dto.pay.AlipayParamDTO;
import com.greenline.hrs.biz.service.dto.pay.ConfirmResultDTO;

/**
 * 
 * 
 * @Type PaymentController
 * @Desc ?
 * @author wangbiao
 * @date 2012-11-26
 * @Version V1.0
 */
@Controller
public class MobilePaymentController {

    private static final Log log = LogFactory.getLog(MobilePaymentController.class);

    @Resource
    private PaymentManager paymentManager;
    @Resource
    private OrderManager orderManager;
    @Resource
    private ExpertManager expertManager;
    @Resource
    private ReservationDOBuilder reservationDOBuilder;
    @Resource
    private MobilePaymentProcess mobilePaymentProcess;

    /**
     * html5?
     * 
     * @param model
     * @param request
     * @param orderId
     * @param subject
     * @param desc
     * @return String
     * @throws Exception
     */
    @MethodRemark(value = "remark=html5?,method=GET")
    @RequestMapping(value = MobileConstants.M_JUMP_TO_PAYMENT_PATH)
    public String jumpToPayment(ModelMap model, HttpServletRequest request,
            @ModelAttribute("orderId") String orderId, @ModelAttribute("subject") String subject,
            @ModelAttribute("desc") String desc) throws Exception {
        log.info("??????");
        String errorMsg = "";
        // ?????
        Integer feeFen = 0;
        Long newdiff = 0L;
        OrderDO orderBrief = null;
        if (StringUtils.isBlank(orderId)) {
            log.error("???");
            model.put("error_message", "???");
            return MobileConstants.M_ERROR;
        } else {
            orderBrief = orderManager.getOrder(orderId);
            if (orderBrief == null) {
                log.error("?????,??:" + orderId);
                errorMsg = "?????,??:" + orderId;
                model.put("error_message", errorMsg);
                return MobileConstants.M_ERROR;
            } else {
                ShiftCaseVO shiftVO = reservationDOBuilder.setLeftPageValue(orderBrief);
                ExpertDO expert = expertManager.getExpert(orderBrief.getExpertId());
                if (null == expert) {
                    log.error(ReservationMsgConstants.ERR_MSG_EXPERT_NOT_EXIST);
                } else {
                    shiftVO.setExpertPhoto(expert.getPhoto());
                    shiftVO.setExpertSex(expert.getSex());
                }
                model.put("shiftCaseVO", shiftVO);
                feeFen = orderBrief.getClinicFee();
                if (feeFen <= 0) {
                    log.error("??0?");
                    errorMsg = "??0?";
                    model.put("error_message", errorMsg);
                    return MobileConstants.M_RESERVATION_FAI;
                }
                // ??
                if (orderBrief.getStatus() != 0) {
                    // ???0??
                    // 15??
                    log.error("?????" + orderBrief.getStatus());
                    errorMsg = "?????";
                    model.put("error_message", errorMsg);
                    model.put("hid", orderBrief.getHospitalId());
                    model.put("hdid", orderBrief.getHospDepartmentId());
                    return MobileConstants.M_RESERVATION_FAI;
                }
                // ??????
                java.util.Date nowtime = new Date();
                Date orderCreateTime = orderBrief.getCreatedTime();
                // ??
                Long diff = (nowtime.getTime() - orderCreateTime.getTime()) / 1000;
                if (diff > 60 * 15) {
                    // 15??
                    log.error("??15?");
                    errorMsg = "??15?";
                    model.put("error_message", errorMsg);
                    return MobileConstants.M_RESERVATION_FAI;
                } else {
                    // ?
                    newdiff = 60 * 15 - diff;
                }
            }
        }
        // 
        FenToYuan ps = new FenToYuan();
        String fee = ps.formatFenToYuanString(String.valueOf(feeFen));
        log.info("" + newdiff / 60 + "");
        // ???
        String servername = (String) request.getAttribute("servername");
        String domainservername = "";
        if (servername != null) {
            domainservername = request.getScheme() + "://" + servername + CommonUtils.getServerPort(request);
        } else {
            // ????
            domainservername = (String) request.getAttribute("guahaourl");
        }
        MobilePayMentDO mpm = new MobilePayMentDO();
        mpm = mobilePaymentProcess.replaceDomain(mpm, domainservername, MobileConstants.M_PAYMENT_RETURN_PATH,
                MobileConstants.M_PAYMENT_NOTIFY_PATH, MobileConstants.M_PAYMENT_EROOR_NOTIFY_PATH);
        String hospitalId = orderBrief.getHospitalId();
        mpm = mobilePaymentProcess.getDirectPaymentInfo(orderBrief.getUserId(), orderId, fee, subject, desc,
                newdiff / 60, mpm.getCall_back_url(), mpm.getNotify_url(), mpm.getMerchant_url(), hospitalId);
        // 
        ResponseDTO<ConfirmResultDTO> rd = paymentManager.payPrepare(orderId, subject, 1, 0, feeFen, desc);
        if (rd != null) {
            if (ResponseCode.isSuccess(rd.getCode())) {
                log.info("?");
            } else {
                log.error("" + rd.getMessage());
                errorMsg = "" + rd.getMessage();
                model.put("error_message", errorMsg);
                return MobileConstants.M_RESERVATION_FAI;
            }
        } else {
            log.error("?null");
            errorMsg = "?null";
            model.put("error_message", errorMsg);
            return MobileConstants.M_RESERVATION_FAI;
        }
        // ??
        Map<String, String> sParaTempToken = new HashMap<String, String>();
        sParaTempToken.put("service", mpm.getService());
        log.info("service:" + mpm.getService());
        sParaTempToken.put("partner", mpm.partner);
        log.info("partner:" + mpm.partner);
        sParaTempToken.put("_input_charset", MobileAlipayConstant.input_charset);
        log.info("_input_charset:" + MobileAlipayConstant.input_charset);
        sParaTempToken.put("sec_id", mpm.sec_id);
        log.info("sec_id:" + mpm.sec_id);
        sParaTempToken.put("format", mpm.format);
        log.info("format:" + mpm.format);
        sParaTempToken.put("v", mpm.v);
        log.info("v:" + mpm.v);
        sParaTempToken.put("req_id", mpm.req_id);
        log.info("req_id:" + mpm.req_id);
        sParaTempToken.put("req_data", mpm.req_data);
        log.info("req_data:" + mpm.req_data);
        sParaTempToken.put("sign", mpm.getSign());
        log.info("sign:" + mpm.getSign());
        // ???????
        String sHtmlTextToken = mobilePaymentProcess.buildRequest(sParaTempToken);
        // URLDECODE?
        sHtmlTextToken = URLDecoder.decode(sHtmlTextToken, MobileAlipayConstant.input_charset);
        log.info("html5???????:" + sHtmlTextToken);
        String request_token = AlipayCore.getRequestToken(sHtmlTextToken);
        log.info("html5?request_token:" + request_token);
        if (StringUtils.isBlank(request_token)) {
            model.put("error_message", "???");
            return MobileConstants.M_ERROR;
        }
        MobilePayMentDO mp = mobilePaymentProcess.getAuthMobilePaymentInfo(request_token, hospitalId);

        model.put("mpm", mp);
        return MobileConstants.M_AUTH_EXECUTE_PAYMENT;
    }

    /**
     * ??(??)
     * 
     * @param model
     * @param request
     * @return String
     * @throws UnsupportedEncodingException
     */
    @SuppressWarnings({ "rawtypes" })
    @MethodRemark(value = "remark=??(??),method=GET")
    @RequestMapping(value = MobileConstants.M_PAYMENT_RETURN_PATH, method = RequestMethod.GET)
    public String paymentResult(ModelMap model, HttpServletRequest request) throws UnsupportedEncodingException {
        // ??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] + ",";
            }
            // ???mysignsign???
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        // ?
        boolean verify_result = AlipayCore.verify(params);
        if (verify_result) {// ??
            String out_trade_no = request.getParameter("out_trade_no");
            model.put("out_trade_no", out_trade_no);
            // ????????
            String orderId = out_trade_no;
            OrderDO orderBrief = orderManager.getOrder(orderId);
            String orderResult = "";
            if (orderBrief == null) {
                orderResult = "?????????,??:"
                        + orderId;
                log.error(orderResult);
                model.put("orderResult", orderResult);
                return MobileConstants.M_PAYMENTERROR;
            } else {
                // ???hrs?
                ExpertDO expert = expertManager.getExpert(orderBrief.getExpertId());
                ShiftCaseVO shiftCaseVO = new ShiftCaseVO();
                if (null != expert) {
                    shiftCaseVO.setExpertId(expert.getId());
                }
                shiftCaseVO.setDeptId(orderBrief.getHospDepartmentId());
                shiftCaseVO.setHospitalId(orderBrief.getHospitalId());
                model.put("shiftCaseVO", shiftCaseVO);
                model.put("orderNo", orderId);
                int orderState = orderBrief.getStatus();
                if (orderState == 6001) {
                    // ?
                    orderResult = "?????????????"
                            + orderId;
                    log.error(orderResult);
                    model.put("orderResult", orderResult);
                    return MobileConstants.M_PAYMENTERROR;
                }
                // ??????????
            }
            return MobileConstants.M_RESERVATION_SUC;
        } else {
            model.put("orderResult", "?sign?");
            log.error("html5?sign?");
            return MobileConstants.M_PAYMENTERROR;
        }

    }

    /**
     * ?url
     * 
     * @param model
     * @param request
     * @param response
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    @MethodRemark(value = "remark=?url,method=POST")
    @RequestMapping(value = MobileConstants.M_PAYMENT_NOTIFY_PATH, method = RequestMethod.POST)
    public void paymentNofity(ModelMap model, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        log.info("html5?...");
        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] + ",";
            }
            params.put(name, valueStr);
        }
        String sign = request.getParameter("sign");
        log.info("sign:" + sign);
        ;
        String sec_id = request.getParameter("sec_id");
        log.info("sec_id:" + sec_id);
        String notify_data = request.getParameter("notify_data");// ?
        log.info("notify_data:" + notify_data);
        Document doc_notify_data = DocumentHelper.parseText(notify_data);
        String payment_type = doc_notify_data.selectSingleNode("//notify/payment_type").getText();
        log.info("payment_type:" + payment_type);
        String subject = doc_notify_data.selectSingleNode("//notify/subject").getText();
        log.info("subject:" + subject);
        String trade_no = doc_notify_data.selectSingleNode("//notify/trade_no").getText();
        log.info("trade_no:" + trade_no);
        String buyer_email = doc_notify_data.selectSingleNode("//notify/buyer_email").getText();
        log.info("buyer_email:" + buyer_email);
        String gmt_create = doc_notify_data.selectSingleNode("//notify/gmt_create").getText();
        log.info("gmt_create:" + gmt_create);
        String notify_type = doc_notify_data.selectSingleNode("//notify/notify_type").getText();
        log.info("notify_type:" + notify_type);
        String quantity = doc_notify_data.selectSingleNode("//notify/quantity").getText();
        log.info("quantity:" + quantity);
        String out_trade_no = doc_notify_data.selectSingleNode("//notify/out_trade_no").getText();
        log.info("out_trade_no:" + out_trade_no);
        String notify_time = doc_notify_data.selectSingleNode("//notify/notify_time").getText();
        log.info("notify_time:" + notify_time);
        String seller_id = doc_notify_data.selectSingleNode("//notify/seller_id").getText();
        log.info("seller_id:" + seller_id);
        String trade_status = doc_notify_data.selectSingleNode("//notify/trade_status").getText();
        log.info("trade_status:" + trade_status);
        String is_total_fee_adjust = doc_notify_data.selectSingleNode("//notify/is_total_fee_adjust").getText();
        log.info("is_total_fee_adjust:" + is_total_fee_adjust);
        String total_fee = doc_notify_data.selectSingleNode("//notify/total_fee").getText();
        log.info("total_fee:" + total_fee);
        String gmt_payment = "";
        if (doc_notify_data.selectSingleNode("//notify/gmt_payment") != null) {
            gmt_payment = doc_notify_data.selectSingleNode("//notify/gmt_payment").getText();
        }
        log.info("gmt_payment:" + gmt_payment);
        String seller_email = doc_notify_data.selectSingleNode("//notify/seller_email").getText();
        log.info("seller_email:" + seller_email);
        String price = doc_notify_data.selectSingleNode("//notify/price").getText();
        log.info("price:" + price);
        String buyer_id = doc_notify_data.selectSingleNode("//notify/buyer_id").getText();
        log.info("buyer_id:" + buyer_id);
        String notify_id = doc_notify_data.selectSingleNode("//notify/notify_id").getText();
        log.info("notify_id:" + notify_id);
        String use_coupon = doc_notify_data.selectSingleNode("//notify/use_coupon").getText();
        log.info("use_coupon:" + use_coupon);
        // 1????url
        // 2????
        AlipayParamDTO param = new AlipayParamDTO();
        param.setBuyerEmail(buyer_email);
        param.setBuyerId(buyer_id);
        param.setSallerEmail(seller_email);
        param.setSallerId(seller_id);
        param.setChannelType("directPay");
        param.setOrderId(out_trade_no);
        param.setTradeNo(trade_no);
        param.setTradeStatus(trade_status);
        param.setGmtPayment(gmt_payment);
        param.setGmtTradeCreate(gmt_create);
        param.setOrderTitle(subject);
        param.setOrderId(out_trade_no);
        param.setPayType(1);
        ResponseDTO<ConfirmResultDTO> pdt = paymentManager.aliPaySucConfirm(param);
        if (pdt == null) {
            log.error("hession??:?null");
            return;
        }
        try {
            if (ResponseCode.isSuccess(pdt.getCode())) {
                log.info("??");
                response.getWriter().print("success");

            } else {
                log.error("?:" + pdt.getMessage());
            }
        } catch (IOException e) {
            log.error("hession??", e);
        }

    }

    /**
     * ?url
     * 
     * @param request
     */
    @MethodRemark(value = "remark=?url,method=POST")
    @RequestMapping(value = MobileConstants.M_PAYMENT_EROOR_NOTIFY_PATH, method = RequestMethod.GET)
    public String payError(HttpServletRequest request, ModelMap model) {
        log.error("??...");
        model.put("error_message", "???");
        return MobileConstants.M_ERROR;
    }

}