Преглед на файлове

Merge branch 'dev' of http://192.168.1.220:10080/Amoy2/wlyy2.0 into dev

# Conflicts:
#	common/common-entity/sql记录
yeshijie преди 3 години
родител
ревизия
c948cd993f
променени са 31 файла, в които са добавени 3369 реда и са изтрити 134 реда
  1. 6 1
      business/base-service/src/main/java/com/yihu/jw/order/BusinessOrderService.java
  2. 12 0
      common/common-entity/sql记录
  3. 62 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/common/WxPayHttpLogDO.java
  4. 2 1
      common/common-entity/src/main/java/com/yihu/jw/entity/order/BusinessOrderDO.java
  5. 3 3
      svr/svr-cloud-care/pom.xml
  6. 17 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/pay/WxPayHttpLogDao.java
  7. 213 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/patient/PayEndpoint.java
  8. 0 16
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/doorCoach/DoctorDoorCoachOrderService.java
  9. 13 20
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/doorCoach/PatientDoorCoachOrderService.java
  10. 7 92
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/lifeCare/LifeCareOrderService.java
  11. 370 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/pay/PayService.java
  12. 80 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/HttpsUtil.java
  13. 51 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/MD5Util.java
  14. 27 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/RequestTrustManager.java
  15. 113 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/WxpayUtil.java
  16. 173 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/XMLUtil.java
  17. 97 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/wxconfig/CareWxPayConfig.java
  18. 42 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/wxconfig/IWXPayDomain.java
  19. 695 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/wxconfig/WXPay.java
  20. 103 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/wxconfig/WXPayConfig.java
  21. 59 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/wxconfig/WXPayConstants.java
  22. 265 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/wxconfig/WXPayReport.java
  23. 258 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/wxconfig/WXPayRequest.java
  24. 294 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/wxconfig/WXPayUtil.java
  25. 30 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/wxconfig/WXPayXmlUtil.java
  26. 9 1
      svr/svr-cloud-care/src/main/resources/application.yml
  27. 298 0
      svr/svr-cloud-care/src/main/resources/wechat/README.md
  28. BIN
      svr/svr-cloud-care/src/main/resources/wechat/apiclient_cert.p12
  29. 24 0
      svr/svr-cloud-care/src/main/resources/wechat/apiclient_cert.pem
  30. 28 0
      svr/svr-cloud-care/src/main/resources/wechat/apiclient_key.pem
  31. 18 0
      svr/svr-cloud-care/src/main/resources/wechat/证书使用说明.txt

+ 6 - 1
business/base-service/src/main/java/com/yihu/jw/order/BusinessOrderService.java

@ -453,9 +453,14 @@ public class BusinessOrderService extends BaseJpaService<BusinessOrderDO,Busines
     */
    @Transactional(rollbackFor = Exception.class)
    public String refund(Map<String,String> par,String appKey) throws Exception {
        WlyyHospitalSysDictDO hospitalSysDictDO = hospitalSysDictDao.findById("REFUND");
        if(StringUtils.isNoneBlank(hospitalSysDictDO.getImgUrl())){
            //公网域名必须为https
            par.put("notify_url",hospitalSysDictDO.getImgUrl());
        }
        String xml= WeiXinPayUtils.getXmlBeforUnifiedorder(par, appKey);
        logger.info("xml:"+xml);
        WlyyHospitalSysDictDO hospitalSysDictDO = hospitalSysDictDao.findById("REFUND");
        return HttpUtil.doRefund("https://api.mch.weixin.qq.com/secapi/pay/refund",xml,hospitalSysDictDO.getDictCode(),hospitalSysDictDO.getDictValue());
    }

+ 12 - 0
common/common-entity/sql记录

@ -1066,3 +1066,15 @@ CREATE TABLE `base_service_news` (
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='服务动态信息';
-- 2021-06-29 ysj
CREATE TABLE `base_wx_pay_http_log` (
  `id` varchar(50) NOT NULL,
  `type` varchar(1) DEFAULT NULL COMMENT '类型1 统一下单 2支付回调',
  `order_no` varchar(50) DEFAULT NULL COMMENT '订单号',
  `order_res` text,
  `order_req` text,
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `index1` (`order_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='微信支付日志表';

+ 62 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/common/WxPayHttpLogDO.java

@ -0,0 +1,62 @@
package com.yihu.jw.entity.care.common;
import com.yihu.jw.entity.UuidIdentityEntityWithCreateTime;
import javax.persistence.Column;
/**
 * Created with IntelliJ IDEA.
 *
 * @Author: yeshijie
 * @Date: 2021/6/29
 * @Description:
 */
public class WxPayHttpLogDO extends UuidIdentityEntityWithCreateTime {
    /**
     * 类型1 统一下单 2支付回调
     */
    private String type;
    /**
     * 订单号
     */
    private String orderNo;
    private String orderRes;
    private String orderReq;
    @Column(name = "type")
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    @Column(name = "order_no")
    public String getOrderNo() {
        return orderNo;
    }
    public void setOrderNo(String orderNo) {
        this.orderNo = orderNo;
    }
    @Column(name = "order_res")
    public String getOrderRes() {
        return orderRes;
    }
    public void setOrderRes(String orderRes) {
        this.orderRes = orderRes;
    }
    @Column(name = "order_req")
    public String getOrderReq() {
        return orderReq;
    }
    public void setOrderReq(String orderReq) {
        this.orderReq = orderReq;
    }
}

+ 2 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/order/BusinessOrderDO.java

@ -28,7 +28,7 @@ public class BusinessOrderDO extends IntegerIdentityEntity {
    private Integer orderType;
    /**
     * 互联网医院- 1:专家咨询|2:图文诊室|3:视频诊室|4处方结算|5就诊卡充值)
     * 医养项目 订单分类 orderType=1 时 1招生,2 课程,3 上门预约(托幼)
     * 医养项目 订单分类 orderType=1 时 1招生,2 课程,3 上门辅导托幼) 4 生活照料
     */
    private String orderCategory;
    private String relationCode;//业务关联code
@ -39,6 +39,7 @@ public class BusinessOrderDO extends IntegerIdentityEntity {
    private Double payPrice;//支付金额
    private Date payTime;//支付时间
    private String doctor;//医生code
    //医养支付状态 0待支付、1已支付、2已取消、3申请退款中、4已售后
    private Integer status;//0待支付1支付成功2支付失败3取消
    private String pcCallbackUrl;//Pc端查看当前订单的会话信息
    private String appCallbackUrl;//App端查看当前订单的会话信息

+ 3 - 3
svr/svr-cloud-care/pom.xml

@ -88,9 +88,9 @@
            <artifactId>common-rest-model</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>wxpay-sdk</artifactId>
            <version>3.0.9</version>
            <groupId>org.jdom</groupId>
            <artifactId>jdom</artifactId>
            <version>2.0.2</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>

+ 17 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/pay/WxPayHttpLogDao.java

@ -0,0 +1,17 @@
package com.yihu.jw.care.dao.pay;
import com.yihu.jw.entity.care.common.WxPayHttpLogDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created with IntelliJ IDEA.
 *
 * @Author: yeshijie
 * @Date: 2021/6/29
 * @Description:
 */
public interface WxPayHttpLogDao extends PagingAndSortingRepository<WxPayHttpLogDO,String>, JpaSpecificationExecutor<WxPayHttpLogDO> {
}

+ 213 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/patient/PayEndpoint.java

@ -0,0 +1,213 @@
package com.yihu.jw.care.endpoint.patient;
import com.alibaba.fastjson.JSON;
import com.yihu.jw.care.exception.BusinessException;
import com.yihu.jw.care.service.doorCoach.PatientDoorCoachOrderService;
import com.yihu.jw.care.service.pay.PayService;
import com.yihu.jw.care.util.XMLUtil;
import com.yihu.jw.entity.order.BusinessOrderDO;
import com.yihu.jw.order.dao.BusinessOrderDao;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;
/**
 * Created with IntelliJ IDEA.
 *
 * @Author: yeshijie
 * @Date: 2021/6/28
 * @Description:
 */
@RestController
@RequestMapping("pay" )
@Api(tags = "支付信息", description = "支付信息")
public class PayEndpoint extends EnvelopRestEndpoint {
    private Logger log = LoggerFactory.getLogger(PatientDoorCoachOrderService.class);
    @Autowired
    private PayService payService;
    @Autowired
    private BusinessOrderDao businessOrderDao;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    @GetMapping(value = "wxWapPay")
    @ApiOperation(value = "微信wap支付")
    public ObjEnvelop wxWapPay(
            @ApiParam(name = "relationId", value = "业务id,如生活照料id 上面辅导id")
            @RequestParam(value = "relationId", required = false) String relationId,
            @ApiParam(name = "orderId", value = "订单id")
            @RequestParam(value = "orderId", required = false) Integer orderId,
            @ApiParam(name = "patientId", value = "居民id")
            @RequestParam(value = "patientId", required = true) String patientId,HttpServletRequest request) {
        try{
            return  payService.wxWapPay(relationId, orderId, patientId, request);
        }catch (Exception e){
            return failedObjEnvelopException2(e);
        }
    }
    @GetMapping(value = "wxRefund")
    @ApiOperation(value = "微信发起退款")
    public ObjEnvelop wxRefund(
            @ApiParam(name = "relationId", value = "业务id,如生活照料id 上面辅导id")
            @RequestParam(value = "relationId", required = false) String relationId,
            @ApiParam(name = "orderId", value = "订单id")
            @RequestParam(value = "orderId", required = false) Integer orderId,
            @ApiParam(name = "patientId", value = "居民id")
            @RequestParam(value = "patientId", required = true) String patientId,HttpServletRequest request) {
        try{
            return  payService.wxWapPay(relationId, orderId, patientId, request);
        }catch (Exception e){
            return failedObjEnvelopException2(e);
        }
    }
    @GetMapping(value = "wxNativePay")
    @ApiOperation(value = "微信native支付")
    public ObjEnvelop wxNativePay(
            @ApiParam(name = "relationId", value = "业务id,如生活照料id 上面辅导id")
            @RequestParam(value = "relationId", required = false) String relationId,
            @ApiParam(name = "orderId", value = "订单id")
            @RequestParam(value = "orderId", required = false) Integer orderId,
            @ApiParam(name = "patientId", value = "居民id")
            @RequestParam(value = "patientId", required = true) String patientId,HttpServletRequest request) {
        try{
            return  payService.wxNativePay(relationId, orderId, patientId, request);
        }catch (Exception e){
            return failedObjEnvelopException2(e);
        }
    }
    /**
     * 微信支付回调
     *
     * @param request
     * @return java.lang.String
     */
    @ResponseBody
    @PostMapping("open/wxPayNotify")
    @ApiOperation(value = "微信wap支付回调")
    public String payNotify(HttpServletRequest request) {
        log.info("【微信支付】回调通知");
        try {
            // 解析xml成map
            Map<String, String> params = XMLUtil.doXMLParse(request);
            String paramsJson = JSON.toJSONString(params);
            log.error("【微信支付】异步通知回调,{}", paramsJson);
            // 支付校验
            String returnCode = params.get("return_code");
            if (!"SUCCESS".equalsIgnoreCase(returnCode)) {
                log.info("【微信支付】订单支付失败");
                return XMLUtil.setXML("FAIL", "支付失败");
            }
            // 商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号
            String outTradeNo = params.get("out_trade_no");
            String payWaterId = outTradeNo.split("_")[0];
            payService.addHttpLog("2",payWaterId,paramsJson,null);
            BusinessOrderDO orderDO = businessOrderDao.selectByOrderNo(payWaterId);
            if (orderDO == null) {
                log.error("支付流水不存在");
                return XMLUtil.setXML("SUCCESS", "OK");
            }
            String wxSeqNo = params.get("transaction_id");
            orderDO.setTraceNo(wxSeqNo);
//            orderDO.setResponseParam(paramsJson);
            // 判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额),
            String totalFee = params.get("total_fee");
            BigDecimal payTotalFee = new BigDecimal(totalFee).setScale(2).divide(new BigDecimal(100), BigDecimal.ROUND_HALF_EVEN);
            log.info("【微信支付】支付金额:{}", payTotalFee);
            if (new BigDecimal(orderDO.getPayPrice()).compareTo(payTotalFee) != 0) {
                //通知资金与实际资金不对称,可能是攻击行为!
                orderDO.setRematk("通知资金与实际资金不对称,可能是攻击行为!");
                businessOrderDao.save(orderDO);
                return XMLUtil.setXML("SUCCESS", "OK");
            }
            // 多线程执行操作
            /*********** 业务处理 start ************/
            taskExecutor.execute(() -> payService.payNotify(orderDO));
            /*********** 业务处理 end ************/
            return XMLUtil.setXML("SUCCESS", "OK");
        } catch (BusinessException e) {
            log.info("【微信支付】回调失败:{}", e.getMessage());
            return XMLUtil.setXML("FAIL", "支付失败");
        } catch (Exception e) {
            log.info("【微信支付】回调异常:{}", e);
            return XMLUtil.setXML("FAIL", "支付失败");
        }
    }
    /**
     * 微信支付退款回调
     *
     * @param request
     * @return java.lang.String
     */
    @ResponseBody
    @PostMapping("open/wxRefundNotify")
    @ApiOperation(value = "微信支付退款回调")
    public String wxRefundNotify(HttpServletRequest request) {
        log.info("【微信支付退款】回调通知");
        try {
            // 解析xml成map
            Map<String, String> params = XMLUtil.doXMLParse(request);
            String paramsJson = JSON.toJSONString(params);
            log.error("【微信支付退款】异步通知回调,{}", paramsJson);
            // 支付校验
            String returnCode = params.get("return_code");
            if (!"SUCCESS".equalsIgnoreCase(returnCode)) {
                log.info("【微信支付退款】订单失败");
                return XMLUtil.setXML("FAIL", "退款失败");
            }
            // 商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号
            String outTradeNo = params.get("out_trade_no");
            String payWaterId = outTradeNo.split("_")[0];
            payService.addHttpLog("2",payWaterId,paramsJson,null);
            BusinessOrderDO orderDO = businessOrderDao.selectByOrderNo(payWaterId);
            if (orderDO == null) {
                log.error("支付流水不存在");
                return XMLUtil.setXML("SUCCESS", "OK");
            }
            String wxSeqNo = params.get("transaction_id");
            orderDO.setTraceNo(wxSeqNo);
//            orderDO.setResponseParam(paramsJson);
            // 判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额),
            String totalFee = params.get("total_fee");
            BigDecimal payTotalFee = new BigDecimal(totalFee).setScale(2).divide(new BigDecimal(100), BigDecimal.ROUND_HALF_EVEN);
            log.info("【微信支付退款】支付金额:{}", payTotalFee);
            if (new BigDecimal(orderDO.getPayPrice()).compareTo(payTotalFee) != 0) {
                //通知资金与实际资金不对称,可能是攻击行为!
                orderDO.setRematk("通知资金与实际资金不对称,可能是攻击行为!");
                businessOrderDao.save(orderDO);
                return XMLUtil.setXML("SUCCESS", "OK");
            }
            // 多线程执行操作
            /*********** 业务处理 start ************/
            taskExecutor.execute(() -> payService.payNotify(orderDO));
            /*********** 业务处理 end ************/
            return XMLUtil.setXML("SUCCESS", "OK");
        } catch (BusinessException e) {
            log.info("【微信支付退款】回调失败:{}", e.getMessage());
            return XMLUtil.setXML("FAIL", "退款失败");
        } catch (Exception e) {
            log.info("【微信支付退款】回调异常:{}", e);
            return XMLUtil.setXML("FAIL", "退款失败");
        }
    }
}

+ 0 - 16
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/doorCoach/DoctorDoorCoachOrderService.java

@ -4,7 +4,6 @@ import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.care.dao.doorCoach.*;
import com.yihu.jw.care.dao.course.DoctorPatientTmpDao;
import com.yihu.jw.care.service.consult.ConsultTeamService;
import com.yihu.jw.care.util.EntranceUtil;
import com.yihu.jw.care.util.MessageUtil;
@ -18,7 +17,6 @@ import com.yihu.jw.entity.base.org.BaseOrgDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.wx.BasePatientWechatDo;
import com.yihu.jw.entity.care.doorCoach.*;
import com.yihu.jw.entity.care.course.DoctorPatientTmpDO;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
@ -786,20 +784,6 @@ public class DoctorDoorCoachOrderService {
        String applicationSql = "";
        String patientTypeTemp = "";
//        if("1".equals(isApplication)){
//            applicationSql +=                 " JOIN ( " +
//                    "         select a.patient, group_concat(v.type) as type " +
//                    "         from wlyy_door_service_voucher v " +
//                    "                  JOIN (select t.id, t.patient, max(t.create_time) " +
//                    "                        from wlyy_door_service_application t " +
//                    "                        where t.status in (2, 3) " +
//                    "                        group by t.patient) as a " +
//                    "                       on a.id = v.service_id " +
//                    "         where v.status = 1 " +
//                    "         group by a.patient " +
//                    "        ) as t1 on o.patient = t1.patient" ;
//            patientTypeTemp = " ,t1.`type` as patientType ";
//        }
        String sql = "SELECT " +
                "  p.name AS patientName, " +

+ 13 - 20
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/doorCoach/PatientDoorCoachOrderService.java

@ -5,6 +5,7 @@ import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.dao.doorCoach.*;
import com.yihu.jw.care.service.consult.ConsultTeamService;
import com.yihu.jw.care.service.message.BaseServiceNewsService;
import com.yihu.jw.care.service.pay.PayService;
import com.yihu.jw.care.util.MessageUtil;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
@ -94,6 +95,8 @@ public class PatientDoorCoachOrderService extends BaseJpaService<BaseDoorCoachOr
    private SystemMessageDao systemMessageDao;
    @Autowired
    private BaseServiceNewsService serviceNewsService;
    @Autowired
    private PayService payService;
    /**
     * 创建上门辅导服务工单
@ -227,6 +230,8 @@ public class PatientDoorCoachOrderService extends BaseJpaService<BaseDoorCoachOr
        serviceNewsService.addServiceNews(orderDO.getPatientName(),orderDO.getPatient(),"1",null);
        //发起支付订单
        payService.submitOrder(orderDO.getPatient(),"3",orderDO.getId(),orderDO.getTotalFee().doubleValue());
        return result;
    }
@ -319,26 +324,13 @@ public class PatientDoorCoachOrderService extends BaseJpaService<BaseDoorCoachOr
        //新增工单与服务项费用关联关系
        if (orderWithPackageItemFeeAdd(result, jsonObjectParam, orderDO,doctorCode)) {return result;}
        if("1".equals(orderDO.getShortcutType())){
            //快捷的当前医生直接接单
            try{
                String sql = "SELECT d.job_title_code,d.job_title_name,o.org_level from base_doctor d,base_doctor_hospital h,base_org o " +
                        "WHERE d.id = h.doctor_code and h.org_code = o.id";
                sql += " and d.id = '"+orderDO.getDoctor()+"'";
                List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
                doorOrderService.acceptOrder1(orderDO.getId(), list.get(0).get("job_title_code").toString(),
                        list.get(0).get("job_title_name").toString(), Integer.valueOf(list.get(0).get("org_level").toString()));
            }catch (Exception e){
                e.printStackTrace();
            }
        // 给服务医生发接单消息
        this.createMessage("服务工单待接单","707",orderDO.getProxyPatient(),orderDO.getProxyPatientName(), orderDO.getId(),orderDO.getDoctor(),orderDO.getDoctorName(), null,"您有新的服务工单,请前往处理");
        //发送智能助手消息
        sendWeixinMessage(4,orderDO.getDoctor(),orderDO.getPatient());
        }else{
            // 给服务医生发接单消息
            this.createMessage("服务工单待接单","707",orderDO.getProxyPatient(),orderDO.getProxyPatientName(), orderDO.getId(),orderDO.getDoctor(),orderDO.getDoctorName(), null,"您有新的服务工单,请前往处理");
            //发送智能助手消息
            sendWeixinMessage(4,orderDO.getDoctor(),orderDO.getPatient());
        }
        //发起支付订单
        payService.submitOrder(orderDO.getPatient(),"3",orderDO.getId(),orderDO.getTotalFee().doubleValue());
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        return result;
@ -1099,7 +1091,8 @@ public class PatientDoorCoachOrderService extends BaseJpaService<BaseDoorCoachOr
                return true;
            }
        }
        order.setTotalFee(totalFee);
        baseDoorCoachOrderDao.save(order);
        return false;
    }

+ 7 - 92
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/lifeCare/LifeCareOrderService.java

@ -8,6 +8,7 @@ import com.yihu.jw.care.dao.lifeCare.LifeCareItemDictDao;
import com.yihu.jw.care.dao.lifeCare.LifeCareOrderDao;
import com.yihu.jw.care.service.common.OrderNoService;
import com.yihu.jw.care.service.message.BaseServiceNewsService;
import com.yihu.jw.care.service.pay.PayService;
import com.yihu.jw.care.util.MessageUtil;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
@ -79,6 +80,8 @@ public class LifeCareOrderService extends BaseJpaService<LifeCareOrderDO, LifeCa
    private OrderNoService orderNoService;
    @Autowired
    private BaseServiceNewsService serviceNewsService;
    @Autowired
    private PayService payService;
    /**
@ -519,7 +522,8 @@ public class LifeCareOrderService extends BaseJpaService<LifeCareOrderDO, LifeCa
        }else {
            serviceNewsService.addServiceNews(orderDO.getPatientName(),orderDO.getPatient(),"3",null);
        }
        //发起支付订单
        payService.submitOrder(orderDO.getPatient(),"4",orderDO.getId(),orderDO.getTotalFee().doubleValue());
        return result;
    }
@ -571,7 +575,8 @@ public class LifeCareOrderService extends BaseJpaService<LifeCareOrderDO, LifeCa
            logger.error(failMsg);
            return true;
        }
        order.setTotalFee(totalFee);
        lifeCareOrderDao.save(order);
        return false;
    }
@ -686,94 +691,4 @@ public class LifeCareOrderService extends BaseJpaService<LifeCareOrderDO, LifeCa
        }
    }
    /**
     * 生活照料代预约-- 废弃用原来的接口
     * @param jsonData
     * @param doctorCode
     * @return
     */
    @Transactional
    public JSONObject proxyCreate(String jsonData,String doctorCode) {
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        LifeCareOrderDO orderDO = null;
        try {
            orderDO = EntityUtils.jsonToEntity(jsonObjectParam.get("order").toString(), LifeCareOrderDO.class);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "生活照料工单服务基本信息:" + e.getMessage();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        if(StringUtils.isEmpty(orderDO.getPatient())){
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前服务对象code为空,请联系管理员检查参数!patient = " + orderDO.getPatient();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        //医生代预约
        orderDO.setType(3);
        BaseDoctorDO doctorDO = doctorDao.findById(doctorCode);
        orderDO.setProxyPatient(doctorCode);
        orderDO.setProxyPatientName(doctorDO.getName());
        orderDO.setProxyPatientPhone(doctorDO.getMobile());
        //判断工单是否已存在,新建或者编辑
        if(StringUtils.isBlank(orderDO.getId())) {
            //已取消的订单也可以申请
            boolean bool = lifeCareOrderDao.existsByPatientAndStatusIn(orderDO.getPatient(),
                    new Integer[]{LifeCareOrderDO.Status.waitForAccept.getType()
                    });
            if(bool){
                String failMsg = "当前服务对象存在未完成的生活照料,请先完成该服务!";
                result.put(ResponseContant.resultFlag, ResponseContant.fail);
                result.put(ResponseContant.resultMsg, failMsg);
                logger.error(failMsg);
                return result;
            }
            orderDO.setNumber(orderNoService.getOrderNo(1));
            orderDO.setHospital(jsonObjectParam.getJSONObject("hospital").get("code").toString());
            orderDO.setCreateTime(new Date());
            orderDO.setCreateUser(orderDO.getProxyPatient());
            orderDO.setCreateUserName(orderDO.getProxyPatientName());
        }else {
            LifeCareOrderDO serviceOrderDO = lifeCareOrderDao.findOne(orderDO.getId());
            // 删除出诊医生或服务项
            Boolean b = this.orderWithFeeDelete(jsonObjectParam, serviceOrderDO);
            if(b){
                String failMsg = "删除服务项失败!";
                result.put(ResponseContant.resultFlag, ResponseContant.fail);
                result.put(ResponseContant.resultMsg, failMsg);
                return result;
            }
            orderDO.setNumber(serviceOrderDO.getNumber());
            orderDO.setHospital(serviceOrderDO.getHospital());
            orderDO.setUpdateTime(new Date());
            orderDO.setUpdateUser(orderDO.getProxyPatient());
            orderDO.setUpdateUserName(orderDO.getProxyPatientName());
        }
        orderDO.setStatus(2);
        orderDO.setType(3);
        this.save(orderDO);
        result.put("orderId",orderDO.getId());
        //新增工单与服务项费用关联关系
        if (orderWithPackageItemFeeAdd(result, jsonObjectParam, orderDO,doctorCode)) {return result;}
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        return result;
    }
}

+ 370 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/pay/PayService.java

@ -0,0 +1,370 @@
package com.yihu.jw.care.service.pay;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.fastdfs.FastDFSUtil;
import com.yihu.jw.care.dao.pay.WxPayHttpLogDao;
import com.yihu.jw.care.service.doorCoach.PatientDoorCoachOrderService;
import com.yihu.jw.care.util.WxpayUtil;
import com.yihu.jw.care.util.XMLUtil;
import com.yihu.jw.care.wxconfig.CareWxPayConfig;
import com.yihu.jw.care.wxconfig.WXPay;
import com.yihu.jw.care.wxconfig.WXPayUtil;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.wx.WxWechatDO;
import com.yihu.jw.entity.care.common.WxPayHttpLogDO;
import com.yihu.jw.entity.order.BusinessOrderDO;
import com.yihu.jw.entity.order.BusinessOrderRefundDO;
import com.yihu.jw.order.BusinessOrderService;
import com.yihu.jw.order.dao.BusinessOrderDao;
import com.yihu.jw.order.dao.BusinessOrderRefundDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.util.common.IpUtil;
import com.yihu.jw.util.common.QrcodeUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.utils.StringUtil;
import com.yihu.jw.wechat.dao.WechatDao;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import static jxl.biff.FormatRecord.logger;
/**
 * Created with IntelliJ IDEA.
 * 支付
 * @Author: yeshijie
 * @Date: 2021/6/28
 * @Description:
 */
@Service
public class PayService {
    private Logger log = LoggerFactory.getLogger(PatientDoorCoachOrderService.class);
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private BusinessOrderDao businessOrderDao;
    @Value("${wechat.id}")
    public String wechatId;
    @Value("${wechat.appId}")
    public String appId;
    @Value("${wechat.mchId}")
    public String mchId;
    @Value("${wechat.apiKey}")
    public String apiKey;
    @Value("${wechat.wechat_base_url}")
    private String serverUrl;
    @Autowired
    private WxPayHttpLogDao wxPayHttpLogDao;
    @Autowired
    private FastDFSUtil fastDFSUtil;
    @Autowired
    private BusinessOrderService businessOrderService;
    @Autowired
    private WechatDao wechatDao;
    @Autowired
    private BusinessOrderRefundDao orderRefundDao;
    /**
     * 微信退款
     * @param patient
     * @param orderNo
     * @param description
     * @return
     * @throws Exception
     */
    public Map<String,Object> orderRefund(String patient,String orderNo,String description) throws Exception {
        WxWechatDO wxWechatDO = wechatDao.findById(wechatId);
        if (wxWechatDO==null){
            throw new Exception("this wechatId is null");
        }
        BusinessOrderDO businessOrderDO = businessOrderDao.selectByOrderNo(orderNo);
        if (businessOrderDO==null){
            throw new Exception("this orderId not exit");
        }
        BasePatientDO patientDO = patientDao.findById(patient);
        if (patientDO==null){
            throw new Exception("this patient not exit");
        }
        BusinessOrderRefundDO orderRefundDO = orderRefundDao.selectByOrderNo(orderNo);
        if (orderRefundDO==null){
            orderRefundDO = new BusinessOrderRefundDO();
        }
        orderRefundDO.setCreateTime(new Date());
        orderRefundDO.setUpdateTime(new Date());
        orderRefundDO.setStatus(1);
        orderRefundDO.setOrderNo(orderNo);
        orderRefundDO.setOrderPrice(businessOrderDO.getPayPrice());
        orderRefundDO.setRefundPrice(businessOrderDO.getPayPrice());
        orderRefundDO.setAppId(wxWechatDO.getAppId());
        orderRefundDO.setMchId(wxWechatDO.getMchId());
        orderRefundDO.setOutRefundNo("CARE"+businessOrderDO.getOrderType()+System.currentTimeMillis()+(int)(Math.random()*900)+100);
        orderRefundDO.setPatient(patient);
        orderRefundDO.setPatientName(patientDO.getName());
        orderRefundDO.setRefundDesc(description);
        orderRefundDO = orderRefundDao.save(orderRefundDO);
        Integer orderPrice = orderRefundDO.getOrderPrice().intValue();
        Integer refundPrice1 = orderRefundDO.getRefundPrice().intValue();
        Map<String,Object> map = businessOrderService.refund(wechatId,orderRefundDO.getOrderNo(),orderRefundDO.getOutRefundNo(),orderPrice.toString(),refundPrice1.toString(),orderRefundDO.getRefundDesc());
        logger.info("map"+map);
        if (map.get("return_code").toString().equalsIgnoreCase("SUCCESS")){
            //退款申请提交成功
        }
        return map;
    }
    /**
     * 添加支付日志
     * @param type
     * @param orderNo
     * @param res
     * @param req
     */
    public void addHttpLog(String type,String orderNo,String res,String req){
        WxPayHttpLogDO logDO = new WxPayHttpLogDO();
        logDO.setType(type);
        logDO.setOrderNo(orderNo);
        logDO.setOrderReq(req);
        logDO.setOrderRes(res);
        wxPayHttpLogDao.save(logDO);
    }
    public CareWxPayConfig getCareWxPayConfig()throws Exception{
        CareWxPayConfig wxPayConfig = new CareWxPayConfig();
        wxPayConfig.setAppId(appId);
        wxPayConfig.setApiKey(apiKey);
        wxPayConfig.setMchId(mchId);
        return wxPayConfig;
    }
    /**
     * 支付成功处理
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void payNotify(BusinessOrderDO orderDO) {
        log.error("【支付通知】请求,payWater:{}", orderDO);
        String type = orderDO.getOrderCategory();
        //防止重复支付
        if (orderDO.getStatus()!=0) {
            return;
        }
        switch (type){
            case "1":
                //desc = "招生报名";
                break;
            case "2":
                //desc = "课程报名";
                break;
            case "3":
                //desc = "上门辅导";
                break;
            case "4":
                //desc = "生活照料服务";
                break;
            default:
                break;
        }
        orderDO.setStatus(1);
        businessOrderDao.save(orderDO);
    }
    /**
     * 微信navite统一下单接口
     *
     * @return prepayId 微信预支付交易会话标识,该值有效期为2小时
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public ObjEnvelop wxNativePay(String relationId,Integer orderId,String patientId,HttpServletRequest request) throws Exception {
        BusinessOrderDO businessOrderDO;
        if(StringUtil.isBlank(relationId)){
            businessOrderDO = businessOrderDao.findOne(orderId);
        }else{
            businessOrderDO = businessOrderDao.selectByRelationCode(relationId);
        }
        Assert.notNull(businessOrderDO, "支付流水不存在");
        if (businessOrderDO.getStatus()!=0) {
            return ObjEnvelop.getError("待支付订单才能支付",-1);
        }
        BasePatientDO patientDO = patientDao.findById(patientId);
        Map<String,String> rs = new HashedMap();
        WXPay wxpay = new WXPay(getCareWxPayConfig());
        //设置没签名的参数
        Map<String, String> wxParam = new HashMap<>();
        wxParam.put("body", businessOrderDO.getDescription());
        wxParam.put("out_trade_no", businessOrderDO.getOrderNo());
        wxParam.put("fee_type", "CNY");
        wxParam.put("trade_type", "NATIVE");
        Double payAmountIntValue = businessOrderDO.getPayPrice() * 100;
        wxParam.put("total_fee", payAmountIntValue.intValue() + "");
        wxParam.put("spbill_create_ip", IpUtil.getIpAddr(request));
        //TODO 回调微信支付结果的接口路径,即 PayLogController 中的 wxPayNotify 回调方法的路径。
        wxParam.put("notify_url", serverUrl+"pay/open/wxPayNotify");
        //微信签名
        Map<String, String> pms = wxpay.fillRequestMD5(wxParam);
        //参数转化XML
        String params = XMLUtil.mapToXml(pms);
        //记录param日志
        logger.info("wxNative_param:"+params.toString());
        String result = HttpClientUtil.sendPost("https://api.mch.weixin.qq.com/pay/unifiedorder", params);
        Map<String,String> wxrs =  XMLUtil.doXMLParse(result);
        //记录param日志
        logger.info("wxNative_result:"+result);
        addHttpLog("1",businessOrderDO.getOrderNo(),params,result);
        if ("SUCCESS".equals(wxrs.get("return_code").toString())) {
            String code_url = wxrs.get("code_url");
            //生成二维码
            InputStream ipt = QrcodeUtil.createQrcode(code_url, 300, "png");
            String fileUrl="";
            try {
                ObjectNode imgNode = fastDFSUtil.upload(ipt, "png", "wx_pay_qrcode" + System.currentTimeMillis());
                JSONObject json = JSONObject.parseObject(imgNode.toString());
                fileUrl = json.getString("fileId");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ObjEnvelop.getSuccess("下单成功",serverUrl+fileUrl);
        } else {
            return ObjEnvelop.getError(wxrs.get("return_msg"),-1);
        }
    }
    /**
     * 微信统一下单接口
     *
     * @return prepayId 微信预支付交易会话标识,该值有效期为2小时
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public ObjEnvelop wxWapPay(String relationId,Integer orderId,String patientId,HttpServletRequest request) throws Exception {
        BusinessOrderDO businessOrderDO;
        if(StringUtil.isBlank(relationId)){
            businessOrderDO = businessOrderDao.findOne(orderId);
        }else{
            businessOrderDO = businessOrderDao.selectByRelationCode(relationId);
        }
        Assert.notNull(businessOrderDO, "支付流水不存在");
        if (businessOrderDO.getStatus()!=0) {
            return ObjEnvelop.getError("待支付订单才能支付",-1);
        }
        BasePatientDO patientDO = patientDao.findById(patientId);
        Map<String,String> rs = new HashedMap();
        WXPay wxpay = new WXPay(getCareWxPayConfig());
        //设置没签名的参数
        Map<String, String> wxParam = new HashMap<>();
        wxParam.put("body", businessOrderDO.getDescription());
        wxParam.put("out_trade_no", businessOrderDO.getOrderNo());
        wxParam.put("fee_type", "CNY");
        wxParam.put("trade_type", "JSAPI");
        Double payAmountIntValue = businessOrderDO.getPayPrice() * 100;
        wxParam.put("total_fee", payAmountIntValue.intValue() + "");
        wxParam.put("spbill_create_ip", IpUtil.getIpAddr(request));
        wxParam.put("openid", patientDO.getOpenid());
        //TODO 回调微信支付结果的接口路径,即 PayLogController 中的 wxPayNotify 回调方法的路径。
        wxParam.put("notify_url", serverUrl+"pay/open/wxPayNotify");
        //微信签名
        Map<String, String> pms = wxpay.fillRequestMD5(wxParam);
        //参数转化XML
        String params = XMLUtil.mapToXml(pms);
        //记录param日志
        logger.info("wxUnifiedOrder_param:"+params.toString());
        String result = HttpClientUtil.sendPost("https://api.mch.weixin.qq.com/pay/unifiedorder", params);
        Map<String,String> wxrs =  XMLUtil.doXMLParse(result);
        //记录param日志
        logger.info("wxUnifiedOrder_result:"+result);
        addHttpLog("1",businessOrderDO.getOrderNo(),params,result);
        if ("SUCCESS".equals(wxrs.get("return_code").toString())) {
            rs.put("timeStamp", WxpayUtil.getTimeStamp());
            rs.put("appId",appId);
            rs.put("nonceStr", WXPayUtil.generateNonceStr());
            rs.put("package","prepay_id="+wxrs.get("prepay_id"));
            rs.put("signType","MD5");
            Map<String, String> sign = wxpay.fillRequestMD5(rs);
            return ObjEnvelop.getSuccess("下单成功",sign);
        } else {
            return ObjEnvelop.getError(wxrs.get("return_msg"),-1);
        }
    }
    /**
     * 提交支付订单
     * 订单类型 1招生,2 课程,3 上门辅导托幼) 4 生活照料
     * @return
     */
    public BusinessOrderDO submitOrder(String patientId,String type,String relationCode,Double price){
        BasePatientDO pateint = patientDao.findById(patientId);
        BusinessOrderDO businessOrderDO = new BusinessOrderDO();
        businessOrderDO.setPatient(pateint.getId());
        //支付账号
        businessOrderDO.setYkOrderId(pateint.getMobile());
        businessOrderDO.setPatientName(pateint.getName());
        businessOrderDO.setOrderType(1);
        businessOrderDO.setOrderCategory(type);
        String desc;
        String relateName;
        switch (type){
            case "1":
                desc = "招生报名费";
                relateName = "招生报名";
                break;
            case "2":
                desc = "课程报名费";
                relateName = "课程报名";
                break;
            case "3":
                desc = "上门辅导服务项目费";
                relateName = "上门辅导";
                break;
            case "4":
                desc = "生活照料服务项目费";
                relateName = "生活照料";
                break;
            default:
                desc = "服务费";
                relateName = "服务";
                break;
        }
        businessOrderDO.setDescription(desc);
        businessOrderDO.setRelationCode(relationCode);
        businessOrderDO.setRelationName(relateName);
        businessOrderDO.setCreateTime(new Date());
        businessOrderDO.setUpdateTime(new Date());
        businessOrderDO.setStatus(0);
        businessOrderDO.setOrderNo(""+System.currentTimeMillis()+(int)(Math.random()*900)+100);
        businessOrderDO.setUploadStatus(0);
        businessOrderDO.setPayType(1);
        businessOrderDO.setPayPrice(Double.valueOf(price));
        businessOrderService.save(businessOrderDO);
        return businessOrderDO;
    }
}

+ 80 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/HttpsUtil.java

@ -0,0 +1,80 @@
package com.yihu.jw.care.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.security.SecureRandom;
/**
 * http请求工具类
 *
 * @author yeshijie
 * @version 1.0
 * @date 2021/06/28 10:20
 */
public class HttpsUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpsUtil.class);
    /**
     * 发送https请求
     *
     * @param requestUrl    请求地址
     * @param requestMethod 请求方式(GET、POST)
     * @param outputStr     提交的数据
     * @return 返回微信服务器响应的信息
     */
    public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        StringBuffer buffer = null;
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            TrustManager[] tm = {new RequestTrustManager()};
            sslContext.init(null, tm, new SecureRandom());
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            conn.setRequestMethod(requestMethod);
            conn.setSSLSocketFactory(ssf);
            conn.connect();
            if (null != outputStr) {
                OutputStream os = conn.getOutputStream();
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }
            //读取服务器端返回的内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            buffer = new StringBuffer();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                buffer.append(line);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            conn.disconnect();
        } catch (ConnectException ce) {
            LOGGER.error("http请求连接超时" + ce);
        } catch (Exception e) {
            LOGGER.error("http请求异常" + e);
        }
        return buffer.toString();
    }
}

+ 51 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/MD5Util.java

@ -0,0 +1,51 @@
package com.yihu.jw.care.util;
import java.security.MessageDigest;
/**
 * MD5加密工具类
 *
 * @author yeshijie
 * @version 1.0.0
 * @date 2021/6/28
 */
public class MD5Util {
    private static final String[] HEX_DIGITS = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
    private static String byteArrayToHexString(byte[] b) {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            buffer.append(byteToHexString(b[i]));
        }
        return buffer.toString();
    }
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return HEX_DIGITS[d1] + HEX_DIGITS[d2];
    }
    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname)) {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            } else {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
            }
        } catch (Exception exception) {
        }
        return resultString;
    }
}

+ 27 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/RequestTrustManager.java

@ -0,0 +1,27 @@
package com.yihu.jw.care.util;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
 * @author yeshijie
 * @version 1.0
 * @date 2021/06/28 10:20
 */
public class RequestTrustManager implements X509TrustManager {
    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
    }
    @Override
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
    }
    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }
}

+ 113 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/WxpayUtil.java

@ -0,0 +1,113 @@
package com.yihu.jw.care.util;
import com.yihu.jw.care.config.WxpayConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
 * 微信支付工具类
 *
 * @author yeshijei
 * @version 1.0
 * @date 2021/06/28 18:21
 */
public class WxpayUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(WxpayUtil.class);
    private static final String STR_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    /**
     * 创建签名
     * 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
     *
     * @param parameters
     * @return
     */
    public static String createSign(SortedMap<String, String> parameters, String key) {
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + key);
        return MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
    }
    /**
     * 创建统一下单
     *
     * @param parameters
     * @return java.lang.String
     */
    public static String createUnifiedorder(SortedMap<String, String> parameters) {
        String outputStr = XMLUtil.mapToXml(parameters);
        LOGGER.info("创建统一下单xml" + outputStr);
//        <xml >
//           <appid > wx2421b1c4370ec43b </appid >
//           <attach > 支付测试 </attach >
//           <body > APP支付测试 </body >
//           <mch_id > 10000100 </mch_id >
//           <nonce_str > 1 add1a30ac87aa2db72f57a2375d8fec</nonce_str >
//           <notify_url > http://wxpay.wxutil.com/pub_v2/pay/notify.v2.php</notify_url>
//           <out_trade_no > 1415659990 </out_trade_no >
//           <spbill_create_ip > 14.23 .150 .211 </spbill_create_ip >
//           <total_fee > 1 </total_fee >
//           <trade_type > APP </trade_type >
//           <sign > 0 CB01533B8C1EF103065174F50BCA001</sign>
//        </xml>
        return HttpsUtil.httpsRequest(WxpayConfig.PREPAY_ID_URL, "POST", outputStr);
    }
    /**
     * 创建自定义长度随机字符串
     *
     * @param length
     * @return java.lang.String
     */
    public static String createNoncestr(int length) {
        String res = "";
        for (int i = 0; i < length; i++) {
            Random rd = new Random();
            res += STR_CHARS.indexOf(rd.nextInt(STR_CHARS.length() - 1));
        }
        return res;
    }
    /**
     * 创建固定长度随机字符串
     *
     * @return java.lang.String
     */
    public static String createNoncestr() {
        String res = "";
        for (int i = 0; i < 16; i++) {
            Random rd = new Random();
            res += STR_CHARS.charAt(rd.nextInt(STR_CHARS.length() - 1));
        }
        return res;
    }
    public static String getNonceStr() {
        Random random = new Random();
        return MD5Util.MD5Encode(String.valueOf(random.nextInt(10000)), "UTF-8");
    }
    public static String getTimeStamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }
    public static void main(String[] args) {
        System.out.println(UUID.randomUUID());
        System.out.println(getNonceStr());
    }
}

+ 173 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/XMLUtil.java

@ -0,0 +1,173 @@
package com.yihu.jw.care.util;
import com.google.common.collect.Maps;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
/**
 * xml工具类
 *
 * @author yeshijie
 * @version 1.0
 * @date 2021/06/26 10:05
 */
public class XMLUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(XMLUtil.class);
    /**
     * 将请求参数转换为xml格式的string
     *
     * @param parameters
     * @return java.lang.String
     */
    public static String mapToXml(Map<String, String> parameters) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set<Map.Entry<String, String>> es = parameters.entrySet();
        Iterator<Map.Entry<String, String>> it = es.iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = it.next();
            if ("attach".equalsIgnoreCase(entry.getKey()) || "body".equalsIgnoreCase(entry.getKey())) {
                sb.append("<" + entry.getKey() + ">" + "<![CDATA[" + entry.getValue() + "]]></" + entry.getKey() + ">");
            } else if ("sign".equalsIgnoreCase(entry.getKey())) {
                continue;
            } else {
                sb.append("<" + entry.getKey() + ">" + entry.getValue() + "</" + entry.getKey() + ">");
            }
        }
        if (parameters.containsKey("sign")) {
            sb.append("<" + "sign" + ">" + parameters.get("sign") + "</" + "sign" + ">");
        }
        sb.append("</xml>");
        return sb.toString();
    }
    /**
     * 返回给微信的参数
     *
     * @param returnCode 返回编码
     * @param returnMsg  返回信息
     * @return
     */
    public static String setXML(String returnCode, String returnMsg) {
        return "<xml><return_code><![CDATA[" + returnCode
                + "]]></return_code><return_msg><![CDATA[" + returnMsg
                + "]]></return_msg></xml>";
    }
    /**
     * 解析request流对象InputStream
     * 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。
     *
     * @throws JDOMException
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    public static Map<String, String> doXMLParse(HttpServletRequest request) throws JDOMException, IOException {
        Map<String, String> m = Maps.newHashMap();
        SAXBuilder builder = new SAXBuilder();
        ServletInputStream in = request.getInputStream();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List<Element> list = root.getChildren();
        Iterator<Element> it = list.iterator();
        while (it.hasNext()) {
            Element e = it.next();
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if (children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = XMLUtil.getChildrenText(children);
            }
            m.put(k, v);
        }
        //关闭流
        in.close();
        return m;
    }
    /**
     * 解析String类型的xml流对象InputStream
     * 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。
     *
     * @param strxml
     * @return
     * @throws JDOMException
     * @throws IOException
     */
    public static Map<String, String> doXMLParse(String strxml) throws JDOMException, IOException {
        if (null == strxml || "".equals(strxml)) {
            return null;
        }
        Map<String, String> m = Maps.newHashMap();
        InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            Element e = (Element) it.next();
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if (children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = XMLUtil.getChildrenText(children);
            }
            m.put(k, v);
        }
        //关闭流
        in.close();
        return m;
    }
    /**
     * 获取子结点的xml
     *
     * @param children
     * @return String
     */
    public static String getChildrenText(List children) {
        StringBuffer sb = new StringBuffer();
        if (!children.isEmpty()) {
            Iterator it = children.iterator();
            while (it.hasNext()) {
                Element e = (Element) it.next();
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");
                if (!list.isEmpty()) {
                    sb.append(XMLUtil.getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }
        return sb.toString();
    }
}

+ 97 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/wxconfig/CareWxPayConfig.java

@ -0,0 +1,97 @@
package com.yihu.jw.care.wxconfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
/**
 * 微信支付配置
 *
 * @author yeshijie
 * @date 2021/06/28 17:41
 */
@Component
public class CareWxPayConfig extends WXPayConfig {
    @Value("${wechat.appId}")
    public String appId;
    @Value("${wechat.mchId}")
    public String mchId;
    @Value("${wechat.apiKey}")
    public String apiKey;
    public byte[] certData;
    public CareWxPayConfig() throws Exception {
        Resource resource = new ClassPathResource("wechat/apiclient_cert.p12");
        File file = resource.getFile();
        InputStream certStream = new FileInputStream(file);
        this.certData = new byte[(int) file.length()];
        certStream.read(this.certData);
        certStream.close();
    }
    @Override
    public String getAppID() {
        return this.appId;
    }
    @Override
    public String getMchID() {
        return this.mchId;
    }
    @Override
    public String getKey() {
        return this.apiKey;
    }
    @Override
    public InputStream getCertStream() {
        ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData);
        return certBis;
    }
    @Override
    public int getHttpConnectTimeoutMs() {
        return 8000;
    }
    @Override
    public int getHttpReadTimeoutMs() {
        return 10000;
    }
    @Override
    public IWXPayDomain getWXPayDomain() {
        return null;
    }
    public void setAppId(String appId) {
        this.appId = appId;
    }
    public void setCertData(byte[] certData) {
        this.certData = certData;
    }
    public void setApiKey(String apiKey) {
        this.apiKey = apiKey;
    }
    public void setMchId(String mchId) {
        this.mchId = mchId;
    }
}

+ 42 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/wxconfig/IWXPayDomain.java

@ -0,0 +1,42 @@
package com.yihu.jw.care.wxconfig;
/**
 * 域名管理,实现主备域名自动切换
 */
public abstract interface IWXPayDomain {
    /**
     * 上报域名网络状况
     * @param domain 域名。 比如:api.mch.weixin.qq.com
     * @param elapsedTimeMillis 耗时
     * @param ex 网络请求中出现的异常。
     *           null表示没有异常
     *           ConnectTimeoutException,表示建立网络连接异常
     *           UnknownHostException, 表示dns解析异常
     */
    abstract void report(final String domain, long elapsedTimeMillis, final Exception ex);
    /**
     * 获取域名
     * @param config 配置
     * @return 域名
     */
    abstract DomainInfo getDomain(final WXPayConfig config);
    static class DomainInfo{
        public String domain;       //域名
        public boolean primaryDomain;     //该域名是否为主域名。例如:api.mch.weixin.qq.com为主域名
        public DomainInfo(String domain, boolean primaryDomain) {
            this.domain = domain;
            this.primaryDomain = primaryDomain;
        }
        @Override
        public String toString() {
            return "DomainInfo{" +
                    "domain='" + domain + '\'' +
                    ", primaryDomain=" + primaryDomain +
                    '}';
        }
    }
}

+ 695 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/wxconfig/WXPay.java

@ -0,0 +1,695 @@
package com.yihu.jw.care.wxconfig;
import java.util.HashMap;
import java.util.Map;
public class WXPay {
    private WXPayConfig config;
    private WXPayConstants.SignType signType;
    private boolean autoReport;
    private boolean useSandbox;
    private String notifyUrl;
    private WXPayRequest wxPayRequest;
    public WXPay(final WXPayConfig config) throws Exception {
        this(config, null, true, false);
    }
    public WXPay(final WXPayConfig config, final boolean autoReport) throws Exception {
        this(config, null, autoReport, false);
    }
    public WXPay(final WXPayConfig config, final boolean autoReport, final boolean useSandbox) throws Exception{
        this(config, null, autoReport, useSandbox);
    }
    public WXPay(final WXPayConfig config, final String notifyUrl) throws Exception {
        this(config, notifyUrl, true, false);
    }
    public WXPay(final WXPayConfig config, final String notifyUrl, final boolean autoReport) throws Exception {
        this(config, notifyUrl, autoReport, false);
    }
    public WXPay(final WXPayConfig config, final String notifyUrl, final boolean autoReport, final boolean useSandbox) throws Exception {
        this.config = config;
        this.notifyUrl = notifyUrl;
        this.autoReport = autoReport;
        this.useSandbox = useSandbox;
        if (useSandbox) {
            this.signType = WXPayConstants.SignType.MD5; // 沙箱环境
        }
        else {
            this.signType = WXPayConstants.SignType.HMACSHA256;
        }
        this.wxPayRequest = new WXPayRequest(config);
    }
    private void checkWXPayConfig() throws Exception {
        if (this.config == null) {
            throw new Exception("config is null");
        }
        if (this.config.getAppID() == null || this.config.getAppID().trim().length() == 0) {
            throw new Exception("appid in config is empty");
        }
        if (this.config.getMchID() == null || this.config.getMchID().trim().length() == 0) {
            throw new Exception("appid in config is empty");
        }
        if (this.config.getCertStream() == null) {
            throw new Exception("cert stream in config is empty");
        }
        if (this.config.getWXPayDomain() == null){
            throw new Exception("config.getWXPayDomain() is null");
        }
        if (this.config.getHttpConnectTimeoutMs() < 10) {
            throw new Exception("http connect timeout is too small");
        }
        if (this.config.getHttpReadTimeoutMs() < 10) {
            throw new Exception("http read timeout is too small");
        }
    }
    /**
     * 向 Map 中添加 appid、mch_id、nonce_str、sign_type、sign <br>
     * 该函数适用于商户适用于统一下单等接口,不适用于红包、代金券接口
     *
     * @param reqData
     * @return
     * @throws Exception
     */
    public Map<String, String> fillRequestData(Map<String, String> reqData) throws Exception {
        reqData.put("appid", config.getAppID());
        reqData.put("mch_id", config.getMchID());
        reqData.put("nonce_str", WXPayUtil.generateNonceStr());
        if (WXPayConstants.SignType.MD5.equals(this.signType)) {
            reqData.put("sign_type", WXPayConstants.MD5);
        }
        else if (WXPayConstants.SignType.HMACSHA256.equals(this.signType)) {
            reqData.put("sign_type", WXPayConstants.HMACSHA256);
        }
        reqData.put("sign", WXPayUtil.generateSignature(reqData, config.getKey(), this.signType));
        return reqData;
    }
    public Map<String, String> fillRequestMD5(Map<String, String> reqData) throws Exception {
        this.signType = WXPayConstants.SignType.MD5;
        reqData.put("sign", WXPayUtil.generateSignature(reqData, config.getKey(), this.signType));
        return reqData;
    }
    /**
     * 判断xml数据的sign是否有效,必须包含sign字段,否则返回false。
     *
     * @param reqData 向wxpay post的请求数据
     * @return 签名是否有效
     * @throws Exception
     */
    public boolean isResponseSignatureValid(Map<String, String> reqData) throws Exception {
        // 返回数据的签名方式和请求中给定的签名方式是一致的
        return WXPayUtil.isSignatureValid(reqData, this.config.getKey(), this.signType);
    }
    /**
     * 判断支付结果通知中的sign是否有效
     *
     * @param reqData 向wxpay post的请求数据
     * @return 签名是否有效
     * @throws Exception
     */
    public boolean isPayResultNotifySignatureValid(Map<String, String> reqData) throws Exception {
        String signTypeInData = reqData.get(WXPayConstants.FIELD_SIGN_TYPE);
        WXPayConstants.SignType signType;
        if (signTypeInData == null) {
            signType = WXPayConstants.SignType.MD5;
        }
        else {
            signTypeInData = signTypeInData.trim();
            if (signTypeInData.length() == 0) {
                signType = WXPayConstants.SignType.MD5;
            }
            else if (WXPayConstants.MD5.equals(signTypeInData)) {
                signType = WXPayConstants.SignType.MD5;
            }
            else if (WXPayConstants.HMACSHA256.equals(signTypeInData)) {
                signType = WXPayConstants.SignType.HMACSHA256;
            }
            else {
                throw new Exception(String.format("Unsupported sign_type: %s", signTypeInData));
            }
        }
        return WXPayUtil.isSignatureValid(reqData, this.config.getKey(), signType);
    }
    /**
     * 不需要证书的请求
     * @param urlSuffix String
     * @param reqData 向wxpay post的请求数据
     * @param connectTimeoutMs 超时时间,单位是毫秒
     * @param readTimeoutMs 超时时间,单位是毫秒
     * @return API返回数据
     * @throws Exception
     */
    public String requestWithoutCert(String urlSuffix, Map<String, String> reqData,
                                     int connectTimeoutMs, int readTimeoutMs) throws Exception {
        String msgUUID = reqData.get("nonce_str");
        String reqBody = WXPayUtil.mapToXml(reqData);
        String resp = this.wxPayRequest.requestWithoutCert(urlSuffix, msgUUID, reqBody, connectTimeoutMs, readTimeoutMs, autoReport);
        return resp;
    }
    /**
     * 需要证书的请求
     * @param urlSuffix String
     * @param reqData 向wxpay post的请求数据  Map
     * @param connectTimeoutMs 超时时间,单位是毫秒
     * @param readTimeoutMs 超时时间,单位是毫秒
     * @return API返回数据
     * @throws Exception
     */
    public String requestWithCert(String urlSuffix, Map<String, String> reqData,
                                  int connectTimeoutMs, int readTimeoutMs) throws Exception {
        String msgUUID= reqData.get("nonce_str");
        String reqBody = WXPayUtil.mapToXml(reqData);
        String resp = this.wxPayRequest.requestWithCert(urlSuffix, msgUUID, reqBody, connectTimeoutMs, readTimeoutMs, this.autoReport);
        return resp;
    }
    /**
     * 处理 HTTPS API返回数据,转换成Map对象。return_code为SUCCESS时,验证签名。
     * @param xmlStr API返回的XML格式数据
     * @return Map类型数据
     * @throws Exception
     */
    public Map<String, String> processResponseXml(String xmlStr) throws Exception {
        String RETURN_CODE = "return_code";
        String return_code;
        Map<String, String> respData = WXPayUtil.xmlToMap(xmlStr);
        if (respData.containsKey(RETURN_CODE)) {
            return_code = respData.get(RETURN_CODE);
        }
        else {
            throw new Exception(String.format("No `return_code` in XML: %s", xmlStr));
        }
        if (return_code.equals(WXPayConstants.FAIL)) {
            return respData;
        }
        else if (return_code.equals(WXPayConstants.SUCCESS)) {
           if (this.isResponseSignatureValid(respData)) {
               return respData;
           }
           else {
               throw new Exception(String.format("Invalid sign value in XML: %s", xmlStr));
           }
        }
        else {
            throw new Exception(String.format("return_code value %s is invalid in XML: %s", return_code, xmlStr));
        }
    }
    /**
     * 作用:提交刷卡支付<br>
     * 场景:刷卡支付
     * @param reqData 向wxpay post的请求数据
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, String> microPay(Map<String, String> reqData) throws Exception {
        return this.microPay(reqData, this.config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
    }
    /**
     * 作用:提交刷卡支付<br>
     * 场景:刷卡支付
     * @param reqData 向wxpay post的请求数据
     * @param connectTimeoutMs 连接超时时间,单位是毫秒
     * @param readTimeoutMs 读超时时间,单位是毫秒
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, String> microPay(Map<String, String> reqData, int connectTimeoutMs, int readTimeoutMs) throws Exception {
        String url;
        if (this.useSandbox) {
            url = WXPayConstants.SANDBOX_MICROPAY_URL_SUFFIX;
        }
        else {
            url = WXPayConstants.MICROPAY_URL_SUFFIX;
        }
        String respXml = this.requestWithoutCert(url, this.fillRequestData(reqData), connectTimeoutMs, readTimeoutMs);
        return this.processResponseXml(respXml);
    }
    /**
     * 提交刷卡支付,针对软POS,尽可能做成功
     * 内置重试机制,最多60s
     * @param reqData
     * @return
     * @throws Exception
     */
    public Map<String, String> microPayWithPos(Map<String, String> reqData) throws Exception {
        return this.microPayWithPos(reqData, this.config.getHttpConnectTimeoutMs());
    }
    /**
     * 提交刷卡支付,针对软POS,尽可能做成功
     * 内置重试机制,最多60s
     * @param reqData
     * @param connectTimeoutMs
     * @return
     * @throws Exception
     */
    public Map<String, String> microPayWithPos(Map<String, String> reqData, int connectTimeoutMs) throws Exception {
        int remainingTimeMs = 60*1000;
        long startTimestampMs = 0;
        Map<String, String> lastResult = null;
        Exception lastException = null;
        while (true) {
            startTimestampMs = WXPayUtil.getCurrentTimestampMs();
            int readTimeoutMs = remainingTimeMs - connectTimeoutMs;
            if (readTimeoutMs > 1000) {
                try {
                    lastResult = this.microPay(reqData, connectTimeoutMs, readTimeoutMs);
                    String returnCode = lastResult.get("return_code");
                    if (returnCode.equals("SUCCESS")) {
                        String resultCode = lastResult.get("result_code");
                        String errCode = lastResult.get("err_code");
                        if (resultCode.equals("SUCCESS")) {
                            break;
                        }
                        else {
                            // 看错误码,若支付结果未知,则重试提交刷卡支付
                            if (errCode.equals("SYSTEMERROR") || errCode.equals("BANKERROR") || errCode.equals("USERPAYING")) {
                                remainingTimeMs = remainingTimeMs - (int)(WXPayUtil.getCurrentTimestampMs() - startTimestampMs);
                                if (remainingTimeMs <= 100) {
                                    break;
                                }
                                else {
                                    WXPayUtil.getLogger().info("microPayWithPos: try micropay again");
                                    if (remainingTimeMs > 5*1000) {
                                        Thread.sleep(5*1000);
                                    }
                                    else {
                                        Thread.sleep(1*1000);
                                    }
                                    continue;
                                }
                            }
                            else {
                                break;
                            }
                        }
                    }
                    else {
                        break;
                    }
                }
                catch (Exception ex) {
                    lastResult = null;
                    lastException = ex;
                }
            }
            else {
                break;
            }
        }
        if (lastResult == null) {
            throw lastException;
        }
        else {
            return lastResult;
        }
    }
    /**
     * 作用:统一下单<br>
     * 场景:公共号支付、扫码支付、APP支付
     * @param reqData 向wxpay post的请求数据
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, String> unifiedOrder(Map<String, String> reqData) throws Exception {
        return this.unifiedOrder(reqData, config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
    }
    /**
     * 作用:统一下单<br>
     * 场景:公共号支付、扫码支付、APP支付
     * @param reqData 向wxpay post的请求数据
     * @param connectTimeoutMs 连接超时时间,单位是毫秒
     * @param readTimeoutMs 读超时时间,单位是毫秒
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, String> unifiedOrder(Map<String, String> reqData,  int connectTimeoutMs, int readTimeoutMs) throws Exception {
        String url;
        if (this.useSandbox) {
            url = WXPayConstants.SANDBOX_UNIFIEDORDER_URL_SUFFIX;
        }
        else {
            url = WXPayConstants.UNIFIEDORDER_URL_SUFFIX;
        }
        if(this.notifyUrl != null) {
            reqData.put("notify_url", this.notifyUrl);
        }
        String respXml = this.requestWithoutCert(url, this.fillRequestData(reqData), connectTimeoutMs, readTimeoutMs);
        return this.processResponseXml(respXml);
    }
    /**
     * 作用:查询订单<br>
     * 场景:刷卡支付、公共号支付、扫码支付、APP支付
     * @param reqData 向wxpay post的请求数据
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, String> orderQuery(Map<String, String> reqData) throws Exception {
        return this.orderQuery(reqData, config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
    }
    /**
     * 作用:查询订单<br>
     * 场景:刷卡支付、公共号支付、扫码支付、APP支付
     * @param reqData 向wxpay post的请求数据 int
     * @param connectTimeoutMs 连接超时时间,单位是毫秒
     * @param readTimeoutMs 读超时时间,单位是毫秒
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, String> orderQuery(Map<String, String> reqData, int connectTimeoutMs, int readTimeoutMs) throws Exception {
        String url;
        if (this.useSandbox) {
            url = WXPayConstants.SANDBOX_ORDERQUERY_URL_SUFFIX;
        }
        else {
            url = WXPayConstants.ORDERQUERY_URL_SUFFIX;
        }
        String respXml = this.requestWithoutCert(url, this.fillRequestData(reqData), connectTimeoutMs, readTimeoutMs);
        return this.processResponseXml(respXml);
    }
    /**
     * 作用:撤销订单<br>
     * 场景:刷卡支付
     * @param reqData 向wxpay post的请求数据
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, String> reverse(Map<String, String> reqData) throws Exception {
        return this.reverse(reqData, config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
    }
    /**
     * 作用:撤销订单<br>
     * 场景:刷卡支付<br>
     * 其他:需要证书
     * @param reqData 向wxpay post的请求数据
     * @param connectTimeoutMs 连接超时时间,单位是毫秒
     * @param readTimeoutMs 读超时时间,单位是毫秒
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, String> reverse(Map<String, String> reqData, int connectTimeoutMs, int readTimeoutMs) throws Exception {
        String url;
        if (this.useSandbox) {
            url = WXPayConstants.SANDBOX_REVERSE_URL_SUFFIX;
        }
        else {
            url = WXPayConstants.REVERSE_URL_SUFFIX;
        }
        String respXml = this.requestWithCert(url, this.fillRequestData(reqData), connectTimeoutMs, readTimeoutMs);
        return this.processResponseXml(respXml);
    }
    /**
     * 作用:关闭订单<br>
     * 场景:公共号支付、扫码支付、APP支付
     * @param reqData 向wxpay post的请求数据
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, String> closeOrder(Map<String, String> reqData) throws Exception {
        return this.closeOrder(reqData, config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
    }
    /**
     * 作用:关闭订单<br>
     * 场景:公共号支付、扫码支付、APP支付
     * @param reqData 向wxpay post的请求数据
     * @param connectTimeoutMs 连接超时时间,单位是毫秒
     * @param readTimeoutMs 读超时时间,单位是毫秒
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, String> closeOrder(Map<String, String> reqData,  int connectTimeoutMs, int readTimeoutMs) throws Exception {
        String url;
        if (this.useSandbox) {
            url = WXPayConstants.SANDBOX_CLOSEORDER_URL_SUFFIX;
        }
        else {
            url = WXPayConstants.CLOSEORDER_URL_SUFFIX;
        }
        String respXml = this.requestWithoutCert(url, this.fillRequestData(reqData), connectTimeoutMs, readTimeoutMs);
        return this.processResponseXml(respXml);
    }
    /**
     * 作用:申请退款<br>
     * 场景:刷卡支付、公共号支付、扫码支付、APP支付
     * @param reqData 向wxpay post的请求数据
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, String> refund(Map<String, String> reqData) throws Exception {
        return this.refund(reqData, this.config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
    }
    /**
     * 作用:申请退款<br>
     * 场景:刷卡支付、公共号支付、扫码支付、APP支付<br>
     * 其他:需要证书
     * @param reqData 向wxpay post的请求数据
     * @param connectTimeoutMs 连接超时时间,单位是毫秒
     * @param readTimeoutMs 读超时时间,单位是毫秒
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, String> refund(Map<String, String> reqData, int connectTimeoutMs, int readTimeoutMs) throws Exception {
        String url;
        if (this.useSandbox) {
            url = WXPayConstants.SANDBOX_REFUND_URL_SUFFIX;
        }
        else {
            url = WXPayConstants.REFUND_URL_SUFFIX;
        }
        String respXml = this.requestWithCert(url, this.fillRequestData(reqData), connectTimeoutMs, readTimeoutMs);
        return this.processResponseXml(respXml);
    }
    /**
     * 作用:退款查询<br>
     * 场景:刷卡支付、公共号支付、扫码支付、APP支付
     * @param reqData 向wxpay post的请求数据
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, String> refundQuery(Map<String, String> reqData) throws Exception {
        return this.refundQuery(reqData, this.config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
    }
    /**
     * 作用:退款查询<br>
     * 场景:刷卡支付、公共号支付、扫码支付、APP支付
     * @param reqData 向wxpay post的请求数据
     * @param connectTimeoutMs 连接超时时间,单位是毫秒
     * @param readTimeoutMs 读超时时间,单位是毫秒
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, String> refundQuery(Map<String, String> reqData, int connectTimeoutMs, int readTimeoutMs) throws Exception {
        String url;
        if (this.useSandbox) {
            url = WXPayConstants.SANDBOX_REFUNDQUERY_URL_SUFFIX;
        }
        else {
            url = WXPayConstants.REFUNDQUERY_URL_SUFFIX;
        }
        String respXml = this.requestWithoutCert(url, this.fillRequestData(reqData), connectTimeoutMs, readTimeoutMs);
        return this.processResponseXml(respXml);
    }
    /**
     * 作用:对账单下载(成功时返回对账单数据,失败时返回XML格式数据)<br>
     * 场景:刷卡支付、公共号支付、扫码支付、APP支付
     * @param reqData 向wxpay post的请求数据
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, String> downloadBill(Map<String, String> reqData) throws Exception {
        return this.downloadBill(reqData, this.config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
    }
    /**
     * 作用:对账单下载<br>
     * 场景:刷卡支付、公共号支付、扫码支付、APP支付<br>
     * 其他:无论是否成功都返回Map。若成功,返回的Map中含有return_code、return_msg、data,
     *      其中return_code为`SUCCESS`,data为对账单数据。
     * @param reqData 向wxpay post的请求数据
     * @param connectTimeoutMs 连接超时时间,单位是毫秒
     * @param readTimeoutMs 读超时时间,单位是毫秒
     * @return 经过封装的API返回数据
     * @throws Exception
     */
    public Map<String, String> downloadBill(Map<String, String> reqData, int connectTimeoutMs, int readTimeoutMs) throws Exception {
        String url;
        if (this.useSandbox) {
            url = WXPayConstants.SANDBOX_DOWNLOADBILL_URL_SUFFIX;
        }
        else {
            url = WXPayConstants.DOWNLOADBILL_URL_SUFFIX;
        }
        String respStr = this.requestWithoutCert(url, this.fillRequestData(reqData), connectTimeoutMs, readTimeoutMs).trim();
        Map<String, String> ret;
        // 出现错误,返回XML数据
        if (respStr.indexOf("<") == 0) {
            ret = WXPayUtil.xmlToMap(respStr);
        }
        else {
            // 正常返回csv数据
            ret = new HashMap<String, String>();
            ret.put("return_code", WXPayConstants.SUCCESS);
            ret.put("return_msg", "ok");
            ret.put("data", respStr);
        }
        return ret;
    }
    /**
     * 作用:交易保障<br>
     * 场景:刷卡支付、公共号支付、扫码支付、APP支付
     * @param reqData 向wxpay post的请求数据
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, String> report(Map<String, String> reqData) throws Exception {
        return this.report(reqData, this.config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
    }
    /**
     * 作用:交易保障<br>
     * 场景:刷卡支付、公共号支付、扫码支付、APP支付
     * @param reqData 向wxpay post的请求数据
     * @param connectTimeoutMs 连接超时时间,单位是毫秒
     * @param readTimeoutMs 读超时时间,单位是毫秒
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, String> report(Map<String, String> reqData, int connectTimeoutMs, int readTimeoutMs) throws Exception {
        String url;
        if (this.useSandbox) {
            url = WXPayConstants.SANDBOX_REPORT_URL_SUFFIX;
        }
        else {
            url = WXPayConstants.REPORT_URL_SUFFIX;
        }
        String respXml = this.requestWithoutCert(url, this.fillRequestData(reqData), connectTimeoutMs, readTimeoutMs);
        return WXPayUtil.xmlToMap(respXml);
    }
    /**
     * 作用:转换短链接<br>
     * 场景:刷卡支付、扫码支付
     * @param reqData 向wxpay post的请求数据
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, String> shortUrl(Map<String, String> reqData) throws Exception {
        return this.shortUrl(reqData, this.config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
    }
    /**
     * 作用:转换短链接<br>
     * 场景:刷卡支付、扫码支付
     * @param reqData 向wxpay post的请求数据
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, String> shortUrl(Map<String, String> reqData, int connectTimeoutMs, int readTimeoutMs) throws Exception {
        String url;
        if (this.useSandbox) {
            url = WXPayConstants.SANDBOX_SHORTURL_URL_SUFFIX;
        }
        else {
            url = WXPayConstants.SHORTURL_URL_SUFFIX;
        }
        String respXml = this.requestWithoutCert(url, this.fillRequestData(reqData), connectTimeoutMs, readTimeoutMs);
        return this.processResponseXml(respXml);
    }
    /**
     * 作用:授权码查询OPENID接口<br>
     * 场景:刷卡支付
     * @param reqData 向wxpay post的请求数据
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, String> authCodeToOpenid(Map<String, String> reqData) throws Exception {
        return this.authCodeToOpenid(reqData, this.config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
    }
    /**
     * 作用:授权码查询OPENID接口<br>
     * 场景:刷卡支付
     * @param reqData 向wxpay post的请求数据
     * @param connectTimeoutMs 连接超时时间,单位是毫秒
     * @param readTimeoutMs 读超时时间,单位是毫秒
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, String> authCodeToOpenid(Map<String, String> reqData, int connectTimeoutMs, int readTimeoutMs) throws Exception {
        String url;
        if (this.useSandbox) {
            url = WXPayConstants.SANDBOX_AUTHCODETOOPENID_URL_SUFFIX;
        }
        else {
            url = WXPayConstants.AUTHCODETOOPENID_URL_SUFFIX;
        }
        String respXml = this.requestWithoutCert(url, this.fillRequestData(reqData), connectTimeoutMs, readTimeoutMs);
        return this.processResponseXml(respXml);
    }
} // end class

+ 103 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/wxconfig/WXPayConfig.java

@ -0,0 +1,103 @@
package com.yihu.jw.care.wxconfig;
import java.io.InputStream;
public abstract class WXPayConfig {
    /**
     * 获取 App ID
     *
     * @return App ID
     */
    abstract String getAppID();
    /**
     * 获取 Mch ID
     *
     * @return Mch ID
     */
    abstract String getMchID();
    /**
     * 获取 API 密钥
     *
     * @return API密钥
     */
    abstract String getKey();
    /**
     * 获取商户证书内容
     *
     * @return 商户证书内容
     */
    abstract InputStream getCertStream();
    /**
     * HTTP(S) 连接超时时间,单位毫秒
     *
     * @return
     */
    public int getHttpConnectTimeoutMs() {
        return 6*1000;
    }
    /**
     * HTTP(S) 读数据超时时间,单位毫秒
     *
     * @return
     */
    public int getHttpReadTimeoutMs() {
        return 8*1000;
    }
    /**
     * 获取WXPayDomain, 用于多域名容灾自动切换
     * @return
     */
    abstract IWXPayDomain getWXPayDomain();
    /**
     * 是否自动上报。
     * 若要关闭自动上报,子类中实现该函数返回 false 即可。
     *
     * @return
     */
    public boolean shouldAutoReport() {
        return true;
    }
    /**
     * 进行健康上报的线程的数量
     *
     * @return
     */
    public int getReportWorkerNum() {
        return 6;
    }
    /**
     * 健康上报缓存消息的最大数量。会有线程去独立上报
     * 粗略计算:加入一条消息200B,10000消息占用空间 2000 KB,约为2MB,可以接受
     *
     * @return
     */
    public int getReportQueueMaxSize() {
        return 10000;
    }
    /**
     * 批量上报,一次最多上报多个数据
     *
     * @return
     */
    public int getReportBatchSize() {
        return 10;
    }
}

+ 59 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/wxconfig/WXPayConstants.java

@ -0,0 +1,59 @@
package com.yihu.jw.care.wxconfig;
import org.apache.http.client.HttpClient;
/**
 * 常量
 */
public class WXPayConstants {
    public enum SignType {
        MD5, HMACSHA256
    }
    public static final String DOMAIN_API = "api.mch.weixin.qq.com";
    public static final String DOMAIN_API2 = "api2.mch.weixin.qq.com";
    public static final String DOMAIN_APIHK = "apihk.mch.weixin.qq.com";
    public static final String DOMAIN_APIUS = "apius.mch.weixin.qq.com";
    public static final String FAIL     = "FAIL";
    public static final String SUCCESS  = "SUCCESS";
    public static final String HMACSHA256 = "HMAC-SHA256";
    public static final String MD5 = "MD5";
    public static final String FIELD_SIGN = "sign";
    public static final String FIELD_SIGN_TYPE = "sign_type";
    public static final String WXPAYSDK_VERSION = "WXPaySDK/3.0.9";
    public static final String USER_AGENT = WXPAYSDK_VERSION +
            " (" + System.getProperty("os.arch") + " " + System.getProperty("os.name") + " " + System.getProperty("os.version") +
            ") Java/" + System.getProperty("java.version") + " HttpClient/" + HttpClient.class.getPackage().getImplementationVersion();
    public static final String MICROPAY_URL_SUFFIX     = "/pay/micropay";
    public static final String UNIFIEDORDER_URL_SUFFIX = "/pay/unifiedorder";
    public static final String ORDERQUERY_URL_SUFFIX   = "/pay/orderquery";
    public static final String REVERSE_URL_SUFFIX      = "/secapi/pay/reverse";
    public static final String CLOSEORDER_URL_SUFFIX   = "/pay/closeorder";
    public static final String REFUND_URL_SUFFIX       = "/secapi/pay/refund";
    public static final String REFUNDQUERY_URL_SUFFIX  = "/pay/refundquery";
    public static final String DOWNLOADBILL_URL_SUFFIX = "/pay/downloadbill";
    public static final String REPORT_URL_SUFFIX       = "/payitil/report";
    public static final String SHORTURL_URL_SUFFIX     = "/tools/shorturl";
    public static final String AUTHCODETOOPENID_URL_SUFFIX = "/tools/authcodetoopenid";
    // sandbox
    public static final String SANDBOX_MICROPAY_URL_SUFFIX     = "/sandboxnew/pay/micropay";
    public static final String SANDBOX_UNIFIEDORDER_URL_SUFFIX = "/sandboxnew/pay/unifiedorder";
    public static final String SANDBOX_ORDERQUERY_URL_SUFFIX   = "/sandboxnew/pay/orderquery";
    public static final String SANDBOX_REVERSE_URL_SUFFIX      = "/sandboxnew/secapi/pay/reverse";
    public static final String SANDBOX_CLOSEORDER_URL_SUFFIX   = "/sandboxnew/pay/closeorder";
    public static final String SANDBOX_REFUND_URL_SUFFIX       = "/sandboxnew/secapi/pay/refund";
    public static final String SANDBOX_REFUNDQUERY_URL_SUFFIX  = "/sandboxnew/pay/refundquery";
    public static final String SANDBOX_DOWNLOADBILL_URL_SUFFIX = "/sandboxnew/pay/downloadbill";
    public static final String SANDBOX_REPORT_URL_SUFFIX       = "/sandboxnew/payitil/report";
    public static final String SANDBOX_SHORTURL_URL_SUFFIX     = "/sandboxnew/tools/shorturl";
    public static final String SANDBOX_AUTHCODETOOPENID_URL_SUFFIX = "/sandboxnew/tools/authcodetoopenid";
}

+ 265 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/wxconfig/WXPayReport.java

@ -0,0 +1,265 @@
package com.yihu.jw.care.wxconfig;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
/**
 * 交易保障
 */
public class WXPayReport {
    public static class ReportInfo {
        /**
         * 布尔变量使用int。0为false, 1为true。
         */
        // 基本信息
        private String version = "v1";
        private String sdk = WXPayConstants.WXPAYSDK_VERSION;
        private String uuid;  // 交易的标识
        private long timestamp;   // 上报时的时间戳,单位秒
        private long elapsedTimeMillis; // 耗时,单位 毫秒
        // 针对主域名
        private String firstDomain;  // 第1次请求的域名
        private boolean primaryDomain; //是否主域名
        private int firstConnectTimeoutMillis;  // 第1次请求设置的连接超时时间,单位 毫秒
        private int firstReadTimeoutMillis;  // 第1次请求设置的读写超时时间,单位 毫秒
        private int firstHasDnsError;  // 第1次请求是否出现dns问题
        private int firstHasConnectTimeout; // 第1次请求是否出现连接超时
        private int firstHasReadTimeout; // 第1次请求是否出现连接超时
        public ReportInfo(String uuid, long timestamp, long elapsedTimeMillis, String firstDomain, boolean primaryDomain, int firstConnectTimeoutMillis, int firstReadTimeoutMillis, boolean firstHasDnsError, boolean firstHasConnectTimeout, boolean firstHasReadTimeout) {
            this.uuid = uuid;
            this.timestamp = timestamp;
            this.elapsedTimeMillis = elapsedTimeMillis;
            this.firstDomain = firstDomain;
            this.primaryDomain = primaryDomain;
            this.firstConnectTimeoutMillis = firstConnectTimeoutMillis;
            this.firstReadTimeoutMillis = firstReadTimeoutMillis;
            this.firstHasDnsError = firstHasDnsError?1:0;
            this.firstHasConnectTimeout = firstHasConnectTimeout?1:0;
            this.firstHasReadTimeout = firstHasReadTimeout?1:0;
         }
        @Override
        public String toString() {
            return "ReportInfo{" +
                    "version='" + version + '\'' +
                    ", sdk='" + sdk + '\'' +
                    ", uuid='" + uuid + '\'' +
                    ", timestamp=" + timestamp +
                    ", elapsedTimeMillis=" + elapsedTimeMillis +
                    ", firstDomain='" + firstDomain + '\'' +
                    ", primaryDomain=" + primaryDomain +
                    ", firstConnectTimeoutMillis=" + firstConnectTimeoutMillis +
                    ", firstReadTimeoutMillis=" + firstReadTimeoutMillis +
                    ", firstHasDnsError=" + firstHasDnsError +
                    ", firstHasConnectTimeout=" + firstHasConnectTimeout +
                    ", firstHasReadTimeout=" + firstHasReadTimeout +
                    '}';
        }
        /**
         * 转换成 csv 格式
         *
         * @return
         */
        public String toLineString(String key) {
            String separator = ",";
            Object[] objects = new Object[] {
                version, sdk, uuid, timestamp, elapsedTimeMillis,
                    firstDomain, primaryDomain, firstConnectTimeoutMillis, firstReadTimeoutMillis,
                    firstHasDnsError, firstHasConnectTimeout, firstHasReadTimeout
            };
            StringBuffer sb = new StringBuffer();
            for(Object obj: objects) {
                sb.append(obj).append(separator);
            }
            try {
                String sign = WXPayUtil.HMACSHA256(sb.toString(), key);
                sb.append(sign);
                return sb.toString();
            }
            catch (Exception ex) {
                return null;
            }
        }
    }
    private static final String REPORT_URL = "http://report.mch.weixin.qq.com/wxpay/report/default";
    // private static final String REPORT_URL = "http://127.0.0.1:5000/test";
    private static final int DEFAULT_CONNECT_TIMEOUT_MS = 6*1000;
    private static final int DEFAULT_READ_TIMEOUT_MS = 8*1000;
    private LinkedBlockingQueue<String> reportMsgQueue = null;
    private WXPayConfig config;
    private ExecutorService executorService;
    private volatile static WXPayReport INSTANCE;
    private WXPayReport(final WXPayConfig config) {
        this.config = config;
        reportMsgQueue = new LinkedBlockingQueue<String>(config.getReportQueueMaxSize());
        // 添加处理线程
        executorService = Executors.newFixedThreadPool(config.getReportWorkerNum(), new ThreadFactory() {
            public Thread newThread(Runnable r) {
                Thread t = Executors.defaultThreadFactory().newThread(r);
                t.setDaemon(true);
                return t;
            }
        });
        if (config.shouldAutoReport()) {
            WXPayUtil.getLogger().info("report worker num: {}", config.getReportWorkerNum());
            for (int i = 0; i < config.getReportWorkerNum(); ++i) {
                executorService.execute(new Runnable() {
                    public void run() {
                        while (true) {
                            // 先用 take 获取数据
                            try {
                                StringBuffer sb = new StringBuffer();
                                String firstMsg = reportMsgQueue.take();
                                WXPayUtil.getLogger().info("get first report msg: {}", firstMsg);
                                String msg = null;
                                sb.append(firstMsg); //会阻塞至有消息
                                int remainNum = config.getReportBatchSize() - 1;
                                for (int j=0; j<remainNum; ++j) {
                                    WXPayUtil.getLogger().info("try get remain report msg");
                                    // msg = reportMsgQueue.poll();  // 不阻塞了
                                    msg = reportMsgQueue.take();
                                    WXPayUtil.getLogger().info("get remain report msg: {}", msg);
                                    if (msg == null) {
                                        break;
                                    }
                                    else {
                                        sb.append("\n");
                                        sb.append(msg);
                                    }
                                }
                                // 上报
                                WXPayReport.httpRequest(sb.toString(), DEFAULT_CONNECT_TIMEOUT_MS, DEFAULT_READ_TIMEOUT_MS);
                            }
                            catch (Exception ex) {
                                WXPayUtil.getLogger().warn("report fail. reason: {}", ex.getMessage());
                            }
                        }
                    }
                });
            }
        }
    }
    /**
     * 单例,双重校验,请在 JDK 1.5及更高版本中使用
     *
     * @param config
     * @return
     */
    public static WXPayReport getInstance(WXPayConfig config) {
        if (INSTANCE == null) {
            synchronized (WXPayReport.class) {
                if (INSTANCE == null) {
                    INSTANCE = new WXPayReport(config);
                }
            }
        }
        return INSTANCE;
    }
    public void report(String uuid, long elapsedTimeMillis,
                       String firstDomain, boolean primaryDomain, int firstConnectTimeoutMillis, int firstReadTimeoutMillis,
                       boolean firstHasDnsError, boolean firstHasConnectTimeout, boolean firstHasReadTimeout) {
        long currentTimestamp = WXPayUtil.getCurrentTimestamp();
        ReportInfo reportInfo = new ReportInfo(uuid, currentTimestamp, elapsedTimeMillis,
                firstDomain, primaryDomain, firstConnectTimeoutMillis, firstReadTimeoutMillis,
                firstHasDnsError, firstHasConnectTimeout, firstHasReadTimeout);
        String data = reportInfo.toLineString(config.getKey());
        WXPayUtil.getLogger().info("report {}", data);
        if (data != null) {
            reportMsgQueue.offer(data);
        }
    }
    @Deprecated
    private void reportSync(final String data) throws Exception {
        httpRequest(data, DEFAULT_CONNECT_TIMEOUT_MS, DEFAULT_READ_TIMEOUT_MS);
    }
    @Deprecated
    private void reportAsync(final String data) throws Exception {
        new Thread(new Runnable() {
            public void run() {
                try {
                    httpRequest(data, DEFAULT_CONNECT_TIMEOUT_MS, DEFAULT_READ_TIMEOUT_MS);
                }
                catch (Exception ex) {
                    WXPayUtil.getLogger().warn("report fail. reason: {}", ex.getMessage());
                }
            }
        }).start();
    }
    /**
     * http 请求
     * @param data
     * @param connectTimeoutMs
     * @param readTimeoutMs
     * @return
     * @throws Exception
     */
    private static String httpRequest(String data, int connectTimeoutMs, int readTimeoutMs) throws Exception{
        BasicHttpClientConnectionManager connManager;
        connManager = new BasicHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", SSLConnectionSocketFactory.getSocketFactory())
                        .build(),
                null,
                null,
                null
        );
        HttpClient httpClient = HttpClientBuilder.create()
                .setConnectionManager(connManager)
                .build();
        HttpPost httpPost = new HttpPost(REPORT_URL);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeoutMs).setConnectTimeout(connectTimeoutMs).build();
        httpPost.setConfig(requestConfig);
        StringEntity postEntity = new StringEntity(data, "UTF-8");
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.addHeader("User-Agent", WXPayConstants.USER_AGENT);
        httpPost.setEntity(postEntity);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        return EntityUtils.toString(httpEntity, "UTF-8");
    }
}

+ 258 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/wxconfig/WXPayRequest.java

@ -0,0 +1,258 @@
package com.yihu.jw.care.wxconfig;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.security.SecureRandom;
import static com.github.wxpay.sdk.WXPayConstants.USER_AGENT;
public class WXPayRequest {
    private WXPayConfig config;
    public WXPayRequest(WXPayConfig config) throws Exception{
        this.config = config;
    }
    /**
     * 请求,只请求一次,不做重试
     * @param domain
     * @param urlSuffix
     * @param uuid
     * @param data
     * @param connectTimeoutMs
     * @param readTimeoutMs
     * @param useCert 是否使用证书,针对退款、撤销等操作
     * @return
     * @throws Exception
     */
    private String requestOnce(final String domain, String urlSuffix, String uuid, String data, int connectTimeoutMs, int readTimeoutMs, boolean useCert) throws Exception {
        BasicHttpClientConnectionManager connManager;
        if (useCert) {
            // 证书
            char[] password = config.getMchID().toCharArray();
            InputStream certStream = config.getCertStream();
            KeyStore ks = KeyStore.getInstance("PKCS12");
            ks.load(certStream, password);
            // 实例化密钥库 & 初始化密钥工厂
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(ks, password);
            // 创建 SSLContext
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                    sslContext,
                    new String[]{"TLSv1"},
                    null,
                    new DefaultHostnameVerifier());
            connManager = new BasicHttpClientConnectionManager(
                    RegistryBuilder.<ConnectionSocketFactory>create()
                            .register("http", PlainConnectionSocketFactory.getSocketFactory())
                            .register("https", sslConnectionSocketFactory)
                            .build(),
                    null,
                    null,
                    null
            );
        }
        else {
            connManager = new BasicHttpClientConnectionManager(
                    RegistryBuilder.<ConnectionSocketFactory>create()
                            .register("http", PlainConnectionSocketFactory.getSocketFactory())
                            .register("https", SSLConnectionSocketFactory.getSocketFactory())
                            .build(),
                    null,
                    null,
                    null
            );
        }
        HttpClient httpClient = HttpClientBuilder.create()
                .setConnectionManager(connManager)
                .build();
        String url = "https://" + domain + urlSuffix;
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeoutMs).setConnectTimeout(connectTimeoutMs).build();
        httpPost.setConfig(requestConfig);
        StringEntity postEntity = new StringEntity(data, "UTF-8");
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.addHeader("User-Agent", USER_AGENT + " " + config.getMchID());
        httpPost.setEntity(postEntity);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        return EntityUtils.toString(httpEntity, "UTF-8");
    }
    private String request(String urlSuffix, String uuid, String data, int connectTimeoutMs, int readTimeoutMs, boolean useCert, boolean autoReport) throws Exception {
        Exception exception = null;
        long elapsedTimeMillis = 0;
        long startTimestampMs = WXPayUtil.getCurrentTimestampMs();
        boolean firstHasDnsErr = false;
        boolean firstHasConnectTimeout = false;
        boolean firstHasReadTimeout = false;
        IWXPayDomain.DomainInfo domainInfo = config.getWXPayDomain().getDomain(config);
        if(domainInfo == null){
            throw new Exception("WXPayConfig.getWXPayDomain().getDomain() is empty or null");
        }
        try {
            String result = requestOnce(domainInfo.domain, urlSuffix, uuid, data, connectTimeoutMs, readTimeoutMs, useCert);
            elapsedTimeMillis = WXPayUtil.getCurrentTimestampMs()-startTimestampMs;
            config.getWXPayDomain().report(domainInfo.domain, elapsedTimeMillis, null);
            WXPayReport.getInstance(config).report(
                    uuid,
                    elapsedTimeMillis,
                    domainInfo.domain,
                    domainInfo.primaryDomain,
                    connectTimeoutMs,
                    readTimeoutMs,
                    firstHasDnsErr,
                    firstHasConnectTimeout,
                    firstHasReadTimeout);
            return result;
        }
        catch (UnknownHostException ex) {  // dns 解析错误,或域名不存在
            exception = ex;
            firstHasDnsErr = true;
            elapsedTimeMillis = WXPayUtil.getCurrentTimestampMs()-startTimestampMs;
            WXPayUtil.getLogger().warn("UnknownHostException for domainInfo {}", domainInfo);
            WXPayReport.getInstance(config).report(
                    uuid,
                    elapsedTimeMillis,
                    domainInfo.domain,
                    domainInfo.primaryDomain,
                    connectTimeoutMs,
                    readTimeoutMs,
                    firstHasDnsErr,
                    firstHasConnectTimeout,
                    firstHasReadTimeout
            );
        }
        catch (ConnectTimeoutException ex) {
            exception = ex;
            firstHasConnectTimeout = true;
            elapsedTimeMillis = WXPayUtil.getCurrentTimestampMs()-startTimestampMs;
            WXPayUtil.getLogger().warn("connect timeout happened for domainInfo {}", domainInfo);
            WXPayReport.getInstance(config).report(
                    uuid,
                    elapsedTimeMillis,
                    domainInfo.domain,
                    domainInfo.primaryDomain,
                    connectTimeoutMs,
                    readTimeoutMs,
                    firstHasDnsErr,
                    firstHasConnectTimeout,
                    firstHasReadTimeout
            );
        }
        catch (SocketTimeoutException ex) {
            exception = ex;
            firstHasReadTimeout = true;
            elapsedTimeMillis = WXPayUtil.getCurrentTimestampMs()-startTimestampMs;
            WXPayUtil.getLogger().warn("timeout happened for domainInfo {}", domainInfo);
            WXPayReport.getInstance(config).report(
                    uuid,
                    elapsedTimeMillis,
                    domainInfo.domain,
                    domainInfo.primaryDomain,
                    connectTimeoutMs,
                    readTimeoutMs,
                    firstHasDnsErr,
                    firstHasConnectTimeout,
                    firstHasReadTimeout);
        }
        catch (Exception ex) {
            exception = ex;
            elapsedTimeMillis = WXPayUtil.getCurrentTimestampMs()-startTimestampMs;
            WXPayReport.getInstance(config).report(
                    uuid,
                    elapsedTimeMillis,
                    domainInfo.domain,
                    domainInfo.primaryDomain,
                    connectTimeoutMs,
                    readTimeoutMs,
                    firstHasDnsErr,
                    firstHasConnectTimeout,
                    firstHasReadTimeout);
        }
        config.getWXPayDomain().report(domainInfo.domain, elapsedTimeMillis, exception);
        throw exception;
    }
    /**
     * 可重试的,非双向认证的请求
     * @param urlSuffix
     * @param uuid
     * @param data
     * @return
     */
    public String requestWithoutCert(String urlSuffix, String uuid, String data, boolean autoReport) throws Exception {
        return this.request(urlSuffix, uuid, data, config.getHttpConnectTimeoutMs(), config.getHttpReadTimeoutMs(), false, autoReport);
    }
    /**
     * 可重试的,非双向认证的请求
     * @param urlSuffix
     * @param uuid
     * @param data
     * @param connectTimeoutMs
     * @param readTimeoutMs
     * @return
     */
    public String requestWithoutCert(String urlSuffix, String uuid, String data, int connectTimeoutMs, int readTimeoutMs,  boolean autoReport) throws Exception {
        return this.request(urlSuffix, uuid, data, connectTimeoutMs, readTimeoutMs, false, autoReport);
    }
    /**
     * 可重试的,双向认证的请求
     * @param urlSuffix
     * @param uuid
     * @param data
     * @return
     */
    public String requestWithCert(String urlSuffix, String uuid, String data, boolean autoReport) throws Exception {
        return this.request(urlSuffix, uuid, data, config.getHttpConnectTimeoutMs(), config.getHttpReadTimeoutMs(), true, autoReport);
    }
    /**
     * 可重试的,双向认证的请求
     * @param urlSuffix
     * @param uuid
     * @param data
     * @param connectTimeoutMs
     * @param readTimeoutMs
     * @return
     */
    public String requestWithCert(String urlSuffix, String uuid, String data, int connectTimeoutMs, int readTimeoutMs, boolean autoReport) throws Exception {
        return this.request(urlSuffix, uuid, data, connectTimeoutMs, readTimeoutMs, true, autoReport);
    }
}

+ 294 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/wxconfig/WXPayUtil.java

@ -0,0 +1,294 @@
package com.yihu.jw.care.wxconfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.*;
public class WXPayUtil {
    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final Random RANDOM = new SecureRandom();
    /**
     * XML格式字符串转换为Map
     *
     * @param strXML XML字符串
     * @return XML数据转换后的Map
     * @throws Exception
     */
    public static Map<String, String> xmlToMap(String strXML) throws Exception {
        try {
            Map<String, String> data = new HashMap<String, String>();
            DocumentBuilder documentBuilder = WXPayXmlUtil.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                // do nothing
            }
            return data;
        } catch (Exception ex) {
            WXPayUtil.getLogger().warn("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(), strXML);
            throw ex;
        }
    }
    /**
     * 将Map转换为XML格式的字符串
     *
     * @param data Map类型数据
     * @return XML格式的字符串
     * @throws Exception
     */
    public static String mapToXml(Map<String, String> data) throws Exception {
        org.w3c.dom.Document document = WXPayXmlUtil.newDocument();
        org.w3c.dom.Element root = document.createElement("xml");
        document.appendChild(root);
        for (String key: data.keySet()) {
            String value = data.get(key);
            if (value == null) {
                value = "";
            }
            value = value.trim();
            org.w3c.dom.Element filed = document.createElement(key);
            filed.appendChild(document.createTextNode(value));
            root.appendChild(filed);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
        try {
            writer.close();
        }
        catch (Exception ex) {
        }
        return output;
    }
    /**
     * 生成带有 sign 的 XML 格式字符串
     *
     * @param data Map类型数据
     * @param key API密钥
     * @return 含有sign字段的XML
     */
    public static String generateSignedXml(final Map<String, String> data, String key) throws Exception {
        return generateSignedXml(data, key, WXPayConstants.SignType.MD5);
    }
    /**
     * 生成带有 sign 的 XML 格式字符串
     *
     * @param data Map类型数据
     * @param key API密钥
     * @param signType 签名类型
     * @return 含有sign字段的XML
     */
    public static String generateSignedXml(final Map<String, String> data, String key, WXPayConstants.SignType signType) throws Exception {
        String sign = generateSignature(data, key, signType);
        data.put(WXPayConstants.FIELD_SIGN, sign);
        return mapToXml(data);
    }
    /**
     * 判断签名是否正确
     *
     * @param xmlStr XML格式数据
     * @param key API密钥
     * @return 签名是否正确
     * @throws Exception
     */
    public static boolean isSignatureValid(String xmlStr, String key) throws Exception {
        Map<String, String> data = xmlToMap(xmlStr);
        if (!data.containsKey(WXPayConstants.FIELD_SIGN) ) {
            return false;
        }
        String sign = data.get(WXPayConstants.FIELD_SIGN);
        return generateSignature(data, key).equals(sign);
    }
    /**
     * 判断签名是否正确,必须包含sign字段,否则返回false。使用MD5签名。
     *
     * @param data Map类型数据
     * @param key API密钥
     * @return 签名是否正确
     * @throws Exception
     */
    public static boolean isSignatureValid(Map<String, String> data, String key) throws Exception {
        return isSignatureValid(data, key, WXPayConstants.SignType.MD5);
    }
    /**
     * 判断签名是否正确,必须包含sign字段,否则返回false。
     *
     * @param data Map类型数据
     * @param key API密钥
     * @param signType 签名方式
     * @return 签名是否正确
     * @throws Exception
     */
    public static boolean isSignatureValid(Map<String, String> data, String key, WXPayConstants.SignType signType) throws Exception {
        if (!data.containsKey(WXPayConstants.FIELD_SIGN) ) {
            return false;
        }
        String sign = data.get(WXPayConstants.FIELD_SIGN);
        return generateSignature(data, key, signType).equals(sign);
    }
    /**
     * 生成签名
     *
     * @param data 待签名数据
     * @param key API密钥
     * @return 签名
     */
    public static String generateSignature(final Map<String, String> data, String key) throws Exception {
        return generateSignature(data, key, WXPayConstants.SignType.MD5);
    }
    /**
     * 生成签名. 注意,若含有sign_type字段,必须和signType参数保持一致。
     *
     * @param data 待签名数据
     * @param key API密钥
     * @param signType 签名方式
     * @return 签名
     */
    public static String generateSignature(final Map<String, String> data, String key, WXPayConstants.SignType signType) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals(WXPayConstants.FIELD_SIGN)) {
                continue;
            }
            if (data.get(k).trim().length() > 0) // 参数值为空,则不参与签名
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
        }
        sb.append("key=").append(key);
        if (WXPayConstants.SignType.MD5.equals(signType)) {
            return MD5(sb.toString()).toUpperCase();
        }
        else if (WXPayConstants.SignType.HMACSHA256.equals(signType)) {
            return HMACSHA256(sb.toString(), key);
        }
        else {
            throw new Exception(String.format("Invalid sign_type: %s", signType));
        }
    }
    /**
     * 获取随机字符串 Nonce Str
     *
     * @return String 随机字符串
     */
    public static String generateNonceStr() {
        char[] nonceChars = new char[32];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }
    /**
     * 生成 MD5
     *
     * @param data 待处理数据
     * @return MD5结果
     */
    public static String MD5(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }
    /**
     * 生成 HMACSHA256
     * @param data 待处理数据
     * @param key 密钥
     * @return 加密结果
     * @throws Exception
     */
    public static String HMACSHA256(String data, String key) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }
    /**
     * 日志
     * @return
     */
    public static Logger getLogger() {
        Logger logger = LoggerFactory.getLogger("wxpay java sdk");
        return logger;
    }
    /**
     * 获取当前时间戳,单位秒
     * @return
     */
    public static long getCurrentTimestamp() {
        return System.currentTimeMillis()/1000;
    }
    /**
     * 获取当前时间戳,单位毫秒
     * @return
     */
    public static long getCurrentTimestampMs() {
        return System.currentTimeMillis();
    }
}

+ 30 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/wxconfig/WXPayXmlUtil.java

@ -0,0 +1,30 @@
package com.yihu.jw.care.wxconfig;
import org.w3c.dom.Document;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
/**
 * 2018/7/3
 */
public final class WXPayXmlUtil {
    public static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        documentBuilderFactory.setXIncludeAware(false);
        documentBuilderFactory.setExpandEntityReferences(false);
        return documentBuilderFactory.newDocumentBuilder();
    }
    public static Document newDocument() throws ParserConfigurationException {
        return newDocumentBuilder().newDocument();
    }
}

+ 9 - 1
svr/svr-cloud-care/src/main/resources/application.yml

@ -132,6 +132,8 @@ hospital:
wechat:
  appId: wxd03f859efdf0873d
  appSecret: 2935b54b53a957d9516c920a544f2537
  apiKey: zhongjianxinlianxiamenkejiyouxia
  mchId: 1611059985
  wechat_token: 27eb3bb24f149a7760cf1bb154b08040
  wechat_base_url: http%3a%2f%2fweixin.xmtyw.cn%2fwlyy-dev
  accId: gh_ffd64560fb21
@ -228,6 +230,8 @@ hospital:
wechat:
  appId: wxd03f859efdf0873d
  appSecret: 2935b54b53a957d9516c920a544f2537
  apiKey: zhongjianxinlianxiamenkejiyouxia
  mchId: 1611059985
  wechat_token: 27eb3bb24f149a7760cf1bb154b08040
  wechat_base_url: http%3a%2f%2fweixin.xmtyw.cn%2fwlyy-dev
  accId: gh_ffd64560fb21
@ -332,6 +336,8 @@ hospital:
wechat:
  appId: wxd03f859efdf0873d
  appSecret: 2935b54b53a957d9516c920a544f2537
  apiKey: zhongjianxinlianxiamenkejiyouxia
  mchId: 1611059985
  wechat_token: 27eb3bb24f149a7760cf1bb154b08040
  wechat_base_url: http%3a%2f%2fweixin.xmtyw.cn%2fwlyy-dev
  accId: gh_ffd64560fb21
@ -439,8 +445,10 @@ hospital:
wechat:
  appId: wx2c55f5b7b2f3cb56
  appSecret: 0dd9927e58125ad5f0efb9299860d145
  apiKey: zhongjianxinlianxiamenkejiyouxia
  mchId: 1611059985
  wechat_token: 27eb3bb24f149a7760cf1bb154b08041
  wechat_base_url: https%3A%2F%2Fzhyzh.hzxc.gov.cn%2Fcityihealth%2FcloudCare%2F
  wechat_base_url: https%3A%2F%2Fzhyzh.hzxc.gov.cn%2FcloudCare%2F
  accId: gh_da06ed9e5751
  id: hz_yyyzh_wx  # base库中,wx_wechat 的id字段
  flag: true #演示环境  true走Mysql数据库  false走Oracle

+ 298 - 0
svr/svr-cloud-care/src/main/resources/wechat/README.md

@ -0,0 +1,298 @@
微信支付 Java SDK
------
对[微信支付开发者文档](https://pay.weixin.qq.com/wiki/doc/api/index.html)中给出的API进行了封装。
com.github.wxpay.sdk.WXPay类下提供了对应的方法:
|方法名 | 说明 |
|--------|--------|
|microPay| 刷卡支付 |
|unifiedOrder | 统一下单|
|orderQuery | 查询订单 |
|reverse | 撤销订单 |
|closeOrder|关闭订单|
|refund|申请退款|
|refundQuery|查询退款|
|downloadBill|下载对账单|
|report|交易保障|
|shortUrl|转换短链接|
|authCodeToOpenid|授权码查询openid|
* 注意:
* 证书文件不能放在web服务器虚拟目录,应放在有访问权限控制的目录中,防止被他人下载
* 建议将证书文件名改为复杂且不容易猜测的文件名
* 商户服务器要做好病毒和木马防护工作,不被非法侵入者窃取证书文件
* 请妥善保管商户支付密钥、公众帐号SECRET,避免密钥泄露
* 参数为`Map<String, String>`对象,返回类型也是`Map<String, String>`
* 方法内部会将参数会转换成含有`appid`、`mch_id`、`nonce_str`、`sign\_type`和`sign`的XML
* 可选HMAC-SHA256算法和MD5算法签名
* 通过HTTPS请求得到返回数据后会对其做必要的处理(例如验证签名,签名错误则抛出异常)
* 对于downloadBill,无论是否成功都返回Map,且都含有`return_code`和`return_msg`,若成功,其中`return_code`为`SUCCESS`,另外`data`对应对账单数据
## 示例
配置类MyConfig:
```java
import com.github.wxpay.sdk.WXPayConfig;
import java.io.*;
public class MyConfig implements WXPayConfig{
    private byte[] certData;
    public MyConfig() throws Exception {
        String certPath = "/path/to/apiclient_cert.p12";
        File file = new File(certPath);
        InputStream certStream = new FileInputStream(file);
        this.certData = new byte[(int) file.length()];
        certStream.read(this.certData);
        certStream.close();
    }
    public String getAppID() {
        return "wx8888888888888888";
    }
    public String getMchID() {
        return "12888888";
    }
    public String getKey() {
        return "88888888888888888888888888888888";
    }
    public InputStream getCertStream() {
        ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData);
        return certBis;
    }
    public int getHttpConnectTimeoutMs() {
        return 8000;
    }
    public int getHttpReadTimeoutMs() {
        return 10000;
    }
}
```
统一下单:
```java
import com.github.wxpay.sdk.WXPay;
import java.util.HashMap;
import java.util.Map;
public class WXPayExample {
    public static void main(String[] args) throws Exception {
        MyConfig config = new MyConfig();
        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "腾讯充值中心-QQ会员充值");
        data.put("out_trade_no", "2016090910595900000012");
        data.put("device_info", "");
        data.put("fee_type", "CNY");
        data.put("total_fee", "1");
        data.put("spbill_create_ip", "123.12.12.123");
        data.put("notify_url", "http://www.example.com/wxpay/notify");
        data.put("trade_type", "NATIVE");  // 此处指定为扫码支付
        data.put("product_id", "12");
        try {
            Map<String, String> resp = wxpay.unifiedOrder(data);
            System.out.println(resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```
订单查询:
```java
import com.github.wxpay.sdk.WXPay;
import java.util.HashMap;
import java.util.Map;
public class WXPayExample {
    public static void main(String[] args) throws Exception {
        MyConfig config = new MyConfig();
        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", "2016090910595900000012");
        try {
            Map<String, String> resp = wxpay.orderQuery(data);
            System.out.println(resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```
退款查询:
```java
import com.github.wxpay.sdk.WXPay;
import java.util.HashMap;
import java.util.Map;
public class WXPayExample {
    public static void main(String[] args) throws Exception {
        MyConfig config = new MyConfig();
        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", "2016090910595900000012");
        try {
            Map<String, String> resp = wxpay.refundQuery(data);
            System.out.println(resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```
下载对账单:
```java
import com.github.wxpay.sdk.WXPay;
import java.util.HashMap;
import java.util.Map;
public class WXPayExample {
    public static void main(String[] args) throws Exception {
        MyConfig config = new MyConfig();
        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<String, String>();
        data.put("bill_date", "20140603");
        data.put("bill_type", "ALL");
        try {
            Map<String, String> resp = wxpay.downloadBill(data);
            System.out.println(resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```
其他API的使用和上面类似。
暂时不支持下载压缩格式的对账单,但可以使用该SDK生成请求用的XML数据:
```java
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import java.util.HashMap;
import java.util.Map;
public class WXPayExample {
    public static void main(String[] args) throws Exception {
        MyConfig config = new MyConfig();
        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<String, String>();
        data.put("bill_date", "20140603");
        data.put("bill_type", "ALL");
        data.put("tar_type", "GZIP");
        try {
            data = wxpay.fillRequestData(data);
            System.out.println(WXPayUtil.mapToXml(data));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```
收到支付结果通知时,需要验证签名,可以这样做:
```java
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import java.util.Map;
public class WXPayExample {
    public static void main(String[] args) throws Exception {
        String notifyData = "...."; // 支付结果通知的xml格式数据
        MyConfig config = new MyConfig();
        WXPay wxpay = new WXPay(config);
        Map<String, String> notifyMap = WXPayUtil.xmlToMap(notifyData);  // 转换成map
        if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {
            // 签名正确
            // 进行处理。
            // 注意特殊情况:订单已经退款,但收到了支付结果成功的通知,不应把商户侧订单状态从退款改成支付成功
        }
        else {
            // 签名错误,如果数据里没有sign字段,也认为是签名错误
        }
    }
}
```
HTTPS请求可选HMAC-SHA256算法和MD5算法签名:
```
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
public class WXPayExample {
    public static void main(String[] args) throws Exception {
        MyConfig config = new MyConfig();
        WXPay wxpay = new WXPay(config, WXPayConstants.SignType.HMACSHA256);
        // ......
    }
}
```
若需要使用sandbox环境:
```
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
public class WXPayExample {
    public static void main(String[] args) throws Exception {
        MyConfig config = new MyConfig();
        WXPay wxpay = new WXPay(config, WXPayConstants.SignType.MD5, true);
        // ......
    }
}
```

BIN
svr/svr-cloud-care/src/main/resources/wechat/apiclient_cert.p12


+ 24 - 0
svr/svr-cloud-care/src/main/resources/wechat/apiclient_cert.pem

@ -0,0 +1,24 @@
-----BEGIN CERTIFICATE-----
MIID9jCCAt6gAwIBAgIUP5vgF5jYeVCwLihSnKh9fiuL3JAwDQYJKoZIhvcNAQEL
BQAwXjELMAkGA1UEBhMCQ04xEzARBgNVBAoTClRlbnBheS5jb20xHTAbBgNVBAsT
FFRlbnBheS5jb20gQ0EgQ2VudGVyMRswGQYDVQQDExJUZW5wYXkuY29tIFJvb3Qg
Q0EwHhcNMjEwNjI4MDg0NzEwWhcNMjYwNjI3MDg0NzEwWjCBhzETMBEGA1UEAwwK
MTYxMTA1OTk4NTEbMBkGA1UECgwS5b6u5L+h5ZWG5oi357O757ufMTMwMQYDVQQL
DCrkvJflgaXkv6HogZTvvIjmna3lt57vvInnp5HmioDmnInpmZDlhazlj7gxCzAJ
BgNVBAYMAkNOMREwDwYDVQQHDAhTaGVuWmhlbjCCASIwDQYJKoZIhvcNAQEBBQAD
ggEPADCCAQoCggEBAMPDQiBC4iyBKmyWmBVRqQMOqYET0CK4P3zdxRvvHe6TbC+B
DbzT3NNbCBeqJ3qS8p4c3SptzxTr0P7q3ixNs7Lvl8oJLeYm+vi9wwF2sqzOBYGn
0i9snmKBWCq0KtNaMz8Y86XKGwdmuUXgHEp88foad12KYJPdp1MuonBv6DSs4KYK
nhTy24fpyFFSlvVqMHAHFUCiUYZIxvv5vkzgyS5c5aQeMCRV+xVoN88uAQNAiCli
+cBoDS5fpH2ahqhupHEUEj1iQunI9BcAOgukFszaL9l/L/LSvA7kZQKtZbO69U3r
wYwJ9inJw7warp6hqJiaL5eFuG5N56Y5uaVxD6cCAwEAAaOBgTB/MAkGA1UdEwQC
MAAwCwYDVR0PBAQDAgTwMGUGA1UdHwReMFwwWqBYoFaGVGh0dHA6Ly9ldmNhLml0
cnVzLmNvbS5jbi9wdWJsaWMvaXRydXNjcmw/Q0E9MUJENDIyMEU1MERCQzA0QjA2
QUQzOTc1NDk4NDZDMDFDM0U4RUJEMjANBgkqhkiG9w0BAQsFAAOCAQEAXhesamB9
4zIxgIEBWZNgSL0tL8Q/HoPfDCssK4BPz7fREx+fGPMZ8K3AVPaRuT1kuXABm/XA
qHVLkUPGtVJvu/DpQSWz9OESD35UEvYhm42V1drj5eMjuwQS7JXMLaH5WaUwR8/p
Dx664gbOgXbUEjVvoHDuqa6fiIGrqtGNNMDbscwK0iL2mUpk34UunuNZUkZdkfs3
ZNlzEfRHQZ6TNZTbNakTRZjG3oVnT2/ZEr+nIVe75ikm22eoTENio7wNoNdv+jDo
LLgoIhqIY5b09jZG1qe3YIBIaBoK3FIuuBFsa03TBvj7QuBJ4JdAYs1f+babAeAJ
c0RBy1fNJgScaA==
-----END CERTIFICATE-----

+ 28 - 0
svr/svr-cloud-care/src/main/resources/wechat/apiclient_key.pem

@ -0,0 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDDw0IgQuIsgSps
lpgVUakDDqmBE9AiuD983cUb7x3uk2wvgQ2809zTWwgXqid6kvKeHN0qbc8U69D+
6t4sTbOy75fKCS3mJvr4vcMBdrKszgWBp9IvbJ5igVgqtCrTWjM/GPOlyhsHZrlF
4BxKfPH6GnddimCT3adTLqJwb+g0rOCmCp4U8tuH6chRUpb1ajBwBxVAolGGSMb7
+b5M4MkuXOWkHjAkVfsVaDfPLgEDQIgpYvnAaA0uX6R9moaobqRxFBI9YkLpyPQX
ADoLpBbM2i/Zfy/y0rwO5GUCrWWzuvVN68GMCfYpycO8Gq6eoaiYmi+XhbhuTeem
ObmlcQ+nAgMBAAECggEAd4MbOarbfaQVjFmb21gRQKaQ4RaBeNDXIZoaneUrdt1V
rOKyylbld7sZg6kDlRdlOxYQB7kmNXWKEDa/EHkXfeQ73MIh3WJq0bS3+orGpizY
u8EC1qUPRMAGXXvEsWdd5eWLyelK+wfBkGEzpF4HNFM4EElMkLk/T88mqFIJhy35
xks6HZ0gAtMG5Y8ze8iAtvQfiCr51K/njTK6/LdO/+NZ2n0J6kD62T63OZcIcIYD
oYuFfUY58rqfMHSJ6LXXqVtF+mtUeL3DSwYQoaSCZJ6sLuZLqdWK3dOP1DUVQEdx
E+uW3hzT4ViB263rJvEPZxgfvQQ79ZHZAGH6RsJ5wQKBgQDu1uJRU6O7d7Ifi1Dg
1Y5l3gBIz+d776lg2UP9foDYHYFtW8F51vmnwR2Nx2wsFZTWTz1p1EVKxyOhSPz3
tTnzKlLy/zA+JgJtkTAlWbwfW8ixr3stVQxbrk1QcTVT55T9vRqLfdGLwrACZGkL
tGiJVcvrOdGtv7FKOrcAO04sNwKBgQDR1AoVfj7z1oKPjBZ2Dq9yexBQ+ZaekHTP
R6PFv89kDNzKIcy4TZKNIYePp3Wm9xLMLY/LbCTc8A3eJuLgV6zTk7IQgMTOFWRZ
I+VTY2qBql2XG5p4rcNgpmtoNaiwIuf7xGJSY7sFE5lYLWBVPuKqK1OeABUCd8DM
9WcXffDgEQKBgGMsbStR7KHyUM9SXRIO+yMHbNzPH5LR8GYbsWS4O64BinWrbQo3
ntDummP908f2aigXHSwtjVxAlmXpVclRwi9bergWCKU1yTpP2EsaGMh4pzxI3n/z
Wb9UAByP9ZHSjoZSGIylgPZksAs+QHQwxFuKebNB/fQErgxhlw2Mkqg/AoGBAL8e
IFU1WUel0ePH2EmN1LY0a0cmHs+sigimmwAqVk8t/AjMQnh4h4yuxpfNEreSgfeh
ZEEH7oeiyy7WQn3Ovec0ttKbRybiizU6Ic4TVlZmg7p39PoIY1XsHxabEVvlX2GN
nXSnzBeyo1CSfBUJI1GWByJ5tqk5xE2rFExsdPLRAoGBAM087YnVLfzKPMiE8nc+
ocTDdnBwBFQseYdfJl+dGoE8IBL+7GGQsT5lCYGbXk5iYOnboyOGfPPqUA/jUZU3
tN1uJA267gQJl8qrghDBeiWl2KkrJz0/BYw+5RR9oUwWSf17N48kiwjod+1lPyaQ
70ldmbdfITOESSvdRZ+hbAQ0
-----END PRIVATE KEY-----

+ 18 - 0
svr/svr-cloud-care/src/main/resources/wechat/证书使用说明.txt

@ -0,0 +1,18 @@
欢迎使用微信支付!
附件中的三份文件(证书pkcs12格式、证书pem格式、证书密钥pem格式),为接口中强制要求时需携带的证书文件。
证书属于敏感信息,请妥善保管不要泄露和被他人复制。
不同开发语言下的证书格式不同,以下为说明指引:
    证书pkcs12格式(apiclient_cert.p12)
        包含了私钥信息的证书文件,为p12(pfx)格式,由微信支付签发给您用来标识和界定您的身份
        部分安全性要求较高的API需要使用该证书来确认您的调用身份
        windows上可以直接双击导入系统,导入过程中会提示输入证书密码,证书密码默认为您的商户号(如:1900006031)
    证书pem格式(apiclient_cert.pem)
        从apiclient_cert.p12中导出证书部分的文件,为pem格式,请妥善保管不要泄漏和被他人复制
        部分开发语言和环境,不能直接使用p12文件,而需要使用pem,所以为了方便您使用,已为您直接提供
        您也可以使用openssl命令来自己导出:openssl pkcs12 -clcerts -nokeys -in apiclient_cert.p12 -out apiclient_cert.pem
    证书密钥pem格式(apiclient_key.pem)
        从apiclient_cert.p12中导出密钥部分的文件,为pem格式
        部分开发语言和环境,不能直接使用p12文件,而需要使用pem,所以为了方便您使用,已为您直接提供
        您也可以使用openssl命令来自己导出:openssl pkcs12 -nocerts -in apiclient_cert.p12 -out apiclient_key.pem
备注说明:  
        由于绝大部分操作系统已内置了微信支付服务器证书的根CA证书,  2018年3月6日后, 不再提供CA证书文件(rootca.pem)下载