package com.minpay.shouhuo; import com.google.zxing.WriterException; import com.min.util.OffSetUtil; import com.minpay.common.bean.User; import com.minpay.common.constant.Constant; import com.minpay.common.constant.ServConstant; import com.minpay.common.format.IFormatService; import com.minpay.common.service.ILogService; import com.minpay.common.service.IPropertiesService; import com.minpay.common.service.IPublicService; import com.minpay.common.service.IQrcodeService; import com.minpay.common.service.impl.QrcodeServiceImpl; import com.minpay.common.util.*; import com.minpay.db.table.mapper.VmPersonInfMapper; import com.minpay.db.table.mapper.VmPersonRoleInfMapper; import com.minpay.db.table.model.VmPersonInf; import com.minpay.db.table.model.VmPersonInfExample; import com.minpay.db.table.model.VmPersonRoleInf; import com.minpay.db.table.model.VmPersonRoleInfExample; import com.minpay.db.table.own.mapper.PersonManageMapper; import com.minpay.db.table.own.mapper.SequenceMapper; import com.minpay.huicai.util.EquCodeCreateUtil; import com.startup.minpay.frame.business.IMINAction; import com.startup.minpay.frame.business.MINHttpServletRequestContext; import com.startup.minpay.frame.business.res.MINActionResult; import com.startup.minpay.frame.constant.IMINBusinessConstant; import com.startup.minpay.frame.constant.IMINTransactionEnum; import com.startup.minpay.frame.data.format.MINCopyFormat; import com.startup.minpay.frame.exception.MINBusinessException; import com.startup.minpay.frame.jdbc.MINRowBounds; import com.startup.minpay.frame.service.base.IMINDataBaseService; import com.startup.minpay.frame.service.base.Service; import com.startup.minpay.frame.session.MINSession; import com.startup.minpay.frame.target.MINAction; import com.startup.minpay.frame.target.MINComponent; import com.startup.minpay.frame.target.MINParam; import net.sf.json.JSONObject; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 用户管理 * @author xbh * */ @MINComponent public class PersManageAction implements IMINAction { /**用户查询**/ public final static String PERSON_QUERY = "personQuery"; /**管理员添加**/ public final static String PERSON_ADD = "personAdd"; /**冻结**/ public final static String PERSON_CANCELLATION = "personCancellation"; /**解冻*/ private final static String PERSON_THAW = "personThaw"; /** 生成包含字符串信息的二维码图片**/ public static final String CREATE_QRCODE = "createQrCode"; /** * 用户查询 * @param page * @param limit * @param dates * @param perName * @param state * @param fapRequest * @return * @throws MINBusinessException */ @MINAction(value = PERSON_QUERY) public MINActionResult personQuery( @MINParam(key = "page", defaultValue = "1") int page, @MINParam(key = "limit", defaultValue = "3") int limit, @MINParam(key = "dates") String dates, @MINParam(key = "perName") String perName, @MINParam(key = "state") String state, @MINParam(key = "roleid") String roleid, MINSession session, MINHttpServletRequestContext fapRequest ) throws MINBusinessException { MINActionResult res = new MINActionResult(); // 创建查询条件 Map p = new HashMap(); User u = session.getUser(); p.put("dates", dates); // 创建日期 p.put("perName", perName); //用户名称 p.put("state", state); //状态 if(!u.getBranchId().equals(Constant.ADMINISTRATION_SYSTEM_NUMBER)){ p.put("branchId", u.getBranchId()); } p.put("channel", u.getChannel());//渠道 p.put("roleid", roleid); MINRowBounds rows = new MINRowBounds(page, limit); // 查询 List> ls = Service.lookup(IMINDataBaseService.class) .getMybatisMapper(PersonManageMapper.class).personQuery(p,rows); ls = Service.lookup(IFormatService.class).formatDateTime(ls, "createTime"); ls = Service.lookup(IFormatService.class).formatDateTime(ls, "modifyTime"); ls = new MINCopyFormat("{state:'stateDesc',channel:'channelDesc',type:'typeDesc',role:'roleDesc'}").format(ls); ls = Service.lookup(IFormatService.class).formatEnum(ls, "{stateDesc:'PERSON_STATE',channelDesc:'PERSON_CHANNEL',typeDesc:'PERSON_TYPE',roleDesc:'USER_ROLE'}"); // 设置返回值 res.set(IMINBusinessConstant.F_PAGING_LAY, ls); res.set(IMINBusinessConstant.F_PAGING_COUNT, rows.getCount()); return res; } /** * 注销 * @param session * @param id * @return * @throws MINBusinessException */ @MINAction(value = PERSON_CANCELLATION) public MINActionResult personCancellation( MINSession session, @MINParam(key = "id") String id ) throws MINBusinessException { //获取当前用户 User user = session.getUser(); MINActionResult res = new MINActionResult(); VmPersonInf ps = new VmPersonInf(); ps.setId(id); ps.setStatus("01");//冻结 ps.setModifyTime(DateUtil.getCurrentDateTimeString());//修改时间 ps.setModifyUser(session.getUser().getId()); //修改人 Service.lookup(IMINDataBaseService.class) .getMybatisMapper(VmPersonInfMapper.class).updateByPrimaryKeySelective(ps); String logInfo = "操作员:"+user.getName()+",注销用户,id:"+id; Service.lookup(ILogService.class).logging(session, logInfo); return res; } /** * 解冻 * @param session * @param id * @return * @throws MINBusinessException */ @MINAction(value = PERSON_THAW) public MINActionResult personThaw( MINSession session, @MINParam(key = "id") String id ) throws MINBusinessException { //获取当前用户 User user = session.getUser(); MINActionResult res = new MINActionResult(); VmPersonInf ps = new VmPersonInf(); ps.setId(id); ps.setStatus("00");//正常 ps.setModifyTime(DateUtil.getCurrentDateTimeString());//修改时间 ps.setModifyUser(session.getUser().getId()); //修改人 Service.lookup(IMINDataBaseService.class) .getMybatisMapper(VmPersonInfMapper.class).updateByPrimaryKeySelective(ps); String logInfo = "操作员:"+user.getName()+",解冻用户,id:"+id; Service.lookup(ILogService.class).logging(session, logInfo); return res; } @MINAction(value = PERSON_ADD,session = false) public MINActionResult personAdd( @MINParam(key = "code") String code, @MINParam(key = "type") String type, @MINParam(key = "channel") String channel, @MINParam(key = "role") String role, @MINParam(key = "branchId") String branchId, HttpServletResponse response, MINHttpServletRequestContext request ) throws MINBusinessException { MINActionResult res = new MINActionResult(); VmPersonInf person = new VmPersonInf(); MINActionResult result = null; String nowTime = DateUtil.getCurrentDateTimeString(); if("WX".equals(type)){ result = this.getWxPayOpenid(channel, code); }else if("AL".equals(type)){ //result = this.getALiPayOpenid(channel, code); } if(CommonUtil.isEmpty((String) result.get("openId"))) { throw new MINBusinessException("JA0001", "非法登录!"); } //用户表可以存在 角色表不可以 VmPersonInfExample personex = new VmPersonInfExample(); personex.createCriteria().andChannelEqualTo(channel).andTypeEqualTo(type).andOpenidEqualTo((String) result.get("openId")); List perLst = Service.lookup(IMINDataBaseService.class).getMybatisMapper(VmPersonInfMapper.class).selectByExample(personex); if(perLst.size() > 1 ){ throw new MINBusinessException("用户异常,请联系管理员!"); } if(perLst.size() == 0) { //新用户,新角色 /**添加用户*/ //获取用户主键 String perId = Service.lookup(IMINDataBaseService.class).getMybatisMapper(SequenceMapper.class).getSequence("VM_PERSON_INF_NO"); person.setId(perId); person.setName((String) result.get("nickName")); person.setHeadpath((String) result.get("headImgurl")); person.setOpenid((String) result.get("openId")); person.setStatus("00");//正常 person.setChannel(channel); person.setIsUser("1");//是否商户0否1是 person.setPhone("00000000000"); person.setType(type);//类型:WX微信AL支付宝 person.setCreateUser(perId); person.setCreateTime(nowTime); person.setModifyUser(perId); person.setModifyTime(nowTime); person.setRole(role); person.setUserId(branchId); Service.lookup(IMINDataBaseService.class).getMybatisMapper(VmPersonInfMapper.class).insertSelective(person); /**添加角色*/ String roleId = Service.lookup(IMINDataBaseService.class).getMybatisMapper(SequenceMapper.class).getSequence("VM_PERSON_ROLE_ID"); VmPersonRoleInf vmPersonRoleInf = new VmPersonRoleInf(); vmPersonRoleInf.setId(roleId); vmPersonRoleInf.setBranchId(branchId); vmPersonRoleInf.setPersonId(perId); vmPersonRoleInf.setRole(role); Service.lookup(IMINDataBaseService.class).getMybatisMapper(VmPersonRoleInfMapper.class).insertSelective(vmPersonRoleInf); }else{ //有用户,无角色 VmPersonInf vmPersonInf = perLst.get(0); if("0".equals(vmPersonInf.getIsUser())){ vmPersonInf.setIsUser("1"); Service.lookup(IMINDataBaseService.class).getMybatisMapper(VmPersonInfMapper.class).updateByPrimaryKeySelective(person); }else{ /**查询是否有此角色*/ VmPersonRoleInfExample vmPersonRoleInfExample = new VmPersonRoleInfExample(); vmPersonRoleInfExample.createCriteria().andRoleEqualTo(role).andPersonIdEqualTo(vmPersonInf.getId()).andStateEqualTo("00"); List vmPersonRoleInfList = Service.lookup(IMINDataBaseService.class).getMybatisMapper(VmPersonRoleInfMapper.class).selectByExample(vmPersonRoleInfExample); if(vmPersonRoleInfList.size() > 0){ throw new MINBusinessException("已有此角色,无需再次添加"); } /**添加角色*/ String roleId = Service.lookup(IMINDataBaseService.class).getMybatisMapper(SequenceMapper.class).getSequence("VM_PERSON_ROLE_ID"); VmPersonRoleInf vmPersonRoleInf = new VmPersonRoleInf(); vmPersonRoleInf.setId(roleId); vmPersonRoleInf.setBranchId(branchId); vmPersonRoleInf.setPersonId(vmPersonInf.getId()); vmPersonRoleInf.setRole(role); Service.lookup(IMINDataBaseService.class).getMybatisMapper(VmPersonRoleInfMapper.class).insertSelective(vmPersonRoleInf); } } return res; } /*** * 微信用户授权,获取用户信息 * @param code * @param channel * @return * @throws MINBusinessException */ private MINActionResult getWxPayOpenid(String channel ,String code) throws MINBusinessException { MINActionResult res = new MINActionResult(); //在微信的appId String appId = Service.lookup(IPublicService.class).getSysParValue(channel + "_APP_ID"); //在微信的secret String appSecret = Service.lookup(IPublicService.class).getSysParValue(channel + "_APP_SECRET"); //微信通用请求路径 String openUrl = "https://api.weixin.qq.com/sns/oauth2/access_token"; //配置参数 StringBuffer paramStr = new StringBuffer(); paramStr.append("appid="); paramStr.append(appId); paramStr.append("&secret="); paramStr.append(appSecret); paramStr.append("&code="); paramStr.append(code); paramStr.append("&grant_type=authorization_code"); try { //发送请求 String jsonObj = HttpPostUtil.sendPost(openUrl, paramStr.toString()); JSONObject js = JSONObject.fromObject(jsonObj); //获取openId String openId = js.getString("openid");//用户唯一标识,请注意,在未关注公众号时,用户访问公众号的网页,也会产生一个用户和公众号唯一的OpenID //微信通用请求路径 String openUrl2 = "https://api.weixin.qq.com/sns/userinfo"; //配置参数 StringBuffer paramStr2 = new StringBuffer(); paramStr2.append("access_token="); paramStr2.append(js.getString("access_token")); paramStr2.append("&openid="); paramStr2.append(openId); paramStr2.append("&lang=zh_CN"); //发送请求 String jsonObj2 = HttpPostUtil.sendPost(openUrl2, paramStr2.toString()); JSONObject js2 = JSONObject.fromObject(jsonObj2); String nickName = EmojiFilter.filterEmoji(js2.getString("nickname")); // String nickName = js2.getString("nickname"); String headImgurl = js2.getString("headimgurl"); res.set("openId", openId); res.set("headImgurl", headImgurl); res.set("nickName", nickName); } catch (Exception e) { throw new MINBusinessException("PAY10006", "微信获取openId失败!"); } return res; } /** * 生成包含字符串信息的二维码图片 * @param flash 是否刷新 */ @MINAction(value = CREATE_QRCODE, transaction = IMINTransactionEnum.CMT) public MINActionResult createQrCode( @MINParam(key = "flash") String flash, @MINParam(key = "role") String role, MINSession session)throws MINBusinessException, FileNotFoundException, WriterException, IOException { MINActionResult res = new MINActionResult(); //获取当前用户信息 User u = session.getUser(); //获取用户id String userId = u.getBranchId(); //刷新,生成 //开发环境修改配置 String basePath = "/home/images/"+ userId+".jpg"; //与nginx配置相同 String os = System.getProperty("os.name"); if(os.toLowerCase().startsWith("win")){ System.out.println(os + " can't gunzip"); basePath = "D:/images/"+ userId+".jpg"; //与nginx配置相同 } File file = new File(basePath); //获取父目录 File fileParent = file.getParentFile(); //判断是否存在 if (!fileParent.exists()) { fileParent.mkdirs(); } //获取渠道号 String channel = u.getChannel(); String address = Service.lookup(IPropertiesService.class) .getSystemProperties().get(channel+"_TO_MACHINE_ERWERMA").getKey();// 为nginx根路径 // 加密客户号 OutputStream outputStream = new FileOutputStream(file); String openUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?"; //String redirect_uri = "http://xubing2.minpay.cc/adm/admin/wxuserManage/addUserTransfer.html?role=".concat(role).concat("&branchId=").concat(userId); String redirect_uri = Service.lookup(IPropertiesService.class) .getSystemProperties().get(channel+"_ADM_URl").getKey(); redirect_uri = redirect_uri.concat("/admin/wxuserManage/addUserTransfer.html?role=").concat(role).concat("&branchId=").concat(userId); redirect_uri = URLEncoder.encode(redirect_uri, "GBK"); //在微信的appId String appId = Service.lookup(IPublicService.class).getSysParValue(channel + "_APP_ID"); //配置参数 StringBuffer paramStr = new StringBuffer(); paramStr.append(openUrl); paramStr.append("appid="); paramStr.append(appId); paramStr.append("&redirect_uri="); paramStr.append(redirect_uri); paramStr.append("&response_type=code&scope=snsapi_userinfo&state=STATE"); //String urlString = URLEncoder.encode(paramStr.toString(), "GBK"); String admUrl = Service.lookup(IPropertiesService.class) .getSystemProperties().get(channel+"_ADM_URl").getKey(); admUrl = admUrl.concat("/admin/h5AddUser.html?role=").concat(role).concat("&branchId=").concat(userId);; IQrcodeService iQrcodeService = new QrcodeServiceImpl(); String urls = iQrcodeService.createQrCode("-1",paramStr.toString(),"-1"); //String urlString = URLEncoder.encode(, "GBK"); http://shjservices.personalpay.cn/adm // 生成二维码图片到本地+ try { EquCodeCreateUtil.createQrCode(outputStream,urls,900,"JPEG"); } catch (com.google.zxing.WriterException e) { // TODO Auto-generated catch block e.printStackTrace(); } outputStream.close(); // 上传图片到服务器 InputStream inputSteam = new FileInputStream(file); String ambient = Service.lookup(IPublicService.class) .getSysParValue("AMBIENT");//当前环境 FileItem fileItem = createFileItem(file ,"itemFileName"); Map map = null; if("00".equals(ambient)){//测试 map =Service.lookup(IPublicService.class).uploadFile(fileItem, "00", 0, true,"V01"); } if("01".equals(ambient)){//生产 map =Service.lookup(IPublicService.class).uploadFileBD(fileItem, "00", 0, true,"V01"); } String url = String.valueOf(map.get("url")); inputSteam.close(); // 删除本地图片 file.delete(); res.set("url", url); return res; } /* 创建FileItem */ private FileItem createFileItem(File file, String fieldName) { FileItemFactory factory = new DiskFileItemFactory(16, null); FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName()); int bytesRead = 0; byte[] buffer = new byte[8192]; try { FileInputStream fis = new FileInputStream(file); OutputStream os = item.getOutputStream(); while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } return item; } }