LoginAction.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. package com.minpay.common.action;
  2. import com.alipay.api.AlipayApiException;
  3. import com.alipay.api.AlipayClient;
  4. import com.alipay.api.DefaultAlipayClient;
  5. import com.alipay.api.request.AlipaySystemOauthTokenRequest;
  6. import com.alipay.api.request.AlipayUserInfoShareRequest;
  7. import com.alipay.api.response.AlipaySystemOauthTokenResponse;
  8. import com.alipay.api.response.AlipayUserInfoShareResponse;
  9. import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
  10. import com.minpay.common.bean.User;
  11. import com.minpay.common.constant.ServConstant;
  12. import com.minpay.common.pay.bean.PrePay;
  13. import com.minpay.common.service.IAccountService;
  14. import com.minpay.common.service.IPayOsService;
  15. import com.minpay.common.service.IPublicService;
  16. import com.minpay.common.service.impl.PayOsServiceImpl;
  17. import com.minpay.common.service.impl.PublicServiceImpl;
  18. import com.minpay.common.util.*;
  19. import com.minpay.db.table.mapper.*;
  20. import com.minpay.db.table.model.*;
  21. import com.minpay.db.table.own.mapper.SequenceMapper;
  22. import com.startup.minpay.frame.business.IMINAction;
  23. import com.startup.minpay.frame.business.MINHttpServletRequestContext;
  24. import com.startup.minpay.frame.business.res.MINActionResult;
  25. import com.startup.minpay.frame.exception.MINBusinessException;
  26. import com.startup.minpay.frame.service.MINServiceLocator;
  27. import com.startup.minpay.frame.service.base.IMINDataBaseService;
  28. import com.startup.minpay.frame.service.base.IMINSessionService;
  29. import com.startup.minpay.frame.service.base.Service;
  30. import com.startup.minpay.frame.session.MINSession;
  31. import com.startup.minpay.frame.target.MINAction;
  32. import com.startup.minpay.frame.target.MINComponent;
  33. import com.startup.minpay.frame.target.MINParam;
  34. import com.startup.minpay.frame.target.MINValidator;
  35. import net.sf.json.JSONObject;
  36. import org.apache.commons.lang.StringUtils;
  37. import javax.servlet.http.HttpServletResponse;
  38. import javax.servlet.http.HttpSession;
  39. import java.util.List;
  40. /**
  41. * 登录处理类
  42. * @author xu
  43. */
  44. @MINComponent
  45. public class LoginAction implements IMINAction {
  46. // 登录
  47. public final static String LOGIN = "login";
  48. // 发送信息
  49. public final static String SENSMS = "sendSmsMsg";
  50. /**
  51. * 发送短信验证码
  52. * @param mobileNo 手机号码
  53. * @param request
  54. * @return
  55. * @throws Exception
  56. */
  57. @MINAction(value = SENSMS)
  58. public MINActionResult sendSmsMsg(
  59. @MINParam(key = "mobileNo", regex = RegexUtil.MOBILE, error = "请输入正确的手机号码") String mobileNo,
  60. @MINParam(key = "channel") String channel,
  61. MINHttpServletRequestContext request
  62. ) throws Exception {
  63. MINActionResult res = new MINActionResult();
  64. // 验证是否已经发送验证码
  65. HttpSession httpSession = request.getSession();
  66. String lastMobileTime = (String)httpSession.getAttribute(ServConstant.LAST_MOBILE_TIME);
  67. // 如果已经发送过短信验证码,并且在60S以内,稍后再发送
  68. if(StringUtils.isNotBlank(lastMobileTime)
  69. && DateUtil.getDifferentTimeByMinute(-1).compareTo(lastMobileTime) < 0) {
  70. throw new MINBusinessException("JA000035", "请勿频繁发送验证码!");
  71. }
  72. // 是否一分钟内已经有短信验证码
  73. PubSendCodeExample deExp = new PubSendCodeExample();
  74. deExp.createCriteria().andUseridEqualTo(mobileNo).andLasttimeGreaterThan(DateUtil.getDifferentTimeByMinute(-1));
  75. List<PubSendCode> deList = Service.lookup(IMINDataBaseService.class).getMybatisMapper(PubSendCodeMapper.class).selectByExample(deExp);
  76. if(deList.size() > 0) {
  77. throw new MINBusinessException("JA000036", "发送验证码过于频繁,请稍后重试!");
  78. }
  79. // 获取随机数
  80. String random = PublicServiceImpl.generateNumber(6);
  81. // 获取验证码时间
  82. httpSession.setAttribute(ServConstant.LAST_MOBILE_TIME, DateUtil.getCurrentDateTimeString());
  83. // 验证码
  84. httpSession.setAttribute(ServConstant.MOBILE_RANDOM, random);
  85. // 手机号
  86. httpSession.setAttribute(ServConstant.MOBILE_NO, mobileNo);
  87. //短信渠道
  88. String messageChannel = Service.lookup(IPublicService.class).getSysParValue("SHORT_MESSAGE_"+channel);
  89. if("aliyun".equals(messageChannel)){
  90. //获取阿里云模板code
  91. String sms = Service.lookup(IPublicService.class).getSysParValue(channel+"_ALI_CODE");
  92. //获取签名
  93. String sign = Service.lookup(IPublicService.class).getSysParValue(channel+"_ALI_SIGN");
  94. // 暂时屏蔽阿里云的
  95. //SendSmsResponse response = SmsAliSendUtil.sendSms(mobileNo, ServConstant.BTXZS_NAME, "SMS_145590111", "{code:" + random + "}");
  96. SendSmsResponse response = SmsAliSendUtil.sendSms(mobileNo, sign, sms, "{code:" + random + "}",channel);
  97. if(!"OK".equals(response.getCode())) {
  98. throw new MINBusinessException("发送短信失败");
  99. }
  100. }else if("jisu".equals(messageChannel)){
  101. String regVal = Service.lookup(IPublicService.class).getSysParValue(channel + "_REG_MOBILE_MODE");
  102. // 发送短信
  103. String msg = regVal.replaceAll("@", random);
  104. // 非debug模式发送短信验证码
  105. if(!ServConstant.IS_DEBUG) {
  106. SmsSendUtil.sendSms(mobileNo, msg);
  107. }
  108. }
  109. String nowTime = DateUtil.getCurrentDateTimeString();
  110. PubSendCode sendDetail = new PubSendCode();
  111. sendDetail.setCode(random);
  112. sendDetail.setUserid(mobileNo);
  113. sendDetail.setLasttime(nowTime);
  114. sendDetail.setStatus("0");
  115. sendDetail.setFirsttime(nowTime);
  116. Service.lookup(IMINDataBaseService.class).getMybatisMapper(PubSendCodeMapper.class).insert(sendDetail);
  117. return res;
  118. }
  119. /**
  120. *小程序获取用户OPENID,然后登陆
  121. * @param code 用户code
  122. * @param type 登录类型:WX微信AL支付宝
  123. * @param channel 渠道:售货机=V01
  124. * @param equNo 售货机编号
  125. * @param version 版本
  126. * @param response
  127. * @param request
  128. * @return
  129. * @throws Exception
  130. */
  131. @MINAction(value = LOGIN, session = false)
  132. public MINActionResult login(
  133. @MINParam(key = "code") String code,
  134. @MINParam(key = "type") String type,
  135. @MINParam(key = "channel") String channel,
  136. @MINParam(key = "equNo") String equNo,
  137. @MINParam(key = "version") String version,
  138. HttpServletResponse response,
  139. MINHttpServletRequestContext request
  140. ) throws Exception {
  141. MINActionResult res = new MINActionResult();
  142. /*if(CommonUtil.isEmpty(equNo)){
  143. throw new BusinessCodeException("JINM1101");//售货机异常,请联系工作人员
  144. }
  145. //解密售货机编号
  146. String equNoNew = OffSetUtil.deScanCode(equNo);*/
  147. String nowTime = DateUtil.getCurrentDateTimeString();
  148. String versionCheck = Service.lookup(IPublicService.class).getSysParValue(channel + "_CHECK_VERSION");
  149. // 检查是否是检查
  150. if(!CommonUtil.isEmpty(version) && versionCheck.equals(version)) {
  151. res.set("isCheckIng", "1");
  152. } else {
  153. res.set("isCheckIng", "0");
  154. }
  155. VmEquipmentInf vmEquipmentInf = Service.lookup(IMINDataBaseService.class).getMybatisMapper(VmEquipmentInfMapper.class).selectByPrimaryKey(equNo);
  156. if(vmEquipmentInf == null){
  157. throw new MINBusinessException("机器不存在");
  158. }
  159. ImBranch imBranch = Service.lookup(IMINDataBaseService.class).getMybatisMapper(ImBranchMapper.class).selectByPrimaryKey(vmEquipmentInf.getBranchid());
  160. if(imBranch == null){
  161. throw new MINBusinessException("商户不存在");
  162. }
  163. MINActionResult result = null;
  164. if("WX".equals(type)){
  165. result = this.getWxPayOpenid(channel, code);
  166. }else if("AL".equals(type)){
  167. result = this.getALiPayOpenid(channel, code);
  168. }
  169. if(CommonUtil.isEmpty(result.get("openId"))) {
  170. throw new MINBusinessException("JA0001", "非法登录!");
  171. }
  172. // 获取是否有用户
  173. VmPersonInf person = new VmPersonInf();
  174. VmPersonInfExample personex = new VmPersonInfExample();
  175. personex.createCriteria().andChannelEqualTo(channel).andTypeEqualTo(type).andOpenidEqualTo(result.get("openId"));
  176. List<VmPersonInf> perLst = Service.lookup(IMINDataBaseService.class).getMybatisMapper(VmPersonInfMapper.class).selectByExample(personex);
  177. if(perLst.size() == 0) {
  178. //获取用户主键
  179. String perId = Service.lookup(IMINDataBaseService.class).getMybatisMapper(SequenceMapper.class).getSequence("VM_PERSON_INF_NO");
  180. person.setId(perId);
  181. person.setName(result.get("nickName"));
  182. person.setHeadpath(result.get("headImgurl"));
  183. person.setOpenid(result.get("openId"));
  184. person.setStatus("00");//正常
  185. person.setChannel(channel);
  186. person.setIsUser("0");//是否商户0否1是
  187. person.setPhone("00000000000");
  188. person.setType(type);//类型:WX微信AL支付宝
  189. person.setCreateUser(perId);
  190. person.setCreateTime(nowTime);
  191. person.setModifyUser(perId);
  192. person.setModifyTime(nowTime);
  193. Service.lookup(IMINDataBaseService.class).getMybatisMapper(VmPersonInfMapper.class).insertSelective(person);
  194. // 创建用户基本账户
  195. IAccountService service = Service.lookup(IAccountService.class);
  196. // 01:基本账户 02:提现账户 03:待结算账户
  197. service.addAccount(channel, perId, "01",equNo);
  198. service.addAccount(channel, perId, "02",equNo);
  199. service.addAccount(channel, perId, "03",equNo);
  200. }if(perLst.size() > 1) {
  201. throw new MINBusinessException("数据异常");
  202. }if(perLst.size() == 1) {
  203. person = perLst.get(0);
  204. if(!person.getStatus().equals("00")){
  205. throw new MINBusinessException("账号异常,请联系管理员");
  206. }
  207. res.set("isMerchants","0");
  208. //查询相关角色
  209. String branchid = vmEquipmentInf.getBranchid();
  210. String personId = person.getId();
  211. VmPersonRoleInfExample vmPersonRoleInfExample = new VmPersonRoleInfExample();
  212. vmPersonRoleInfExample.createCriteria().andBranchIdEqualTo(branchid).andStateEqualTo("00").andPersonIdEqualTo(personId);
  213. List<VmPersonRoleInf> vmPersonRoleInfList = Service.lookup(IMINDataBaseService.class).getMybatisMapper(VmPersonRoleInfMapper.class).selectByExample(vmPersonRoleInfExample);
  214. String role = "";
  215. for (int i = 0; i < vmPersonRoleInfList.size(); i++) {
  216. role += vmPersonRoleInfList.get(i).getRole().concat(",");
  217. }
  218. if(vmPersonRoleInfList.size() != 0){
  219. res.set("isMerchants","1"); //是本机器的商户(是否管理员)
  220. }
  221. res.set("role",role);
  222. //查询是否有所属机器是否有账户
  223. VmAccountExample vmAccountExample = new VmAccountExample();
  224. vmAccountExample.createCriteria().andEquipmentIdEqualTo(equNo).andUsridEqualTo(person.getId()).andChannelEqualTo(person.getChannel());
  225. List<VmAccount> vmAccountList = Service.lookup(IMINDataBaseService.class).getMybatisMapper(VmAccountMapper.class).selectByExample(vmAccountExample);
  226. if(vmAccountList.size() == 0){
  227. // 创建用户基本账户
  228. IAccountService service = Service.lookup(IAccountService.class);
  229. // 01:基本账户 02:提现账户 03:待结算账户
  230. service.addAccount(channel, person.getId(), "01",equNo);
  231. service.addAccount(channel, person.getId(), "02",equNo);
  232. service.addAccount(channel, person.getId(), "03",equNo);
  233. }
  234. person.setName(result.get("nickName"));
  235. person.setHeadpath(result.get("headImgurl"));
  236. person.setModifyTime(nowTime);
  237. Service.lookup(IMINDataBaseService.class).getMybatisMapper(VmPersonInfMapper.class).updateByExampleSelective(person, personex);
  238. }
  239. // 注册到session
  240. User sessionUser = new User(person);
  241. sessionUser.setEquipmentNo(equNo);
  242. sessionUser.setBranchId(vmEquipmentInf.getBranchid());
  243. res.setSessionId(MINServiceLocator.getInstance().lookup(IMINSessionService.class).registerSession(request, sessionUser));
  244. res.set("nickName", result.get("nickName")); //用户昵称
  245. res.set("headImgurl", result.get("headImgurl"));
  246. res.set("equipmentAddress", vmEquipmentInf.getAddress());
  247. res.set("headImeiaddr", vmEquipmentInf.getImeiAddr());
  248. res.set("versionType", vmEquipmentInf.getVersionType());
  249. res.set("equType", vmEquipmentInf.getEquType());
  250. res.set("payment", vmEquipmentInf.getPayment());
  251. res.set("branchName", imBranch.getName()); //商户名称
  252. return res;
  253. }
  254. @MINValidator(value = LOGIN)
  255. public MINActionResult loginValidator(
  256. @MINParam(key = "code" ) String code,
  257. @MINParam(key = "type") String type,
  258. @MINParam(key = "channel") String channel,
  259. @MINParam(key = "equNo") String equNo,
  260. @MINParam(key = "version") String version,
  261. MINSession session) throws MINBusinessException {
  262. MINActionResult res = new MINActionResult();
  263. if(CommonUtil.isEmpty(code) ||
  264. CommonUtil.isEmpty(type) ||
  265. CommonUtil.isEmpty(channel) ||
  266. CommonUtil.isEmpty(equNo) ||
  267. CommonUtil.isEmpty(version)){
  268. throw new MINBusinessException("参数为空或数据异常");
  269. }
  270. //校验机器编号是否存在
  271. VmEquipmentInf vmEquipmentInf = Service.lookup(IMINDataBaseService.class).getMybatisMapper(VmEquipmentInfMapper.class).selectByPrimaryKey(equNo);
  272. if(vmEquipmentInf == null){
  273. throw new MINBusinessException("机器不存在或异常!");
  274. }
  275. return res;
  276. }
  277. /***
  278. * 微信用户授权,获取用户信息
  279. * @param code
  280. * @param channel
  281. * @return
  282. * @throws MINBusinessException
  283. */
  284. private MINActionResult getWxPayOpenid(String channel ,String code) throws MINBusinessException {
  285. MINActionResult res = new MINActionResult();
  286. //在微信的appId
  287. String appId = Service.lookup(IPublicService.class).getSysParValue(channel + "_APP_ID");
  288. //在微信的secret
  289. String appSecret = Service.lookup(IPublicService.class).getSysParValue(channel + "_APP_SECRET");
  290. //微信通用请求路径
  291. String openUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
  292. //配置参数
  293. StringBuffer paramStr = new StringBuffer();
  294. paramStr.append("appid=");
  295. paramStr.append(appId);
  296. paramStr.append("&secret=");
  297. paramStr.append(appSecret);
  298. paramStr.append("&code=");
  299. paramStr.append(code);
  300. paramStr.append("&grant_type=authorization_code");
  301. try {
  302. if("123".equals(code)){
  303. res.set("nickName", "Clearlove");
  304. res.set("headImgurl", "https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIZ3h0UPPibR06bowe0Zpq5LeEib67VrRT44bibRDFkEQq89G6cMc9JxoOn1vPG89icEbXyZiaNKbhRLsw/132");
  305. res.set("openId", "oKW8s1T5vCXVAqfZ44tcFAbYdetI");
  306. }else{
  307. //发送请求
  308. String jsonObj = HttpPostUtil.sendPost(openUrl, paramStr.toString());
  309. JSONObject js = JSONObject.fromObject(jsonObj);
  310. //获取openId
  311. String openId = js.getString("openid");//用户唯一标识,请注意,在未关注公众号时,用户访问公众号的网页,也会产生一个用户和公众号唯一的OpenID
  312. //微信通用请求路径
  313. String openUrl2 = "https://api.weixin.qq.com/sns/userinfo";
  314. //配置参数
  315. StringBuffer paramStr2 = new StringBuffer();
  316. paramStr2.append("access_token=");
  317. paramStr2.append(js.getString("access_token"));
  318. paramStr2.append("&openid=");
  319. paramStr2.append(openId);
  320. paramStr2.append("&lang=zh_CN");
  321. //发送请求
  322. String jsonObj2 = HttpPostUtil.sendPost(openUrl2, paramStr2.toString());
  323. JSONObject js2 = JSONObject.fromObject(jsonObj2);
  324. String nickName = EmojiFilter.filterEmoji(js2.getString("nickname"));
  325. // String nickName = js2.getString("nickname");
  326. String headImgurl = js2.getString("headimgurl");
  327. res.set("openId", openId);
  328. res.set("headImgurl", headImgurl);
  329. res.set("nickName", nickName);
  330. }
  331. } catch (Exception e) {
  332. throw new MINBusinessException("PAY10006", "微信获取openId失败!");
  333. }
  334. return res;
  335. }
  336. /***
  337. * 支付宝用户授权,获取用户信息
  338. * @param code
  339. * @param channel
  340. * @return
  341. * @throws MINBusinessException
  342. */
  343. private MINActionResult getALiPayOpenid(String channel ,String code) throws MINBusinessException {
  344. MINActionResult res = new MINActionResult();
  345. if("123".equals(code)){
  346. res.set("nickName", "啦啦啦");
  347. res.set("headImgurl", "https://tfs.alipayobjects.com/images/partner/T103tfXjpXXXXXXXXX");
  348. res.set("openId", "2088412369546572");
  349. }else{
  350. //在支付宝的appId
  351. String appId = Service.lookup(IPublicService.class).getSysParValue(channel + "_ZHIFUBAO_APP_ID");
  352. //在支付宝的私钥
  353. String privateKeyLocation = ServConstant.PRIVATE_KEY_LOCATION;
  354. //支付宝的公钥s
  355. String publicKeyLocation = ServConstant.PUBLIC_KEY_LOCATION;
  356. //支付宝通用请求路径
  357. String openUrl = "https://openapi.alipay.com/gateway.do";
  358. //根据code获取accessToken
  359. AlipayClient alipayClient = new DefaultAlipayClient(openUrl,
  360. appId, privateKeyLocation, "json","UTF-8", publicKeyLocation,"RSA2");
  361. AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
  362. request.setCode(code);
  363. request.setGrantType("authorization_code");//固定值authorization_code
  364. AlipaySystemOauthTokenResponse response = null;
  365. try {
  366. response = alipayClient.execute(request);
  367. } catch (AlipayApiException e) {
  368. throw new MINBusinessException("PAY10007", "支付宝获取openId失败!");
  369. }
  370. if (response.isSuccess()) {
  371. System.out.println(response.getBody());
  372. System.out.println(response.getAlipayUserId());
  373. String openId = response.getAlipayUserId();
  374. AlipayUserInfoShareRequest request2 = new AlipayUserInfoShareRequest();
  375. AlipayUserInfoShareResponse response2 = null;
  376. try {
  377. response2 = alipayClient.execute(request2,response.getAccessToken());
  378. } catch (AlipayApiException e) {
  379. // TODO Auto-generated catch block
  380. e.printStackTrace();
  381. }
  382. if (response2.isSuccess()) {
  383. System.out.println(response2.getBody());
  384. System.out.println(response2.getUserId());
  385. String avatar = response2.getAvatar();
  386. String nickName = EmojiFilter.filterEmoji(response2.getNickName());
  387. // String nickName = response2.getNickName();
  388. String userId = response2.getUserId();
  389. res.set("openId", userId);
  390. res.set("headImgurl", avatar);
  391. res.set("nickName", nickName);
  392. }
  393. }
  394. }
  395. return res;
  396. }
  397. // public static void main(String args[]) {
  398. // String appId = "2019051764975953";
  399. // //在支付宝的私钥
  400. // String privateKeyLocation = ServConstant.PRIVATE_KEY_LOCATION;
  401. // //支付宝的公钥s
  402. // String publicKeyLocation = ServConstant.PUBLIC_KEY_LOCATION;
  403. // //支付宝通用请求路径
  404. // String openUrl = "https://openapi.alipay.com/gateway.do";
  405. // //根据code获取accessToken
  406. // AlipayClient alipayClient = new DefaultAlipayClient(openUrl,
  407. // appId, privateKeyLocation, "json","GBK", publicKeyLocation);
  408. // AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
  409. // request.setCode("21321321321");
  410. // request.setGrantType("authorization_code");//固定值authorization_code
  411. // AlipaySystemOauthTokenResponse response = null;
  412. // try {
  413. // response = alipayClient.execute(request);
  414. // } catch (AlipayApiException e) {
  415. // e.printStackTrace();
  416. // }
  417. // if (response.isSuccess()) {
  418. // System.out.println(response.getBody());
  419. // System.out.println(response.getAlipayUserId());
  420. // }
  421. // }
  422. @MINAction(value = "test" , session = false)
  423. public MINActionResult test(
  424. MINSession session ) throws MINBusinessException{
  425. MINActionResult res = new MINActionResult();
  426. PrePay prePay = new PrePay();
  427. IPayOsService IPayOsService = new PayOsServiceImpl();
  428. prePay.setBody("大头");
  429. try {
  430. IPayOsService.prePay(prePay);
  431. } catch (MINBusinessException e) {
  432. e.printStackTrace();
  433. }
  434. return res;
  435. }
  436. }