UserInfoServiceImpl.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. package com.izouma.awesomeadmin.service.impl;
  2. import com.izouma.awesomeadmin.constant.AppConstant;
  3. import com.izouma.awesomeadmin.dao.*;
  4. import com.izouma.awesomeadmin.dto.Page;
  5. import com.izouma.awesomeadmin.model.AlipayTemp;
  6. import com.izouma.awesomeadmin.model.MemberCoin;
  7. import com.izouma.awesomeadmin.model.UserInfo;
  8. import com.izouma.awesomeadmin.service.OSSFileService;
  9. import com.izouma.awesomeadmin.service.UserInfoService;
  10. import com.izouma.awesomeadmin.util.MD5Util;
  11. import com.izouma.awesomeadmin.util.PropertiesFileLoader;
  12. import com.izouma.awesomeadmin.util.WeixinUtil;
  13. import io.jsonwebtoken.Claims;
  14. import io.jsonwebtoken.Jwt;
  15. import io.jsonwebtoken.Jwts;
  16. import io.jsonwebtoken.security.Keys;
  17. import io.rong.RongCloud;
  18. import io.rong.models.SMSVerifyCodeResult;
  19. import org.apache.commons.lang.StringUtils;
  20. import org.apache.log4j.Logger;
  21. import org.json.JSONException;
  22. import org.json.JSONObject;
  23. import org.springframework.beans.factory.annotation.Autowired;
  24. import org.springframework.stereotype.Service;
  25. import javax.crypto.SecretKey;
  26. import java.io.IOException;
  27. import java.math.BigDecimal;
  28. import java.net.HttpURLConnection;
  29. import java.net.URL;
  30. import java.text.SimpleDateFormat;
  31. import java.util.*;
  32. /**
  33. * user_info service接口实现类
  34. * Tue Apr 17 10:32:49 CST 2018 Suo Chen Cheng
  35. */
  36. @Service
  37. public class UserInfoServiceImpl implements UserInfoService {
  38. private static Logger logger = Logger.getLogger(UserInfoServiceImpl.class);
  39. private RongCloud rongCloud = RongCloud.getInstance(PropertiesFileLoader.getProperties("rongyunappkey"), PropertiesFileLoader.getProperties("rongyunappsecret"));
  40. @Autowired
  41. private UserInfoMapper userInfoMapper;
  42. @Autowired
  43. private SysRoleMapper sysRoleMapper;
  44. @Autowired
  45. private DepartInfoMapper departInfoMapper;
  46. @Autowired
  47. private SysAppTokenMapper sysAppTokenMapper;
  48. @Autowired
  49. private OSSFileService ossFileService;
  50. @Autowired
  51. private AlipayTempMapper alipayTempMapper;
  52. @Autowired
  53. private MemberCoinMapper memberCoinMapper;
  54. @Override
  55. public List<UserInfo> getUserInfoList(UserInfo record) {
  56. logger.info("getUserInfoList");
  57. try {
  58. return userInfoMapper.queryAllUserInfo(record);
  59. } catch (Exception e) {
  60. logger.error("getUserInfoList", e);
  61. }
  62. return null;
  63. }
  64. @Override
  65. public List<UserInfo> getUserInfoByPage(Page page, UserInfo record) {
  66. logger.info("getUserInfoByPage");
  67. try {
  68. Map<String, Object> parameter = new HashMap<String, Object>();
  69. parameter.put("record", record);
  70. parameter.put(AppConstant.PAGE, page);
  71. return userInfoMapper.queryUserInfosByPage(parameter);
  72. } catch (Exception e) {
  73. logger.error("getUserInfoByPage", e);
  74. }
  75. return null;
  76. }
  77. @Override
  78. public UserInfo getUserInfoById(String id) {
  79. logger.info("getUserInfoById");
  80. try {
  81. return userInfoMapper.selectByPrimaryKey(Integer.valueOf(id));
  82. } catch (Exception e) {
  83. logger.error("getUserInfoById", e);
  84. }
  85. return null;
  86. }
  87. @Override
  88. public UserInfo getUserInfo(UserInfo record) {
  89. logger.info("getUserInfo");
  90. try {
  91. return userInfoMapper.queryUserInfo(record);
  92. } catch (Exception e) {
  93. logger.error("getUserInfo", e);
  94. }
  95. return null;
  96. }
  97. @Override
  98. public UserInfo getSingleUserInfo(UserInfo record) {
  99. logger.info("getSingleUserInfo");
  100. try {
  101. return userInfoMapper.querySingleUserInfo(record);
  102. } catch (Exception e) {
  103. logger.error("getSingleUserInfo", e);
  104. }
  105. return null;
  106. }
  107. @Override
  108. public boolean createUserInfo(UserInfo record) {
  109. logger.info("createUserInfo");
  110. try {
  111. if (StringUtils.isNotEmpty(record.getPassword())) {
  112. record.setPassword(MD5Util.getMD5(record.getPassword()));
  113. }
  114. int updates = userInfoMapper.insertSelective(record);
  115. if (updates > 0) {
  116. songMoney(record);//赠送余额
  117. }
  118. if (updateUserRolesAndDeparts(record, updates)) return true;
  119. } catch (Exception e) {
  120. logger.error("createUserInfo", e);
  121. }
  122. return false;
  123. }
  124. /**
  125. * 用户注册赠送余额
  126. *
  127. * @param record
  128. */
  129. private void songMoney(UserInfo record) {
  130. try {
  131. MemberCoin memberCoin = new MemberCoin();
  132. memberCoin.setMoney(BigDecimal.valueOf(1000));
  133. memberCoin.setUserId(record.getId());
  134. double money = memberCoin.getMoney().doubleValue();
  135. int userId = Integer.valueOf(memberCoin.getUserId());
  136. UserInfo userInfo = userInfoMapper.selectByPrimaryKey(record.getId());
  137. UserInfo updateUser = new UserInfo();
  138. updateUser.setId(userId);
  139. double balance = userInfo.getMoneyCoin();
  140. double moneyCoin = balance + money;
  141. memberCoin.setCreateUser("管理员");
  142. memberCoin.setBalance(BigDecimal.valueOf(moneyCoin));
  143. memberCoin.setTypeFlag(AppConstant.CoinType.SONG);
  144. memberCoin.setRemark("新用户注册,后台赠送:" + money + "余额");
  145. memberCoinMapper.insertSelective(memberCoin);
  146. updateUser.setMoneyCoin(moneyCoin);
  147. this.updateUserInfo(updateUser);
  148. } catch (Exception e) {
  149. logger.error("新用户注册赠送余额异常", e);
  150. }
  151. }
  152. private boolean updateUserRolesAndDeparts(UserInfo record, int updates) {
  153. if (updates > 0) {
  154. if (record.getDepartId() != null) {
  155. departInfoMapper.clearUserDeparts(record.getId());
  156. departInfoMapper.setUserDeparts(record.getId(), Arrays.asList(record.getDepartId().split(",")));
  157. }
  158. if (record.getRoleId() != null) {
  159. sysRoleMapper.clearUserRoles(record.getId());
  160. sysRoleMapper.setUserRoles(record.getId(), Arrays.asList(record.getRoleId().split(",")));
  161. }
  162. return true;
  163. }
  164. return false;
  165. }
  166. @Override
  167. public boolean deleteUserInfo(String id) {
  168. logger.info("deleteUserInfo");
  169. try {
  170. int updates = userInfoMapper.delete(id);
  171. departInfoMapper.clearUserDeparts(Integer.valueOf(id));
  172. sysRoleMapper.clearUserRoles(Integer.valueOf(id));
  173. if (updates > 0) {
  174. return true;
  175. }
  176. } catch (Exception e) {
  177. logger.error("deleteUserInfo", e);
  178. }
  179. return false;
  180. }
  181. @Override
  182. public boolean updateUserInfo(UserInfo record) {
  183. logger.info("updateUserInfo");
  184. try {
  185. int updates = userInfoMapper.updateByPrimaryKeySelective(record);
  186. if (updateUserRolesAndDeparts(record, updates)) return true;
  187. } catch (Exception e) {
  188. logger.error("updateUserInfo", e);
  189. }
  190. return false;
  191. }
  192. @Override
  193. public boolean updatePassword(UserInfo record) {
  194. logger.info("updatePassword");
  195. try {
  196. if (StringUtils.isNotEmpty(record.getPassword())) {
  197. record.setPassword(MD5Util.getMD5(record.getPassword()));
  198. }
  199. int updates = userInfoMapper.updatePassword(record);
  200. if (updates > 0) {
  201. return true;
  202. }
  203. } catch (Exception e) {
  204. logger.error("updatePassword", e);
  205. }
  206. return false;
  207. }
  208. @Override
  209. public UserInfo login(String username, String password) {
  210. logger.info("login");
  211. try {
  212. Map<String, Object> map = new HashMap<>();
  213. map.put("username", username);
  214. map.put("password", MD5Util.getMD5(password));
  215. UserInfo result = userInfoMapper.login(map);
  216. return result;
  217. } catch (Exception e) {
  218. logger.error("login", e);
  219. }
  220. return null;
  221. }
  222. // @Override
  223. // public UserInfo loginSms(String phone, String code, String sessionId) throws LoginException {
  224. // logger.info("loginSms");
  225. //// SMSVerifyCodeResult sMSVerifyCodeResult;
  226. //// try {
  227. //// sMSVerifyCodeResult = rongCloud.sms.verifyCode(sessionId, code);
  228. //// } catch (Exception e) {
  229. //// e.printStackTrace();
  230. //// throw new LoginException("验证码错误");
  231. //// }
  232. // try {
  233. // if (code.toLowerCase().equals(sessionId)) {
  234. // UserInfo userInfo = new UserInfo();
  235. // userInfo.setPhone(phone);
  236. // userInfo = getUserInfo(userInfo);
  237. // if (userInfo == null) {
  238. // userInfo = new UserInfo();
  239. // userInfo.setPhone(phone);
  240. // userInfo.setUsername(phone);
  241. // userInfo.setNickname(phone);
  242. // userInfo.setIcon("https://microball.oss-cn-hangzhou.aliyuncs.com/huanbaojia/icon_morentouxiang.png");
  243. // if (!createUserInfo(userInfo)) {
  244. // throw new LoginException("登录失败");
  245. // }
  246. // }
  247. // return userInfo;
  248. // }
  249. // } catch (Exception e) {
  250. // e.printStackTrace();
  251. // throw new LoginException("验证码错误");
  252. // }
  253. // throw new LoginException("验证码错误");
  254. // }
  255. @Override
  256. public UserInfo loginSms(String phone, String code, String sessionId) throws LoginException {
  257. logger.info("loginSms");
  258. SMSVerifyCodeResult sMSVerifyCodeResult;
  259. try {
  260. sMSVerifyCodeResult = rongCloud.sms.verifyCode(sessionId, code);
  261. } catch (Exception e) {
  262. e.printStackTrace();
  263. throw new LoginException("验证码错误");
  264. }
  265. if (200 == sMSVerifyCodeResult.getCode()) {
  266. Boolean success = sMSVerifyCodeResult.getSuccess();
  267. if (success) {
  268. UserInfo userInfo = new UserInfo();
  269. userInfo.setPhone(phone);
  270. userInfo = getUserInfo(userInfo);
  271. if (userInfo == null) {
  272. userInfo = new UserInfo();
  273. userInfo.setPhone(phone);
  274. userInfo.setUsername(phone);
  275. userInfo.setNickname(phone);
  276. userInfo.setIcon("https://microball.oss-cn-hangzhou.aliyuncs.com/huanbaojia/icon_morentouxiang.png");
  277. if (!createUserInfo(userInfo)) {
  278. throw new LoginException("登录失败");
  279. }
  280. }
  281. return userInfo;
  282. }
  283. }
  284. throw new LoginException("验证码错误");
  285. }
  286. @Override
  287. public UserInfo loginAppToken(String token) {
  288. logger.info("loginAppToken");
  289. UserInfo userInfo = null;
  290. try {
  291. // AppToken appToken = sysAppTokenMapper.getToken(token);
  292. // if (appToken != null) {
  293. SecretKey key = Keys.hmacShaKeyFor(Base64.getDecoder().decode(PropertiesFileLoader.getProperties("jwtsecret").getBytes()));
  294. Jwt jwt = Jwts.parser()
  295. .setSigningKey(key)
  296. .parse(token);
  297. Claims claims = (Claims) jwt.getBody();
  298. if (claims.getExpiration() != null) {
  299. if (claims.getExpiration().before(new Date())) {
  300. return null;
  301. }
  302. }
  303. if (claims.getSubject().equals("guest")) {
  304. userInfo = new UserInfo();
  305. } else {
  306. userInfo = getUserInfoById(claims.getSubject());
  307. }
  308. // }
  309. } catch (Exception e) {
  310. logger.error("loginAppToken", e);
  311. }
  312. return userInfo;
  313. }
  314. @Override
  315. public List<String> findDepartLeader(String userId) {
  316. logger.info("findDepartLeader");
  317. try {
  318. return userInfoMapper.findDepartLeader(userId);
  319. } catch (Exception e) {
  320. logger.error("findDepartLeader", e);
  321. }
  322. return null;
  323. }
  324. @Override
  325. public List<String> findUserByRoleName(String roleName) {
  326. logger.info("findUserByRoleName");
  327. try {
  328. return userInfoMapper.findUserByRoleName(roleName);
  329. } catch (Exception e) {
  330. logger.error("findUserByRoleName", e);
  331. }
  332. return null;
  333. }
  334. public class LoginException extends Exception {
  335. public LoginException(String message) {
  336. super(message);
  337. }
  338. }
  339. @Override
  340. public UserInfo loginWechat(String code) {
  341. try {
  342. final String APP_ID = PropertiesFileLoader.getProperties("weixinappid");
  343. final String APP_SECRET = PropertiesFileLoader.getProperties("weixinsecret");
  344. String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID + "&secret=" + APP_SECRET + "&code=" + code
  345. + "&grant_type=authorization_code";
  346. JSONObject data = WeixinUtil.loadJSON(accessTokenUrl);
  347. logger.debug("微信授权获取access_token:\n" + data.toString(4));
  348. String openId = data.getString("openid");
  349. String access_token = data.getString("access_token");
  350. String userDataUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openId;
  351. JSONObject userData = WeixinUtil.loadJSON(userDataUrl);
  352. logger.debug("微信授权获取用户信息:\n" + userData.toString(4));
  353. UserInfo userInfo = new UserInfo();
  354. userInfo.setOpenId(openId);
  355. userInfo = getUserInfo(userInfo);
  356. if (userInfo != null) {
  357. return userInfo;
  358. }
  359. userInfo = new UserInfo();
  360. userInfo.setOpenId(openId);
  361. String nickname = userData.getString("nickname");
  362. userInfo.setNickname(nickname);
  363. userInfo.setUsername(nickname);
  364. try {
  365. String country = userData.getString("country");
  366. userInfo.setCountry(country);
  367. } catch (JSONException ignored) {
  368. }
  369. try {
  370. String province = userData.getString("province");
  371. userInfo.setProvince(province);
  372. } catch (JSONException ignored) {
  373. }
  374. try {
  375. String city = userData.getString("city");
  376. userInfo.setCity(city);
  377. } catch (JSONException ignored) {
  378. }
  379. int sex = 1;
  380. try {
  381. sex = userData.getInt("sex");
  382. } catch (JSONException ignored) {
  383. }
  384. userInfo.setSex(sex == 1 ? "男" : "女");
  385. String headimgurl = null;
  386. try {
  387. headimgurl = userData.getString("headimgurl");
  388. } catch (JSONException ignored) {
  389. }
  390. userInfo.setIcon(saveAvatar(headimgurl));
  391. if (createUserInfo(userInfo)) {
  392. return userInfo;
  393. }
  394. } catch (Exception e) {
  395. logger.error("loginWechat", e);
  396. }
  397. return null;
  398. }
  399. private String saveAvatar(String url) {
  400. String path;
  401. HttpURLConnection httpUrl = null;
  402. URL iconUrl = null;
  403. try {
  404. iconUrl = new URL(url);
  405. httpUrl = (HttpURLConnection) iconUrl.openConnection();
  406. httpUrl.connect();
  407. Random random = new Random();
  408. StringBuilder randomCode = new StringBuilder();
  409. for (int i = 0; i < 8; i++) {
  410. randomCode.append(Integer.toString(random.nextInt(36), 36));
  411. }
  412. String uploadPath = String.format("images/%s-%s.jpg", new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss").format(new Date()), randomCode);
  413. path = ossFileService.upload(httpUrl.getInputStream(), uploadPath);
  414. } catch (IOException e) {
  415. path = "https://microball.oss-cn-hangzhou.aliyuncs.com/huanbaojia/icon_morentouxiang.png";
  416. e.printStackTrace();
  417. } finally {
  418. if (httpUrl != null) {
  419. httpUrl.disconnect();
  420. }
  421. }
  422. return path;
  423. }
  424. /**
  425. * <p>支付宝支付成功回调接口。充值</p>
  426. *
  427. * @param tradeNo
  428. * @param tradeStatus
  429. */
  430. @Override
  431. public void alipaySuccess(String tradeNo, String tradeStatus) {
  432. logger.info("alipaySuccess:支付宝支付成功回调接口 tradeNo:" + tradeNo + ", tradeStatus:" + tradeStatus);
  433. try {
  434. AlipayTemp alipayTemp = new AlipayTemp();
  435. alipayTemp.setOutTradeNo(tradeNo);
  436. alipayTemp = alipayTempMapper.queryAlipayTemp(alipayTemp);
  437. if (alipayTemp != null) {
  438. if (!AppConstant.Aliapi.TRADE_SUCCESS.equals(alipayTemp.getTradeStatus())) {
  439. UserInfo userInfo = this.getUserInfoById(alipayTemp.getOrderId());
  440. int cashPledge = userInfo.getCashPledge();
  441. UserInfo updateUser = new UserInfo();
  442. updateUser.setId(userInfo.getId());
  443. updateUser.setCashPledge(cashPledge + alipayTemp.getTotalAmount().intValue());
  444. if (userInfo.getApproveStep() == 3) {
  445. //如果是交押金状态,更新为完成。
  446. updateUser.setApproveStep(4);
  447. }
  448. this.updateUserInfo(updateUser);
  449. alipayTemp.setTradeStatus(tradeStatus);
  450. alipayTempMapper.updateByPrimaryKeySelective(alipayTemp);
  451. }
  452. }
  453. } catch (Exception e) {
  454. logger.error("alipaySuccess:支付宝支付成功回调接口异常 tradeNo:" + tradeNo + ", tradeStatus:" + tradeStatus, e);
  455. }
  456. }
  457. }