支付宝PC扫码支付

今年做了支付宝支付项目包括支付宝PC扫码支付。
现在总结如下:

1、pom

<dependency>
			<groupId>com.alipay.scanQR</groupId>
			<artifactId>alipay-sdk-java</artifactId>
			<version>2.0</version>
		</dependency>
		<dependency>
			<groupId>com.alipay.scanQR</groupId>
			<artifactId>alipay-trade-sdk</artifactId>
			<version>2.0</version>
		</dependency>
		<dependency>
			<groupId>com.alipay.scanQR</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.10</version>
		</dependency>
		<dependency>
			<groupId>com.alipay.scanQR</groupId>
			<artifactId>commons-configuration</artifactId>
			<version>1.10</version>
		</dependency>
		<dependency>
			<groupId>com.alipay.scanQR</groupId>
			<artifactId>core</artifactId>
			<version>2.1</version>
		</dependency>
		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>javase</artifactId>
			<version>3.0.0</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-mongodb</artifactId>
			<version>${spring-data-mongodb-version}</version>
		</dependency>
		<dependency>
			<groupId>cn.jpush.api</groupId>
			<artifactId>jmessage-client</artifactId>
			<version>1.1.7</version>
		</dependency>
		<dependency>
			<groupId>cn.jpush.api</groupId>
			<artifactId>jiguang-common</artifactId>
			<version>1.1.0</version>
		</dependency>

2、spring-core.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:security="http://www.springframework.org/schema/security"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
     http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
     http://www.springframework.org/schema/security   
     http://www.springframework.org/schema/security/spring-security-4.0.xsd  
     http://www.springframework.org/schema/tx 
     http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	 http://www.springframework.org/schema/jee 
	 http://www.springframework.org/schema/jee/spring-jee-4.0.xsd 
	 http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-4.0.xsd
     http://www.springframework.org/schema/aop
	 http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
	 http://www.springframework.org/schema/mvc
	 http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
	 http://www.springframework.org/schema/util 
	 http://www.springframework.org/schema/util/spring-util-3.0.xsd"
	default-lazy-init="true">

	<description>Spring Core Configuration</description>

	<!-- 使用annotation 自动注册bean,并保证@Required,@Autowired的属性被注入 解决事物失效问题:在主容器中不扫描@Controller注解,在SpringMvc中只扫描@Controller注解 -->
	<context:component-scan base-package="com.haier">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>

	<!-- Configures applicationContext -->
	<bean class="com.haier.commons.utils.SpringContextGuster" lazy-init="false" />
	<import resource="spring-mybatis.xml" />
	<util:properties id="configProperties" location="classpath*:/config/systemconfig.properties"/>
	<util:properties id="settlementCenterProperties" location="classpath*:/config/systemconfig.properties"/>

	
</beans>

3、systemconfig.properties

#正式
recharge_return_url = http://xxx.xxx.xxx/alipay/recharge/return
recharge_notify_url = http://xxx.xxx.xxx/alipay/recharge/notify

4、controller

@Controller
@RequestMapping("/alipay")
public class AlipayController{
    public Logger logger = Logger.getLogger(getClass());
    @Autowired
    private AlipayService alipayService;
    @Autowired
    private CustomerInfoService customerInfoService;
    @Autowired
    private CarsTeamInfoService carsTeamInfoService;
    @Autowired
    private BdUserInfoService bdUserInfoService;
    @Autowired
    private CityStationService cityStationService;
    
    @RequestMapping("/findCustomer")
    @ResponseBody
    public ResultMsg findCustomer(){
        ResultMsg result = new ResultMsg();
        String custIds = Securitys.getAuthorityIds();
        String userId  = Securitys.getUserId();
        String userType = Securitys.getUserType();
        if(userType.equals("03")){
            CustomerInfo customerInfo = getRechargeCust(custIds,Securitys.getUserType());
            if(null==customerInfo){
                result.setSuccess(false);
                result.setMsg("此账户不能充值");
            }else{
                result.setSuccess(true);
                result.setMsg("此账户可以充值");
            }
        }else if(userType.equals("05")){
            BdUserInfo bdUserInfo = bdUserInfoService.getUserInfoById(userId);
            CarsTeamInfo carsTeamInfo = null;
            if(bdUserInfo!=null){
                carsTeamInfo = carsTeamInfoService.getCarsTeamByTel(bdUserInfo.getUserTel());
            }else{
                throw new RuntimeException("获取用户信息异常");
            }
            if(carsTeamInfo!=null&&carsTeamInfo.getCarsTeamId()!=null){
                result.setSuccess(true);
                result.setMsg("此账户可以充值");
            }else{
                result.setSuccess(false);
                result.setMsg("此账户不能充值");
            }
        }else if(userType.equals("06")){
            String businessId = Securitys.getAuthorityIdList().get(0);
            if(null==businessId&&("").equals(businessId)){
                result.setSuccess(false);
                result.setMsg("此账户不能充值");
            } else{
                result.setSuccess(true);
                result.setMsg("此账户可以充值");
            }
        }else{
            CustomerInfo customerInfo = getRechargeCust(custIds,Securitys.getUserType());
            if(null==customerInfo){
                result.setSuccess(false);
                result.setMsg("此账户不能充值");
            } else{
                result.setSuccess(true);
                result.setMsg("此账户可以充值");
            }
        }
        return result;
    }


    /**
     * 充值页面
     *
     * @return0
     */
    @RequestMapping("/recharge")
    public ModelAndView recharge(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("layouts.express.alipay.recharge.new");
        String userId = Securitys.getUserId();
        String userType = Securitys.getUserType();
        List<String> tempIds = Securitys.getAuthorityIdList();
        PrechargeInfo prechargeInfo = null;
        if(tempIds.size()>0){
            prechargeInfo = alipayService.getPrechargeInfo(tempIds.get(0).toString(), userType);
            if(userType.equals("06")){
                //Station
                CityStationInfoModel cityStationInfoModel = cityStationService.getById(tempIds.get(0).toString());
                modelAndView.addObject("custName", cityStationInfoModel.getStationName());
            }else if(userType.equals("05")){
                CarsTeamInfo carsTeamInfo = carsTeamInfoService.findById(tempIds.get(0).toString());
                modelAndView.addObject("custName", carsTeamInfo.getCarsTeamName());
            }else if(userType.equals("03")){
                CustomerInfo customerInfo = customerInfoService.findByCustId(tempIds.get(0).toString());
                modelAndView.addObject("custName", customerInfo.getCustName());
            }else{
                UserInfo userInfo = bdUserInfoService.getById(tempIds.get(0).toString());
                modelAndView.addObject("custName", userInfo.getUserName());
            }
        }else{
            prechargeInfo = alipayService.getPrechargeInfo(userId, userType);
            UserInfo userInfo = bdUserInfoService.getById(userId);
            modelAndView.addObject("custName", userInfo.getUserName());
        }
        modelAndView.addObject("prechargeInfo", prechargeInfo);
        return modelAndView;
    }

    /**
     * 充值操作
     *
     * @param payParam
     * @return
     */
    @RequestMapping("/doRecharge")
    @ResponseBody
    public ModelAndView doRecharge(PayParam payParam){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("layouts.express.alipay.alipay");
        String userType = Securitys.getUserType();
        List<String> tempIds = Securitys.getAuthorityIdList();
        if(userType.equals("10") || userType.equals("11")||userType.equals("09")){
            userType = "09";
        }
        Result result = new Result();
        if(tempIds.size()>0){
            String eventType = payParam.getEventType();
            String bizType = payParam.getBizType();
            String formHtml = null;
            try{
                formHtml = alipayService.getRechargeHtml(tempIds.get(0).toString(), userType, eventType, bizType, payParam.getRecAmount());
            }catch(Exception e){
                result.setResCode(ResultCode.ORDER_PAY_ERROR.getIndex());//支付异常或未找到订单
            }
            modelAndView.addObject("rechargeHtml", formHtml);
        }else{
            throw new RuntimeException("获取用户信息异常");
        }
        return modelAndView;
    }


    /**
     * 充值操作
     *
     * @param payParam
     * @return
     */
    @RequestMapping("/checkPayStatus")
    @ResponseBody
    public ResultMsg checkPayStatus(PayParam payParam){
        ResultMsg result = new ResultMsg();
        String userType = Securitys.getUserType();
        if(userType.equals("10") || userType.equals("11")||userType.equals("09")){
            userType = "09";
        }
        List<String> tempIds = Securitys.getAuthorityIdList();
        if(tempIds.size()>0){
            String status = alipayService.queryRechargeStatus(payParam.getRechargeRecordsId(),tempIds.get(0).toString(),userType);
	        result.setObj(status);
	        return result;
        }else{
            throw new RuntimeException("获取用户信息异常");
        }
    }


    @RequestMapping("/recharge/notify")
    @ResponseBody
    public String rechargeNotifyRequest(HttpServletRequest request, Model model){
        logger.info("---------------------------Enter AlipayController rechargeNotifyRequest For pay/notify --------------------------");
        String res = "";
        try{
            Map<String, String> params = new HashMap<String, String>();
            for(Iterator iter = request.getParameterMap().keySet().iterator(); iter.hasNext(); ){
                String name = (String)iter.next();
                String[] values = (String[])request.getParameterMap().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 fee = params.get("total_fee");
            BigDecimal totalFee = null;
            if(fee == null || "".equals(fee)){
                totalFee = new BigDecimal("0");
            }
            else{
                totalFee = new BigDecimal(Double.valueOf(fee) * 100);

                BigDecimal feevalue = new BigDecimal("100");
                BigDecimal totalFee2 = new BigDecimal(fee).multiply(feevalue);
                logger.debug("支付宝回调参数" + totalFee.intValue() + "," + totalFee2.intValue());
            }
            logger.debug("支付宝回调信息" + params);
            //商户订单号
            String out_trade_no = params.get("out_trade_no");
            //支付宝交易号
            String trade_no = params.get("trade_no");
            //交易状态
            String trade_status = params.get("trade_status");
            if(AlipayNotify.verify(params)){//验证成功
                res = alipayService.notifyRecharge(request.getParameterMap());
            }
            else{
                logger.debug("支付回调验证失败");
                res = "fail";
                alipayService.updateRechargeInfo(params, "fail", trade_status);
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return res;
    }


    @RequestMapping("/recharge/return")
    public ModelAndView rechargeReturnRequest(HttpServletRequest request, Model model){
        logger.info("---------------------------Enter AlipayController rechargeReturnRequest For pay/return --------------------------");
        String res = "";
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("layouts.express.alipay.recharge.result");
        String userType = Securitys.getUserType();
        if(userType.equals("10") || userType.equals("11")||userType.equals("09")){
            userType = "09";
        }
        List<String> tempIds = Securitys.getAuthorityIdList();
        logger.info("------------------获取当前用户的getAuthorityIdList:-----------------------"+ tempIds);
        try{
            Map<String, String> params = new HashMap<String, String>();
            for(Iterator<?> iter = request.getParameterMap().keySet().iterator(); iter.hasNext(); ){
                String name = (String)iter.next();
                String[] values = (String[])request.getParameterMap().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 fee = params.get("total_fee");
            BigDecimal totalFee = null;
            if(fee == null || "".equals(fee)){
                totalFee = new BigDecimal("0");
            }
            else{
                totalFee = new BigDecimal(Double.valueOf(fee) * 100);

                BigDecimal feevalue = new BigDecimal("100");
                BigDecimal totalFee2 = new BigDecimal(fee).multiply(feevalue);
                logger.debug("支付宝回调参数" + totalFee.intValue() + "," + totalFee2.intValue());
            }
            logger.debug("支付宝回调信息" + params);
            //商户订单号
            // String out_trade_no = params.get("out_trade_no");
            //支付宝交易号
            // String trade_no = params.get("trade_no");
            //交易状态
            String trade_status = params.get("trade_status");
            if(AlipayNotify.verify(params)){//验证成功
                res = "success";
            }
            else{
                logger.debug("支付回调验证失败");
                res = "fail";
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
        modelAndView.addObject("result",res);
        return modelAndView;
    }

    private CustomerInfo getRechargeCust(String custIds,String userType){
        CustomerInfoModel customerInfoModel = new CustomerInfoModel();
        customerInfoModel.setCustId(custIds);
        customerInfoModel.setCustType(userType);
        List<CustomerInfo> custs = customerInfoService.getByCustModel(customerInfoModel);
        if(null != custs && custs.size()>0){
            if(custs.size()>1){
                return null;
            }else{
                return custs.get(0);
            }
        }
        return null;
    }


    /**
     * 充值对账操作
     * @param prechargeRecords
     * @return
     */
    @RequestMapping("/toBalanceOfAccount")
    @ResponseBody
    public ResultMsg toBalanceOfAccount(PrechargeRecords prechargeRecords){
        ResultMsg result = new ResultMsg();
        String userType = Securitys.getUserType();
        if(userType.equals("10") || userType.equals("11")||userType.equals("09")){
            userType = "09";
        }
        List<String> tempIds = Securitys.getAuthorityIdList();
        if(tempIds.size()>0){
            String res = "fail";
            if (alipayService.toBalanceOfAccount(prechargeRecords.getPrechargeSn(), tempIds.get(0).toString(),userType)) {
                res = "success";
            }
            result.setObj(res);
        }else{
            throw new RuntimeException("获取用户信息异常");
        }
    }
}

5、支付宝支付服务

5.1AlipayService

public interface AlipayService{
    /**
     * 支付form方法
     * @param userName
     * @param eventType 事件类型
     * @param bizType 交易类型
     * @param recAmount 充值金额
     * @return
     * @throws UnsupportedEncodingException
     */
    String getRechargeHtml(String userName, String userType,String eventType,String bizType,String recAmount);

    /**
     * 生成充值流水数据并返回支付流水号
     * @param userName
     * @param eventType 事件类型
     * @param bizType   交易类型
     * @param recAmount 充值金额
     * @return
     */
    String getRechargeId(String userName, String userType, String eventType, String bizType,String recAmount);


    PrechargeInfo getPrechargeInfo(String userId, String userType);


    /**
     * 接收充值结果
     * @param requestParams
     * @return
     */
    String notifyRecharge(Map requestParams, String userId,String userType) throws UnsupportedEncodingException;

    String notifyRecharge(Map requestParams) throws UnsupportedEncodingException;

    /**
     * 更新充值流水
     * @param params
     * @param result
     * @param tradeStatus
     * @return
     */
    int updateRechargeInfo(Map<String,String> params,String result,String tradeStatus, String userId,String userType);

    int updateRechargeInfo(Map<String,String> params,String result,String tradeStatus);
    /**
     * 验证充值是否成功
     * @param rechargeRecordsId
     * @return
     */
    String queryRechargeStatus(String rechargeRecordsId ,String custId, String userType);

    /**
     * 更新充值订单支付状态和支付时间并更新余额
     * @param recordsAlipay
     * @param params
     * @param payState
     * @return
     */
    int updateRechargeOrderInfo(FinAlipayRecord recordsAlipay, Map<String,String> params, String payState, String userId,String userType);

    /**
     * 通过交易流水号进行手动对账操作
     * @param pRechargeRecordsId
     * @return
     */
    boolean toBalanceOfAccount(String pRechargeRecordsId, String userId,String userType);

    /**
     * 县域 客户的支付方法
     * @param custId
     * @param userType
     * @param eventType
     * @param bizType
     * @param recAmount
     * @return
     */
//    String getRechargeHtmlXY(String custId, String userType,String eventType,String bizType,String recAmount);
}

5.2 AlipayService实现

@Service
public class AlipayServiceImpl implements AlipayService{
    public Logger logger = Logger.getLogger(getClass());
    @Value("#{configProperties['recharge_notify_url']}")
    private String notifyUrl;

    @Value("#{configProperties['recharge_return_url']}")
    private String returnUrl;
    
    @Autowired
    private FinAlipayRecordDao finAlipayRecordDao;
    @Autowired
    private PrechargeInfoDao prechargeInfoDao;
    @Autowired
    private PrechargeRecordsDao prechargeRecordsDao;
    @Autowired
    private FinSettleCustDetailDao finSettleCustDetailDao;
    @Autowired
    private UserStationsDao userStationsDao;
    @Autowired
    private CityStationInfoDao cityStationInfoDao;
    @Override
    public String getRechargeHtml(String userId, String userType, String eventType, String bizType, String recAmount){

        ///生成支付流水数据并返回支付流水号

        String outTradeNo = getRechargeId(userId, userType, eventType, bizType, recAmount);
        //组织参数提交到支付宝
        //支付类型
        String payment_type = "1";
        //必填,不能修改
        //服务器异步通知页面路径
        String notify_url = notifyUrl;
        //需http://格式的完整路径,不能加?id=123这类自定义参数
        //页面跳转同步通知页面路径
        String return_url = returnUrl;
        //订单名称
        String subject = "客服后台充值支付";
        //new String(httpRequest.getParameter("WIDsubject").getBytes("ISO-8859-1"),"UTF-8");
        //必填
        //付款金额
        FinAlipayRecord finAlipayRecord = finAlipayRecordDao.selectPayByOutTradeNo(outTradeNo);
        String total_fee = String.valueOf(finAlipayRecord.getTotalAmounts().doubleValue() / 100);
        //必填
        //订单描述
        String body = "";
        //商品展示地址
        String show_url = "";
        //需以http://开头的完整路径,例如:http://www.商户网址.com/myorder.html
        //防钓鱼时间戳
        String anti_phishing_key = "";
        //若要使用请调用类文件submit中的query_timestamp函数
        //客户端的IP地址
        String exter_invoke_ip = "";
        //把请求参数打包成数组
        Map<String, String> sParaTemp = new HashMap<>();
        sParaTemp.put("service", "create_direct_pay_by_user");
        sParaTemp.put("partner", AlipayConfig.partner);
        sParaTemp.put("seller_email", AlipayConfig.seller_email);
        sParaTemp.put("_input_charset", AlipayConfig.input_charset);
        sParaTemp.put("payment_type", payment_type);
        sParaTemp.put("notify_url", notify_url);
        sParaTemp.put("return_url", return_url);
        sParaTemp.put("out_trade_no", outTradeNo);
        sParaTemp.put("subject", subject);
        sParaTemp.put("total_fee", total_fee);
        sParaTemp.put("body", body);
        sParaTemp.put("show_url", show_url);
        sParaTemp.put("anti_phishing_key", anti_phishing_key);
        sParaTemp.put("exter_invoke_ip", exter_invoke_ip);

        //建立请求
        String sHtmlText = AlipaySubmit.buildRequest(sParaTemp, "post", "确认");

        return sHtmlText;
    }

    /**
     * 生成支付流水数据并返回支付流水号
     *
     * @param userId
     * @param eventType 事件类型:ET01客服,ET02货主PC,ET03货主Android,ET04货主iOS,ET05司机Android,ET06司机iOS
     * @param bizType   交易类型:BIZ17快递充值
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public String getRechargeId(String userId, String userType, String eventType, String bizType, String recAmount){
        String orderCode = SNUtil.create15();
        PrechargeRecords prechargeRecords = new PrechargeRecords();
        prechargeRecords.setBusinessId(userId);
        prechargeRecords.setUserType(userType);
        prechargeRecords.setPrechargeValue(getAmount(recAmount));
        prechargeRecords.setPrechargeType("01");//充值
        prechargeRecords.setComefromId(userId);
        prechargeRecords.setCreateUser(userId);
        prechargeRecords.setPrechargeState("00");
        prechargeRecords.setGmtCreate(new Date());
        prechargeRecords.setPrechargeOrderCode(orderCode);
        prechargeRecords.setPayType("alipay");
        //t_precharge_info
        prechargeRecordsDao.insert(prechargeRecords);
        //生成 SELECT GETOUTTRADENO()  from DUAL
        String outTradeNo = finAlipayRecordDao.getKey();


        FinAlipayRecord recordsAlipay = new FinAlipayRecord();
        recordsAlipay.setOrderCode(orderCode);//订单号
        recordsAlipay.setOutTradeNo(outTradeNo);//交易流水号
        recordsAlipay.setEventType(eventType);//事件类型
        recordsAlipay.setBizType(bizType);//交易类型
        recordsAlipay.setGmtCreate(new Date());//创建时间
        recordsAlipay.setCreateUser(userId);//创建人
        recordsAlipay.setConsumeAmounts(getAmount(recAmount));//订单金额
        recordsAlipay.setTotalAmounts(getAmount(recAmount));//多个订单支付时总金额 totalFee
        recordsAlipay.setConsumeType("I");//收支类型
        recordsAlipay.setAlipayResult("submit");//交易结果
        //insert into t_fin_alipay_records
        int res = finAlipayRecordDao.insert(recordsAlipay);

        if(0 < res){
            //nothing to do.
            finAlipayRecordDao.insert4Fin(recordsAlipay);
        }

        return outTradeNo;
    }

    @Override
    public PrechargeInfo getPrechargeInfo(String userId, String userType){
        synchronized(this){
            PrechargeInfo prechargeInfoParm = new PrechargeInfo();
            prechargeInfoParm.setBusinessId(userId);
            prechargeInfoParm.setUserType(userType);

            PrechargeInfo prechargeInfo = (PrechargeInfo)prechargeInfoDao.selectByPrimaryKey(prechargeInfoParm);
            //充值信息表是否存在,不存在需先生成充值信息数据
            if(null == prechargeInfo){
                prechargeInfo = new PrechargeInfo();
                prechargeInfo.setAvailableValue(0);
                prechargeInfo.setBusinessId(userId);
                prechargeInfo.setFrozenValue(0);
                prechargeInfo.setPrechargeValue(0);
                prechargeInfo.setCreateUser(userId);
                prechargeInfo.setUserType(userType);
                prechargeInfoDao.insert(prechargeInfo);
            }
            return prechargeInfo;
        }
    }

    @Override
    public String queryRechargeStatus(String rechargeRecordsId ,String custId, String userType){
        //PrechargeRecords prechargeRecords = (PrechargeRecords)prechargeRecordsDao.selectByPrimaryKey(rechargeRecordsId);
        PrechargeRecords param = new PrechargeRecords();
        param.setBusinessId(custId);
        param.setUserType(userType);
        PrechargeRecords prechargeRecords = (PrechargeRecords)prechargeRecordsDao.getPrechargeRecordsByBussinesId(param);
        if(null != prechargeRecords && "01".equalsIgnoreCase(prechargeRecords.getPrechargeState())){
            return "Y";
        }else{
            return "N";
        }
    }


    /**
     * 接收充值结果
     *
     * @param requestParams
     * @return
     */
    @Transactional
    @Override
    public String notifyRecharge(Map requestParams, String userId,String userType) throws UnsupportedEncodingException{
        String result = "";
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        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 out_trade_no = params.get("out_trade_no");
        //支付宝交易号
        String trade_no = params.get("trade_no");
        //交易状态
        String trade_status = params.get("trade_status");
        int updateNum = 0;
        int fail_state = 0;
        //请在这里加上商户的业务逻辑程序代码
        if(trade_status.equals("TRADE_FINISHED")){
            //判断该笔订单是否在商户网站中已经做过处理
            //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
            //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
            //如果有做过处理,不执行商户的业务程序
            //注意:
            //退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知
        }
        else if(trade_status.equals("TRADE_SUCCESS")){
            updateNum = updateRechargeInfo(params, "success", trade_status, userId,userType);
            //——请根据您的业务逻辑来编写程序(以上代码仅作参考)——
            if(updateNum > 0){
                FinAlipayRecord finAlipayRecord = finAlipayRecordDao.selectPayByOutTradeNo(out_trade_no);
                String fee = params.get("total_fee");
                BigDecimal totalFee = null;
                if(fee == null || "".equals(fee)){
                    totalFee = new BigDecimal("0");
                }
                else{
                    BigDecimal feevalue = new BigDecimal("100");
                    totalFee = new BigDecimal(fee).multiply(feevalue);
                }
                if(Math.abs(finAlipayRecord.getTotalAmounts().intValue() - totalFee.intValue()) <= 1){
                    logger.error(finAlipayRecord.getTotalAmounts() + "===支付宝金额" + totalFee.intValue());
                    updateRechargeOrderInfo(finAlipayRecord, params, "01", userId,userType);//支付成功
                }
                else{
                    updateRechargeOrderInfo(finAlipayRecord, params, "01", userId,userType);//支付成功金额对应不上
                }
                logger.debug("支付宝支付回调成功");
                result = "success";//请不要修改或删除
            }
            else{
                result = "fail";//请不要修改或删除
                logger.debug("支付回调更新时未找到支付流水信息");
                fail_state = 1;
            }
        }
        else{
            logger.debug("支付宝支付回调状态" + trade_status);
            result = "success";
        }
        if(fail_state == 1){
            Map<String, Object> map = new HashMap<>();
            map.put("outTradeNo", out_trade_no);
            List<FinAlipayRecord> list = (List<FinAlipayRecord>)finAlipayRecordDao.selectByMap(map);
            for(FinAlipayRecord finAlipayRecord : list){
                PrechargeRecords prechargeRecords = (PrechargeRecords)prechargeRecordsDao.selectByPrimaryKey(finAlipayRecord.getOrderCode());
                prechargeRecords.setPrechargeSn(finAlipayRecord.getOrderCode());
                prechargeRecords.setPrechargeType("02");
                prechargeRecordsDao.update(prechargeRecords);
            }
        }
        return result;
    }
    @Transactional
    @Override
    public String notifyRecharge(Map requestParams) throws UnsupportedEncodingException {
        String result = "";
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        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 out_trade_no = params.get("out_trade_no");
        //支付宝交易号
        String trade_no = params.get("trade_no");
        //交易状态
        String trade_status = params.get("trade_status");
        int updateNum = 0;
        int fail_state = 0;
        //请在这里加上商户的业务逻辑程序代码
        if(trade_status.equals("TRADE_FINISHED")){
            //判断该笔订单是否在商户网站中已经做过处理
            //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
            //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
            //如果有做过处理,不执行商户的业务程序
            //注意:
            //退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知
        }
        else if(trade_status.equals("TRADE_SUCCESS")){
            updateNum = updateRechargeInfo(params, "success", trade_status);
            //——请根据您的业务逻辑来编写程序(以上代码仅作参考)——
            if(updateNum > 0){
                Map<String, Object> map = new HashMap<>();
                map.put("outTradeNo", out_trade_no);
                List<FinAlipayRecord> list = (List<FinAlipayRecord>)finAlipayRecordDao.selectByMap(map);
                String fee = params.get("total_fee");
                BigDecimal totalFee = null;
                if(fee == null || "".equals(fee)){
                    totalFee = new BigDecimal("0");
                }
                else{
                    BigDecimal feevalue = new BigDecimal("100");
                    totalFee = new BigDecimal(fee).multiply(feevalue);
                }
                if(Math.abs(list.get(0).getTotalAmounts().intValue() - totalFee.intValue()) <= 1){
                    logger.error(list.get(0).getTotalAmounts() + "===支付宝金额" + totalFee.intValue());
                    updateRechargeOrderInfo((FinAlipayRecord)list.get(0), params, "01");//支付成功
                }
                else{
                    updateRechargeOrderInfo((FinAlipayRecord)list.get(0), params, "01");//支付成功金额对应不上
                }
                logger.debug("alipay notify success");
                result = "success";//请不要修改或删除
            }
            else{
                result = "fail";//请不要修改或删除
                logger.debug("支付回调更新时未找到支付流水信息");
                fail_state = 1;
            }
        }
        else{
            logger.debug("alipay notify status" + trade_status);
            result = "success";
        }
        if(fail_state == 1){
            Map<String, Object> map = new HashMap<>();
            map.put("outTradeNo", out_trade_no);
            List<FinAlipayRecord> list = (List<FinAlipayRecord>)finAlipayRecordDao.selectByMap(map);
            for(FinAlipayRecord finAlipayRecord : list){
                PrechargeRecords prechargeRecords = (PrechargeRecords)prechargeRecordsDao.selectByPrimaryKey(finAlipayRecord.getOrderCode());
                prechargeRecords.setPrechargeSn(finAlipayRecord.getOrderCode());
                prechargeRecords.setPrechargeType("02");
                prechargeRecordsDao.update(prechargeRecords);
            }
        }
        return result;
    }


    /**
     * 更新支付流水表
     *
     * @param params
     * @param result
     * @param tradeStatus
     * @return
     */
    @Override
    public int updateRechargeInfo(Map<String, String> params, String result, String tradeStatus, String userId,String userType){
        FinAlipayRecord recordsAlipay = new FinAlipayRecord();
        recordsAlipay.setOutTradeNo(params.get("out_trade_no"));//商户交易流水号
        recordsAlipay.setAlipayTradeNo(params.get("trade_no"));//支付宝交易号
        //recordsAlipay.setEventType("");//事件类型
        recordsAlipay.setGmtModified(new Date());//更新时间
        recordsAlipay.setModifiedUser("支付宝");//更新人
        recordsAlipay.setBuyerLogonId(params.get("buyer_email"));//买家支付宝账号
        recordsAlipay.setBuyerUserId(params.get("buyer_id"));//买家支付宝用户号
        recordsAlipay.setBuyerEmail(params.get("buyer_email"));//买家支付宝账号
        String fee = params.get("total_fee");
        BigDecimal totalFee = null;
        if(fee == null || "".equals(fee)){
            fee = "0";
        }
        else{
            totalFee = new BigDecimal(Double.valueOf(fee) * 100);
        }
        recordsAlipay.setAlipayResult(result);//支付结果
        recordsAlipay.setBuyerPayAmount(totalFee.intValue());//实际支付宝支付金额
        recordsAlipay.setRemarks(String.valueOf(totalFee.intValue()));
        int num = 0;
        if("fail".equals(result)){
            recordsAlipay.setAlipayErrorCode(tradeStatus);
            recordsAlipay.setAlipayErrorMsg(RechargeCodeConstant.getMsg(tradeStatus));
            updateRechargeOrderInfo(recordsAlipay, params, "02", userId,userType);//支付失败
        }
        else{
            num = finAlipayRecordDao.updateNotifyPay(recordsAlipay);
        }
        return num;
    }

    @Override
    public int updateRechargeInfo(Map<String, String> params, String result, String tradeStatus) {
        FinAlipayRecord recordsAlipay = new FinAlipayRecord();
        recordsAlipay.setOutTradeNo(params.get("out_trade_no"));//商户交易流水号
        recordsAlipay.setAlipayTradeNo(params.get("trade_no"));//支付宝交易号
        //recordsAlipay.setEventType("");//事件类型
        recordsAlipay.setGmtModified(new Date());//更新时间
        recordsAlipay.setModifiedUser("支付宝");//更新人
        recordsAlipay.setBuyerLogonId(params.get("buyer_email"));//买家支付宝账号
        recordsAlipay.setBuyerUserId(params.get("buyer_id"));//买家支付宝用户号
        recordsAlipay.setBuyerEmail(params.get("buyer_email"));//买家支付宝账号
        String fee = params.get("total_fee");
        BigDecimal totalFee = null;
        if(fee == null || "".equals(fee)){
            fee = "0";
        }
        else{
            totalFee = new BigDecimal(Double.valueOf(fee) * 100);
        }
        recordsAlipay.setAlipayResult(result);//支付结果
        recordsAlipay.setBuyerPayAmount(totalFee.intValue());//实际支付宝支付金额
        recordsAlipay.setRemarks(String.valueOf(totalFee.intValue()));
        int num = 0;
        if("fail".equals(result)){
            recordsAlipay.setAlipayErrorCode(tradeStatus);
            recordsAlipay.setAlipayErrorMsg("fail");
            updateRechargeOrderInfo(recordsAlipay, params, "02");//支付失败
        }
        else{
            num = finAlipayRecordDao.updateNotifyPay(recordsAlipay);
        }
        return num;
    }

    private int updateRechargeOrderInfo(FinAlipayRecord recordsAlipay, Map<String, String> params, String payState) {
        int upNum = 0;
        Map<String, Object> map = new HashMap<>();
        map.put("outTradeNo", recordsAlipay.getOutTradeNo());
        List<FinAlipayRecord> list = (List<FinAlipayRecord>)finAlipayRecordDao.selectByMap(map);
        for(FinAlipayRecord finAlipayRecord : list){
			PrechargeRecords prechargeRecordsParam = new PrechargeRecords();
			prechargeRecordsParam.setPrechargeOrderCode(finAlipayRecord.getOrderCode());
            PrechargeRecords prechargeRecords = prechargeRecordsDao.getPrechargeRecordsByOrderCode(prechargeRecordsParam);
            if("01".equals(payState)){
                if(null != prechargeRecords && "00".equals(prechargeRecords.getPrechargeState())){

                    //更新客户可用额度
                    PrechargeInfo prechargeInfoParm = new PrechargeInfo();
                    prechargeInfoParm.setBusinessId(prechargeRecords.getBusinessId());
                    prechargeInfoParm.setUserType(prechargeRecords.getUserType());
                    PrechargeInfo prechargeInfo = prechargeInfoDao.get4UpdAmount(prechargeInfoParm);
                    Integer availableAmount = 0;
                    if(null != prechargeInfo){
                        availableAmount = prechargeInfo.getAvailableValue() + recordsAlipay.getConsumeAmounts();
                        prechargeInfo.setAvailableValue(availableAmount);
                        prechargeInfo.setPrechargeValue(prechargeInfo.getPrechargeValue() + recordsAlipay.getConsumeAmounts());
                        prechargeInfo.setModifiedUser("alipay");
                        prechargeInfo.setGmtModified(new Date());
                        prechargeInfoDao.update(prechargeInfo);
                        logger.debug("updateRechargeOrderInfo 更新t_precharge_info");
                    }

                    //更新充值记录状态
                    prechargeRecords.setBusinessId(prechargeRecords.getBusinessId());
                    prechargeRecords.setPrechargeState("01");
                    prechargeRecords.setModifiedUser("alipay");
                    prechargeRecords.setGmtModified(new Date());
                    prechargeRecords.setCurrentAvailableValue(availableAmount);
                    prechargeRecordsDao.update(prechargeRecords);
                }
            }else if("02".equalsIgnoreCase(payState)){
                if(null != prechargeRecords && "00".equals(prechargeRecords.getPrechargeState())){
                    prechargeRecords.setPrechargeState("02");
                    prechargeRecords.setModifiedUser("alipay");
                    prechargeRecords.setGmtModified(new Date());
                    prechargeRecordsDao.update(prechargeRecords);
                }
            }
            upNum++;
            //更新结算收款明细付款渠道
            FinSettleCustDetail fin = new FinSettleCustDetail();
            fin.setOrderCode(finAlipayRecord.getOrderCode());
            FinSettleCustDetail dbcustdetail = (FinSettleCustDetail) finSettleCustDetailDao.select("selectByPrimaryKey",finAlipayRecord.getOrderCode());
            if(null != dbcustdetail){
                FinSettleCustDetail custdetail = new FinSettleCustDetail();
                custdetail.setOrderCode(finAlipayRecord.getOrderCode());
                custdetail.setPayChannel("alipay");//付款渠道
                finSettleCustDetailDao.update(custdetail);
            }
        }
        if(upNum != list.size()){
            logger.error("未将全部订单支付状态更新");
        }
        return upNum;
    }


    /**
     * 更新充值订单支付状态和支付时间并更新余额
     *
     * @param recordsAlipay
     * @param params
     * @param payState
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public int updateRechargeOrderInfo(FinAlipayRecord recordsAlipay, Map<String, String> params, String payState, String userId,String userType){
        int upNum = 0;
        Map<String, Object> map = new HashMap<>();
        map.put("outTradeNo", recordsAlipay.getOutTradeNo());
        List<FinAlipayRecord> list = (List<FinAlipayRecord>)finAlipayRecordDao.selectByMap(map);
        for(FinAlipayRecord finAlipayRecord : list){
            PrechargeRecords prechargeRecordsParam = new PrechargeRecords();
            prechargeRecordsParam.setPrechargeOrderCode(finAlipayRecord.getOrderCode());
            PrechargeRecords prechargeRecords = (PrechargeRecords)prechargeRecordsDao.getPrechargeRecordsByOrderCode(prechargeRecordsParam);
            if("01".equals(payState)){
                if(null != prechargeRecords && "00".equals(prechargeRecords.getPrechargeState())){
                    //更新客户可用额度
                    PrechargeInfo prechargeInfoParm = new PrechargeInfo();
                    prechargeInfoParm.setBusinessId(userId);
                    prechargeInfoParm.setUserType(userType);
                    PrechargeInfo prechargeInfo = prechargeInfoDao.get4UpdAmount(prechargeInfoParm);
                    Integer availableAmount = 0;
                    if(null != prechargeInfo){
                        availableAmount = prechargeInfo.getAvailableValue() + recordsAlipay.getConsumeAmounts();
                        prechargeInfo.setAvailableValue(availableAmount);
                        prechargeInfo.setPrechargeValue(prechargeInfo.getPrechargeValue() + recordsAlipay.getConsumeAmounts());
                        prechargeInfo.setModifiedUser("alipay");
                        prechargeInfo.setGmtModified(new Date());
                        prechargeInfoDao.update(prechargeInfo);
                        logger.debug("updateRechargeOrderInfo 更新t_precharge_info");
                    }
                    //更新充值记录状态
                    prechargeRecords.setBusinessId(userId);
                    prechargeRecords.setPrechargeState("01");
                    prechargeRecords.setModifiedUser("alipay");
                    prechargeRecords.setGmtModified(new Date());
                    prechargeRecords.setCurrentAvailableValue(availableAmount);
                    prechargeRecordsDao.update(prechargeRecords);
                }
            }else if("02".equalsIgnoreCase(payState)){
                if(null != prechargeRecords && "00".equals(prechargeRecords.getPrechargeState())){
                    prechargeRecords.setPrechargeState("02");
                    prechargeRecords.setModifiedUser("alipay");
                    prechargeRecords.setGmtModified(new Date());
                    prechargeRecordsDao.update(prechargeRecords);
                }
            }
            upNum++;
            //更新结算收款明细付款渠道
            FinSettleCustDetail dbcustdetail = (FinSettleCustDetail)finSettleCustDetailDao.selectByPrimaryKey(finAlipayRecord.getOrderCode());
            if(null != dbcustdetail){
                FinSettleCustDetail custdetail = new FinSettleCustDetail();
                custdetail.setOrderCode(finAlipayRecord.getOrderCode());
                custdetail.setPayChannel("alipay");//付款渠道
                //t_fin_settle_cust
                finSettleCustDetailDao.update(custdetail);
            }
        }
        if(upNum != list.size()){
            logger.error("未将全部订单支付状态更新");
        }
        return upNum;
    }

    private Integer getAmount(String recAmount){
        return new BigDecimal(recAmount).multiply(new BigDecimal(100)).intValue();
    }

    @Override
    public boolean toBalanceOfAccount(String pRechargeRecordsId, String userId,String userType){
        String tempId = "";
        if(userType.equals("06")){
            //getstationId
            UserStations userStations =userStationsDao.findByUser_Id(userId);
            List<CityStationInfoModel> cityStationInfoModelList = cityStationInfoDao.getByStationCode(userStations.getStationCode());
            tempId = cityStationInfoModelList.get(0).getStationId();
        }else{
            tempId = userId;
        }


        boolean resRet = false;
        PrechargeRecords prechargeRecords = new PrechargeRecords();
        prechargeRecords.setPrechargeSn(pRechargeRecordsId);
        prechargeRecords = (PrechargeRecords)prechargeRecordsDao.selectByPrimaryKey(prechargeRecords);
        String prechargeOrderCode = prechargeRecords.getPrechargeOrderCode();
        if(StringUtils.isNotBlank(prechargeOrderCode)){
            List<FinAlipayRecord> res = finAlipayRecordDao.selectPayRecordByCodes(new String[]{prechargeOrderCode});
            if(res.size()>0){
                FinAlipayRecord finAlipayRecord = res.get(0);
                int i = updateRechargeOrderInfo4BalanceOfAccount(finAlipayRecord,prechargeRecords,tempId);
                if(i > 0){
                    resRet = true;
                }
            }
        }
        return resRet;
    }


    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    private int updateRechargeOrderInfo4BalanceOfAccount(FinAlipayRecord finAlipayRecord, PrechargeRecords prechargeRecords, String userId){
        int upNum = 0;
        if(null != prechargeRecords && "02".equals(prechargeRecords.getPrechargeState())){ //改为充值失败验证

            //更新客户可用额度
            PrechargeInfo prechargeInfoParm = new PrechargeInfo();
            prechargeInfoParm.setBusinessId(prechargeRecords.getBusinessId());
            PrechargeInfo prechargeInfo = prechargeInfoDao.get4UpdAmount(prechargeInfoParm);
            Integer availableAmount = 0;
            if(null != prechargeInfo){
                availableAmount = prechargeInfo.getAvailableValue() + finAlipayRecord.getConsumeAmounts();
                prechargeInfo.setAvailableValue(availableAmount);
                prechargeInfo.setPrechargeValue(prechargeInfo.getPrechargeValue() + finAlipayRecord.getConsumeAmounts());
                prechargeInfo.setModifiedUser("alipay");
                prechargeInfo.setGmtModified(new Date());
                prechargeInfoDao.update(prechargeInfo);
                logger.debug("updateRechargeOrderInfo 更新t_precharge_info");
            }

            //更新充值记录状态
            prechargeRecords.setPrechargeState("01");
            prechargeRecords.setModifiedUser("alipay");
            prechargeRecords.setGmtModified(new Date());
            prechargeRecords.setCurrentAvailableValue(availableAmount);
            upNum = prechargeRecordsDao.update(prechargeRecords);
        }

        return upNum;
    }

}

6、代码片段

支付宝PC支付

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值