Przeglądaj źródła

Merge remote-tracking branch 'origin/dev' into dev

zdm 5 lat temu
rodzic
commit
806d3a089c

+ 32 - 10
business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/PrescriptionService.java

@ -1665,6 +1665,16 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                    "GROUP BY a.score_type";
            List<Map<String,Object>> listscore = jdbcTemplate.queryForList(sqlscore);
    
            Double doctorScore = new Double("0");
    
            if(listscore!=null&&listscore.size()>0){
                for(Map<String,Object> _listscore :listscore){
                    doctorScore += (Double)_listscore.get("score");
                }
            }
            doctorScore = doctorScore/3;
            rs.put("doctorScore",doctorScore);
    
            if(listscore!=null&&listscore.size()>0){
                rs.put("scoreDoctor",listscore);
            }else{
@ -1674,6 +1684,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            //查询评价明细
            String sqlScoreList = "SELECT " +
                    "a.score as score," +
                    "b.score as doctorscore," +
                    "a.score_type as score_type," +
                    "a.content as content," +
                    "b.create_time as create_time," +
@ -2237,16 +2248,26 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        return rs;
    }
    @Autowired
    private HttpClientUtil httpClientUtil;
//    @Autowired
//    private HttpClientUtil httpClientUtil;
    public String test() {
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("clientId", "ihealth_pa8DIRJasL"));
        params.add(new BasicNameValuePair("clientSecret", "jkzl1h7aj39dnasyi23fnkv92"));
        params.add(new BasicNameValuePair("code", "b60bab0617c04b23b7fa0a059cc83eb6"));
        params.add(new BasicNameValuePair("openid","oULM4xAj9sOsHJ95ttKYd_Fjh6Hc"));
        String res = httpClientUtil.post("http://www.xmtyw.cn/wlyy/iHealth/userInfo", params, "UTF-8");
        return res;
//        List<NameValuePair> params = new ArrayList<>();
////        params.add(new BasicNameValuePair("clientId", "ihealth_pa8DIRJasL"));
////        params.add(new BasicNameValuePair("clientSecret", "jkzl1h7aj39dnasyi23fnkv92"));
////        params.add(new BasicNameValuePair("code", "b60bab0617c04b23b7fa0a059cc83eb6"));
//        params.add(new BasicNameValuePair("openid","o0hubt3byGmNYLyC-UvmSVyUuZkI"));
//        //String res = httpClientUtil.post("http://www.xmtyw.cn/wlyy/iHealth/userInfo", params, "UTF-8");
//        //https://wx.xmzsh.com
//        String res = httpClientUtil.post("https://wx.xmzsh.com/interface/getUserInfoByOpenId.htm", params, "UTF-8");
//        return res;
//
//        com.alibaba.fastjson.JSONObject jsonObject=new com.alibaba.fastjson.JSONObject();
//        jsonObject.put("openId","o0hubt3byGmNYLyC-UvmSVyUuZkI");
//        String responseMsg =httpClientUtil.sendPost("https://wx.xmzsh.com/interface/getUserInfoByOpenId.htm",jsonObject.toString());
//        com.alibaba.fastjson.JSONObject object1 = com.alibaba.fastjson.JSONObject.parseObject(responseMsg);
//        return object1.toString();
        return null;
    }
    
    
@ -2269,7 +2290,8 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                "room.reservation_type AS reservation_type," +
                "outpatient.disease_img AS disease_img," +
                "outpatient.description AS description," +
                "outpatient.origin_con_no AS origin_con_no " +
                "outpatient.origin_con_no AS origin_con_no, " +
                "consult.consult AS consult " +
                "FROM " +
                "wlyy_hospital_waiting_room room," +
                "base_patient patient," +

+ 75 - 0
business/base-service/src/main/java/com/yihu/jw/wechat/service/WechatInfoService.java

@ -1,6 +1,8 @@
package com.yihu.jw.wechat.service;
import com.yihu.jw.entity.base.wx.JsApiTicket;
import com.yihu.jw.entity.base.wx.WxWechatDO;
import com.yihu.jw.hospital.prescription.service.entrance.EntranceService;
import com.yihu.jw.util.wechat.wxhttp.HttpUtil;
import com.yihu.jw.wechat.dao.WechatDao;
import org.json.JSONObject;
@ -12,6 +14,11 @@ public class WechatInfoService {
    @Autowired
    private WechatDao wechatDao;
    
    @Autowired
    private WxAccessTokenService wxAccessTokenService;
    @Autowired
    private EntranceService entranceService;
    /**
     * 通过code获取判断openid
@ -43,4 +50,72 @@ public class WechatInfoService {
        WxWechatDO wxWechatDO = wechatDao.findById(wxId);
        return getOpenidByCode(code,wxWechatDO.getAppId(),wxWechatDO.getAppSecret());
    }
    
    /**
     * 获取微信的jsapi_ticket
     *
     * @return
     */
    public String getJsapi_ticketByToken(String wxId) throws Exception {
        try {
            
            Iterable<JsApiTicket> jsapiTickets = null;
            WxWechatDO wxWechat = null;
            
            //中山医院互联网医院
            if("xm_zsyy_wx".equals(wxId)){
                jsapiTickets = wxAccessTokenService.findJsapiTicket(wxId);
            }else{
                wxWechat = wxAccessTokenService.getWxInfo(wxId);
                jsapiTickets = wxAccessTokenService.findJsapiTicket(wxWechat.getAppOriginId());
            }
            
            if (jsapiTickets != null) {
                for (JsApiTicket jsApiTicket : jsapiTickets) {
                    if ((System.currentTimeMillis() - jsApiTicket.getAdd_timestamp()) < (jsApiTicket.getExpires_in() * 1000)) {
                        return jsApiTicket.getJsapi_ticket();
                    } else {
                        wxAccessTokenService.delJsapiTicket(jsApiTicket);
                        break;
                    }
                }
            }
            String token = "";
            
            //中山医院互联网医院
            if("xm_zsyy_wx".equals(wxId)){
                token = entranceService.getAccessToken("100033");
            }else{
                token = wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
            }
            
            if (token != null) {
                String token_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
                String params = "access_token=" + token + "&type=jsapi";
                String result = HttpUtil.sendGet(token_url, params);
                JSONObject json = new JSONObject(result);
                if (json.has("ticket")) {
                    String ticket = json.get("ticket").toString();
                    String expires_in = json.get("expires_in").toString();
                    JsApiTicket newJsApiTicket = new JsApiTicket();
                    newJsApiTicket.setJsapi_ticket(ticket);
                    newJsApiTicket.setExpires_in(Long.parseLong(expires_in));
                    if("xm_zsyy_wx".equals(wxId)){
                        newJsApiTicket.setAcc_id(wxId);
                    }else{
                        newJsApiTicket.setAcc_id(wxWechat.getAppOriginId());
                    }
                    
                    wxAccessTokenService.addJsapiTicket(newJsApiTicket);
                    return ticket;
                } else {
                    return null;
                }
            } else {
                return null;
            }
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }
}

+ 59 - 19
business/im-service/src/main/java/com/yihu/jw/im/service/ImService.java

@ -962,6 +962,28 @@ public class ImService {
			return -1;
		}
		
		
		String name = "";
		String returnJson = "";
		
		/**
		 * 发送评价消息
		 */
		BaseDoctorDO doctor = baseDoctorDao.findById(consultTeam.getDoctor());
		BasePatientDO patient = basePatientDao.findById(consultTeam.getPatient());
		JSONObject evalueContent = new JSONObject();
		evalueContent.put("patientCode",consultTeam.getPatient());
		evalueContent.put("patientName",patient.getName());
		evalueContent.put("doctorCode",consultTeam.getDoctor());
		evalueContent.put("doctorName",doctor.getName());
		evalueContent.put("doctorPhoto",doctor.getPhoto());
		evalueContent.put("consultCode",consult);
		
//		returnJson = imUtil.sendIM(consultTeam.getDoctor(), consultTeam.getPatient(), "28", evalueContent.toString());
		String response = imUtil.sendTopicIM(consultTeam.getDoctor(), doctor.getName(), consult, "28", evalueContent.toString(),null);
		
		
		
		String endName = "";
		String endId = "";
		JSONObject obj = new JSONObject();
@ -992,21 +1014,7 @@ public class ImService {
		}
		
		
		String name = "";
		String returnJson = "";
		
		BasePatientDO p = basePatientDao.findById(endOperator);
		BaseDoctorDO d = baseDoctorDao.findById(endOperator);
		name = d.getName();
		
		JSONObject evalueContent = new JSONObject();
		evalueContent.put("patientCode",p.getId());
		evalueContent.put("patientName",p.getName());
		evalueContent.put("doctorCode",d.getId());
		evalueContent.put("doctorName",d.getName());
		evalueContent.put("consultCode",consult);
		
		returnJson = imUtil.sendIM(consultTeam.getDoctor(), consultTeam.getPatient(), "28", name + "结束了本次咨询");
//		//推送给IM文字消息
//		if (endType == 1) {
//			BasePatientDO p = basePatientDao.findById(endOperator);
@ -1065,7 +1073,7 @@ public class ImService {
		
		JSONObject object = imUtil.getTopic(consult);
		
		ConsultTeamDo consultTeamDo = consultTeamDao.findOne(consult);
		ConsultTeamDo consultTeamDo = consultTeamDao.findByConsult(consult);
		
		object.put("doctorCode",consultTeamDo.getDoctor());
		
@ -1186,9 +1194,15 @@ public class ImService {
			consultTeamDo.setEvaluateTime(new Date());
			consultTeamDao.save(consultTeamDo);
			
			/**
			 * todo 保存就诊记录表已评价标识
			 */
			ConsultDo consultDo = consultDao.findOne(consult);
			
			//如果是复诊咨询,则修改成已评价
			if("9".equals(consultDo.getType())){
				WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findOne(consultTeamDo.getRelationCode());
				wlyyOutpatientDO.setEvaluateStatus("1");
				outpatientDao.save(wlyyOutpatientDO);
			}
			
		
		}
		
@ -1204,4 +1218,30 @@ public class ImService {
		baseDoctorDO.setConsultStatus(consultStatus);
		baseDoctorDao.save(baseDoctorDO);
	}
	
	public List<Map<String,Object>> getEvaluationByConsultCode(String consult) {
		//查询评价明细
		String sqlScoreList = "SELECT " +
				"a.score as score," +
				"a.score_type as score_type," +
				"a.content as content," +
				"b.create_time as create_time," +
				"c.type as type," +
				"c.name as patientname," +
				"b.id as id," +
				"c.photo as patientphoto," +
				"b.type as niming " +
				"FROM " +
				"base_evaluate a " +
				"LEFT JOIN base_evaluate_score b ON b.id=a.relation_code " +
				"LEFT JOIN wlyy_consult_team c ON c.consult=b.relation_code " +
				"WHERE a.relation_code=b.id "+
				"AND c.consult='"+consult+"'";
		List<Map<String,Object>> scoreList = jdbcTemplate.queryForList(sqlScoreList);
		if(scoreList.isEmpty()){
			return null;
		}else{
			return scoreList;
		}
	}
}

+ 6 - 0
common/common-request-mapping/src/main/java/com/yihu/jw/rm/hospital/BaseHospitalRequestMapping.java

@ -315,6 +315,12 @@ public class BaseHospitalRequestMapping {
        
        //评价咨询
        public static final String evaluationByConsultCode = "/evaluationByConsultCode";
        
        //根据咨询CODE返回评价详情
        public static final String getEvaluationByConsultCode = "getEvaluationByConsultCode";
    
        //获取微信签名
        public static final String getSign ="/getSign";
        
    }

+ 193 - 93
server/svr-authentication/src/main/java/com/yihu/jw/security/core/userdetails/jdbc/WlyyUserDetailsService.java

@ -118,10 +118,12 @@ public class WlyyUserDetailsService extends JdbcDaoSupport implements UserDetail
        } else if ("2".equals(loginType)) {//2.为医生账号
            //解除锁定
            this.getJdbcTemplate().update("update base_doctor d set d.login_failure_count = 0, d.locked = 0 where d.mobile = ? or d.idcard = ?", username, username);
        } else if ("3".equals(loginType) || "4".equals(loginType)) { //3.患者账号
        } else if ("3".equals(loginType)) { //3.患者账号
            //解除锁定
            this.getJdbcTemplate().update("update base_patient p set p.login_failure_count = 5, p.locked = 0 where p.mobile = ? or p.idcard = ?", username, username);
        } //...
        } else if("4".equals(loginType)){
            this.getJdbcTemplate().update("update base_patient p set p.login_failure_count = 5, p.locked = 0 where p.mobile = ? or p.idcard = ?", username, getIdcard());
        }//...
    }
    /**
@ -155,98 +157,175 @@ public class WlyyUserDetailsService extends JdbcDaoSupport implements UserDetail
                redisTemplate.delete(BespeakRegist + username);
            }
            users = this.getJdbcTemplate().query(DEFAULT_PATIENT_DETAILS_STATEMENT, new BeanPropertyRowMapper(WlyyUserDetails.class), username, username);
            // 去i健康查询用户
            // 第三方同步居民,端查询用户
        }else if("4".equals(loginType)){
            users = this.getJdbcTemplate().query(DEFAULT_PATIENT_DETAILS_IDCARD_STATEMENT, new BeanPropertyRowMapper(WlyyUserDetails.class), getIdcard());
            if ((null == users || users.size() == 0) && "4".equals(loginType)) {
                List<NameValuePair> params = new ArrayList<>();
                params.add(new BasicNameValuePair("clientId", getClientId()));
                ClientDetails clientDetails = clientDetailsService.loadClientByClientId(getClientId());
                params.add(new BasicNameValuePair("clientSecret", clientDetails.getClientSecret()));
                params.add(new BasicNameValuePair("code", username));
                params.add(new BasicNameValuePair("openid", getOpenid()));
                String res = null;
                try{
                    res = httpClientUtil.post(iHealthUserInfoUrl, params, "UTF-8");
                }catch (Exception e){
                    logger.error("远程请求i健康用户信息异常:" + e.getMessage());
                    return users;
                }
                if(null == res){
                    return users;
                }
                JSONObject patient = JSONObject.parseObject(res);
                if(patient.getInteger("status") == -1){
                    logger.error("去i健康查询用户信息失败:" + patient.getString("error"));
                    return users;
                }
                try {
                    String salt = randomString(5);
                    String idcard = patient.getString("idcard");
                    String pw = idcard.substring(idcard.length()-6);
                    this.getJdbcTemplate().update(DEFAULT_PATIENT_INSERT_STATEMENT,
                            new Object[]{patient.getString("code"),
                                    patient.getString("photo"),
                                    patient.getString("idcard"),
                                    MD5.md5Hex(pw + "{" + salt + "}"),
                                    patient.getString("salt"),
                                    patient.getString("name"),
                                    patient.getDate("birthday"),
                                    patient.getInteger("sex"),
                                    patient.getString("mobile"),
                                    patient.getString("province"),
                                    patient.getString("provinceName"),
                                    patient.getString("city"),
                                    patient.getString("cityName"),
                                    patient.getString("town"),
                                    patient.getString("townName"),
                                    patient.getString("street"),
                                    patient.getString("streetName"),
                                    patient.getString("address"),
                                    1,
                                    0,
                                    1,
                                    0,
                                    new Date()
                            }
                    );
                }catch (Exception e){
                    logger.error("将i健康居民数据同步到互联网医院居民表失败:" + e.getMessage());
                    return users;
                }
                try {
                    this.getJdbcTemplate().update(PATIENT_INSERT_WEHCAT,
                            new Object[]{
                                    UUID.randomUUID().toString(),
                                    getWechatId(),
                                    patient.getString("code"),
                                    getOpenid(),
                                    new Date()
                            }
                    );
                }catch (Exception e){
                    logger.error("将i健康居民微信openid数据同步到互联网医院居民微信关联表失败:" + e.getMessage());
                    return users;
                }
            users = this.getJdbcTemplate().query(DEFAULT_PATIENT_DETAILS_STATEMENT, new BeanPropertyRowMapper(WlyyUserDetails.class),username,getIdcard());
            if (null == users || users.size() == 0) {
                //厦门I健康账号同步
                if("xm_ihealth_wx".equals(getWechatId())){
                    List<NameValuePair> params = new ArrayList<>();
                    params.add(new BasicNameValuePair("clientId", getClientId()));
                    ClientDetails clientDetails = clientDetailsService.loadClientByClientId(getClientId());
                    params.add(new BasicNameValuePair("clientSecret", clientDetails.getClientSecret()));
                    params.add(new BasicNameValuePair("code", username));
                    params.add(new BasicNameValuePair("openid", getOpenid()));
                    String res = null;
                    try{
                        res = httpClientUtil.post(getSynPath(getWechatId()), params, "UTF-8");
                    }catch (Exception e){
                        logger.error("远程请求i健康用户信息异常:" + e.getMessage());
                        return users;
                    }
                    if(null == res){
                        return users;
                    }
                    JSONObject patient = JSONObject.parseObject(res);
                    if(patient.getInteger("status") == -1){
                        logger.error("去i健康查询用户信息失败:" + patient.getString("error"));
                        return users;
                    }
                    try {
                        String salt = randomString(5);
                        String idcard = patient.getString("idcard");
                        String pw = idcard.substring(idcard.length()-6);
                        this.getJdbcTemplate().update(DEFAULT_PATIENT_INSERT_STATEMENT,
                                new Object[]{patient.getString("code"),
                                        patient.getString("photo"),
                                        patient.getString("idcard"),
                                        MD5.md5Hex(pw + "{" + salt + "}"),
                                        salt,
                                        patient.getString("name"),
                                        patient.getDate("birthday"),
                                        patient.getInteger("sex"),
                                        patient.getString("mobile"),
                                        patient.getString("province"),
                                        patient.getString("provinceName"),
                                        patient.getString("city"),
                                        patient.getString("cityName"),
                                        patient.getString("town"),
                                        patient.getString("townName"),
                                        patient.getString("street"),
                                        patient.getString("streetName"),
                                        patient.getString("address"),
                                        1,
                                        0,
                                        1,
                                        0,
                                        new Date()
                                }
                        );
                    }catch (Exception e){
                        logger.error("将i健康居民数据同步到互联网医院居民表失败:" + e.getMessage());
                        return users;
                    }
                    try {
                        this.getJdbcTemplate().update(PATIENT_INSERT_WEHCAT,
                                new Object[]{
                                        UUID.randomUUID().toString(),
                                        getWechatId(),
                                        patient.getString("code"),
                                        getOpenid(),
                                        new Date()
                                }
                        );
                    }catch (Exception e){
                        logger.error("将i健康居民微信openid数据同步到互联网医院居民微信关联表失败:" + e.getMessage());
                        return users;
                    }
                    WlyyUserDetails user = new WlyyUserDetails();
                    user.setName(patient.getString("name"));
                    user.setPassword(patient.getString("password"));
                    if(patient.getInteger("sex") == 1){
                        user.setGender(WlyyUserDetails.Gender.male);
                    }else if(patient.getInteger("sex") == 2){
                        user.setGender(WlyyUserDetails.Gender.female);
                    }
                    user.setId(username);
                    user.setIdcard(patient.getString("idcard"));
                    user.setMobile(patient.getString("mobile"));
                    user.setEnabled(true);
                    user.setLocked(false);
                    user.setLockedDate(null);
                    users.add(user);
                }else if("xm_zsyy_wx".equals(getWechatId())){
                    JSONObject jsonObject=new JSONObject();
                    jsonObject.put("openId",getOpenid());
                    String res = null;
                    try{
                        res = httpClientUtil.sendPost(getSynPath("xm_zsyy_wx"), jsonObject.toString());
                    }catch (Exception e){
                        logger.error("远程请求中山医院用户信息异常:" + e.getMessage());
                        return users;
                    }
                    if(null == res){
                        return users;
                    }
                    JSONObject object1 = JSONObject.parseObject(res);
                    if (null != object1&&null!=object1.get("status") && "200".equals(object1.get("status").toString())) {
                        JSONObject patient = object1.getJSONObject("userinfo");
                        String salt = randomString(5);
                        String mobile = patient.getString("mobile");
                        String pw = mobile.substring(mobile.length()-6);
                        try {
                            this.getJdbcTemplate().update(DEFAULT_PATIENT_INSERT_STATEMENT,
                                    new Object[]{patient.getString("id"),
                                            null,
                                            patient.getString("idcard"),
                                            MD5.md5Hex(pw + "{" + salt + "}"),
                                            salt,
                                            patient.getString("name"),
                                            patient.getDate("birthday"),
                                            patient.getInteger("sex"),
                                            mobile,
                                            null,
                                            null,
                                            null,
                                            null,
                                            null,
                                            null,
                                            null,
                                            null,
                                            null,
                                            1,
                                            0,
                                            1,
                                            0,
                                            new Date()
                                    }
                            );
                        }catch (Exception e){
                            logger.error("将中山医院居民数据同步到互联网医院居民表失败:" + e.getMessage());
                            return users;
                        }
                        WlyyUserDetails user = new WlyyUserDetails();
                        user.setName(patient.getString("name"));
                        user.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                        if(patient.getInteger("sex") == 1){
                            user.setGender(WlyyUserDetails.Gender.male);
                        }else if(patient.getInteger("sex") == 2){
                            user.setGender(WlyyUserDetails.Gender.female);
                        }
                        user.setId(patient.getString("id"));
                        user.setIdcard(patient.getString("idcard"));
                        user.setMobile(patient.getString("mobile"));
                        user.setEnabled(true);
                        user.setLocked(false);
                        user.setLockedDate(null);
                        users.add(user);
                    }else{
                        logger.error("远程请求中山医院用户信息异常:" + res.toString());
                        return users;
                    }
                WlyyUserDetails user = new WlyyUserDetails();
                user.setName(patient.getString("name"));
                user.setPassword(patient.getString("password"));
                if(patient.getInteger("sex") == 1){
                    user.setGender(WlyyUserDetails.Gender.male);
                }else if(patient.getInteger("sex") == 2){
                    user.setGender(WlyyUserDetails.Gender.female);
                }
                user.setId(username);
                user.setIdcard(patient.getString("idcard"));
                user.setMobile(patient.getString("mobile"));
                user.setEnabled(true);
                user.setLocked(false);
                user.setLockedDate(null);
                users.add(user);
            }
        }
        return users;
@ -313,6 +392,8 @@ public class WlyyUserDetailsService extends JdbcDaoSupport implements UserDetail
            result = this.getJdbcTemplate().queryForMap("select d.login_failure_count,d.last_login_failure_time from base_doctor d where d.mobile = ? or d.idcard = ?", username, username);
        } else if ("3".equals(loginType)) { //3.患者账号
            result = this.getJdbcTemplate().queryForMap("select p.login_failure_count,p.last_login_failure_time from base_patient p where p.mobile = ? or p.idcard = ?", username, username);
        } else if ("4".equals(loginType)) { //4.第三方患者账号
            result = this.getJdbcTemplate().queryForMap("select p.login_failure_count,p.last_login_failure_time from base_patient p where p.mobile = ? or p.idcard = ?", username, getIdcard());
        }
        return result;
    }
@ -333,7 +414,10 @@ public class WlyyUserDetailsService extends JdbcDaoSupport implements UserDetail
        } else if ("3".equals(loginType)) { //3.患者账号
            //账号锁定
            this.getJdbcTemplate().update("update base_patient p set p.login_failure_count = 5, p.locked = 1, p.locked_date = ?  where p.mobile = ? or p.idcard = ?", new Date(), username, username);
        } //...
        }else if ("4".equals(loginType)) { //3.同步的患者账号
            //账号锁定
            this.getJdbcTemplate().update("update base_patient p set p.login_failure_count = 5, p.locked = 1, p.locked_date = ?  where p.mobile = ? or p.idcard = ?", new Date(), username, getIdcard());
        }  //...
    }
    /**
@ -353,6 +437,9 @@ public class WlyyUserDetailsService extends JdbcDaoSupport implements UserDetail
        } else if ("3".equals(loginType)) { //3.患者账号
            //更新失败次数
            this.getJdbcTemplate().update("update base_patient p set p.login_failure_count = ? ,p.last_login_failure_time = ? where p.mobile = ? or p.idcard = ?", loginFailureCount, new Date(), username, username);
        } else if ("4".equals(loginType)) { //4.第三方同步患者账号
            //更新失败次数
            this.getJdbcTemplate().update("update base_patient p set p.login_failure_count = ? ,p.last_login_failure_time = ? where p.mobile = ? or p.idcard = ?", loginFailureCount, new Date(), username, getIdcard());
        } //...
    }
@ -392,7 +479,7 @@ public class WlyyUserDetailsService extends JdbcDaoSupport implements UserDetail
            users = this.getJdbcTemplate().query(DEFAULT_PATIENT_DETAILS_STATEMENT, new BeanPropertyRowMapper(WlyyUserSimple.class), username, username);
        } else if("4".equals(loginType)){
            //更新登录时间
            this.getJdbcTemplate().update("update base_patient p set p.login_failure_count = 0, p.login_date = ? where p.mobile = ? or p.idcard = ?", new Date(), username, username);
            this.getJdbcTemplate().update("update base_patient p set p.login_failure_count = 0, p.login_date = ? where p.mobile = ? or p.idcard = ?", new Date(), username, getIdcard());
            users = this.getJdbcTemplate().query(DEFAULT_PATIENT_DETAILS_IDCARD_STATEMENT, new BeanPropertyRowMapper(WlyyUserSimple.class), getIdcard());
        }
@ -485,6 +572,19 @@ public class WlyyUserDetailsService extends JdbcDaoSupport implements UserDetail
        this.getJdbcTemplate().update("update base_patient p set p.openid = ? where p.id= ?", openid, userId);
    }
    public String getSynPath(String wxId){
        String sql = "SELECT w.syn_path AS sysPath FROM wx_wechat w WHERE w.id ='"+wxId+"'";
        List<Map<String,Object>> list = this.getJdbcTemplate().queryForList(sql);
        if(list!=null&&list.size()>0){
            return (String)list.get(0).get("sysPath");
        }else{
            logger.error("getSynPath error");
        }
        return "";
    }
    public String randomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuffer buffer = new StringBuffer();

+ 13 - 0
server/svr-authentication/src/main/java/com/yihu/jw/security/dao/OauthKeypairDao.java

@ -0,0 +1,13 @@
package com.yihu.jw.security.dao;
import com.yihu.jw.security.model.OauthKeypairDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Trick on 2019/7/23.
 */
public interface OauthKeypairDao extends PagingAndSortingRepository<OauthKeypairDO, String>, JpaSpecificationExecutor<OauthKeypairDO> {
    OauthKeypairDO findByCode(String code);
}

+ 47 - 0
server/svr-authentication/src/main/java/com/yihu/jw/security/model/OauthKeypairDO.java

@ -0,0 +1,47 @@
package com.yihu.jw.security.model;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
/**
 * Created by Trick on 2019/7/23.
 */
@Entity
@Table(name = "oauth_keypair")
public class OauthKeypairDO {
    private Integer id;
    private String code;
    private byte[] keyPair;
    @Id
    @GeneratedValue(generator = "generator")
    @GenericGenerator(name = "generator", strategy = "identity")
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    @Column(name = "code")
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    @Column(name = "key_pair")
    public byte[] getKeyPair() {
        return keyPair;
    }
    public void setKeyPair(byte[] keyPair) {
        this.keyPair = keyPair;
    }
}

+ 57 - 1
server/svr-authentication/src/main/java/com/yihu/jw/security/oauth2/provider/endpoint/WlyyLoginEndpoint.java

@ -1,16 +1,20 @@
package com.yihu.jw.security.oauth2.provider.endpoint;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.entity.base.login.BaseLoginLogDO;
import com.yihu.jw.restmodel.ResultStatus;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.security.core.userdetails.jdbc.WlyyUserDetailsService;
import com.yihu.jw.security.dao.OauthKeypairDao;
import com.yihu.jw.security.login.service.BaseLoginLogService;
import com.yihu.jw.security.model.*;
import com.yihu.jw.security.oauth2.core.redis.WlyyRedisVerifyCodeService;
import com.yihu.jw.security.oauth2.provider.WlyyTokenGranter;
import com.yihu.jw.security.oauth2.provider.error.WlyyOAuth2ExceptionTranslator;
import com.yihu.jw.security.utils.SerializeUtil;
import com.yihu.utils.security.RSAUtils;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@ -45,6 +49,7 @@ import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.text.SimpleDateFormat;
@ -52,6 +57,7 @@ import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import com.alibaba.fastjson.JSON;
/**
 * <p>
@ -90,6 +96,8 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    private StringRedisTemplate redisTemplate;
    @Autowired
    private BaseLoginLogService baseLoginLogService;
    @Autowired
    private OauthKeypairDao oauthKeypairDao;
    @PostConstruct
    private void init() {
@ -104,7 +112,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
     *                    captcha 验证码
     *                    password 密码
     *                    username 用户名/手机/身份证号
     *                    login_type 用户类型 1或默认为user,2:医生登录,3:患者登录
     *                    login_type 用户类型 1或默认为user,2:医生登录,3:患者登录,4:第三方同步账号登录
     * @param httpSession
     * @return
     * @throws Exception
@ -127,6 +135,7 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
                String password = com.yihu.jw.security.utils.RSAUtils.decryptBase64(parameters.get("password"), keyPair);
                parameters.put("password", password);
            } else {
                //第三方同步账号模式登录
                parameters.put("grant_type", "ihealthCode");
            }
        } else {
@ -597,4 +606,51 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        return response;
    }
    @RequestMapping(value = "/oauth/getHwlyyPublicKey", method = RequestMethod.GET)
    public ObjEnvelop getHwlyyPublicKey(){
        OauthKeypairDO keypairDO = oauthKeypairDao.findByCode("hwlyyKey");
        if(keypairDO==null){
            KeyPair keyPair = com.yihu.jw.security.utils.RSAUtils.getKey();
            byte[] bytekey = SerializeUtil.ObjTOSerialize(keyPair);
            OauthKeypairDO kpDO = new OauthKeypairDO();
            kpDO.setCode("hwlyyKey");
            kpDO.setKeyPair(bytekey);
            keypairDO = oauthKeypairDao.save(kpDO);
        }
        KeyPair key = (KeyPair)SerializeUtil.unSerialize(keypairDO.getKeyPair());
        PublickeyVO pk = new PublickeyVO();
        pk.setPublicKey(com.yihu.jw.security.utils.RSAUtils.generateBase64PublicKey(key));
        return ObjEnvelop.getSuccess("success", pk);
    }
    @RequestMapping(value = "/oauth/getHwlyyDecrypt", method = RequestMethod.POST)
    public ObjEnvelop getHwlyyDecrypt(String openid,String idcard,String wechatId){
        Map<String,Object> rs = new HashedMap();
        try{
            OauthKeypairDO keypairDO = oauthKeypairDao.findByCode("hwlyyKey");
            KeyPair keyPair = (KeyPair)SerializeUtil.unSerialize(keypairDO.getKeyPair());
            //解密openid
            if(org.apache.commons.lang3.StringUtils.isNotBlank(openid)){
                rs.put("openid",com.yihu.jw.security.utils.RSAUtils.decryptBase64(openid, keyPair));
            }else {
                rs.put("openid",openid);
            }
            //解密idcard
            if(org.apache.commons.lang3.StringUtils.isNotBlank(idcard)){
                rs.put("idcard",com.yihu.jw.security.utils.RSAUtils.decryptBase64(idcard, keyPair));
            }else {
                rs.put("idcard",idcard);
            }
            //解密wechatId
            if(org.apache.commons.lang3.StringUtils.isNotBlank(wechatId)){
                rs.put("wechatId",com.yihu.jw.security.utils.RSAUtils.decryptBase64(wechatId, keyPair));
            }else {
                rs.put("wechatId",wechatId);
            }
        }catch (Exception e){
            logger.error(e);
        }
        return ObjEnvelop.getSuccess("success", rs);
    }
}

+ 58 - 2
server/svr-authentication/src/main/java/com/yihu/jw/security/utils/HttpClientUtil.java

@ -19,8 +19,9 @@ import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@ -303,4 +304,59 @@ public class HttpClientUtil {
        }
        return null;
    }
    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL带上参数
     * @param param
     *            POST参数。
     * @return 所代表远程资源的响应结果
     */
    public  String sendPost(String url, String param) {
        StringBuffer buffer = new StringBuffer();
        PrintWriter out = null;
        BufferedReader in = null;
        HttpURLConnection conn = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            osw.write(param.toString());
            osw.flush();
            // 读取返回内容
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                buffer.append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return buffer.toString();
    }
}

+ 58 - 0
server/svr-authentication/src/main/java/com/yihu/jw/security/utils/SerializeUtil.java

@ -0,0 +1,58 @@
package com.yihu.jw.security.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
 * Created by Trick on 2019/7/23.
 */
public class SerializeUtil {
    private static final Logger log = LoggerFactory.getLogger(SerializeUtil.class);
    /**
     *
     * <p>Title: ObjTOSerialize</p>
     * <p>Description: 序列化一个对象</p>
     * @param obj
     * @return
     * @author guangshuai.wang
     */
    public static byte[] ObjTOSerialize(Object obj){
        ObjectOutputStream oos = null;
        ByteArrayOutputStream byteOut = null;
        try{
            byteOut = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(byteOut);
            oos.writeObject(obj);
            byte[] bytes = byteOut.toByteArray();
            return bytes;
        }catch (Exception e) {
            log.error("对象序列化失败");
        }
        return null;
    }
    /**
     *
     * <p>Title: unSerialize</p>
     * <p>Description: 反序列化</p>
     * @param bytes
     * @return
     * @author guangshuai.wang
     */
    public static Object unSerialize(byte[] bytes){
        ByteArrayInputStream in = null;
        try{
            in = new ByteArrayInputStream(bytes);
            ObjectInputStream objIn = new ObjectInputStream(in);
            return objIn.readObject();
        }catch (Exception e) {
            log.error("反序列化失败");
        }
        return null;
    }
}

+ 72 - 6
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/consult/PatientConsultEndpoint.java

@ -12,7 +12,9 @@ import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.hospital.BaseHospitalRequestMapping;
import com.yihu.jw.rm.patient.PatientRequestMapping;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.wechat.service.WechatInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@ -20,9 +22,8 @@ import org.apache.axis.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.security.MessageDigest;
import java.util.*;
/**
 * @author huangwenjie
@ -41,6 +42,10 @@ public class PatientConsultEndpoint extends EnvelopRestEndpoint {
	@Autowired
	private BasePatientService basePatientService;
	
	
	@Autowired
	private WechatInfoService wechatInfoService;
	
	@GetMapping(value = BaseHospitalRequestMapping.PatientIM.records)
	@ApiOperation(value = "患者咨询记录查询")
	public ListEnvelop records(
@ -301,11 +306,72 @@ public class PatientConsultEndpoint extends EnvelopRestEndpoint {
			@RequestParam(value = "scoreContent",required = false) String scoreContent,
			@ApiParam(name = "type", value = "1、实名,2、匿名")
			@RequestParam(value = "type",required = true) Integer type)throws Exception{
		if(StringUtils.isEmpty(scoreContent)){
			scoreContent= "[{\"scoreType\":\"1\",\"score\":100,\"content\":\"\"},{\"scoreType\":\"2\",\"score\":80,\"content\":\"\"},{\"scoreType\":\"3\",\"score\":80,\"content\":\"\"},{\"scoreType\":\"4\",\"score\":0,\"content\":\"测试评语。。。。123123\"}]";
		}
//		if(StringUtils.isEmpty(scoreContent)){
//			scoreContent= "[{\"scoreType\":\"1\",\"score\":100,\"content\":\"\"},{\"scoreType\":\"2\",\"score\":80,\"content\":\"\"},{\"scoreType\":\"3\",\"score\":80,\"content\":\"\"},{\"scoreType\":\"4\",\"score\":0,\"content\":\"测试评语。。。。123123\"}]";
//		}
		imService.evaluationByConsultCode(consult,scoreContent,type);
		return success("请求成功");
	}
	
	@GetMapping(value = BaseHospitalRequestMapping.PatientIM.getEvaluationByConsultCode)
	@ApiOperation(value = "评价咨询", notes = "评价咨询")
	public ListEnvelop getEvaluationByConsultCode(
			@ApiParam(name = "consult", value = "咨询CODE")
			@RequestParam(value = "consult",required = true) String consult)throws Exception{
//		if(StringUtils.isEmpty(scoreContent)){
//			scoreContent= "[{\"scoreType\":\"1\",\"score\":100,\"content\":\"\"},{\"scoreType\":\"2\",\"score\":80,\"content\":\"\"},{\"scoreType\":\"3\",\"score\":80,\"content\":\"\"},{\"scoreType\":\"4\",\"score\":0,\"content\":\"测试评语。。。。123123\"}]";
//		}
		
		return success("请求成功",imService.getEvaluationByConsultCode(consult));
	}
	
	@PostMapping(value = BaseHospitalRequestMapping.PatientIM.getSign)
	@ApiOperation(value = "获取微信签名", notes = "获取微信签名")
	public Envelop getSign(@ApiParam(name = "pageUrl", value = "授权页面")
	                       @RequestParam(value = "pageUrl", required = true)String pageUrl,
	                       @ApiParam(name = "wxId", value = "微信id")
	                       @RequestParam(value = "wxId", required = true)String wxId) throws Exception {
		
		String ticket = wechatInfoService.getJsapi_ticketByToken(wxId);
		Map<Object, Object> map = new HashMap<Object, Object>();
		if (ticket != null) {
			String noncestr = UUID.randomUUID().toString();
			long timestamp = System.currentTimeMillis() / 1000;
			String url = pageUrl;
			String str = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
			// sha1加密
			String signature = SHA1(str);
			map.put("noncestr", noncestr);
			map.put("timestamp", timestamp);
			map.put("signature", signature);
			return success(PatientRequestMapping.Wechat.api_success,map);
		}
		return failed(PatientRequestMapping.Wechat.api_error);
	}
	
	/**
	 * @description: SHA、SHA1加密 @parameter: str:待加密字符串 @return: 加密串
	 **/
	public String SHA1(String str) throws Exception {
		try {
			MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1"); // 如果是SHA加密只需要将"SHA-1"改成"SHA"即可
			digest.update(str.getBytes());
			byte messageDigest[] = digest.digest();
			// Create Hex String
			StringBuffer hexStr = new StringBuffer();
			// 字节数组转换为 十六进制 数
			for (int i = 0; i < messageDigest.length; i++) {
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexStr.append(0);
				}
				hexStr.append(shaHex);
			}
			return hexStr.toString();
			
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
}

+ 6 - 53
svr/svr-patient/src/main/java/com/yihu/jw/patient/endpoint/wechat/WechatInfoEndPoint.java

@ -1,8 +1,8 @@
package com.yihu.jw.patient.endpoint.wechat;
import com.sun.net.httpserver.Authenticator;
import com.yihu.jw.entity.base.wx.JsApiTicket;
import com.yihu.jw.entity.base.wx.WxWechatDO;
import com.yihu.jw.hospital.prescription.service.entrance.EntranceService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
@ -42,19 +42,18 @@ public class WechatInfoEndPoint extends EnvelopRestEndpoint {
    private static Logger logger = LoggerFactory.getLogger(WechatInfoEndPoint.class);
    @Autowired
    private WxAccessTokenService wxAccessTokenService;
    @Autowired
    private WechatInfoService wechatInfoService;
    @Value("${wechat.id}")
    private String wxId;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private WxUrlConfigService wxUrlConfigService;
    @RequestMapping(value =  PatientRequestMapping.Wechat.getWxWechatConfig, method = RequestMethod.GET)
    @ResponseBody
    public ObjEnvelop<Map<String,Object>> getWxWechatConfig(@ApiParam(name = "url", value = "域名地址")
@ -72,9 +71,9 @@ public class WechatInfoEndPoint extends EnvelopRestEndpoint {
    public Envelop getSign(@ApiParam(name = "pageUrl", value = "授权页面")
                           @RequestParam(value = "pageUrl", required = true)String pageUrl,
                           @ApiParam(name = "wxId", value = "微信id")
                           @RequestParam(value = "wxId", required = true)String wxId) {
                           @RequestParam(value = "wxId", required = true)String wxId) throws Exception {
        String ticket = getJsapi_ticketByToken(wxId);
        String ticket = wechatInfoService.getJsapi_ticketByToken(wxId);
        Map<Object, Object> map = new HashMap<Object, Object>();
        if (ticket != null) {
            String noncestr = UUID.randomUUID().toString();
@ -113,53 +112,7 @@ public class WechatInfoEndPoint extends EnvelopRestEndpoint {
        return success(PatientRequestMapping.Wechat.api_success,openid);
    }
    /**
     * 获取微信的jsapi_ticket
     *
     * @return
     */
    public String getJsapi_ticketByToken(String wxId) {
        try {
            WxWechatDO wxWechat = wxAccessTokenService.getWxInfo(wxId);
            Iterable<JsApiTicket> jsapiTickets = wxAccessTokenService.findJsapiTicket(wxWechat.getAppOriginId());
            if (jsapiTickets != null) {
                for (JsApiTicket jsApiTicket : jsapiTickets) {
                    if ((System.currentTimeMillis() - jsApiTicket.getAdd_timestamp()) < (jsApiTicket.getExpires_in() * 1000)) {
                        return jsApiTicket.getJsapi_ticket();
                    } else {
                        wxAccessTokenService.delJsapiTicket(jsApiTicket);
                        break;
                    }
                }
            }
            String token = wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
            if (token != null) {
                String token_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
                String params = "access_token=" + token + "&type=jsapi";
                String result = HttpUtil.sendGet(token_url, params);
                JSONObject json = new JSONObject(result);
                if (json.has("ticket")) {
                    String ticket = json.get("ticket").toString();
                    String expires_in = json.get("expires_in").toString();
                    JsApiTicket newJsApiTicket = new JsApiTicket();
                    newJsApiTicket.setJsapi_ticket(ticket);
                    newJsApiTicket.setExpires_in(Long.parseLong(expires_in));
                    newJsApiTicket.setAcc_id(wxWechat.getAppOriginId());
                    newJsApiTicket.setAcc_id(wxWechat.getAppOriginId());
                    wxAccessTokenService.addJsapiTicket(newJsApiTicket);
                    return ticket;
                } else {
                    return null;
                }
            } else {
                return null;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
    }
    /**
     * @description: SHA、SHA1加密 @parameter: str:待加密字符串 @return: 加密串