Trick 6 yıl önce
ebeveyn
işleme
eed261afcf
24 değiştirilmiş dosya ile 1893 ekleme ve 91 silme
  1. 2 0
      business/base-service/src/main/java/com/yihu/jw/message/dao/MessageDao.java
  2. 4 0
      business/base-service/src/main/java/com/yihu/jw/message/service/MessageService.java
  3. 16 1
      business/base-service/src/main/java/com/yihu/jw/patient/service/BasePatientService.java
  4. 29 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/security/RSA.java
  5. 20 0
      common/common-entity/src/main/java/com/yihu/jw/entity/myFamily/PatientApplyLog.java
  6. 8 0
      common/common-request-mapping/src/main/java/com/yihu/jw/rm/patient/PatientRequestMapping.java
  7. 4 0
      common/common-util/pom.xml
  8. 79 8
      common/common-util/src/main/java/com/yihu/jw/util/common/RSAUtils.java
  9. 812 0
      common/common-util/src/main/java/com/yihu/jw/util/common/XMLUtil.java
  10. 59 0
      common/common-util/src/main/java/com/yihu/jw/util/wechat/WXPayConstants.java
  11. 148 0
      common/common-util/src/main/java/com/yihu/jw/util/wechat/WeiXinPayUtils.java
  12. 0 39
      svr/svr-base/pom.xml
  13. 7 0
      svr/svr-patient/src/main/java/com/yihu/jw/patient/dao/myFamily/PatientApplyLogDao.java
  14. 6 0
      svr/svr-patient/src/main/java/com/yihu/jw/patient/dao/personal_info/PatientDao.java
  15. 14 0
      svr/svr-patient/src/main/java/com/yihu/jw/patient/dao/security/RSADao.java
  16. 375 0
      svr/svr-patient/src/main/java/com/yihu/jw/patient/endpoint/patient/PatientInfoEndpint.java
  17. 2 2
      svr/svr-patient/src/main/java/com/yihu/jw/patient/endpoint/personal_info/PatientEndpoint.java
  18. 77 21
      svr/svr-patient/src/main/java/com/yihu/jw/patient/service/myFamily/MyFamilyService.java
  19. 12 1
      svr/svr-patient/src/main/java/com/yihu/jw/patient/service/myFamily/PatientApplyLogService.java
  20. 10 18
      svr/svr-patient/src/main/java/com/yihu/jw/patient/service/personal_Info/PatientService.java
  21. 20 0
      svr/svr-patient/src/main/java/com/yihu/jw/patient/util/CommonUtils.java
  22. 182 0
      svr/svr-patient/src/main/java/com/yihu/jw/patient/util/RSAService.java
  23. 1 1
      svr/svr-patient/src/main/resources/bootstrap.yml
  24. 6 0
      wlyy-parent-pom/pom.xml

+ 2 - 0
business/base-service/src/main/java/com/yihu/jw/message/dao/MessageDao.java

@ -19,4 +19,6 @@ public interface MessageDao extends PagingAndSortingRepository<BaseMessageDO, St
    @Query("select count(m.id) from BaseMessageDO m where m.platform=?1 and m.receiver=?2 and m.saasId=?3 and m.del=1 and m.msgTypeCode like ?4 and m.readState=1")
    @Query("select count(m.id) from BaseMessageDO m where m.platform=?1 and m.receiver=?2 and m.saasId=?3 and m.del=1 and m.msgTypeCode like ?4 and m.readState=1")
    Integer countMessage(Integer platform, String code, String saasId,String msgTypeCode);
    Integer countMessage(Integer platform, String code, String saasId,String msgTypeCode);
    BaseMessageDO findById(Integer id);
}
}

+ 4 - 0
business/base-service/src/main/java/com/yihu/jw/message/service/MessageService.java

@ -166,4 +166,8 @@ public class MessageService extends BaseJpaService<BaseMessageDO, MessageDao> {
        }
        }
    }
    }
    public BaseMessageDO findById(Integer id){
        return messageDao.findById(id);
    }
}
}

+ 16 - 1
business/base-service/src/main/java/com/yihu/jw/patient/service/BasePatientService.java

@ -10,6 +10,7 @@ import com.yihu.jw.patient.util.ConstantUtils;
import com.yihu.mysql.query.BaseJpaService;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.CrudRepository;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Transactional;
@ -34,7 +35,7 @@ import java.util.Set;
 * @since 1.
 * @since 1.
 */
 */
@Service
@Service
public class BasePatientService extends BaseJpaService<BasePatientDO, BasePatientDao> {
public class BasePatientService<T, R extends CrudRepository> extends BaseJpaService<BasePatientDO, BasePatientDao> {
    @Autowired
    @Autowired
    private BasePatientDao basePatientDao;
    private BasePatientDao basePatientDao;
@ -161,4 +162,18 @@ public class BasePatientService extends BaseJpaService<BasePatientDO, BasePatien
        }
        }
        return ConstantUtils.SUCCESS;
        return ConstantUtils.SUCCESS;
    }
    }
    /**
     * 根据patient的id获取居民信息
     * @param patient
     * @return
     */
    public BasePatientDO findByIdAndDel(String patient) throws Exception{
        BasePatientDO basePatientDO = basePatientDao.findByIdAndDel(patient,"1");
        if(basePatientDO==null){
            throw new Exception("not patient");
        }
        return basePatientDO;
    }
}
}

+ 29 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/security/RSA.java

@ -0,0 +1,29 @@
package com.yihu.jw.entity.base.security;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.Table;
/**
 * 非对象算法加密信息
 * @author George
 *
 */
@Entity
@Table(name = "dm_rsa")
public class RSA extends UuidIdentityEntity {
	private static final long serialVersionUID = 7832717679571844202L;
	
	private byte[] data;
	@Lob
	public byte[] getData() {
	    return data;
	}
	
	public void setData(byte[] data){
		this.data = data;
	}
}

+ 20 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/myFamily/PatientApplyLog.java

@ -3,6 +3,7 @@ package com.yihu.jw.entity.myFamily;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IntegerIdentityEntity;
import com.yihu.jw.entity.IntegerIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Table;
import java.util.Date;
import java.util.Date;
@ -23,7 +24,9 @@ public class PatientApplyLog extends IntegerIdentityEntity {
    private Date createTime;//创建时间
    private Date createTime;//创建时间
    private String createUser;//申请人
    private String createUser;//申请人
    private String createUserName;//申请人姓名
    private String createUserName;//申请人姓名
    private Integer remindType;//提醒方式(1、打电话,2、发短信,3、微信)
    @Column(name = "patient_family_member_name")
    public String getPatientFamilyMemberName() {
    public String getPatientFamilyMemberName() {
        return patientFamilyMemberName;
        return patientFamilyMemberName;
    }
    }
@ -32,6 +35,7 @@ public class PatientApplyLog extends IntegerIdentityEntity {
        this.patientFamilyMemberName = patientFamilyMemberName;
        this.patientFamilyMemberName = patientFamilyMemberName;
    }
    }
    @Column(name = "patient_family_member_code")
    public String getPatienyFamilyMemberCode() {
    public String getPatienyFamilyMemberCode() {
        return patienyFamilyMemberCode;
        return patienyFamilyMemberCode;
    }
    }
@ -40,6 +44,7 @@ public class PatientApplyLog extends IntegerIdentityEntity {
        this.patienyFamilyMemberCode = patienyFamilyMemberCode;
        this.patienyFamilyMemberCode = patienyFamilyMemberCode;
    }
    }
    @Column(name = "qr_code")
    public String getQrCode() {
    public String getQrCode() {
        return qrCode;
        return qrCode;
    }
    }
@ -48,6 +53,7 @@ public class PatientApplyLog extends IntegerIdentityEntity {
        this.qrCode = qrCode;
        this.qrCode = qrCode;
    }
    }
    @Column(name = "failure_time")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getFailureTime() {
    public Date getFailureTime() {
        return failureTime;
        return failureTime;
@ -57,6 +63,7 @@ public class PatientApplyLog extends IntegerIdentityEntity {
        this.failureTime = failureTime;
        this.failureTime = failureTime;
    }
    }
    @Column(name = "status")
    public Integer getStatus() {
    public Integer getStatus() {
        return status;
        return status;
    }
    }
@ -65,6 +72,7 @@ public class PatientApplyLog extends IntegerIdentityEntity {
        this.status = status;
        this.status = status;
    }
    }
    @Column(name = "del")
    public Integer getDel() {
    public Integer getDel() {
        return del;
        return del;
    }
    }
@ -73,6 +81,7 @@ public class PatientApplyLog extends IntegerIdentityEntity {
        this.del = del;
        this.del = del;
    }
    }
    @Column(name = "create_time")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCreateTime() {
    public Date getCreateTime() {
        return createTime;
        return createTime;
@ -82,6 +91,7 @@ public class PatientApplyLog extends IntegerIdentityEntity {
        this.createTime = createTime;
        this.createTime = createTime;
    }
    }
    @Column(name = "create_user")
    public String getCreateUser() {
    public String getCreateUser() {
        return createUser;
        return createUser;
    }
    }
@ -90,6 +100,7 @@ public class PatientApplyLog extends IntegerIdentityEntity {
        this.createUser = createUser;
        this.createUser = createUser;
    }
    }
    @Column(name = "create_user_name")
    public String getCreateUserName() {
    public String getCreateUserName() {
        return createUserName;
        return createUserName;
    }
    }
@ -97,4 +108,13 @@ public class PatientApplyLog extends IntegerIdentityEntity {
    public void setCreateUserName(String createUserName) {
    public void setCreateUserName(String createUserName) {
        this.createUserName = createUserName;
        this.createUserName = createUserName;
    }
    }
    @Column(name = "remind_type")
    public Integer getRemindType() {
        return remindType;
    }
    public void setRemindType(Integer remindType) {
        this.remindType = remindType;
    }
}
}

+ 8 - 0
common/common-request-mapping/src/main/java/com/yihu/jw/rm/patient/PatientRequestMapping.java

@ -25,6 +25,14 @@ public class PatientRequestMapping {
        public static final String getSign ="/getSign";
        public static final String getSign ="/getSign";
    }
    }
    /**
     * patientInfo
     */
    public static class PatientInfo extends Basic {
        public static final String PREFIX  = "/patientInfo";
    }
    /**
    /**
     * signPackage
     * signPackage
     */
     */

+ 4 - 0
common/common-util/pom.xml

@ -65,5 +65,9 @@
            <groupId>com.squareup.okhttp3</groupId>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <artifactId>okhttp</artifactId>
        </dependency>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>
    </dependencies>
    </dependencies>
</project>
</project>

+ 79 - 8
common/common-util/src/main/java/com/yihu/jw/util/common/RSAUtils.java

@ -1,22 +1,30 @@
package com.yihu.jw.util.common;
package com.yihu.jw.util.common;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.Security;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.interfaces.RSAPublicKey;
import javax.crypto.Cipher;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.util.Assert;
public class RSAUtils {
public class RSAUtils {
//    private static final KeyPair keyPair = initKey();
//    private static final KeyPair keyPair = initKey();
    private static KeyPair initKey(){
    /**
     * 算法名称
     */
    private static final String ALGORITHOM = "RSA";
    /**
     * 默认的安全服务提供者
     */
    private static final Provider DEFAULT_PROVIDER = new BouncyCastleProvider();
    public static KeyPair initKey(){
        try {
        try {
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            SecureRandom random = new SecureRandom();
            SecureRandom random = new SecureRandom();
@ -37,6 +45,12 @@ public class RSAUtils {
        return new String(Base64.encodeBase64(key.getEncoded()));
        return new String(Base64.encodeBase64(key.getEncoded()));
    }
    }
    public static String generateBase64PublicKey() {
        KeyPair keyPair = initKey();
        PublicKey publicKey = keyPair.getPublic();
        return new String(Base64.encodeBase64(publicKey.getEncoded()));
    }
    /**
    /**
     * 解密
     * 解密
     * @param string
     * @param string
@ -46,7 +60,7 @@ public class RSAUtils {
        return new String(decrypt(Base64.decodeBase64(string),keyPair));
        return new String(decrypt(Base64.decodeBase64(string),keyPair));
    }
    }
    private static byte[] decrypt(byte[] string,KeyPair keyPair) {
    public static byte[] decrypt(byte[] string,KeyPair keyPair) {
        try {
        try {
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
            Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
@ -58,15 +72,72 @@ public class RSAUtils {
            throw new RuntimeException(e);
            throw new RuntimeException(e);
        }
        }
    }
    }
    /** 安全服务提供者 */
    private static final Provider PROVIDER = new BouncyCastleProvider();
    /**
     * 加密
     * @param publicKey
     *            公钥
     * @param data
     *            数据
     * @return 加密后的数据
     */
    public static byte[] encrypt(PublicKey publicKey, byte[] data) {
        Assert.notNull(publicKey);
        Assert.notNull(data);
        try {
            Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", PROVIDER);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return cipher.doFinal(data);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 加密
     * @param publicKey
     *            公钥
     * @param text
     *            字符串
     * @return Base64编码字符串
     */
    public static String encrypt(PublicKey publicKey, String text) {
        Assert.notNull(publicKey);
        Assert.notNull(text);
        byte[] data = encrypt(publicKey, text.getBytes());
        return data != null ? Base64.encodeBase64String(data) : null;
    }
    /**
     * 使用指定的私钥解密数据。
     *
     * @param privateKey 给定的私钥。
     * @param data       要解密的数据。
     * @return 原数据。
     */
    public static byte[] decrypt(PrivateKey privateKey, byte[] data) throws Exception {
        Cipher ci = Cipher.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
        ci.init(Cipher.DECRYPT_MODE, privateKey);
        return ci.doFinal(data);
    }
    public static void main(String[] args) {
    public static void main(String[] args) {
        KeyPair keyPair =  initKey();
        KeyPair keyPair =  initKey();
        // 生成public key
        // 生成public key
        System.out.println(generateBase64PublicKey(keyPair));
        String aa = encrypt(keyPair.getPublic(), "ee");
        System.out.println(aa);
        // 解密
        // 解密
        System.out.println(decryptBase64("wAfY9JkoKay9SxcPIs1FcG+t6sR+wYwAs/mh9DpfcBraxzqoZdb9LyaAigzFQ0EKck9OyHL0dhv+Uxuw5hHw6CPT0B2Z0i1gwrjDUNaL1gWvqt1pDJVGrIYPLJSjs9xktFhY1jbxQgXGjyCt06Rwid5sJknw90AUO0CyQulfipg=",keyPair));
        System.out.println(decryptBase64(aa,keyPair));
    }
    }
}
}

+ 812 - 0
common/common-util/src/main/java/com/yihu/jw/util/common/XMLUtil.java

@ -0,0 +1,812 @@
package com.yihu.jw.util.common;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.dom4j.tree.DefaultAttribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.*;
public class XMLUtil {
    private static Logger logger = LoggerFactory.getLogger(XMLUtil.class);
    /**
     * 把xml字符串转换成 Document对象。
     *
     * @param xml 需要转换的xml字符串
     * @return 返回Document对象
     * @throws Exception 如果转换成Document对象异常的话抛出异常。
     */
    public static Document parseXml(String xml) throws Exception {
        try {
            return DocumentHelper.parseText(xml);
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new Exception("传入的 xml 不是标准的xml字符串,请检查字符串是否合法。");
        }
    }
    /**
     * 转换成xml字符串
     *
     * @param xmlDoc 需要解析的xml对象
     * @throws Exception
     */
    public static String toXML_UTF_8(Document xmlDoc) throws Exception {
        return toXML(xmlDoc, "UTF-8", true);
    }
    /**
     * 转换成xml字符串
     *
     * @param xmlDoc 需要解析的xml对象
     * @throws Exception
     */
    public static String toXML_GBK(Document xmlDoc) throws Exception {
        return toXML(xmlDoc, "GBK", true);
    }
    /**
     * 转换成xml字符串
     *
     * @param xmlDoc   需要解析的xml对象
     * @param encoding 编码格式:UTF-8、GBK
     * @param iscom    是否为紧凑型格式
     * @return 修正完成后的xml字符串
     * @throws Exception
     */
    public static String toXML(Document xmlDoc, String encoding,
                               boolean iscom) throws Exception {
        ByteArrayOutputStream byteRep = new ByteArrayOutputStream();
        OutputFormat format = null;
        if (iscom) {
            format = OutputFormat.createCompactFormat();// 紧凑型格式
        } else {
            format = OutputFormat.createPrettyPrint();// 缩减型格式
        }
        format.setEncoding(encoding);// 设置编码
        format.setTrimText(false);// 设置text中是否要删除其中多余的空格
        XMLWriter xw;
        try {
            xw = new XMLWriter(byteRep, format);
            xw.write(xmlDoc);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new Exception("传入的编码格式错误,请传入正确的编码。");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new Exception("文档转换成xml字符串时出错。" + xmlDoc.asXML());
        }
        return byteRep.toString();
    }
    /**
     * 对节点Element 添加节点。
     *
     * @param e     需要添加的节点
     * @param name  添加的节点的名称
     * @param value 添加的内容
     *              <br/>
     *              Demo:
     *              < Root > aaa < /Root >
     *              <br/>
     *              call-->  addChildElement(root, "A", "a");
     *              <br/>
     *              result--> < Root >< A >a< /A >< /Root >
     */
    public static void addElement(Element e, String name, Object value) {
        if (isBlank(value)) {
            e.addElement(name).addText("");
        } else {
            e.addElement(name).addText(value.toString());
        }
    }
    /**
     * 判断对象是否为空!(null,"", "null")
     *
     * @param value
     * @return
     */
    private static boolean isBlank(String value) {
        if (value == null || value.length() == 0) {
            return true;
        } else if (StringUtils.isEmpty(value)) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 判断对象是否非空!(null,"", "null")
     *
     * @param obj
     * @return
     */
    public static boolean isNotBlank(Object obj) {
        return !isBlank(obj);
    }
    /**
     * 判断对象是否为空!(null,"", "null")
     *
     * @param obj
     * @return
     */
    public static boolean isBlank(Object obj) {
        if (obj == null) {
            return true;
        }
        if (obj instanceof String) {
            return isBlank((String) obj);
        } else {
            return isBlank(obj.toString());
        }
    }
    public static void addElement(Element e, String name, Integer value) {
        Element current = e.addElement(name);
        if (value != null) {
            current.setText(Integer.toString(value));
        }
    }
    /**
     * 添加CDATA 类型节点
     *
     * @param e
     * @param name
     * @param value
     */
    public static void addCDATAElement(Element e, String name, String value) {
        Element current = e.addElement(name);
        if (value != null) {
            current.addCDATA(value.trim());
        }
    }
    /**
     * 添加CDATA 类型节点
     *
     * @param e
     * @param name
     * @param value
     */
    public static void addCDATAElement(Element e, String name, Integer value) {
        Element current = e.addElement(name);
        if (value != null) {
            current.addCDATA(value.toString());
        }
    }
    /**
     * 获取节点中的整数
     *
     * @throws Exception
     */
    public static int getInt(Element e, String name, boolean isMust) throws Exception {
        Element current = e.element(name);
        if (current == null || current.getText() == null || "".equals(current.getText().trim()) || current.getText().length() <= 0) {
            if (isMust) {
                throw new Exception("在 $" + e.asXML() + "$中获取节点:" + name + " 的值为空。");
            }
            return 0;
        }
        Integer i = 0;
        try {
            i = Integer.parseInt(current.getTextTrim());
        } catch (NumberFormatException e1) {
            i = 0;
            if (isMust) {
                throw new Exception("在 $" + e.asXML() + "$中获取节点:" + name + " 的值不是整形。");
            }
        }
        return i;
    }
    /**
     * 获取节点中的字符串
     *
     * @throws Exception
     */
    public static String getString(Element e, String name, boolean isMust) throws Exception {
        return getString(e, name, isMust, null);
    }
    /**
     * 获取节点中的字符串
     *
     * @param e
     * @param name
     * @param isMust 是否必填 true 必填  false非必填
     * @param defVal 默认值
     * @return
     * @throws Exception
     */
    public static String getString(Element e, String name, boolean isMust, String defVal) throws Exception {
        Element current = e.element(name);
        if (current == null || current.getText() == null || StringUtils.isEmpty(current.getText().trim())) {
            if (isMust) {
                throw new Exception("在 $" + e.asXML() + "$中获取节点:" + name + " 的值为空。");
            }
            return defVal;
        }
        return current.getTextTrim();
    }
    public static String ElementStringValue(String str) {
        if (str != null) {
            return str;
        } else {
            return "";
        }
    }
    public static Integer ElementIntegerValue(Integer str) {
        if (str != null) {
            return str;
        } else {
            return 0;
        }
    }
    public static String ElementValue(String str) {
        if (str != null && !str.equalsIgnoreCase("null")) {
            return str;
        } else {
            return "";
        }
    }
    public static String xml2json(String xml){
        StringWriter w = new StringWriter();
        ObjectMapper objectMapper = new ObjectMapper();
        XmlMapper xmlMapper = new XmlMapper();
        JsonParser jp;
        try {
            jp = xmlMapper.getFactory().createParser(xml);
            JsonGenerator jg = objectMapper.getFactory().createGenerator(w);
            while (jp.nextToken() != null) {
                String name = jp.getParsingContext().getCurrentName();
                if ("".equals(name)){
                    jp.overrideCurrentName("text");
                }
                jg.copyCurrentEvent(jp);
            }
            jp.close();
            jg.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return w.toString();
    }
    public static String formatXML(Document doc) throws Exception {
        StringWriter out = null;
        try {
            OutputFormat formate = OutputFormat.createPrettyPrint();
            out = new StringWriter();
            XMLWriter writer = new XMLWriter(out, formate);
            writer.write(doc);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
        return out.toString();
    }
    // ---------- map转XML--------------
    public static String map2xml(Map<String, String> dataMap) {
        synchronized (XMLUtil.class) {
            StringBuilder strBuilder = new StringBuilder();
            strBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            strBuilder.append("<QUERY_FORM>");
            Set<String> objSet = dataMap.keySet();
            for (Object key : objSet) {
                if (key == null) {
                    continue;
                }
                strBuilder.append("<").append(key.toString()).append(">");
                Object value = dataMap.get(key);
                strBuilder.append(coverter(value));
                strBuilder.append("</").append(key.toString()).append(">");
            }
            strBuilder.append("</QUERY_FORM>");
            return strBuilder.toString();
        }
    }
    public static String map2xmlForWx(Map<String, String> dataMap) {
        synchronized (XMLUtil.class) {
            StringBuilder strBuilder = new StringBuilder();
            strBuilder.append("<xml>");
            Set<String> objSet = dataMap.keySet();
            for (Object key : objSet) {
                if (key == null) {
                    continue;
                }
                strBuilder.append("<").append(key.toString()).append(">");
                Object value = dataMap.get(key);
                strBuilder.append(coverter(value));
                strBuilder.append("</").append(key.toString()).append(">");
            }
            strBuilder.append("</xml>");
            return strBuilder.toString();
        }
    }
    public static String coverter(Object[] objects) {
        StringBuilder strBuilder = new StringBuilder();
        for (Object obj : objects) {
            strBuilder.append("<item className=").append(obj.getClass().getName()).append(">\n");
            strBuilder.append(coverter(obj));
            strBuilder.append("</item>\n");
        }
        return strBuilder.toString();
    }
    public static String coverter(Collection<?> objects) {
        StringBuilder strBuilder = new StringBuilder();
        for (Object obj : objects) {
            strBuilder.append("<item className=").append(obj.getClass().getName()).append(">\n");
            strBuilder.append(coverter(obj));
            strBuilder.append("</item>\n");
        }
        return strBuilder.toString();
    }
    public static String coverter(Object object) {
        if (object instanceof Object[]) {
            return coverter((Object[]) object);
        }
        if (object instanceof Collection) {
            return coverter((Collection<?>) object);
        }
        StringBuilder strBuilder = new StringBuilder();
        if (isObject(object)) {
            Class<? extends Object> clz = object.getClass();
            Field[] fields = clz.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                if (field == null) {
                    continue;
                }
                String fieldName = field.getName();
                Object value = null;
                try {
                    value = field.get(object);
                } catch (IllegalArgumentException e) {
                    continue;
                } catch (IllegalAccessException e) {
                    continue;
                }
                strBuilder.append("<").append(fieldName)
                        .append(" className=\"").append(
                        value.getClass().getName()).append("\">");
                if (isObject(value)) {
                    strBuilder.append(coverter(value));
                } else if (value == null) {
                    strBuilder.append("null");
                } else {
                    strBuilder.append(value.toString() + "");
                }
                strBuilder.append("</").append(fieldName).append(">");
            }
        } else if (object == null) {
            strBuilder.append("null");
        } else {
            strBuilder.append(object.toString());
        }
        return strBuilder.toString();
    }
    private static boolean isObject(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj instanceof String) {
            return false;
        }
        if (obj instanceof Integer) {
            return false;
        }
        if (obj instanceof Double) {
            return false;
        }
        if (obj instanceof Float) {
            return false;
        }
        if (obj instanceof Byte) {
            return false;
        }
        if (obj instanceof Long) {
            return false;
        }
        if (obj instanceof Character) {
            return false;
        }
        if (obj instanceof Short) {
            return false;
        }
        if (obj instanceof Boolean) {
            return false;
        }
        return true;
    }
    // --------------------xml转map---------------
    private static void ele2map(Map map, Element ele)  {
        // 获得当前节点的子节点
        List<Element> elements = ele.elements();
        if (elements.size() == 0) {
            // 没有子节点说明当前节点是叶子节点,直接取值即可
            map.put(ele.getName(), ele.getText());
        } else if (elements.size() == 1) {
            // 只有一个子节点说明不用考虑list的情况,直接继续递归即可
            Map<String, Object> tempMap = new HashMap<String, Object>();
            ele2map(tempMap, elements.get(0));
            //设置标签属性
            setAttributes(tempMap,elements.get(0));
            if (tempMap.size()==1){
                map.put(ele.getName(), ele.getText());
            }else {
                map.put(ele.getName(), tempMap);
            }
        } else {
            // 多个子节点的话就得考虑list的情况了,比如多个子节点有节点名称相同的
            // 构造一个map用来去重
            Map<String, Object> tempMap = new HashMap<String, Object>();
            for (Element element : elements) {
                tempMap.put(element.getName(), null);
            }
            Set<String> keySet = tempMap.keySet();
            for (String string : keySet) {
                Namespace namespace = elements.get(0).getNamespace();
                List<Element> elements2 = ele.elements(new QName(string, namespace));
                // 如果同名的数目大于1则表示要构建list
                if (elements2.size() > 1) {
                    List<Map> list = new ArrayList<Map>();
                    for (Element element : elements2) {
                        Map<String, Object> tempMap1 = new HashMap<String, Object>();
                        ele2map(tempMap1, element);
                        setAttributes(tempMap1,element);//属性值设置
                        list.add(tempMap1);
                    }
                    map.put(string, list);
                } else {
                    // 同名的数量不大于1则直接递归去
                    Map<String, Object> tempMap1 = new HashMap<String, Object>();
                    ele2map(tempMap1, elements2.get(0));
                    setAttributes(tempMap1,elements2.get(0));//属性值设置
                    if (tempMap1.containsKey(string)) {
                        map.put(string, tempMap1.get(string));
                    }else {
                        map.put(string, tempMap1);
                    }
                }
            }
        }
    }
    /**
     *
     * 设置属性值(xml转map)
     * @param map
     * @param element
     */
    public static void setAttributes(Map map,Element element){
        List list = element.attributes();
        Map<String,Object> attrMap = null;
        DefaultAttribute e = null;
        if (!list.isEmpty()) {
            attrMap = new HashMap<>();
            for (int i = 0; i < list.size(); i++) {
                e = (DefaultAttribute) list.get(i);
                attrMap.put(e.getName(),e.getText());
            }
            attrMap.put("text",element.getText());
        }
        if (attrMap!=null && !attrMap.isEmpty()){
            map.put(element.getName(),attrMap);
        }
    }
//============================================
    public static Object xml2map(Element element) {
        System.out.println(element);
        Map<String, Object> map = new HashMap<String, Object>();
        List<Element> elements = element.elements();
        if (elements.size() == 0) {
            map.put(element.getName(), element.getText());
            if (!element.isRootElement()) {
                return element.getText();
            }
        } else if (elements.size() == 1) {
            map.put(elements.get(0).getName(), xml2map(elements.get(0)));
        } else if (elements.size() > 1) {
            // 多个子节点的话就得考虑list的情况了,比如多个子节点有节点名称相同的
            // 构造一个map用来去重
            Map<String, Element> tempMap = new HashMap<String, Element>();
            for (Element ele : elements) {
                tempMap.put(ele.getName(), ele);
            }
            Set<String> keySet = tempMap.keySet();
            for (String string : keySet) {
                Namespace namespace = tempMap.get(string).getNamespace();
                List<Element> elements2 = element.elements(new QName(string, namespace));
                // 如果同名的数目大于1则表示要构建list
                if (elements2.size() > 1) {
                    List<Object> list = new ArrayList<Object>();
                    for (Element ele : elements2) {
                        list.add(xml2map(ele));
                    }
                    map.put(string, list);
                } else {
                    // 同名的数量不大于1则直接递归去
                    map.put(string, xml2map(elements2.get(0)));
                }
            }
        }
        return map;
    }
//    ============================================
    public static Map xmltoMap(String xml) {
        if (!StringUtils.isEmpty(xml)) {
            try {
                Map map = new HashMap();
                Document document = DocumentHelper.parseText(xml);
                Element nodeElement = document.getRootElement();
                List node = nodeElement.elements();
                for (Iterator it = node.iterator(); it.hasNext(); ) {
                    Element elm = (Element) it.next();
                    List list = elm.elements();
                    if(list.size() > 0){
                        Map xmltoMap = xmltoMap(elm.asXML());
                        map.putAll(xmltoMap);
                    }else{
                        map.put(elm.getName(), elm.getText());
                    }
                    elm = null;
                }
                node = null;
                nodeElement = null;
                document = null;
                return map;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public static Map xmltoMap2(String xml) {
        Map<String,Object> map = new HashMap<String,Object>();
        Document doc;
        try {
            doc = DocumentHelper.parseText(xml);
            Element el = doc.getRootElement();
            map.put(el.getName(), DiGui(el));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return map;
    }
    public static void main(String[] args) {
        String aa="<HisTrans>\n" +
                "  <TranCode>GetHealthYE</TranCode>\n" +
                "  <RespMsg />\n" +
                "  <RespCode>0</RespCode>\n" +
                "  <Order>\n" +
                "    <HealthYE>3.94</HealthYE>\n" +
                "    <HospitalizationYE />\n" +
                "  </Order>\n" +
                "</HisTrans>";
//        String aa= "<HisTrans>\n" +
//                "  <TranCode>GetHealthYE</TranCode>\n" +
//                "  <RespMsg />\n" +
//                "  <RespCode>0</RespCode>\n" +
//                "  <Order>\n" +
//                "    <HealthYE>3.94</HealthYE>\n" +
//                "    <HospitalizationYE></HospitalizationYE>\n" +
//                "  </Order>\n" +
//                "</HisTrans>";
        Map map = xmltoMap(aa);
        System.out.println(map);
    }
    public static List xmltoList(String xml) {
        if (!StringUtils.isEmpty(xml)) {
            try {
                List<Map> list = new ArrayList<Map>();
                Document document = DocumentHelper.parseText(xml);
                Element nodesElement = document.getRootElement();
                List nodes = nodesElement.elements();
                for (Iterator its = nodes.iterator(); its.hasNext(); ) {
                    Element nodeElement = (Element) its.next();
                    Map map = xmltoMap(nodeElement.asXML());
                    list.add(map);
                    map = null;
                }
                nodes = null;
                nodesElement = null;
                document = null;
                return list;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public static Map DiGui(Element rootElement) {
        // 对节点进行判断
        int flag = hasGradeChrid(rootElement);
        // 存储本层的map,采用LinkedHashMap,保证的顺序
        Map<String, Object> map_this = new LinkedHashMap<String, Object>();
        // 存储子节点的map,采用LinkedHashMap,保证的顺序
        Map<String, Object> map_children = new LinkedHashMap<String, Object>();
        // 获取节点迭代器
        Iterator<Element> iterator = rootElement.elementIterator();
        if (flag == 0) {// 说明该节点所有子节点均有子节点,进入递归
            int num = 0;
            while (iterator.hasNext()) {// 依次继续对节点进行操作
                Element childelement = iterator.next();
                map_children = DiGui(childelement);
                map_this.put(childelement.getName() + "_" + num, map_children);
                num++;
            }
        }
        if (flag == 1) {// 说明该节点的所有子节点均无子节点,封装数据
            while (iterator.hasNext()) {
                Element childelement = iterator.next();
                map_this.put(childelement.getName(),
                        (String) childelement.getData());
            }
        }
        if (flag == 2) {// 说明了该节点的子节点有些拥有子节点,有些不拥有
            int nodes = rootElement.elements().size();// 获取子节点个数
            while (nodes >= 1) {
                nodes--;
                int num = 0;//为了让循环重复的节点,避免了key的冲突
                Element element = iterator.next();
                flag = hasGradeChrid(element);//对节点进行判断
                if (flag == 1) {                          //对于子节点,如果只是普通的子节点,那么直接将数进行封装
                    // 封装如map,String,String
                    map_this.put(element.getName(), element.getData());
                }
                else{                                     //非普通子节点,那么进行递归
                    map_children = DiGui(element);
                    map_this.put(element.getName() + "_" + num, map_children);//为了让循环重复的节点,避免了key的冲突
                }
            }
        }
        return map_this;
    }
    /**
     * 用于判断该节点的类型 0:说明该节点所有子节点均有子节点 1:说明该节点的所有子节点均无子节点 2:说明了该节点的子节点有些拥有子节点,有些不拥有
     *
     * @param rootelement
     * @return
     */
    public static int hasGradeChrid(Element rootelement) {
        int flag = 1;// 初始为1,用与处理对没有子节点的节点进行判断
        StringBuffer flag_arr = new StringBuffer();
        Iterator<Element> iterator = rootelement.elementIterator();
        while (iterator.hasNext()) {
            Element element = iterator.next();// 获取入参rootelement节点的子节点
            // Iterator<Element> iterator_chirld = element.elementIterator();
            if (element.elements().size() > 0) {// 判断是否有子节点
                flag_arr.append("0");
            } else {
                flag_arr.append("1");
            }
        }
        // 如果只包含0,说明该节点所有子节点均有子节点
        if (flag_arr.toString().contains("0")) {
            flag = 0;
        }
        // 如果只包含1,说明该节点的所有子节点均无子节点
        if (flag_arr.toString().contains("1")) {
            flag = 1;
        }
        // 如果同时包含了,0,1,说明了该节点的子节点有些拥有子节点,有些不拥有
        if (flag_arr.toString().contains("0")
                && flag_arr.toString().contains("1")) {
            flag = 2;
        }
        return flag;
    }
    /* ============================== 以下暂时添加,后面可删除 ========================================= */
//    public static String maptoXml(Map map) {
//        Document document = DocumentHelper.createDocument();
//        Element nodeElement = document.addElement("node");
//        for (Object obj : map.keySet()) {
//            Element keyElement = nodeElement.addElement("key");
//            keyElement.addAttribute("label", String.valueOf(obj));
//            keyElement.setText(String.valueOf(map.get(obj)));
//        }
//        return doc2String(document);
//    }
//
//    public static String listtoXml(List list) throws Exception {
//        Document document = DocumentHelper.createDocument();
//        Element nodesElement = document.addElement("nodes");
//        int i = 0;
//        for (Object o : list) {
//            Element nodeElement = nodesElement.addElement("node");
//            if (o instanceof Map) {
//                for (Object obj : ((Map) o).keySet()) {
//                    Element keyElement = nodeElement.addElement("key");
//                    keyElement.addAttribute("label", String.valueOf(obj));
//                    keyElement.setText(String.valueOf(((Map) o).get(obj)));
//                }
//            } else {
//                Element keyElement = nodeElement.addElement("key");
//                keyElement.addAttribute("label", String.valueOf(i));
//                keyElement.setText(String.valueOf(o));
//            }
//            i++;
//        }
//        return doc2String(document);
//    }
//
//    public static String doc2String(Document document) {
//        String s = "";
//        try {
//            // 使用输出流来进行转化
//            ByteArrayOutputStream out = new ByteArrayOutputStream();
//            // 使用UTF-8编码
//            OutputFormat format = new OutputFormat("   ", true, "UTF-8");
//            XMLWriter writer = new XMLWriter(out, format);
//            writer.write(document);
//            s = out.toString("UTF-8");
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        }
//        return s;
//    }
}

+ 59 - 0
common/common-util/src/main/java/com/yihu/jw/util/wechat/WXPayConstants.java

@ -0,0 +1,59 @@
package com.yihu.jw.util.wechat;
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";
}

+ 148 - 0
common/common-util/src/main/java/com/yihu/jw/util/wechat/WeiXinPayUtils.java

@ -0,0 +1,148 @@
package com.yihu.jw.util.wechat;
import com.yihu.jw.util.common.XMLUtil;
import com.yihu.jw.util.wechat.wxhttp.HttpUtil;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.*;
public class WeiXinPayUtils {
    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final Random RANDOM = new SecureRandom();
    /**
     *
     * 微信支付,统一下单
     *
     * param 对应的key值参见文档 https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_1 (sign,nonce_str两个参数,此接口会自动生成)
     *
     * @param param
     * @param appKey
     * @return
     * @throws Exception
     */
    public static Map<String,Object> unifiedorder(Map<String, String> param,String appKey) throws Exception {
        param.put("nonce_str",generateNonceStr());
        WXPayConstants.SignType  wxSignType = WXPayConstants.SignType.MD5;
        String signType = param.get("sign_type");
        if("HMAC-SHA256".equalsIgnoreCase(signType)){
            wxSignType = WXPayConstants.SignType.HMACSHA256;
        }
        //获取微信签名
        String signature = WeiXinPayUtils.generateSignature(param, appKey, wxSignType);
        param.put("sign",signature);
        //参数转化XML
        String params = XMLUtil.map2xmlForWx(param);
        String result = HttpUtil.sendPost("https://api.mch.weixin.qq.com/pay/unifiedorder", params);
        Map<String,Object> wxrs =  XMLUtil.xmltoMap(result);
        return wxrs;
    }
    /**
     * 获取随机字符串 Nonce Str
     *
     * @return String 随机字符串
     */
    private 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);
    }
    /**
     * 生成签名. 注意,若含有sign_type字段,必须和signType参数保持一致。
     *
     * @param data 待签名数据
     * @param key API密钥
     * @param signType 签名方式
     * @return 签名
     */
    private 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));
        }
    }
    /**
     * 生成 MD5
     *
     * @param data 待处理数据
     * @return MD5结果
     */
    private 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
     */
    private 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();
    }
    public static void main(String[] args) throws Exception {
        HashMap<String, String> map = new HashMap<>();
        map.put("appid","wx0a06b75a40b28f2a");
        map.put("mch_id","1516700601");
        map.put("body","腾讯充值中心-QQ会员充值");
        map.put("out_trade_no","20181127112445");
        map.put("total_fee","1");
        map.put("spbill_create_ip","192.168.6.109");
        map.put("notify_url","http://www.baidu.com");
        map.put("trade_type","JSAPI");
        map.put("openid", "oDGGt0QrJvH-YbDCHFgjd3Exc0Sw");
        Map<String, Object> pay = unifiedorder(map, "yF4e9Rr1sVdqCF6c7cqqMPSNsCjYGyf9");
        System.out.println("--------------");
    }
}

+ 0 - 39
svr/svr-base/pom.xml

@ -118,11 +118,6 @@
            <artifactId>mysql-starter</artifactId>
            <artifactId>mysql-starter</artifactId>
            <version>2.0.0</version>
            <version>2.0.0</version>
        </dependency>
        </dependency>
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>elasticsearch-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
        <dependency>
            <groupId>io.github.swagger2markup</groupId>
            <groupId>io.github.swagger2markup</groupId>
@ -136,41 +131,7 @@
            </exclusions>
            </exclusions>
        </dependency>
        </dependency>
        <!-- 发送邮件 -->
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.4.7</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <!--   poi xml导入导出工具 start-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>com.yihu.ehr</groupId>
                    <artifactId>commons-util</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.apache.commons</groupId>
                    <artifactId>commons-collections4</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
        </dependency>
        <!-- xlsx  依赖这个包 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
        </dependency>
        <dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <artifactId>spring-security-core</artifactId>

+ 7 - 0
svr/svr-patient/src/main/java/com/yihu/jw/patient/dao/myFamily/PatientApplyLogDao.java

@ -2,10 +2,17 @@ package com.yihu.jw.patient.dao.myFamily;
import com.yihu.jw.entity.myFamily.PatientApplyLog;
import com.yihu.jw.entity.myFamily.PatientApplyLog;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
/**
 * @author liuwenbin on 2018/11/30.
 * @author liuwenbin on 2018/11/30.
 */
 */
public interface PatientApplyLogDao extends PagingAndSortingRepository<PatientApplyLog, String>, JpaSpecificationExecutor<PatientApplyLog> {
public interface PatientApplyLogDao extends PagingAndSortingRepository<PatientApplyLog, String>, JpaSpecificationExecutor<PatientApplyLog> {
    @Modifying
    @Query("update PatientApplyLog t set t.remindType = ?1 where t.id=?2 ")
    int updateRemindTypeById(Integer remindType, Integer patientApplyLogId);
}
}

+ 6 - 0
svr/svr-patient/src/main/java/com/yihu/jw/patient/dao/personal_info/PatientDao.java

@ -26,4 +26,10 @@ public interface PatientDao extends PagingAndSortingRepository<BasePatientDO, St
    @Query("select id as id,idcard as idcard,name as name,case sex when 1 then '男' when 2 then '女' else '未知' end as sex,phone as phone,committeeName as committeeName,concat(provinceName,cityName,townName,streetName) as address from BasePatientDO")
    @Query("select id as id,idcard as idcard,name as name,case sex when 1 then '男' when 2 then '女' else '未知' end as sex,phone as phone,committeeName as committeeName,concat(provinceName,cityName,townName,streetName) as address from BasePatientDO")
    List<Map<String,Object>> findBaseInfo(Pageable pageable);
    List<Map<String,Object>> findBaseInfo(Pageable pageable);
    @Query("from BasePatientDO where mobile = ?1")
    List<BasePatientDO> findByMobile(String mobile);
    @Query("from BasePatientDO p where p.mobile = ?1 and p.del=?2")
    List<BasePatientDO> findByMobileAndDel(String mobile,String del);
}
}

+ 14 - 0
svr/svr-patient/src/main/java/com/yihu/jw/patient/dao/security/RSADao.java

@ -0,0 +1,14 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.jw.patient.dao.security;
import com.yihu.jw.entity.base.security.RSA;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface RSADao extends PagingAndSortingRepository<RSA, String>, JpaSpecificationExecutor<String> {
	
}

+ 375 - 0
svr/svr-patient/src/main/java/com/yihu/jw/patient/endpoint/patient/PatientInfoEndpint.java

@ -0,0 +1,375 @@
package com.yihu.jw.patient.endpoint.patient;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.patient.dao.personal_info.PatientDao;
import com.yihu.jw.patient.service.personal_Info.PatientService;
import com.yihu.jw.patient.util.CommonUtils;
import com.yihu.jw.patient.util.RSAService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.patient.PatientRequestMapping;
import com.yihu.jw.util.security.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@RestController
@RequestMapping(PatientRequestMapping.PatientInfo.PREFIX)
@Api(value = "患者注册,登陆等", description = "患者注册,登陆等", tags = {"居民端 - 患者注册,登陆等"})
public class PatientInfoEndpint extends EnvelopRestEndpoint {
    @Autowired
    private PatientDao patientDao;
    @Autowired
    private PatientService patientService;
    @Autowired
    private RSAService rsaService;
    /**
     * 公钥生成并返回接口
     *
     * @return
     */
    @RequestMapping(value = "getKey", method = RequestMethod.GET)
    @ApiOperation("获取公钥")
    public Envelop publicKey() {
        String modulus = rsaService.getModulus();
        String exponent = rsaService.getExponent();
        Map<String, String> map = new HashMap<>();
        map.put("modulus", modulus); //加密指数
        map.put("exponent", exponent);//加密系数
        return success(map);
    }
    @ApiOperation("居民注册接口")
    @RequestMapping(value = "regist", method = RequestMethod.POST)
    @ResponseBody
    public Envelop regist(@ApiParam(value = "手机号", name = "mobile") @RequestParam(required = true)String mobile ,
                         @ApiParam(value = "验证码", name = "captcha") @RequestParam(value = "captcha", required = true) String captcha,
                         @ApiParam(value = "微信openId", name = "openid") @RequestParam(value = "openid", required = false) String openid,
                         @ApiParam(value = "密码", name = "password") @RequestParam(value = "password", required = false) String password) {
        Envelop envelop = new Envelop();
        boolean b = CommonUtils.isMobile(mobile);
        if(!b){
            envelop.setMessage("手机号码格式不正确");
            envelop.setStatus(-1);
            return envelop;
        }
        //验证手机是否被注册
        List<BasePatientDO> list =  patientDao.findByMobileAndDel(mobile,"1");
        if(list!=null && list.size()> 0){
            envelop.setMessage("该手机号已经注册!");
            envelop.setStatus(-1);
            return envelop;
        }
        // 对验证码进行校验 todo cyx
//            int res = smsService.check(mobile, 1, captcha);
//            switch (res) {
//                case -2:
//                    return error(-1, "验证码已过期!");
//                case -1:
//                    return error(-1, "请输入正确的验证码!");
//                case 0:
//                    return error(-1, "验证码无效!");
//            }
        BasePatientDO patient = new BasePatientDO();
        patient.setMobile(mobile);
        if(StringUtils.isNotBlank(password)){
            //增加密码
            String salt = UUID.randomUUID().toString().replace("-", "");
            patient.setSalt(salt);
            password = rsaService.decryptString(password);
            password = StringUtils.reverse(password);
            if(password.length()<6 || password.length()>20){
                envelop.setMessage("密码长度需为6-20位");
                envelop.setStatus(-1);
                return envelop;
            }
            patient.setPassword(MD5.GetMD5Code(password + salt));
        }
        if(!"undefined".equals(openid) && StringUtils.isNotBlank(openid)){
            patient.setOpenid(openid);
            patient.setOpenidTime(new Date());
        }
        patient.setDel("1");
        patient.setPatientStatus("1");
        patientService.save(patient);
        envelop.setMessage("注册成功");
        envelop.setStatus(200);
        return envelop;
    }
    /**
     * 患者微信登录接口
     *
     * @param captcha  短信号
     * @param mobile   电话号码
     * @param password 登录密码
     * @return
     */
        @RequestMapping(value = "login", method = RequestMethod.POST)
        @ResponseBody
        public Envelop login(
                @RequestParam(required = true) String mobile,
                @RequestParam(required = false) String captcha,
                @RequestParam(required = false) String password,
                @RequestParam(required = false) String openId) {
        Envelop envelop = new Envelop();
        boolean b = CommonUtils.isMobile(mobile);
        if(!b){
            envelop.setMessage("手机号码格式不正确");
            envelop.setStatus(-1);
            return envelop;
        }
        //验证手机是否被注册
        List<BasePatientDO> list = patientDao.findByMobileAndDel(mobile,"1");
        if(CollectionUtils.isEmpty(list)){
            envelop.setMessage("该手机未注册");
            envelop.setStatus(-1);
            return envelop;
        }
        if(list.size()> 1){
            envelop.setMessage("该手机号存在多个账号,请联系管理员");
            envelop.setStatus(-1);
            return envelop;
        }
        BasePatientDO p = list.get(0);
        //用于判断是否登陆成功,若登陆成功,且openId不为空,则更新openId
        boolean isLogin = false;
        if(StringUtils.isNotBlank(password)){
            password = rsaService.decryptString(password);
            password = StringUtils.reverse(password);
            //生成MD5
            String loginPassword = MD5.GetMD5Code(password + p.getSalt());
            if (loginPassword.equals(p.getPassword())) {
                //使用密码登录成功
            }else{
                //使用密码登录失败
            }
        } else {
          //验证码登陆
        }
        if(isLogin && StringUtils.isNotBlank(openId) && !"undefined".equals(openId)){
            //更新openId
            if(!openId.equals(p.getOpenid())){
            }
        }
//         String errorMessage;
//        try {
//            //账号登录 mobile可能是电话号也可能是身份证
//            if (StringUtils.isNoneEmpty(mobile) && StringUtils.isNoneEmpty(password)) {
//                BasePatientDO p = patientService.findByMobile(mobile);
//                //生成MD5
//                String loginPassword = MD5.GetMD5Code(password + p.getSalt());
//                //判断d登录密码是否正确
//                if (loginPassword.equals(p.getPassword())) {
//                    // 绑定用户手机号和openid
//                    if (StringUtils.isNotBlank(openId) && !"undefined".equals(openId)) {//undefined不更新数据库
//                        //patient.setOpenid(openId);
//                        //1.判斷居民OPenid是不是空
//                        if(StringUtils.isNotBlank(p.getOpenid())){
//                            //如果OPenid与原来用户不相等,则判断登录的openids是否被大于10人登录
//                            if(!p.getOpenid().equals(openId)){
//                                //判断登录的openids是否被大于10人登录
////                                if(!patientService.checkOpenidCount(openId)){
////                                    errorMessage ="您已超过系统允许登录的最大居民账号数量,当前不再允许使用该微信登录新的居民账号,请使用其他微信号进行登录";
////                                    return error(-2, errorMessage);
////                                }
//                            }
//                            patientService.updatePatient(p, openId);
//                        }else{
//                            // 判断登录的openids是否被大于10人登录
//                            if(!patientService.checkOpenidCount(openId)){
////                                errorMessage ="您已超过系统允许登录的最大居民账号数量,当前不再允许使用该微信登录新的居民账号,请使用其他微信号进行登录";
////                                return error(-2, errorMessage);
//                            }else{
//                                //未达到上限更新用户openid
//                                patientService.updatePatient(p, openId);
//                            }
//                        }
//                    }
//
//                    // 用户校验通过,生成token
//                    Token token = tokenService.newTxToken(p.getCode(), openId);
//                    Map<Object, Object> map = new HashMap<Object, Object>();
//                    map.put("id", p.getId());
//                    map.put("uid", p.getCode());
//                    map.put("name", p.getName());
//                    map.put("token", token.getToken());
//                    map.put("photo", p.getPhoto());
//                    if (StringUtils.isNoneEmpty(openId)) {
//                        //发送微信模板
//                        familyService.sendWXMessage(p);
//                    }
//
//                    loginLog.setLoginType("1");
//                    loginLogService.saveLog(loginLog);
//                    //判断是否打过标签
//                    //if (!(Patient.isWchatTage.yes.getValue() == p.getIsWxtag())) {
//
//                    //清空患者的微信标签
//                    weiXinTagUtil.deleteTagWithOpenid(p.getOpenid());
//                    //给患者打微信标签
//                    weiXinTagUtil.addTagWithOpenid(openId, p.getCode(), p.getName());
//                    //}
//                    return write(200, "登录成功", "data", map);
//                } else {
//                    errorMessage = "密码错误,登录失败";
//                    loginLog.setErrorMessage(errorMessage);
//                    loginLogService.saveLog(loginLog);
//                    return error(-1, errorMessage);
//                }
//            }
//            //短信登录
//            if (StringUtils.isNoneEmpty(mobile) && StringUtils.isNoneEmpty(captcha)) {
//                List<Patient> patients = patientService.findByMobile(mobile);
//                if (patients.size() > 1) {
//                    return error(-1, "此手机存在多个用户,请用身份证和密码登录!");
//                }
//                // 对验证码进行校验
//                int res = smsService.check(mobile, 4, captcha);
//                switch (res) {
//                    case -2: {
//                        errorMessage = "验证码已过期!";
//                        loginLog.setErrorMessage(errorMessage);
//                        loginLogService.saveLog(loginLog);
//                        return error(-1, errorMessage);
//                    }
//                    case -1: {
//                        errorMessage = "请输入正确的验证码!";
//                        loginLog.setErrorMessage(errorMessage);
//                        loginLogService.saveLog(loginLog);
//                        return error(-1, errorMessage);
//                    }
//                    case 0: {
//                        errorMessage = "验证码无效!";
//                        loginLog.setErrorMessage(errorMessage);
//                        loginLogService.saveLog(loginLog);
//                        return error(-1, errorMessage);
//                    }
//                }
//
//                loginLog.setLoginType("1");
//                if (patients == null || patients.size() == 0) {
//                    if (mobile.length() == 11) {
//                        errorMessage = "该手机号暂未注册账号,请确认后重新输入!";
//                    } else {
//                        errorMessage = "该身份证号暂未注册账号,请确认后重新输入!";
//                    }
//                    loginLog.setErrorMessage(errorMessage);
//                    loginLogService.saveLog(loginLog);
//                    return error(-1, errorMessage);
//                } else {
//                    Patient p = null;
//                    if (patients.size() == 1) {
//                        p = patients.get(0);
//                    }
//                    if (p.getStatus() == 0) {
//                        if (mobile.length() == 11) {
//                            errorMessage = "该手机号已被禁止使用!";
//                        } else {
//                            errorMessage = "该身份证号已被禁止使用!";
//                        }
//                        loginLog.setErrorMessage(errorMessage);
//                        loginLogService.saveLog(loginLog);
//                        return error(-1, errorMessage);
//                    } else if (p.getStatus() == 2) {
//                        errorMessage = "该账号正在审核中,请确认审核通过后再登录,“如有疑问,拨打400-6677-400转2人工客服”";
//                        loginLog.setErrorMessage(errorMessage);
//                        loginLogService.saveLog(loginLog);
//                        return error(-1, errorMessage);
//                    } else if (StringUtils.isEmpty(openId)) {
//                        errorMessage = "无效的OpenID!";
//                        loginLog.setErrorMessage(errorMessage);
//                        loginLogService.saveLog(loginLog);
//                        return error(-1, errorMessage);
//                    }
//                    loginLog.setUserCode(p.getCode());
//                    // 绑定用户手机号和openid
////                    if (!StringUtils.equals(p.getOpenid(), openId) && !"undefined".equals(openId)) {//undefined不更新数据库
////                        //patient.setOpenid(openId);
////                        patientService.updatePatient(p, openId);
////                    }
//                    if (StringUtils.isNotBlank(openId) && !"undefined".equals(openId)) {//undefined不更新数据库
//                        //patient.setOpenid(openId);
//                        //1.判斷居民OPenid是不是空
//                        if(StringUtils.isNotBlank(p.getOpenid())){
//                            //如果OPenid与原来用户不相等,则判断登录的openids是否被大于10人登录
//                            if(!p.getOpenid().equals(openId)){
//                                //判断登录的openids是否被大于10人登录
//                                if(!patientService.checkOpenidCount(openId)){
////                                    errorMessage ="您已超过系统允许登录的最大居民账号数量,当前不再允许使用该微信登录新的居民账号,请使用其他微信号进行登录";
////                                    return error(-2, errorMessage);
//                                }
//                            }
//                            patientService.updatePatient(p, openId);
//                        }else{
//                            // 判断登录的openids是否被大于10人登录
//                            if(!patientService.checkOpenidCount(openId)){
////                                errorMessage ="您已超过系统允许登录的最大居民账号数量,当前不再允许使用该微信登录新的居民账号,请使用其他微信号进行登录";
////                                return error(-2, errorMessage);
//                            }else{
//                                //未达到上限更新用户openid
//                                patientService.updatePatient(p, openId);
//                            }
//                        }
//                    }
//
//                    // 用户校验通过,生成token
//                    Token token = tokenService.newTxToken(p.getCode(), openId);
//                    Map<Object, Object> map = new HashMap<Object, Object>();
//                    map.put("id", p.getId());
//                    map.put("uid", p.getCode());
//                    map.put("name", p.getName());
//                    map.put("token", token.getToken());
//                    map.put("photo", p.getPhoto());
//                    if (StringUtils.isNoneEmpty(openId)) {
//                        //发送微信模板
//                        familyService.sendWXMessage(p);
//                    }
//                    loginLog.setType("1");
//                    loginLogService.saveLog(loginLog);
//                    //判断是否打过标签
//                    //if (!(Patient.isWchatTage.yes.getValue() == p.getIsWxtag())) {
//                    //清空患者的微信标签
//                    weiXinTagUtil.deleteTagWithOpenid(p.getOpenid());
//                    //给患者打微信标签
//                    weiXinTagUtil.addTagWithOpenid(openId, p.getCode(), p.getName());
//                    //}
//                    return write(200, "登录成功", "data", map);
//                }
//            }
//            return error(-1, "登录失败");
//        } catch (Exception e) {
//
//            errorMessage = "系统异常,登录失败";
//            loginLog.setErrorMessage(errorMessage);
//            loginLogService.saveLog(loginLog);
//            error(e);
//            return error(-1, "系统异常,登录失败");
//        }
            return null;
    }
}

+ 2 - 2
svr/svr-patient/src/main/java/com/yihu/jw/patient/endpoint/personal_info/PatientEndpoint.java

@ -4,7 +4,7 @@ import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.sms.SmsDO;
import com.yihu.jw.entity.base.sms.SmsDO;
import com.yihu.jw.entity.base.sms.SmsTemplateDO;
import com.yihu.jw.entity.base.sms.SmsTemplateDO;
import com.yihu.jw.patient.service.personal_Info.PatientService;
import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.patient.util.ConstantUtils;
import com.yihu.jw.patient.util.ConstantUtils;
import com.yihu.jw.restmodel.base.patient.BasePatientVO;
import com.yihu.jw.restmodel.base.patient.BasePatientVO;
import com.yihu.jw.restmodel.base.sms.SmsVO;
import com.yihu.jw.restmodel.base.sms.SmsVO;
@ -42,7 +42,7 @@ import java.util.Map;
public class PatientEndpoint extends EnvelopRestEndpoint {
public class PatientEndpoint extends EnvelopRestEndpoint {
    @Autowired
    @Autowired
    private PatientService patientService;
    private BasePatientService patientService;
    @Value("sms.clientId")
    @Value("sms.clientId")
    private String clientId;
    private String clientId;

+ 77 - 21
svr/svr-patient/src/main/java/com/yihu/jw/patient/service/myFamily/MyFamilyService.java

@ -1,17 +1,19 @@
package com.yihu.jw.patient.service.myFamily;
package com.yihu.jw.patient.service.myFamily;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.base.message.BaseMessageDO;
import com.yihu.jw.entity.base.message.BaseMessageDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.patient.BasePatientFamilyMemberDO;
import com.yihu.jw.entity.base.patient.BasePatientFamilyMemberDO;
import com.yihu.jw.entity.myFamily.PatientApplyLog;
import com.yihu.jw.entity.myFamily.PatientApplyLog;
import com.yihu.jw.message.service.MessageService;
import com.yihu.jw.message.service.MessageService;
import com.yihu.jw.patient.service.personal_Info.PatientService;
import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.wechat.service.WeChatQrcodeService;
import com.yihu.jw.wechat.service.WeChatQrcodeService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.*;
@ -25,7 +27,7 @@ public class MyFamilyService {
    @Autowired
    @Autowired
    private PatientFamilyMemberService patientFamilyMemberService;
    private PatientFamilyMemberService patientFamilyMemberService;
    @Autowired
    @Autowired
    private PatientService patientService;
    private BasePatientService patientService;
    @Autowired
    @Autowired
    private MessageService messageService;
    private MessageService messageService;
    @Value("${myFamily.qrCodeFailurTime}")
    @Value("${myFamily.qrCodeFailurTime}")
@ -84,7 +86,18 @@ public class MyFamilyService {
        return resultList;
        return resultList;
    }
    }
    public void bindingMyFamily(HttpServletRequest request,String wechatId, String saasId, String patient, String familyMobile, Integer platform) throws Exception{
    /**
     * 一键绑定
     * @param request
     * @param wechatId
     * @param saasId
     * @param patient
     * @param familyMobile
     * @param platform
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public PatientApplyLog bindingMyFamily(HttpServletRequest request,String wechatId, String saasId, String patient, String familyMobile, Integer platform) throws Exception{
        BasePatientDO patientDO = patientService.findByIdAndDel(patient);
        BasePatientDO patientDO = patientService.findByIdAndDel(patient);
        //1、检验手机号码是否有存在账号,
        //1、检验手机号码是否有存在账号,
@ -94,24 +107,7 @@ public class MyFamilyService {
        BasePatientDO familyPatient = null;
        BasePatientDO familyPatient = null;
        //3、生成申请绑定的记录,二维码
        //3、生成申请绑定的记录,二维码
        PatientApplyLog patientApplyLog = new PatientApplyLog();
        patientApplyLog.setPatientFamilyMemberName(familyPatient.getName());
        patientApplyLog.setPatienyFamilyMemberCode(familyPatient.getId());
        String scene ="family_"+patient+"_"+familyPatient.getId();
        String qrCode = weChatQrcodeService.getQrcode(request,wechatId, scene);
        if(StringUtils.isEmpty(qrCode)){
            throw new Exception("qrCode is null");
        }
        patientApplyLog.setQrCode(qrCode);
        Long time = 1000*60*60*Long.valueOf(qrCodeFailurTime);
        Long failurTime = (new Date()).getTime()+time;
        patientApplyLog.setFailureTime(new Date(failurTime));
        patientApplyLog.setDel(1);
        patientApplyLog.setCreateTime(new Date());
        patientApplyLog.setCreateUser(patient);
        patientApplyLog.setCreateUserName(patientDO.getName());
        patientApplyLogService.save(patientApplyLog);
        PatientApplyLog patientApplyLog = createFamilyQrCode(request,familyPatient,wechatId,patient);
        //4、发送绑定家人的系统消息
        //4、发送绑定家人的系统消息
        BaseMessageDO messageDO = new BaseMessageDO();
        BaseMessageDO messageDO = new BaseMessageDO();
        messageDO.setSaasId(saasId);
        messageDO.setSaasId(saasId);
@ -132,13 +128,73 @@ public class MyFamilyService {
        messageDO.setDel("1");
        messageDO.setDel("1");
        messageDO.setCreateTime(new Date());
        messageDO.setCreateTime(new Date());
        messageService.save(messageDO);
        messageService.save(messageDO);
        return patientApplyLog;
    }
    /**
     * 生成绑定家人的二维码
     * @param request
     * @param familyPatient
     * @param wechatId
     * @param patient
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public PatientApplyLog createFamilyQrCode(HttpServletRequest request,BasePatientDO familyPatient,String wechatId, String patient) throws Exception{
        BasePatientDO patientDO = patientService.findByIdAndDel(patient);
        PatientApplyLog patientApplyLog = new PatientApplyLog();
        patientApplyLog.setPatientFamilyMemberName(familyPatient.getName());
        patientApplyLog.setPatienyFamilyMemberCode(familyPatient.getId());
        String scene ="family_"+familyPatient.getId()+"_"+familyPatient.getId();
        String qrCode = weChatQrcodeService.getQrcode(request,wechatId, scene);
        if(StringUtils.isEmpty(qrCode)){
            throw new Exception("qrCode is null");
        }
        patientApplyLog.setQrCode(qrCode);
        Long time = 1000*60*60*Long.valueOf(qrCodeFailurTime);
        Long failurTime = (new Date()).getTime()+time;
        patientApplyLog.setFailureTime(new Date(failurTime));
        patientApplyLog.setDel(1);
        patientApplyLog.setCreateTime(new Date());
        patientApplyLog.setCreateUser(familyPatient.getId());
        patientApplyLog.setCreateUserName(patientDO.getName());
        patientApplyLogService.save(patientApplyLog);
        return patientApplyLog;
    }
    }
    /**
     * 更新提醒方式
     * @param patientApplyLogId
     * @param remindType
     * @throws Exception
     */
    public void remindMyFamily(Integer patientApplyLogId,Integer remindType) throws Exception{
        int i = patientApplyLogService.updateRemindTypeById(remindType,patientApplyLogId);
        if(i<0){
            throw new Exception("update data failur !");
        }
    }
    public void confirmApply(Integer messageId,Integer patientApplyLogId){
        BaseMessageDO messageDO = null;
        if(messageId!=null){
            messageDO = messageService.findById(messageId);
        }
        if(messageDO!=null&&patientApplyLogId==null){
            String json = messageDO.getRelationData();
            JSONObject jsonObject = JSONObject.parseObject(json);
            patientApplyLogId = (Integer)jsonObject.get("patientApplyLogId");
            messageDO.setReadState(1);
            messageDO.setReadTime(new Date());
            messageService.save(messageDO);
        }
    }
    /**
    /**
     * 家庭关系转换
     * 家庭关系转换

+ 12 - 1
svr/svr-patient/src/main/java/com/yihu/jw/patient/service/myFamily/PatientApplyLogService.java

@ -3,7 +3,6 @@ package com.yihu.jw.patient.service.myFamily;
import com.yihu.jw.entity.myFamily.PatientApplyLog;
import com.yihu.jw.entity.myFamily.PatientApplyLog;
import com.yihu.jw.patient.dao.myFamily.PatientApplyLogDao;
import com.yihu.jw.patient.dao.myFamily.PatientApplyLogDao;
import com.yihu.mysql.query.BaseJpaService;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.stereotype.Service;
/**
/**
 * @author liuwenbin on 2018/11/30.
 * @author liuwenbin on 2018/11/30.
@ -11,4 +10,16 @@ import org.springframework.stereotype.Service;
@Service
@Service
public class PatientApplyLogService extends BaseJpaService<PatientApplyLog, PatientApplyLogDao> {
public class PatientApplyLogService extends BaseJpaService<PatientApplyLog, PatientApplyLogDao> {
    @Autowired
    private PatientApplyLogDao patientApplyLogDao;
    /**
     * 更新提醒方式
     * @param remindType 提醒方式(1、打电话,2、发短信,3、微信)
     * @param patientApplyLogId
     * @return
     */
    public int updateRemindTypeById(Integer remindType, Integer patientApplyLogId){
        return  patientApplyLogDao.updateRemindTypeById(remindType,patientApplyLogId);
    }
}
}

+ 10 - 18
svr/svr-patient/src/main/java/com/yihu/jw/patient/service/personal_Info/PatientService.java

@ -5,6 +5,7 @@ import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.exception.business.patient.CapthcaInvalidException;
import com.yihu.jw.exception.business.patient.CapthcaInvalidException;
import com.yihu.jw.exception.business.patient.NotFoundPatientException;
import com.yihu.jw.exception.business.patient.NotFoundPatientException;
import com.yihu.jw.file_upload.FileUploadService;
import com.yihu.jw.file_upload.FileUploadService;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.dao.personal_info.PatientDao;
import com.yihu.jw.patient.dao.personal_info.PatientDao;
import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.patient.util.ConstantUtils;
import com.yihu.jw.patient.util.ConstantUtils;
@ -15,12 +16,14 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Transactional;
import java.util.UUID;
/**
/**
 * 居民信息服务
 * 居民信息服务
 * @author litaohong on  2018年11月28日
 * @author litaohong on  2018年11月28日
 */
 */
@Service
@Service
public class PatientService extends BasePatientService {
public class PatientService extends BasePatientService<BasePatientDO, BasePatientDao> {
    @Autowired
    @Autowired
    private PatientDao patientDao;
    private PatientDao patientDao;
@ -28,9 +31,6 @@ public class PatientService extends BasePatientService {
    @Autowired
    @Autowired
    private BaseSmsService baseSmsService;
    private BaseSmsService baseSmsService;
    @Autowired
    private FileUploadService fileUploadService;
    /**
    /**
     * 设置登录密码
     * 设置登录密码
     * @param id
     * @param id
@ -43,9 +43,10 @@ public class PatientService extends BasePatientService {
        if(null == patient){
        if(null == patient){
            throw new NotFoundPatientException("当前居民不存在:【 " + id + "】");
            throw new NotFoundPatientException("当前居民不存在:【 " + id + "】");
        }
        }
        patient.setSalt(randomString(5));
        String salt = UUID.randomUUID().toString().replace("-", "");
        patient.setSalt(salt);
        password = patient.getIdcard().substring(0, 5);
        password = patient.getIdcard().substring(0, 5);
        patient.setPassword(MD5.md5Hex(password + "{" + patient.getSalt() + "}"));
        patient.setPassword(MD5.md5Hex(password + patient.getSalt()));
        return ConstantUtils.SUCCESS;
        return ConstantUtils.SUCCESS;
    }
    }
@ -65,7 +66,7 @@ public class PatientService extends BasePatientService {
            throw new NotFoundPatientException("当前居民不存在:【 " + id + "】");
            throw new NotFoundPatientException("当前居民不存在:【 " + id + "】");
        }
        }
        patient.setSalt(randomString(5));
        patient.setSalt(randomString(5));
        patient.setPassword(MD5.md5Hex(newPassword + "{" + patient.getSalt() + "}"));
        patient.setPassword(MD5.md5Hex(newPassword + patient.getSalt() ));
        return ConstantUtils.SUCCESS;
        return ConstantUtils.SUCCESS;
    }
    }
@ -100,17 +101,8 @@ public class PatientService extends BasePatientService {
        return patientDO;
        return patientDO;
    }
    }
    /**
     * 根据patient的id获取居民信息
     * @param patient
     * @return
     */
    public BasePatientDO findByIdAndDel(String patient) throws Exception{
        BasePatientDO basePatientDO = patientDao.findByIdAndDel(patient,"1");
        if(basePatientDO==null){
            throw new Exception("not patient");
        }
        return basePatientDO;
    public void updateOpenId(String openId){
    }
    }
}
}

+ 20 - 0
svr/svr-patient/src/main/java/com/yihu/jw/patient/util/CommonUtils.java

@ -0,0 +1,20 @@
package com.yihu.jw.patient.util;
import org.apache.commons.lang3.StringUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CommonUtils {
    public static boolean isMobile(String str) {
        boolean b = false;
        String s2="^[1](([3][0-9])|([4][5,7,9])|([5][^4,6,9])|([6][6])|([7][3,5,6,7,8])|([8][0-9])|([9][8,9]))[0-9]{8}$";// 验证手机号
        if(StringUtils.isNotBlank(str)){
            Pattern p = Pattern.compile(s2);
            Matcher m = p.matcher(str);
            b = m.matches();
        }
        return b;
    }
}

+ 182 - 0
svr/svr-patient/src/main/java/com/yihu/jw/patient/util/RSAService.java

@ -0,0 +1,182 @@
package com.yihu.jw.patient.util;
import java.io.*;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Iterator;
import com.yihu.jw.entity.base.security.RSA;
import com.yihu.jw.patient.dao.security.RSADao;
import com.yihu.jw.util.common.RSAUtils;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class RSAService {
    @Autowired
    private RSADao rsaDao;
    /**
     * 缓存的密钥对。
     */
    private KeyPair oneKeyPair = null;
    /**
     * 读取RSA加密信息
     * @return
     */
    public RSA loadRSA() {
        Iterable<RSA> iterable = rsaDao.findAll();
        if (iterable != null) {
            Iterator<RSA> it = iterable.iterator();
            if (it != null && it.hasNext()) {
                return it.next();
            }
        }
        return null;
    }
    public KeyPair getKeyPair() {
        if (oneKeyPair == null) {
            // 从数据库加载
            RSA rsa = loadRSA();
            if (rsa == null) {
                // 生成密钥
                generateKeyPair();
            } else {
                // 由数据库取出来
                Object obj = toObject(rsa.getData());
                oneKeyPair = (KeyPair) obj;
            }
        }
        return oneKeyPair;
    }
    /**
     * 生成并返回RSA密钥对。
     */
    private synchronized KeyPair generateKeyPair() {
        try {
            oneKeyPair = RSAUtils.initKey();
            // 保存到数据库
            saveRSA(oneKeyPair);
            return oneKeyPair;
        } catch (InvalidParameterException ex) {
            ex.printStackTrace();
        } catch (NullPointerException ex) {
            ex.printStackTrace();
        }
        return null;
    }
    /**
     * 保存RSA加密信息
     * @return
     */
    public RSA saveRSA(KeyPair keyPair) {
        RSA rsa = new RSA();
        rsa.setData(toByteArray(keyPair));
        // 先清空
        rsaDao.deleteAll();
        // 再添加
        return rsaDao.save(rsa);
    }
    /**
     * 返回已初始化的默认的公钥。
     */
    public RSAPublicKey getDefaultPublicKey() {
        KeyPair keyPair = getKeyPair();
        if (keyPair != null) {
            return (RSAPublicKey) keyPair.getPublic();
        }
        return null;
    }
    public String getModulus() {
        return new String(Hex.encodeHex(getDefaultPublicKey().getModulus().toByteArray()));
    }
    public String getExponent() {
        return new String(Hex.encodeHex(getDefaultPublicKey().getPublicExponent().toByteArray()));
    }
    /**
     * 对象转数组
     *
     * @param obj
     * @return
     */
    public byte[] toByteArray(Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray();
            oos.close();
            bos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return bytes;
    }
    /**
     * 数组转对象
     *
     * @param bytes
     * @return
     */
    public Object toObject(byte[] bytes) {
        Object obj = null;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bis);
            obj = ois.readObject();
            ois.close();
            bis.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        return obj;
    }
    /**
     * 使用默认的私钥解密给定的字符串。
     * <p>
     * 若{@code encrypttext} 为 {@code null}或空字符串则返回 {@code null}。
     * 私钥不匹配时,返回 {@code null}。
     *
     * @param encrypttext 密文。
     * @return 原文字符串。
     */
    public String decryptString(String encrypttext) {
        if (StringUtils.isBlank(encrypttext)) {
            return null;
        }
        try {
            byte[] en_data = Hex.decodeHex(encrypttext.toCharArray());
            byte[] data =   RSAUtils.decrypt((RSAPrivateKey) getKeyPair().getPrivate(), en_data);
            return new String(data);
        } catch (NullPointerException ex) {
            ex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}

+ 1 - 1
svr/svr-patient/src/main/resources/bootstrap.yml

@ -1,6 +1,6 @@
spring:
spring:
  application:
  application:
    name: svr-patient
    name: svr-patient-lyx
  cloud:
  cloud:
    config:
    config:
      failFast: true
      failFast: true

+ 6 - 0
wlyy-parent-pom/pom.xml

@ -99,6 +99,7 @@
        <version.poi>3.17</version.poi>
        <version.poi>3.17</version.poi>
        <version.jxl>2.6.10</version.jxl>
        <version.jxl>2.6.10</version.jxl>
        <version.okhttp>3.4.1</version.okhttp>
        <version.okhttp>3.4.1</version.okhttp>
        <version.jackson-dataformat-xml>2.6.6</version.jackson-dataformat-xml>
        <!-- Version end -->
        <!-- Version end -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@ -170,6 +171,11 @@
                <artifactId>common-tracer</artifactId>
                <artifactId>common-tracer</artifactId>
                <version>${version.wlyy-common}</version>
                <version>${version.wlyy-common}</version>
            </dependency>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.dataformat</groupId>
                <artifactId>jackson-dataformat-xml</artifactId>
                <version>${version.jackson-dataformat-xml}</version>
            </dependency>
            <!-- Jkzl Starter -->
            <!-- Jkzl Starter -->
            <dependency>
            <dependency>