Browse Source

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

wsl 2 years ago
parent
commit
44c67f3cce

+ 36 - 2
business/base-service/src/main/java/com/yihu/jw/wechat/service/WechatInfoService.java

@ -1,6 +1,5 @@
package com.yihu.jw.wechat.service;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
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;
@ -8,8 +7,10 @@ import com.yihu.jw.hospital.prescription.service.entrance.HcyyEntranceService;
import com.yihu.jw.hospital.prescription.service.entrance.TnyyEntranceService;
import com.yihu.jw.hospital.prescription.service.entrance.XzzxEntranceService;
import com.yihu.jw.util.wechat.wxhttp.HttpUtil;
import com.yihu.jw.utils.StringUtil;
import com.yihu.jw.wechat.dao.WechatDao;
import com.yihu.utils.network.HttpResponse;
import com.yihu.utils.network.HttpUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.LoggerFactory;
@ -17,6 +18,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service
public class WechatInfoService {
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(WechatInfoService.class);
@ -57,6 +60,37 @@ public class WechatInfoService {
        }
    }
    public JSONObject getXOpenidByCode(String code,String wxId) throws Exception {
        //通过wxId获取appId和appSecret
        WxWechatDO wxWechatDO = wechatDao.findById(wxId);
        return getXOpenidByCode(code,wxWechatDO.getApplets(),wxWechatDO.getAppletsSecret());
    }
    /**
     * 获取小程序openid
     * @param code
     * @param appid
     * @param appSecret
     * @return
     * @throws Exception
     */
    public JSONObject getXOpenidByCode(String code, String appid, String appSecret) throws Exception {
        HttpUtils httpUtils = new HttpUtils();
        Map<String, Object> param = new HashedMap();
        param.put("appid", appid);
        param.put("secret", appSecret);
        param.put("js_code", code);
        param.put("grant_type", "authorization_code");
        HttpResponse response = httpUtils.doGet("https://api.weixin.qq.com/sns/jscode2session", param);
        JSONObject json = new JSONObject(response.getContent());
        LOGGER.info("checkApplets:"+response.getContent());
        if (!json.has("unionid")) {
            json.put("unionid","123456");
        }
        return json;
    }
    /**
     * 通过code获取判断openid
     *

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

@ -2283,3 +2283,6 @@ CREATE TABLE `base_patient_family_pushonoff` (
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=263 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='家属端推送开关';
-- 2022-10-31 ysj
alter table base_patient_wechat add column xopenid varchar(50) default null comment '微信小程序openid';

+ 12 - 3
common/common-entity/src/main/java/com/yihu/jw/entity/base/wx/BasePatientWechatDo.java

@ -1,7 +1,6 @@
package com.yihu.jw.entity.base.wx;
import com.yihu.jw.entity.UuidIdentityEntity;
import com.yihu.jw.entity.UuidIdentityEntityWithOperator;
import javax.persistence.Column;
import javax.persistence.Entity;
@ -19,7 +18,8 @@ public class BasePatientWechatDo extends UuidIdentityEntity {
	private String saasId;
	private String wechatId;
	private String patientId;
	private String openid;
	private String openid;//公众号openid
	private String xopenid;//小程序openid
	private String unionid;
	private Date createTime;
	
@ -65,7 +65,16 @@ public class BasePatientWechatDo extends UuidIdentityEntity {
	public void setUnionid(String unionid) {
		this.unionid = unionid;
	}
	
	public String getXopenid() {
		return xopenid;
	}
	@Column(name = "xopenid")
	public void setXopenid(String xopenid) {
		this.xopenid = xopenid;
	}
	@Column(name = "create_time")
	public Date getCreateTime() {
		return createTime;

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

@ -980,6 +980,24 @@ public class WlyyUserDetailsService extends JdbcDaoSupport implements UserDetail
        }
    }
    public void updateXOpenIdAndWechatId(String openid,String unionid, String userId,String wechatId) {
        List<BasePatientWechatDo> patientWechatDos = basePatientWechatDao.findByWechatIdAndPatientId(wechatId,userId);
        if (patientWechatDos!=null&&patientWechatDos.size()!=0){
            BasePatientWechatDo basePatientWechatDo = patientWechatDos.get(0);
            basePatientWechatDo.setXopenid(openid);
            basePatientWechatDo.setUnionid(unionid);
            basePatientWechatDao.save(basePatientWechatDo);
        }else {
            BasePatientWechatDo basePatientWechatDo=new BasePatientWechatDo();
            basePatientWechatDo.setCreateTime(new Date());
            basePatientWechatDo.setXopenid(openid);
            basePatientWechatDo.setUnionid(unionid);
            basePatientWechatDo.setPatientId(userId);
            basePatientWechatDo.setWechatId(wechatId);
            basePatientWechatDao.save(basePatientWechatDo);
        }
    }
    public String getSynPath(String wxId){
        String sql = "SELECT w.syn_path AS sysPath FROM wx_wechat w WHERE w.id ='"+wxId+"'";

+ 30 - 0
server/svr-authentication/src/main/java/com/yihu/jw/security/dao/patient/WxAppletsAccessTokenDao.java

@ -0,0 +1,30 @@
package com.yihu.jw.security.dao.patient;
import com.yihu.jw.entity.base.wx.WxAppletsAccessTokenDO;
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 java.util.List;
/**
 * Created by Administrator on 2017/5/18 0018.
 */
public interface WxAppletsAccessTokenDao extends PagingAndSortingRepository<WxAppletsAccessTokenDO, String>, JpaSpecificationExecutor<WxAppletsAccessTokenDO> {
    @Query("from WxAppletsAccessTokenDO w where w.wechatId =?1 order by w.addTimestamp desc")
    List<WxAppletsAccessTokenDO> getWxAccessTokenById(String wechatId);
    
    @Modifying
    @Query("delete from WxAppletsAccessTokenDO p where p.wechatId=?1 ")
    void deleteByWechatId(String wechatId);
    @Query("select p from WxAppletsAccessTokenDO p where p.code = ?1 order by p.addTimestamp desc")
    Iterable<WxAppletsAccessTokenDO> findAccessToken(String accId);
    @Modifying
    @Query("delete from WxAppletsAccessTokenDO p where p.code=?1 ")
    void deleteByAccId(String accId);
}

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

@ -79,6 +79,7 @@ import org.springframework.web.context.request.ServletRequestAttributes;
import sun.misc.BASE64Encoder;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
@ -185,6 +186,8 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Resource
    private WechatService wechatService;
    @PostConstruct
    private void init() {
@ -379,6 +382,23 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
                    Oauth2Envelop<WlyyUserSimple> oauth2Envelop = new Oauth2Envelop<>(jsonObject.getString("message"), -1, null);
                    return new ResponseEntity<>(oauth2Envelop, headers, HttpStatus.OK);
                }
            }else if("wxApplets".equals(flag)){
                //微信小程序登录
                parameters.put("grant_type", "dingTalk");
                String authCode = parameters.get("authCode");
                if(org.apache.commons.lang3.StringUtils.isBlank(authCode)){
                    throw new InvalidRequestException("请求参数错误");
                }
                String userPhone = wechatService.getUserPhoneByApplets(authCode);
                if (!StringUtils.isEmpty(userPhone)){
                    parameters.put("username", userPhone);
                }else{
                    HttpHeaders headers = new HttpHeaders();
                    headers.set("Cache-Control", "no-store");
                    headers.set("Pragma", "no-cache");
                    Oauth2Envelop<WlyyUserSimple> oauth2Envelop = new Oauth2Envelop<>("获取用户手机号失败", -1, null);
                    return new ResponseEntity<>(oauth2Envelop, headers, HttpStatus.OK);
                }
            }else if (StringUtils.isEmpty(parameters.get("captcha"))) {
                parameters.put("grant_type", "password");
                //解密密码
@ -446,6 +466,8 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
            wlyyUserSimple.setState(parameters.get("state"));
            String loginType = parameters.get("login_type");
            String openid = parameters.get("openid");
            String xopenid = parameters.get("xopenid");
            String unionid = parameters.get("unionid");
            String wechatId = parameters.get("wechatId");
            logger.info("login:登录进入7");
            //更新患者openId
@ -468,6 +490,14 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
                    userDetailsService.updateDoctorOpenId(openid, wlyyUserSimple.getId());
                }
            }
        if (!StringUtils.isEmpty(xopenid) && !"undefined".equalsIgnoreCase(xopenid) && ("3".equals(loginType)||"4".equalsIgnoreCase(loginType))) {
            baseLoginLogDO.setOpenid(xopenid);
            logger.info("gengxin进入"+xopenid);
            if (!StringUtils.isEmpty(wechatId)&& !"undefined".equalsIgnoreCase(wechatId)){
                logger.info("gengxin进入"+wechatId);
                userDetailsService.updateXOpenIdAndWechatId(xopenid,unionid,wlyyUserSimple.getId(),wechatId);
            }
        }
            if (parameters.get("password") != null) {
                //使用密码登录成功后, 更新失败次数为 0

+ 125 - 0
server/svr-authentication/src/main/java/com/yihu/jw/security/service/WechatService.java

@ -0,0 +1,125 @@
package com.yihu.jw.security.service;
import com.yihu.jw.entity.base.wx.WxAppletsAccessTokenDO;
import com.yihu.jw.entity.base.wx.WxWechatDO;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.jw.security.dao.patient.WechatDao;
import com.yihu.jw.security.dao.patient.WxAppletsAccessTokenDao;
import com.yihu.jw.util.wechat.wxhttp.HttpUtil;
import com.yihu.utils.network.HttpUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.*;
/**
 * Created by yeshijie on 2022/11/2.
 */
@Service
public class WechatService {
    private static Logger logger = LoggerFactory.getLogger(WechatService.class);
    @Value("${wechat.id}")
    private String wxId;
    @Autowired
    private WechatDao wechatDao;
    @Autowired
    private WxAppletsAccessTokenDao wxAppletsAccessTokenDao;
    /**
     * 根据小程序获取用户手机号
     *
     * @param code
     * @return
     * @throws Exception
     */
    public String getUserPhoneByApplets(String code) throws Exception {
        String token = getWxAppletsAccessTokenById(wxId).getAccessToken();
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(code)){
            String token_url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token;
            String params = "{\"code\": \""+code+"\"}";
            logger.info("参数:"+params);
            String result = HttpUtil.sendPost(token_url, params);
            logger.info("步骤1:"+result);
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(result)){
                com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(result);
                if (object.getString("errcode").equalsIgnoreCase("0")){
                    com.alibaba.fastjson.JSONObject jsonObject= object.getJSONObject("phone_info");
                    return jsonObject.getString("phoneNumber");
                }
            }
            return null;
        }else {
            return null;
        }
    }
    /**
     * 生成小程序token
     * @param wechatId
     * @return
     */
    public WxAppletsAccessTokenDO getWxAppletsAccessTokenById(String wechatId) {
        try {
            //根据wechatCode查找出appid和appSecret
            WxWechatDO wxWechat = wechatDao.findById(wechatId);
            List<WxAppletsAccessTokenDO> wxAccessTokens =  wxAppletsAccessTokenDao.getWxAccessTokenById(wechatId);
            if(wxWechat==null){
                throw new ApiException("wxWechat is not exist", ExceptionCode.common_error_params_code);
            }
            if(wxAccessTokens!=null&&wxAccessTokens.size()>0){
                for (WxAppletsAccessTokenDO accessToken : wxAccessTokens) {
                    if ((System.currentTimeMillis() - accessToken.getAddTimestamp()) < (accessToken.getExpiresIn() * 500)) {
                        return accessToken;
                    } else {
                        wxAppletsAccessTokenDao.delete(accessToken);
                        break;
                    }
                }
            }
            String token_url = "https://api.weixin.qq.com/cgi-bin/token";
            String appId="";
            String appSecret="";
            appId = wxWechat.getApplets();
            appSecret = wxWechat.getAppletsSecret();
            if (StringUtils.isEmpty(appId)){
                throw new ApiException("appId is null", ExceptionCode.common_error_params_code);
            }
            if (StringUtils.isEmpty(appSecret)){
                throw new ApiException("appSecret is null", ExceptionCode.common_error_params_code);
            }
            Map<String, Object> params = new HashMap<>();
            params.put("grant_type", "client_credential");
            params.put("appid", appId);
            params.put("secret", appSecret);
            String result = HttpUtils.doGet(token_url, params).getContent();
            logger.info("--------------wechat token return:"+result+"---------------");
            JSONObject json = new JSONObject(result);
            if (json.has("access_token")) {
                String token = json.get("access_token").toString();
                String expires_in = json.get("expires_in").toString();
                WxAppletsAccessTokenDO newaccessToken = new WxAppletsAccessTokenDO();
                newaccessToken.setAccessToken(token);
                newaccessToken.setExpiresIn(Long.parseLong(expires_in));
                newaccessToken.setAddTimestamp(System.currentTimeMillis());
                newaccessToken.setCzrq(new Date());
                newaccessToken.setCode(UUID.randomUUID().toString().replace("-",""));
                newaccessToken.setWechatId(wechatId);
                wxAppletsAccessTokenDao.save(newaccessToken);
                return newaccessToken;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

+ 46 - 1
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/third/patient/PatientNoLoginEndPoint.java

@ -54,6 +54,52 @@ public class PatientNoLoginEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private ConsultService consultService;
    /**
     * 获取微信小程序openid
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "/getXOpenidByCode", method = {RequestMethod.POST, RequestMethod.GET})
    public Envelop getXOpenidByCode(String code, @RequestParam(value = "patientId", required = false)String patientId) throws Exception {
        try {
            //通过redis获取openid, 获取不到,则调用微信接口去取
            String key = wxId+":code";
            String openid = redisTemplate.opsForValue().get(key);
            if(!StringUtils.isEmpty(openid)){
                return success(PatientRequestMapping.Wechat.api_success,openid);
            }
            org.json.JSONObject json = wechatInfoService.getXOpenidByCode(code, wxId);
            if (!StringUtils.isEmpty(patientId)){
                openid = json.getString("openid");
                String unionid = json.getString("unionid");
                List<BasePatientWechatDo> list = basePatientWechatDao.findByWechatIdAndPatientId(wxId,patientId);
                if (list!=null&&list.size()>0){
                    for (BasePatientWechatDo basePatientWechatDo:list){
                        basePatientWechatDo.setXopenid(openid);
                        basePatientWechatDo.setUnionid(unionid);
                        basePatientWechatDao.save(basePatientWechatDo);
                    }
                }else {
                    BasePatientWechatDo basePatientWechatDo = new BasePatientWechatDo();
                    basePatientWechatDo.setPatientId(patientId);
                    basePatientWechatDo.setWechatId(wxId);
                    basePatientWechatDo.setCreateTime(new Date());
                    basePatientWechatDo.setXopenid(openid);
                    basePatientWechatDo.setUnionid(unionid);
                    basePatientWechatDao.save(basePatientWechatDo);
                }
            }
            redisTemplate.opsForValue().set(key,openid);
            redisTemplate.expire(key,10, TimeUnit.SECONDS);
            return success(PatientRequestMapping.Wechat.api_success,json);
        } catch (Exception e){
            return  failedException2(e);
        }
    }
    /**
     * 获取微信openid
     *
@ -61,7 +107,6 @@ public class PatientNoLoginEndPoint extends EnvelopRestEndpoint {
     * @return
     */
    @RequestMapping(value = "/getOpenidByCode", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Envelop getOpenidByCode(String code, @RequestParam(value = "patientId", required = false)String patientId) throws Exception {
        try {