package com.yihu.wlyy.web.wx; import com.alibaba.fastjson.JSON; import com.yihu.wlyy.entity.charge.WlyyCharge; import com.yihu.wlyy.entity.patient.Patient; import com.yihu.wlyy.entity.patient.SignFamily; import com.yihu.wlyy.repository.charge.ChargeDao; import com.yihu.wlyy.repository.patient.PatientDao; import com.yihu.wlyy.repository.patient.SignFamilyDao; import com.yihu.wlyy.service.third.httplog.LogService; import com.yihu.wlyy.service.weixin.wxpay.common.Configure; import com.yihu.wlyy.service.weixin.wxpay.model.BindCard; import com.yihu.wlyy.service.weixin.wxpay.model.Charge; import com.yihu.wlyy.service.weixin.wxpay.service.OnePayService; import com.yihu.wlyy.util.SystemConf; import com.yihu.wlyy.web.WeixinBaseController; import com.ylzinfo.onepay.sdk.OnepayDefaultClient; import com.ylzinfo.onepay.sdk.domain.RequestParams; import com.ylzinfo.onepay.sdk.domain.ResponseParams; import com.ylzinfo.onepay.sdk.exception.PayException; import com.ylzinfo.onepay.sdk.utils.StringUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.apache.commons.lang3.StringUtils; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.util.StreamUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URLDecoder; import java.nio.charset.Charset; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; /** * Created by hzp on 2017/05/23. */ @Controller @RequestMapping(value = "/onepay", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @Api(description = "统一支付服务") public class OnePayController extends WeixinBaseController { private static final Logger LOGGER = LoggerFactory.getLogger(OnePayController.class); @Autowired private OnePayService pay; @Autowired private PatientDao patientDao; @Autowired private SignFamilyDao signFamilyDao; @Autowired private ChargeDao chargeDao; @Autowired LogService logService; @Autowired private Configure config; @RequestMapping(value = "expensesStatus", method = RequestMethod.GET) @ApiOperation("居民缴费状态查询") @ResponseBody public String expensesStatus() throws Exception { try { // 获取居民个人信息 要根据签约code去查找签约扣费状态 String patient = getUID(); // String singCode = "044701ea-5b23-11e6-8344-fa163e8aee56"; // SignFamily sign = signFamilyDao.findByCode(singCode); // String patient = "915cc456-5b1d-11e6-8344-fa163e8aee56"; SignFamily signFamily = signFamilyDao.findPatientExpensesStatus(patient); String expensesStatus = signFamily.getExpensesStatus(); if ("0".equals(expensesStatus)) { return write(200, "未扣费!", "expensesStatus", expensesStatus); } else if ("1".equals(expensesStatus)) { return write(200, "已扣费!", "expensesStatus", expensesStatus); } else if ("2".equals(expensesStatus)) { return write(200, "已退费!", "expensesStatus", expensesStatus); } else { return write(200, "扣费状态数据有误!", "expensesStatus", expensesStatus); } } catch (Exception e) { return error(-1, e.getMessage()); } } /** * 补贴类型:无补贴01,全补贴02,补个人承担部分(20)03,补统筹基金(70)04 * * @param expensesType 补贴类型 * @return * @throws Exception */ @RequestMapping(value = "bill", method = RequestMethod.GET) @ApiOperation("居民缴费账单") @ResponseBody public String getBill(@RequestParam String expensesType) throws Exception { try { Pattern pattern = Pattern.compile("[0-9]*"); Boolean flag = pattern.matcher(expensesType).matches(); JSONObject json = new JSONObject(); if (flag) { switch (expensesType) { case "01": json.put("selfpayAmount", 20); json.put("financialAmount", 0); json.put("insuranceAmount", 70); json.put("totalAmount", 90); break; case "02": json.put("selfpayAmount", 0); json.put("financialAmount", 90); json.put("insuranceAmount", 0); json.put("totalAmount", 90); break; case "03": json.put("selfpayAmount", 0); json.put("financialAmount", 20); json.put("insuranceAmount", 70); json.put("totalAmount", 90); break; case "04": json.put("selfpayAmount", 20); json.put("financialAmount", 70); json.put("insuranceAmount", 0); json.put("totalAmount", 90); break; } } return write(200, "查询缴费账单成功!", "data", json); } catch (Exception e) { return error(-1, e.getMessage()); } } @RequestMapping(value = "createSicard", method = RequestMethod.POST) @ApiOperation("生成电子社保卡") @ResponseBody public String createSicard() throws Exception { try { String sicardUrl = pay.createSicard("0cc6e4562de2437ab2dbbf51a9fc3b49", "oULM4xAj9sOsHJ95ttKYd_Fjh6Hc");//getUID(), getOpenid()); return write(200, "生成电子社保卡成功!", "data", sicardUrl); } catch (Exception e) { return error(-1, e.getMessage()); } } @RequestMapping(value = "bindCard", method = RequestMethod.POST) @ApiOperation("查询绑卡信息") @ResponseBody public String bindCard() throws Exception { try { String patient = getUID(); String openid = getOpenid(); // String patient = "0cc6e4562de2437ab2dbbf51a9fc3b49"; // String openid = "oULM4xAj9sOsHJ95ttKYd_Fjh6Hc"; BindCard bindCard = pay.bindCard(patient, openid);//getUID(), getOpenid()); oULM4xAj9sOsHJ95ttKYd_Fjh6Hc String sicardUrl = pay.createSicard(patient, openid);//getUID(), getOpenid()); if (bindCard != null) { JSONObject json = new JSONObject(bindCard); json.put("bindStatus", "000000"); json.put("sicardUrl", sicardUrl); return write(200, "查询绑卡信息成功!", "data", json); } else { // 返回电子社保卡链接 JSONObject json = new JSONObject(); json.put("sicardUrl", sicardUrl); json.put("bindStatus", "030007"); return write(200, "生成电子社保卡成功!", "data", json); } // BindCard bindCard = pay.bindCard("0cc6e4562de2437ab2dbbf51a9fc3b49", "oULM4xAj9sOsHJ95ttKYd_Fjh6Hc");//getUID(), getOpenid()); oULM4xAj9sOsHJ95ttKYd_Fjh6Hc // return write(200, "查询绑卡信息成功!", "data", bindCard); } catch (Exception e) { return error(-1, e.getMessage()); } } @RequestMapping(value = "charge", method = RequestMethod.POST) @ApiOperation("家庭医生签约支付") @ResponseBody public String charge( @ApiParam(name = "orgCode", value = "医疗机构编号", defaultValue = "3502050300") @RequestParam String orgCode, @ApiParam(name = "chargeType", value = "支付类型", defaultValue = "1") @RequestParam String chargeType, @ApiParam(name = "chargeRelation", value = "支付关联代码", defaultValue = "044701ea5b2311e68344fa163e8aee56") @RequestParam String chargeRelation, @ApiParam(name = "totalAmount", value = "交易总金额(分)", defaultValue = "1") @RequestParam Integer totalAmount, /*@ApiParam(name = "selfpayAmount", value = "自费金额(分)", defaultValue = "0") @RequestParam Integer selfpayAmount, @ApiParam(name = "insuranceAmount", value = "医保支付金额(分)", defaultValue = "1") @RequestParam Integer insuranceAmount, @ApiParam(name = "insuranceAmount", value = "区财政补贴金额(分)", defaultValue = "1") @RequestParam Integer financialAmount,*/ @ApiParam(name = "feeDetail", value = "费用明细", defaultValue = "[{\"itemName\":\"家庭医生签约支付\",\"itemDesc\":\"家庭医生签约支付\",\"itemOrigPrice\":\"1\",\"itemNowPrice\":\"1\",\"itemNum\":\"1\",\"itemTotalAmt\":\"1\"}]") @RequestParam String feeDetail) throws Exception { try { // 获取居民个人信息 String patient = getUID(); String openId = getOpenid(); // String patient = "0cc6e4562de2437ab2dbbf51a9fc3b49"; // String openId = "oULM4xAj9sOsHJ95ttKYd_Fjh6Hc"; if (StringUtils.isNotEmpty(openId)) { String settleNo = pay.charge(orgCode, chargeType, chargeRelation, totalAmount, feeDetail, patient, openId,getAccessToken()); //ohNH9sh4uwuJCxIwcLJtGTX-BaSk getUID(),getOpenid() return write(200, "家庭医生签约支付成功!", "data", settleNo); } else { return write(-1, "openId为空!"); } // String settleNo = pay.charge(orgCode, chargeType, chargeRelation, totalAmount, selfpayAmount, insuranceAmount, feeDetail, "0cc6e4562de2437ab2dbbf51a9fc3b49", "oULM4xAj9sOsHJ95ttKYd_Fjh6Hc"); //getUID(),getOpenid() // return write(200, "家庭医生签约支付成功!", "data", settleNo); } catch (Exception e) { return error(-1, e.getMessage()); } } @RequestMapping(value = "chargeQuery", method = RequestMethod.POST) @ApiOperation("家庭医生签约支付查询") @ResponseBody public String chargeQuery(@ApiParam(name = "code", value = "接入应用业务流水号", defaultValue = "") @RequestParam String code) throws Exception { try { Charge charge = pay.chargeQuery(code,getAccessToken()); return write(200, "家庭医生签约支付查询成功!", "data", charge); } catch (Exception e) { return error(-1, e.getMessage()); } } @RequestMapping(value = "chargeList", method = RequestMethod.POST) @ApiOperation("获取某次签约的支付记录") @ResponseBody public String chargeList(@ApiParam(name = "chargeType", value = "支付类型", defaultValue = "1") @RequestParam String chargeType, @ApiParam(name = "chargeRelation", value = "支付关联代码", defaultValue = "044701ea5b2311e68344fa163e8aee56") @RequestParam String chargeRelation) throws Exception { try { List charge = pay.chargeList(chargeType, chargeRelation,getAccessToken()); return write(200, "获取某次签约的支付记录成功!", "data", charge); } catch (Exception e) { return error(-1, e.getMessage()); } } @RequestMapping(value = "chargeListByPatient", method = RequestMethod.POST) @ApiOperation("获取患者的支付记录") @ResponseBody public String chargeListByPatient(@ApiParam(name = "patient", value = "患者代码", defaultValue = "") @RequestParam String patient, @ApiParam(name = "page", value = "第几页,从1开始", defaultValue = "1") @RequestParam Integer page, @ApiParam(name = "size", value = "每页几行", defaultValue = "10") @RequestParam Integer size) throws Exception { try { List charge = pay.chargeListByPatient(patient,getAccessToken(), page, size); return write(200, "获取患者的支付记录成功!", "data", charge); } catch (Exception e) { return error(-1, e.getMessage()); } } /** * 解析URL参数串 * * @param formContext * @param wordFirstsplitRegex * @param wordSecondsplitRegex * @return */ private static Map resolveFormContext(String formContext, String wordFirstsplitRegex, String wordSecondsplitRegex) { if (StringUtil.isEmpty(formContext)) { return null; } Map targetMap = new HashMap(); String[] wordSeconds = formContext.split(wordSecondsplitRegex); for (String wordSecond : wordSeconds) { if (StringUtil.isEmpty(wordSecond)) { continue; } int idx = wordSecond.indexOf(wordFirstsplitRegex); targetMap.put(wordSecond.substring(0, idx), wordSecond.substring(idx + 1, wordSecond.length())); } return targetMap; } /** * 转换URL参数中为Map * * @param reqQueryString * @return * @throws PayException */ private Map getRequestMap(String reqQueryString) throws PayException { if (StringUtil.isEmpty(reqQueryString)) { throw new PayException("跳转参数为空"); } Map targetMap = null; try { reqQueryString = URLDecoder.decode(reqQueryString, "utf-8"); targetMap = resolveFormContext(reqQueryString, "=", "&"); } catch (Exception e) { throw new PayException("跳转参数处理异常," + reqQueryString); } return targetMap; } /** * 页面回调更新数据 */ @RequestMapping(value = "/returnUrl", method = RequestMethod.GET) @ApiOperation("商户页面跳转") public String testReturnUrl(@RequestParam String jsonData) throws IOException, PayException { try { JSONObject json = new JSONObject(jsonData); JSONObject requestParam = json.getJSONObject("param");//业务出参 String chargeNo = requestParam.getString("chargeNo"); //支付平台流水号 String chargeTime = requestParam.getString("chargeTime");//支付平台交易成功时间 String outChargeNo = requestParam.getString("outChargeNo");//接入应用业务流水号 String outChargeTime = requestParam.getString("outChargeTime");//接入应用时间 String channel = requestParam.getString("channel");//支付方式 String billNo = requestParam.getString("billNo");//待结算费用单据号 String cardNo = requestParam.getString("cardNo");//医保卡号 String totalAmount = requestParam.getString("totalAmount");//交易总金额 String insuranceAmount = requestParam.getString("insuranceAmount");//医保支付金额 String selfPayAmount = requestParam.getString("selfPayAmount");//自付金额 String userId = requestParam.getString("userId");//用户openID String userName = requestParam.getString("userName");//用户名字 String idType = requestParam.getString("idType");//证件类型 String idNo = requestParam.getString("idNo");//证件号码 String tradeStatus = requestParam.getString("tradeStatus");//交易状态 JSONObject responseContents = json.getJSONObject("responseContent");//医保结构体 String miRegisterNo = responseContents.getString("miRegisterNo");//医保签约号 String miCollectDate = responseContents.getString("miCollectDate");//扣费日期 String miCollectTime = responseContents.getString("miCollectTime");//扣费时间 String miSettleNo = responseContents.getString("miSettleNo");//扣费单据号 String miCollectStatus = responseContents.getString("miCollectStatus");//扣费状态 String miRegisterStatus = responseContents.getString("miRegisterStatus");//登记状态 String cadresPay = responseContents.getString("cadresPay");//政府补贴支付 String miTotalFee = responseContents.getString("miTotalFee");//扣费总额 String healthCarePay = responseContents.getString("healthCarePay");//医保统筹支付 // responseContents.getString("healthPay"); String heathPay = responseContents.getString("heathPay");//健康账户支付 String accountPay = responseContents.getString("accountPay");//医保账户支付 String selfPay = responseContents.getString("selfPay");//个人现金支付 // 判断是否需要更新数据 needUpload为0不需要更新 WlyyCharge charge = chargeDao.getUploadStatus(outChargeNo); if (charge!=null&&!("0".equals(charge.getNeedUpload()))){ pay.updateData(outChargeNo, chargeNo,chargeTime,totalAmount,insuranceAmount,selfPayAmount,billNo,miRegisterNo); } return write(200, "请求成功!"); } catch (Exception e) { return error(-1, e.getMessage()); } } /** * 支付真正完成,异步回调返回支付参数 后台做数据操作 * * @param request * @param response * @throws IOException * @throws PayException */ @RequestMapping(value = "/receiveNotify", method = RequestMethod.POST) @ApiOperation("异步回调数据更改") public void receiveNotify(HttpServletRequest request, HttpServletResponse response) throws IOException, PayException { Boolean isSuccess = false; String error= ""; String responses = ""; response.setContentType("text/html;charset=utf-8"); String appId = "1BHEOI11C00J7B2CA8C0000071FA53E1"; String appSecret = "1BHEOH8HB0006E0A0A0A00002DB28BC5"; InputStream inputStream = request.getInputStream(); String params = StreamUtils.copyToString(inputStream, Charset.forName("UTF-8")); LOGGER.info("回调参数:{}", params); if (StringUtil.isEmpty(params)) { response.getWriter().write("empty"); return; } // 参数转换 ResponseParams encryptRes = JSON.parseObject(params, ResponseParams.class); OnepayDefaultClient client = new OnepayDefaultClient("", appId, appSecret, encryptRes.getSignType(), encryptRes.getEncryptType()); try { // 已经封装的加解密及签名验证 RequestParams requestParams = JSON.parseObject(params, RequestParams.class); ResponseParams res = client.execute(requestParams); responses = JSON.toJSONString(res); if (OnepayDefaultClient.isSuccessful(res)) { isSuccess = true; String param = request.getParameter("param");//业务出参 JSONObject requestParam = new JSONObject(param); String chargeNo = requestParam.getString("chargeNo"); //支付平台流水号 String chargeTime = requestParam.getString("chargeTime");//支付平台交易成功时间 String outChargeNo = requestParam.getString("outChargeNo");//接入应用业务流水号 String outChargeTime = requestParam.getString("outChargeTime");//接入应用时间 String channel = requestParam.getString("channel");//支付方式 String billNo = requestParam.getString("billNo");//待结算费用单据号 String cardNo = requestParam.getString("cardNo");//医保卡号 String totalAmount = requestParam.getString("totalAmount");//交易总金额 String insuranceAmount = requestParam.getString("insuranceAmount");//医保支付金额 String selfPayAmount = requestParam.getString("selfPayAmount");//自付金额 String userId = requestParam.getString("userId");//用户openID String userName = requestParam.getString("userName");//用户名字 String idType = requestParam.getString("idType");//证件类型 String idNo = requestParam.getString("idNo");//证件号码 String tradeStatus = requestParam.getString("tradeStatus");//交易状态 String responseContent = request.getParameter("responseContent");//医保结构体 JSONObject responseContents = new JSONObject(responseContent); String miRegisterNo = responseContents.getString("miRegisterNo");//医保签约号 String miCollectDate = responseContents.getString("miCollectDate");//扣费日期 String miCollectTime = responseContents.getString("miCollectTime");//扣费时间 String miSettleNo = responseContents.getString("miSettleNo");//扣费单据号 String miCollectStatus = responseContents.getString("miCollectStatus");//扣费状态 String miRegisterStatus = responseContents.getString("miRegisterStatus");//登记状态 String cadresPay = responseContents.getString("cadresPay");//政府补贴支付 String miTotalFee = responseContents.getString("miTotalFee");//扣费总额 String healthCarePay = responseContents.getString("healthCarePay");//医保统筹支付 // responseContents.getString("healthPay"); String heathPay = responseContents.getString("heathPay");//健康账户支付 String accountPay = responseContents.getString("accountPay");//医保账户支付 String selfPay = responseContents.getString("selfPay");//个人现金支付 // 判断是否需要更新数据 needUpload为0不需要更新 WlyyCharge charge = chargeDao.getUploadStatus(outChargeNo); if (charge!=null&&!("0".equals(charge.getNeedUpload()))){ pay.updateData(outChargeNo, chargeNo,chargeTime,totalAmount,insuranceAmount,selfPayAmount,billNo,miRegisterNo); } }else { isSuccess = false; error = "请求失败,返回结果:" + res.getRespCode() + "," + res.getRespMsg(); } } catch (Exception ex) { isSuccess = false; StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); error = sw.toString(); response.getWriter().write(ex.getMessage()); } // 记录log日志到数据库 logService.saveHttpLog(isSuccess, config.getReceiveNotify(), "异步支付通知", "POST", null, params, responses, error, logService.onepayType); } }