package com.minpay.common.action; import com.alipay.api.AlipayApiException; import com.alipay.api.AlipayClient; import com.alipay.api.DefaultAlipayClient; import com.alipay.api.request.AlipaySystemOauthTokenRequest; import com.alipay.api.request.AlipayUserInfoShareRequest; import com.alipay.api.response.AlipaySystemOauthTokenResponse; import com.alipay.api.response.AlipayUserInfoShareResponse; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; import com.minpay.common.bean.User; import com.minpay.common.constant.ServConstant; import com.minpay.common.pay.bean.PrePay; import com.minpay.common.service.IAccountService; import com.minpay.common.service.IPayOsService; import com.minpay.common.service.IPublicService; import com.minpay.common.service.impl.PayOsServiceImpl; import com.minpay.common.service.impl.PublicServiceImpl; import com.minpay.common.util.*; import com.minpay.db.table.mapper.PubSendCodeMapper; import com.minpay.db.table.mapper.VmAccountMapper; import com.minpay.db.table.mapper.VmEquipmentInfMapper; import com.minpay.db.table.mapper.VmPersonInfMapper; import com.minpay.db.table.model.*; import com.minpay.db.table.own.mapper.SequenceMapper; 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.exception.MINBusinessException; import com.startup.minpay.frame.service.MINServiceLocator; import com.startup.minpay.frame.service.base.IMINDataBaseService; import com.startup.minpay.frame.service.base.IMINSessionService; 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 com.startup.minpay.frame.target.MINValidator; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.List; /** * 登录处理类 * @author xu */ @MINComponent public class LoginAction implements IMINAction { // 登录 public final static String LOGIN = "login"; // 发送信息 public final static String SENSMS = "sendSmsMsg"; /** * 发送短信验证码 * @param mobileNo 手机号码 * @param request * @return * @throws Exception */ @MINAction(value = SENSMS) public MINActionResult sendSmsMsg( @MINParam(key = "mobileNo", regex = RegexUtil.MOBILE, error = "请输入正确的手机号码") String mobileNo, @MINParam(key = "channel") String channel, MINHttpServletRequestContext request ) throws Exception { MINActionResult res = new MINActionResult(); // 验证是否已经发送验证码 HttpSession httpSession = request.getSession(); String lastMobileTime = (String)httpSession.getAttribute(ServConstant.LAST_MOBILE_TIME); // 如果已经发送过短信验证码,并且在60S以内,稍后再发送 if(StringUtils.isNotBlank(lastMobileTime) && DateUtil.getDifferentTimeByMinute(-1).compareTo(lastMobileTime) < 0) { throw new MINBusinessException("JA000035", "请勿频繁发送验证码!"); } // 是否一分钟内已经有短信验证码 PubSendCodeExample deExp = new PubSendCodeExample(); deExp.createCriteria().andUseridEqualTo(mobileNo).andLasttimeGreaterThan(DateUtil.getDifferentTimeByMinute(-1)); List deList = Service.lookup(IMINDataBaseService.class).getMybatisMapper(PubSendCodeMapper.class).selectByExample(deExp); if(deList.size() > 0) { throw new MINBusinessException("JA000036", "发送验证码过于频繁,请稍后重试!"); } // 获取随机数 String random = PublicServiceImpl.generateNumber(6); // 获取验证码时间 httpSession.setAttribute(ServConstant.LAST_MOBILE_TIME, DateUtil.getCurrentDateTimeString()); // 验证码 httpSession.setAttribute(ServConstant.MOBILE_RANDOM, random); // 手机号 httpSession.setAttribute(ServConstant.MOBILE_NO, mobileNo); //短信渠道 String messageChannel = Service.lookup(IPublicService.class).getSysParValue("SHORT_MESSAGE_"+channel); if("aliyun".equals(messageChannel)){ //获取阿里云模板code String sms = Service.lookup(IPublicService.class).getSysParValue(channel+"_ALI_CODE"); //获取签名 String sign = Service.lookup(IPublicService.class).getSysParValue(channel+"_ALI_SIGN"); // 暂时屏蔽阿里云的 //SendSmsResponse response = SmsAliSendUtil.sendSms(mobileNo, ServConstant.BTXZS_NAME, "SMS_145590111", "{code:" + random + "}"); SendSmsResponse response = SmsAliSendUtil.sendSms(mobileNo, sign, sms, "{code:" + random + "}",channel); if(!"OK".equals(response.getCode())) { throw new MINBusinessException("发送短信失败"); } }else if("jisu".equals(messageChannel)){ String regVal = Service.lookup(IPublicService.class).getSysParValue(channel + "_REG_MOBILE_MODE"); // 发送短信 String msg = regVal.replaceAll("@", random); // 非debug模式发送短信验证码 if(!ServConstant.IS_DEBUG) { SmsSendUtil.sendSms(mobileNo, msg); } } String nowTime = DateUtil.getCurrentDateTimeString(); PubSendCode sendDetail = new PubSendCode(); sendDetail.setCode(random); sendDetail.setUserid(mobileNo); sendDetail.setLasttime(nowTime); sendDetail.setStatus("0"); sendDetail.setFirsttime(nowTime); Service.lookup(IMINDataBaseService.class).getMybatisMapper(PubSendCodeMapper.class).insert(sendDetail); return res; } /** *小程序获取用户OPENID,然后登陆 * @param code 用户code * @param type 登录类型:WX微信AL支付宝 * @param channel 渠道:售货机=V01 * @param equNo 售货机编号 * @param version 版本 * @param response * @param request * @return * @throws Exception */ @MINAction(value = LOGIN, session = false) public MINActionResult login( @MINParam(key = "code") String code, @MINParam(key = "type") String type, @MINParam(key = "channel") String channel, @MINParam(key = "equNo") String equNo, @MINParam(key = "version") String version, HttpServletResponse response, MINHttpServletRequestContext request ) throws Exception { MINActionResult res = new MINActionResult(); /*if(CommonUtil.isEmpty(equNo)){ throw new BusinessCodeException("JINM1101");//售货机异常,请联系工作人员 } //解密售货机编号 String equNoNew = OffSetUtil.deScanCode(equNo);*/ String nowTime = DateUtil.getCurrentDateTimeString(); String versionCheck = Service.lookup(IPublicService.class).getSysParValue(channel + "_CHECK_VERSION"); // 检查是否是检查 if(!CommonUtil.isEmpty(version) && versionCheck.equals(version)) { res.set("isCheckIng", "1"); } else { res.set("isCheckIng", "0"); } VmEquipmentInf vmEquipmentInf = Service.lookup(IMINDataBaseService.class).getMybatisMapper(VmEquipmentInfMapper.class).selectByPrimaryKey(equNo); if(vmEquipmentInf == null){ throw new MINBusinessException("机器不存在"); } MINActionResult result = null; if("WX".equals(type)){ result = this.getWxPayOpenid(channel, code); }else if("AL".equals(type)){ result = this.getALiPayOpenid(channel, code); } if(CommonUtil.isEmpty(result.get("openId"))) { throw new MINBusinessException("JA0001", "非法登录!"); } // 获取是否有用户 VmPersonInf person = new VmPersonInf(); VmPersonInfExample personex = new VmPersonInfExample(); personex.createCriteria().andChannelEqualTo(channel).andTypeEqualTo(type).andOpenidEqualTo(result.get("openId")); List perLst = Service.lookup(IMINDataBaseService.class).getMybatisMapper(VmPersonInfMapper.class).selectByExample(personex); if(perLst.size() == 0) { //获取用户主键 String perId = Service.lookup(IMINDataBaseService.class).getMybatisMapper(SequenceMapper.class).getSequence("VM_PERSON_INF_NO"); person.setId(perId); person.setName(result.get("nickName")); person.setHeadpath(result.get("headImgurl")); person.setOpenid(result.get("openId")); person.setStatus("00");//正常 person.setChannel(channel); person.setIsUser("0");//是否商户0否1是 person.setPhone("00000000000"); person.setType(type);//类型:WX微信AL支付宝 person.setCreateUser(perId); person.setCreateTime(nowTime); person.setModifyUser(perId); person.setModifyTime(nowTime); Service.lookup(IMINDataBaseService.class).getMybatisMapper(VmPersonInfMapper.class).insertSelective(person); // 创建用户基本账户 IAccountService service = Service.lookup(IAccountService.class); // 01:基本账户 02:提现账户 03:待结算账户 service.addAccount(channel, perId, "01",equNo); service.addAccount(channel, perId, "02",equNo); service.addAccount(channel, perId, "03",equNo); }if(perLst.size() > 1) { throw new MINBusinessException("数据异常"); }if(perLst.size() == 1) { person = perLst.get(0); if(!person.getStatus().equals("00")){ throw new MINBusinessException("账号异常,请联系管理员"); } res.set("isMerchants","0"); if("1".equals(person.getIsUser())){ if(vmEquipmentInf.getBranchid().equals(person.getUserId())){ res.set("isMerchants",person.getIsUser()); //是本机器的商户(是否管理员) res.set("role",person.getRole()); } } //查询是否有所属机器是否有账户 VmAccountExample vmAccountExample = new VmAccountExample(); vmAccountExample.createCriteria().andEquipmentIdEqualTo(equNo).andUsridEqualTo(person.getId()).andChannelEqualTo(person.getChannel()); List vmAccountList = Service.lookup(IMINDataBaseService.class).getMybatisMapper(VmAccountMapper.class).selectByExample(vmAccountExample); if(vmAccountList.size() == 0){ // 创建用户基本账户 IAccountService service = Service.lookup(IAccountService.class); // 01:基本账户 02:提现账户 03:待结算账户 service.addAccount(channel, person.getId(), "01",equNo); service.addAccount(channel, person.getId(), "02",equNo); service.addAccount(channel, person.getId(), "03",equNo); } person.setName(result.get("nickName")); person.setHeadpath(result.get("headImgurl")); person.setModifyTime(nowTime); Service.lookup(IMINDataBaseService.class).getMybatisMapper(VmPersonInfMapper.class).updateByExampleSelective(person, personex); } // 注册到session User sessionUser = new User(person); sessionUser.setEquipmentNo(equNo); sessionUser.setBranchId(vmEquipmentInf.getBranchid()); res.setSessionId(MINServiceLocator.getInstance().lookup(IMINSessionService.class).registerSession(request, sessionUser)); res.set("nickName", result.get("nickName")); res.set("headImgurl", result.get("headImgurl")); res.set("equipmentAddress", vmEquipmentInf.getAddress()); res.set("headImeiaddr", vmEquipmentInf.getImeiAddr()); res.set("versionType", vmEquipmentInf.getVersionType()); res.set("equType", vmEquipmentInf.getEquType()); res.set("payment", vmEquipmentInf.getPayment()); //支付金额 return res; } @MINValidator(value = LOGIN) public MINActionResult loginValidator( @MINParam(key = "code" ) String code, @MINParam(key = "type") String type, @MINParam(key = "channel") String channel, @MINParam(key = "equNo") String equNo, @MINParam(key = "version") String version, MINSession session) throws MINBusinessException { MINActionResult res = new MINActionResult(); if(CommonUtil.isEmpty(code) || CommonUtil.isEmpty(type) || CommonUtil.isEmpty(channel) || CommonUtil.isEmpty(equNo) || CommonUtil.isEmpty(version)){ throw new MINBusinessException("参数为空或数据异常"); } //校验机器编号是否存在 VmEquipmentInf vmEquipmentInf = Service.lookup(IMINDataBaseService.class).getMybatisMapper(VmEquipmentInfMapper.class).selectByPrimaryKey(equNo); if(vmEquipmentInf == null){ throw new MINBusinessException("机器不存在或异常!"); } 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 { if("123".equals(code)){ res.set("nickName", "Clearlove"); res.set("headImgurl", "https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIZ3h0UPPibR06bowe0Zpq5LeEib67VrRT44bibRDFkEQq89G6cMc9JxoOn1vPG89icEbXyZiaNKbhRLsw/132"); res.set("openId", "oKW8s1T5vCXVAqfZ44tcFAbYdetI"); }else{ //发送请求 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 code * @param channel * @return * @throws MINBusinessException */ private MINActionResult getALiPayOpenid(String channel ,String code) throws MINBusinessException { MINActionResult res = new MINActionResult(); if("123".equals(code)){ res.set("nickName", "啦啦啦"); res.set("headImgurl", "https://tfs.alipayobjects.com/images/partner/T103tfXjpXXXXXXXXX"); res.set("openId", "2088412369546572"); }else{ //在支付宝的appId String appId = Service.lookup(IPublicService.class).getSysParValue(channel + "_ZHIFUBAO_APP_ID"); //在支付宝的私钥 String privateKeyLocation = ServConstant.PRIVATE_KEY_LOCATION; //支付宝的公钥s String publicKeyLocation = ServConstant.PUBLIC_KEY_LOCATION; //支付宝通用请求路径 String openUrl = "https://openapi.alipay.com/gateway.do"; //根据code获取accessToken AlipayClient alipayClient = new DefaultAlipayClient(openUrl, appId, privateKeyLocation, "json","UTF-8", publicKeyLocation,"RSA2"); AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest(); request.setCode(code); request.setGrantType("authorization_code");//固定值authorization_code AlipaySystemOauthTokenResponse response = null; try { response = alipayClient.execute(request); } catch (AlipayApiException e) { throw new MINBusinessException("PAY10007", "支付宝获取openId失败!"); } if (response.isSuccess()) { System.out.println(response.getBody()); System.out.println(response.getAlipayUserId()); String openId = response.getAlipayUserId(); AlipayUserInfoShareRequest request2 = new AlipayUserInfoShareRequest(); AlipayUserInfoShareResponse response2 = null; try { response2 = alipayClient.execute(request2,response.getAccessToken()); } catch (AlipayApiException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (response2.isSuccess()) { System.out.println(response2.getBody()); System.out.println(response2.getUserId()); String avatar = response2.getAvatar(); String nickName = EmojiFilter.filterEmoji(response2.getNickName()); // String nickName = response2.getNickName(); String userId = response2.getUserId(); res.set("openId", userId); res.set("headImgurl", avatar); res.set("nickName", nickName); } } } return res; } // public static void main(String args[]) { // String appId = "2019051764975953"; // //在支付宝的私钥 // String privateKeyLocation = ServConstant.PRIVATE_KEY_LOCATION; // //支付宝的公钥s // String publicKeyLocation = ServConstant.PUBLIC_KEY_LOCATION; // //支付宝通用请求路径 // String openUrl = "https://openapi.alipay.com/gateway.do"; // //根据code获取accessToken // AlipayClient alipayClient = new DefaultAlipayClient(openUrl, // appId, privateKeyLocation, "json","GBK", publicKeyLocation); // AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest(); // request.setCode("21321321321"); // request.setGrantType("authorization_code");//固定值authorization_code // AlipaySystemOauthTokenResponse response = null; // try { // response = alipayClient.execute(request); // } catch (AlipayApiException e) { // e.printStackTrace(); // } // if (response.isSuccess()) { // System.out.println(response.getBody()); // System.out.println(response.getAlipayUserId()); // } // } @MINAction(value = "test" , session = false) public MINActionResult test( MINSession session ) throws MINBusinessException{ MINActionResult res = new MINActionResult(); PrePay prePay = new PrePay(); IPayOsService IPayOsService = new PayOsServiceImpl(); prePay.setBody("大头"); try { IPayOsService.prePay(prePay); } catch (MINBusinessException e) { e.printStackTrace(); } return res; } }