浏览代码

Merge branch 'dev' of wujunjie/patient-co-management into dev

chenweida 7 年之前
父节点
当前提交
eb55fd77cb

+ 198 - 28
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/app/prescription/PatientPrescriptionPayService.java

@ -97,28 +97,30 @@ public class PatientPrescriptionPayService extends BaseService {
    private AccessTokenService accessTokenService;
    @Autowired
    private com.yihu.wlyy.util.HttpUtil HttpUtil;
    @Autowired
    private PrescriptionExpressageDao expressageDao;
    /**
     * 家庭医生签约支付查询
     */
    public String chargeQuery(String code, String accessToken) throws Exception {
        PayConfigura config = configuraDao.findWorkConfigura();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        int flag = 0;
        Boolean isSuccess = true;
        String msgBody = "";
        String response = "";
        String error = "";
        String result = null;
        try {
            PrescriptionPay charge = payDao.findByCode(code);
            String prescriptionCode = charge.getPrescriptionCode();
            Prescription prescription = prescriptionDao.findByCode(prescriptionCode);
            HospitalMapping hospitalMapping = mappingDao.findByCode(prescription.getHospital());
        PrescriptionPay charge = payDao.findByCode(code);
        String prescriptionCode = charge.getPrescriptionCode();
        Prescription prescription = prescriptionDao.findByCode(prescriptionCode);
        HospitalMapping hospitalMapping = mappingDao.findByCode(prescription.getHospital());
//          ***************************  测通流程 ***************************************
        OnepayDefaultClient onepayClient = new OnepayDefaultClient(config.getOnepayApi(), hospitalMapping.getAppId(), hospitalMapping.getAppSecret(), signType, encryptType);
            OnepayDefaultClient onepayClient = new OnepayDefaultClient(config.getOnepayApi(), hospitalMapping.getAppId(), hospitalMapping.getAppSecret(), signType, encryptType);
        try {
            RequestParams requestParams = new RequestParams();
//            requestParams.setVersion();
//            requestParams.setSign();
@ -138,16 +140,17 @@ public class PatientPrescriptionPayService extends BaseService {
            requestParams.setParam(params);
            msgBody = JSON.toJSONString(requestParams);
//              ***************************  测通流程 ***************************************
            //执行支付 返回原生返回值
            ResponseParams<JSONObject> res = onepayClient.execute(requestParams);
            response = JSON.toJSONString(res);
            if (OnepayDefaultClient.isSuccessful(res)) {
                //业务处理*******************
//                只返回业务出参
                flag = 1;
                result = JSON.toJSONString(res.getParam());
//                新增保存数据
//             新增保存数据
                JSONObject request = JSON.parseObject(result);
//                String tradeStatus = request.getString("tradeStatus");//交易状态
                String chargeStatus = request.getString("chargeStatus");//交易状态
                String chargeNo = request.getString("chargeNo");//支付平台流水号
                String chargeTime = request.getString("chargeTime");//支付平台交易成功时间
@ -179,7 +182,7 @@ public class PatientPrescriptionPayService extends BaseService {
                    String miCollectDate = null;//收费日期
                    String miCollectTime = null;//收费时间
                    String miCollectorName = null;//收费人姓名
                    String miTotalFee ="0";//本次报销总额
                    String miTotalFee = "0";//本次报销总额
                    String selfPay = "0";//个人现金支付
                    String accountPay = "0";//个人账户支付
                    String heathPay = "0";//健康账户支付
@ -258,7 +261,6 @@ public class PatientPrescriptionPayService extends BaseService {
                    if (responseContents.containsKey("healthBalance")) {
                        healthBalance = responseContents.getString("healthBalance");
                    }
                    prescriptionPay.setMiSettleNo(miSettleNo);//医保收费单据号
                    prescriptionPay.setMiRegisterNo(miRegisterNo);//医保挂号
                    SimpleDateFormat formatDate = new SimpleDateFormat("yyyyMMdd");
@ -284,29 +286,39 @@ public class PatientPrescriptionPayService extends BaseService {
                    prescriptionPay.setHealthBalance(Integer.parseInt(healthBalance));//健康账户余额
                }
                if ("0".equals(chargeStatus) || "SUCCESS".equals(chargeStatus)) {
                    prescriptionPay.setTradeStatus("1");//交易状态 成功1 失败0
                }else {
                    prescriptionPay.setTradeStatus("0");//交易状态 成功1 失败0
                }
                prescriptionPay.setTradeStatus(chargeStatus);
                prescriptionPay.setChargeNo(chargeNo);//支付流水号
                SimpleDateFormat formatDate = new SimpleDateFormat("yyyyMMddHHmmss");
                prescriptionPay.setChargeTime(formatDate.parse(chargeTime));//支付平台交易成功时间
                prescriptionPay.setOutChargeTime(formatDate.parse(outChargeTime));//接入应用内业务时间
                prescriptionPay.setMedOrgNo(medOrgNo);//医疗机构编号
                prescriptionPay.setMedOrgName(medOrgName);//医疗机构名称
                prescriptionPay.setBillNo(billNo);//待结算费用单据号
                prescriptionPay.setCardNo(cardNo);//医保卡号
                prescriptionPay.setTotalAmount(Integer.parseInt(totalAmount));//交易总金额
                prescriptionPay.setChargeTime(format.parse(chargeTime));
                prescriptionPay.setOutChargeTime(format.parse(outChargeTime));
                prescriptionPay.setMedOrgNo(medOrgNo);
                prescriptionPay.setMedOrgName(medOrgName);
                prescriptionPay.setBillNo(billNo);
                prescriptionPay.setPrincipalCardNo(cardNo);
                prescriptionPay.setTotalAmount(Integer.parseInt(totalAmount));
                prescriptionPay.setInsuranceAmount(Integer.parseInt(insuranceAmount));//医保支付金额
                prescriptionPay.setSelfPayAmount(Integer.parseInt(selfPayAmount));//自付金额
                prescriptionPay.setOpenid(userId);
                prescriptionPay.setUserName(userName);
                prescriptionPay.setIdType(idType);//证件类型
                prescriptionPay.setIdNo(idNo);//证件号码
                prescriptionPay.setIdType(idType);
                prescriptionPay.setIdNo(idNo);
                //        保存数据库更改记录
                payDao.save(prescriptionPay);
                PrescriptionExpressage expressage = expressageDao.findByPrescriptionPay(prescriptionCode);
                if ("0".equals(chargeStatus) || "SUCCESS".equals(chargeStatus)) {
                    prescriptionPay.setTradeStatus("1");//交易状态 成功1 失败0
                    prescription.setStatus(PrescriptionLog.PrescriptionLogStatus.pay_success.getValue());//续费状态 枚举 支付成功
                    expressage.setDel(1);//快递信息状态 1可用 0删除
                    expressageDao.save(expressage);
                    prescriptionDao.save(prescription);
                } else if ("1".equals(chargeStatus) || "FAIL".equals(chargeStatus)) {
                    prescriptionPay.setTradeStatus("0");//交易状态 成功1 失败0
                    prescription.setStatus(PrescriptionLog.PrescriptionLogStatus.pay_error.getValue());////续费状态 支付失败
                    expressage.setDel(0);//快递信息状态 1可用 0删除
                    expressageDao.save(expressage);
                    prescriptionDao.save(prescription);
                }
                logger.info("请求成功,返回参数: " + result);
            } else {
                isSuccess = false;
@ -319,6 +331,7 @@ public class PatientPrescriptionPayService extends BaseService {
            ex.printStackTrace(pw);
            error = sw.toString();
        }
        if (!isSuccess) {
            throw new Exception(error);
        }
@ -326,6 +339,163 @@ public class PatientPrescriptionPayService extends BaseService {
        return result;
    }
    public String getSignFamilyPayResult(String outChargeNo, String accessToken, String appId, String appSecret) throws Exception {
        PayConfigura config = configuraDao.findWorkConfigura();
        Boolean isSuccess = true;
        String msgBody = "";
        String response = "";
        String error = "";
        String result = null;
//      ***************************  测通流程 ***************************************
        OnepayDefaultClient onepayClient = new OnepayDefaultClient(config.getOnepayApi(), appId, appSecret, signType, encryptType);
        try {
            RequestParams requestParams = new RequestParams();
            requestParams.setAppId(appId);
            requestParams.setTimestamp(DateUtil.getCurrentDateTime());
            requestParams.setSignType(signType);
            requestParams.setEncryptType(encryptType);
            requestParams.setTransType(config.getChargeQueryType());
            //业务参数
            JSONObject params = new JSONObject();
            params.put("outChargeNo", outChargeNo);  //接入应用结算业务流水号
            params.put("wxToken", accessToken);
            requestParams.setParam(params);
            msgBody = JSON.toJSONString(requestParams);
//              ***************************  测通流程 ***************************************
            //执行支付 返回原生返回值
            ResponseParams<JSONObject> res = onepayClient.execute(requestParams);
            response = JSON.toJSONString(res);
            if (OnepayDefaultClient.isSuccessful(res)) {
                //业务处理*******************
//                只返回业务出参
                result = JSON.toJSONString(res.getParam());
//                logger.info("请求成功,返回参数: " + result);
            } 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();
        }
        //type = 3易联众接口保存http日志
//        logger.info("api - " + config.getChargeQueryType());
//        logger.info("request - " + msgBody);
//        logger.info("responses - " + response);
//        logger.info("error - " + error);
        if (!isSuccess) {
            throw new Exception(error);
        }
        return result;
    }
    /**
     * 1.根据时间范围遍历没有医保签约号的家庭签约支付记录
     * 2.询家庭签约支付结果,补更新医保签约号
     * @param startdate
     * @param enddate
     */
    public void getSignFamilyPayResultJob(Date startdate, Date enddate) throws Exception {
        //根据时间范围遍历没有医保签约号的家庭签约支付记录
        List<WlyyCharge> charges = chargeDao.findByTradeStatusAndMiRegisterNoAndUpdateTime(0,enddate,startdate);
        if(!charges.isEmpty()){
            logger.info("根据时间范围遍历没有医保签约号的家庭签约支付记录:"+charges.size()+"条");
            String accessToken = this.getAccessToken();
            for (WlyyCharge charge:charges) {
                try {
                    //1.根据签约ID获取家庭签约记录,判断是否有效
                    SignFamily signFamily = signFamilyDao.findByCode(charge.getChargeRelation());
                    if(1 == signFamily.getStatus()){
                        HospitalMapping hospitalMapping = hospitalMappingDao.findByCode(charge.getHospital());
                        String appid = hospitalMapping.getAppId();
                        String appsecert =  hospitalMapping.getAppSecret();
                        String signFamilyPayResultJson = this.getSignFamilyPayResult(charge.getCode(),"",appid,appsecert);
                        if(StringUtils.isNotBlank(signFamilyPayResultJson)){
                            JSONObject reobj =  JSON.parseObject(signFamilyPayResultJson);
                            if(reobj.containsKey("responseContent")){
                                JSONObject responseContent = reobj.getJSONObject("responseContent");
                                if(responseContent.containsKey("miRegisterNo") && StringUtils.isNotBlank(responseContent.getString("miRegisterNo"))){
                                    String miRegisterNo = responseContent.getString("miRegisterNo");
                                    charge.setMiRegisterNo(miRegisterNo);
                                    charge.setNeedUpload("1");
                                    charge.setUpdateTime(new Date());
                                    chargeDao.save(charge);
                                }else{
                                    logger.info("ERROR======获取家庭签约支付医保签约号JOB,CODE:"+charge.getCode()+",message:miRegisterNo不存在");
                                }
                            }else{
                                logger.info("ERROR======获取家庭签约支付医保签约号JOB,CODE:"+charge.getCode()+",message:responseContent不存在");
                            }
                        }else{
                            logger.info("ERROR======获取家庭签约支付医保签约号JOB,CODE:"+charge.getCode()+",message:接口无返回值");
                        }
                    }else{
                        logger.info("ERROR======获取家庭签约支付医保签约号JOB,CODE:"+charge.getCode()+",message:对应的签约记录无效");
                    }
                }catch (Exception e){
                    logger.info("ERROR======获取家庭签约支付医保签约号JOB,CODE:"+charge.getCode()+",message:" +e.getMessage());
                    continue;
                }
            }
        }
    }
    /**
     * 获取微信的access_token
     *
     * @return
     */
    public String getAccessToken() throws Exception{
        Iterable<AccessToken> accessTokens = accessTokenService.findAccessToken();
        if (accessTokens != null) {
            for (AccessToken accessToken : accessTokens) {
                if ((System.currentTimeMillis() - accessToken.getAdd_timestamp()) < (accessToken.getExpires_in() * 1000)) {
                    return accessToken.getAccess_token();
                } else {
                    accessTokenService.delAccessToken(accessToken);
                    break;
                }
            }
        }
        String token_url = "https://api.weixin.qq.com/cgi-bin/token";
        String params = "grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
        String result = HttpUtil.sendGet(token_url, params);
        org.json.JSONObject json = new org.json.JSONObject(result);
        if (json.has("access_token")) {
            String token = json.get("access_token").toString();
            String expires_in = json.get("expires_in").toString();
            AccessToken newaccessToken = new AccessToken();
            newaccessToken.setAccess_token(token);
            newaccessToken.setExpires_in(Long.parseLong(expires_in));
            newaccessToken.setAcc_id(accId);
            accessTokenService.addAccessToken(newaccessToken);
            return token;
        } else {
            return null;
        }
    }
}