| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692 |
- package com.izouma.awesomeadmin.service.impl;
- import cn.binarywang.wx.miniapp.api.WxMaService;
- import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
- import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
- import com.izouma.awesomeadmin.constant.AppConstant;
- import com.izouma.awesomeadmin.dao.*;
- import com.izouma.awesomeadmin.dto.Page;
- import com.izouma.awesomeadmin.dto.Result;
- import com.izouma.awesomeadmin.model.AlipayTemp;
- import com.izouma.awesomeadmin.model.RecommenderLog;
- import com.izouma.awesomeadmin.model.UserInfo;
- import com.izouma.awesomeadmin.service.OSSFileService;
- import com.izouma.awesomeadmin.service.UserInfoService;
- import com.izouma.awesomeadmin.util.MD5Util;
- import com.izouma.awesomeadmin.util.PropertiesFileLoader;
- import com.izouma.weixin.util.WeixinUtil;
- import io.jsonwebtoken.Claims;
- import io.jsonwebtoken.Jwt;
- import io.jsonwebtoken.Jwts;
- import io.jsonwebtoken.security.Keys;
- import io.rong.RongCloud;
- import io.rong.models.SMSVerifyCodeResult;
- import org.apache.commons.lang.RandomStringUtils;
- import org.apache.commons.lang.StringUtils;
- import org.apache.log4j.Logger;
- import org.json.JSONException;
- import org.json.JSONObject;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Lazy;
- import org.springframework.stereotype.Service;
- import javax.crypto.SecretKey;
- import java.io.IOException;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.text.SimpleDateFormat;
- import java.util.*;
- /**
- * user_info service接口实现类
- * Tue Apr 17 10:32:49 CST 2018 Suo Chen Cheng
- */
- @Service
- public class UserInfoServiceImpl implements UserInfoService {
- private static Logger logger = Logger.getLogger(UserInfoServiceImpl.class);
- private RongCloud rongCloud = RongCloud.getInstance(PropertiesFileLoader.getProperties("rongyunappkey"), PropertiesFileLoader.getProperties("rongyunappsecret"));
- @Autowired
- private UserInfoMapper userInfoMapper;
- @Autowired
- private SysRoleMapper sysRoleMapper;
- @Autowired
- private DepartInfoMapper departInfoMapper;
- @Autowired
- private OSSFileService ossFileService;
- @Autowired
- private AlipayTempMapper alipayTempMapper;
- @Autowired
- private RecommenderLogMapper recommenderLogMapper;
- @Autowired
- @Lazy
- private WxMaService wxMaService;
- @Override
- public List<UserInfo> getUserInfoList(UserInfo record) {
- logger.info("getUserInfoList");
- try {
- return userInfoMapper.queryAllUserInfo(record);
- } catch (Exception e) {
- logger.error("getUserInfoList", e);
- }
- return null;
- }
- @Override
- public List<UserInfo> getUserInfoByPage(Page page, UserInfo record) {
- logger.info("getUserInfoByPage");
- try {
- Map<String, Object> parameter = new HashMap<String, Object>();
- parameter.put("record", record);
- parameter.put(AppConstant.PAGE, page);
- return userInfoMapper.queryUserInfosByPage(parameter);
- } catch (Exception e) {
- logger.error("getUserInfoByPage", e);
- }
- return null;
- }
- @Override
- public UserInfo getUserInfoById(String id) {
- logger.info("getUserInfoById");
- try {
- return userInfoMapper.selectByPrimaryKey(Integer.valueOf(id));
- } catch (Exception e) {
- logger.error("getUserInfoById", e);
- }
- return null;
- }
- @Override
- public UserInfo getUserInfo(UserInfo record) {
- logger.info("getUserInfo");
- try {
- return userInfoMapper.queryUserInfo(record);
- } catch (Exception e) {
- logger.error("getUserInfo", e);
- }
- return null;
- }
- @Override
- public UserInfo getSingleUserInfo(UserInfo record) {
- logger.info("getSingleUserInfo");
- try {
- return userInfoMapper.querySingleUserInfo(record);
- } catch (Exception e) {
- logger.error("getSingleUserInfo", e);
- }
- return null;
- }
- @Override
- public boolean createUserInfo(UserInfo record) {
- logger.info("createUserInfo");
- try {
- if (StringUtils.isNotEmpty(record.getPhone())) {//检测是否有推荐用户,并更新推荐人
- RecommenderLog recommenderLog = new RecommenderLog();
- recommenderLog.setTelephone(record.getPhone());
- recommenderLog = recommenderLogMapper.queryRecommenderLog(recommenderLog);
- if (recommenderLog != null) {
- record.setRecommender(recommenderLog.getUserId());
- }
- }
- if (StringUtils.isNotEmpty(record.getPassword())) {
- record.setPassword(MD5Util.getMD5(record.getPassword()));
- }
- int updates = userInfoMapper.insertSelective(record);
- if (updateUserRolesAndDeparts(record, updates)) return true;
- } catch (Exception e) {
- logger.error("createUserInfo", e);
- }
- return false;
- }
- // /**
- // * 用户注册赠送余额
- // *
- // * @param record
- // */
- // private void songMoney(UserInfo record) {
- //
- // try {
- //
- // String registerSong = systemVariableService.get("registerSong");
- // if (StringUtils.isNotEmpty(registerSong)) {
- //
- // int song = Integer.valueOf(registerSong);
- // if (song > 0) {
- // MemberCoin memberCoin = new MemberCoin();
- // memberCoin.setMoney(BigDecimal.valueOf(song));
- // memberCoin.setUserId(record.getId());
- // double money = memberCoin.getMoney().doubleValue();
- //
- //
- // int userId = Integer.valueOf(memberCoin.getUserId());
- // UserInfo userInfo = userInfoMapper.selectByPrimaryKey(record.getId());
- //
- // UserInfo updateUser = new UserInfo();
- // updateUser.setId(userId);
- //
- //
- // double balance = userInfo.getMoneyCoin();
- // double moneyCoin = balance + money;
- //
- // memberCoin.setCreateUser("管理员");
- // memberCoin.setBalance(BigDecimal.valueOf(moneyCoin));
- // memberCoin.setTypeFlag(AppConstant.CoinType.SONG);
- // memberCoin.setRemark("新用户注册,后台赠送:" + money + "余额");
- // memberCoinMapper.insertSelective(memberCoin);
- //
- // updateUser.setMoneyCoin(moneyCoin);
- // this.updateUserInfo(updateUser);
- // }
- // }
- //
- // } catch (Exception e) {
- // logger.error("新用户注册赠送余额异常", e);
- // }
- //
- //
- // }
- private boolean updateUserRolesAndDeparts(UserInfo record, int updates) {
- if (updates > 0) {
- if (StringUtils.isNotEmpty(record.getDepartId())) {
- departInfoMapper.clearUserDeparts(record.getId());
- departInfoMapper.setUserDeparts(record.getId(), Arrays.asList(record.getDepartId().split(",")));
- }
- if (StringUtils.isNotEmpty(record.getRoleId())) {
- sysRoleMapper.clearUserRoles(record.getId());
- sysRoleMapper.setUserRoles(record.getId(), Arrays.asList(record.getRoleId().split(",")));
- }
- return true;
- }
- return false;
- }
- @Override
- public boolean deleteUserInfo(String id) {
- logger.info("deleteUserInfo");
- try {
- int updates = userInfoMapper.delete(id);
- departInfoMapper.clearUserDeparts(Integer.valueOf(id));
- sysRoleMapper.clearUserRoles(Integer.valueOf(id));
- if (updates > 0) {
- return true;
- }
- } catch (Exception e) {
- logger.error("deleteUserInfo", e);
- }
- return false;
- }
- @Override
- public boolean updateUserInfo(UserInfo record) {
- logger.info("updateUserInfo");
- try {
- int updates = userInfoMapper.updateByPrimaryKeySelective(record);
- if (updateUserRolesAndDeparts(record, updates)) return true;
- } catch (Exception e) {
- logger.error("updateUserInfo", e);
- }
- return false;
- }
- @Override
- public boolean updatePassword(UserInfo record) {
- logger.info("updatePassword");
- try {
- if (record.getId() != null ||
- StringUtils.isNotEmpty(record.getUsername()) ||
- StringUtils.isNotEmpty(record.getPhone()) ||
- StringUtils.isNotEmpty(record.getMail())) {
- if (StringUtils.isNotEmpty(record.getPassword())) {
- record.setPassword(MD5Util.getMD5(record.getPassword()));
- }
- int updates = userInfoMapper.updatePassword(record);
- if (updates > 0) {
- return true;
- }
- }
- } catch (Exception e) {
- logger.error("updatePassword", e);
- }
- return false;
- }
- @Override
- public Result weiren(UserInfo record) {
- logger.info("weiren");
- try {
- if (record.getId() != null) {
- if (record.getLevelId() > 1) {//如果委任非普通会员,可以创建房间
- record.setCreateFlag("Y");
- }
- int updates = userInfoMapper.updateByPrimaryKeySelective(record);
- if (updates > 0) {
- return new Result(true, "委任成功");
- }
- }
- } catch (Exception e) {
- logger.error("weiren", e);
- }
- return new Result(false, "委任失败");
- }
- @Override
- public UserInfo login(String username, String password) {
- logger.info("login");
- try {
- Map<String, Object> map = new HashMap<>();
- map.put("username", username);
- map.put("password", MD5Util.getMD5(password));
- UserInfo result = userInfoMapper.login(map);
- return result;
- } catch (Exception e) {
- logger.error("login", e);
- }
- return null;
- }
- // @Override
- // public UserInfo loginSms(String phone, String code, String sessionId) throws LoginException {
- // logger.info("loginSms");
- //// SMSVerifyCodeResult sMSVerifyCodeResult;
- //// try {
- //// sMSVerifyCodeResult = rongCloud.sms.verifyCode(sessionId, code);
- //// } catch (Exception e) {
- //// e.printStackTrace();
- //// throw new LoginException("验证码错误");
- //// }
- // try {
- // if (code.toLowerCase().equals(sessionId)) {
- // UserInfo userInfo = new UserInfo();
- // userInfo.setPhone(phone);
- // userInfo = getUserInfo(userInfo);
- // if (userInfo == null) {
- // userInfo = new UserInfo();
- // userInfo.setPhone(phone);
- // userInfo.setUsername(phone);
- // userInfo.setNickname(phone);
- // userInfo.setIcon("https://microball.oss-cn-hangzhou.aliyuncs.com/huanbaojia/icon_morentouxiang.png");
- // if (!createUserInfo(userInfo)) {
- // throw new LoginException("登录失败");
- // }
- // }
- // return userInfo;
- // }
- // } catch (Exception e) {
- // e.printStackTrace();
- // throw new LoginException("验证码错误");
- // }
- // throw new LoginException("验证码错误");
- // }
- @Override
- public UserInfo loginSms(String phone, String code, String sessionId) throws LoginException {
- logger.info("loginSms");
- SMSVerifyCodeResult sMSVerifyCodeResult;
- try {
- sMSVerifyCodeResult = rongCloud.sms.verifyCode(sessionId, code);
- } catch (Exception e) {
- e.printStackTrace();
- throw new LoginException("验证码错误");
- }
- if (200 == sMSVerifyCodeResult.getCode()) {
- Boolean success = sMSVerifyCodeResult.getSuccess();
- if (success) {
- UserInfo userInfo = new UserInfo();
- userInfo.setPhone(phone);
- userInfo = getUserInfo(userInfo);
- if (userInfo == null) {
- userInfo = new UserInfo();
- userInfo.setPhone(phone);
- userInfo.setUsername(phone);
- userInfo.setNickname(phone);
- userInfo.setIcon("https://microball.oss-cn-hangzhou.aliyuncs.com/huanbaojia/icon_morentouxiang.png");
- if (!createUserInfo(userInfo)) {
- throw new LoginException("登录失败");
- }
- }
- return userInfo;
- }
- }
- throw new LoginException("验证码错误");
- }
- @Override
- public UserInfo loginAppToken(String token) {
- logger.info("loginAppToken");
- UserInfo userInfo = null;
- try {
- // AppToken appToken = sysAppTokenMapper.getToken(token);
- // if (appToken != null) {
- SecretKey key = Keys.hmacShaKeyFor(Base64.getDecoder().decode(PropertiesFileLoader.getProperties("jwtsecret").getBytes()));
- Jwt jwt = Jwts.parser()
- .setSigningKey(key)
- .parse(token);
- Claims claims = (Claims) jwt.getBody();
- if (claims.getExpiration() != null) {
- if (claims.getExpiration().before(new Date())) {
- return null;
- }
- }
- if (claims.getSubject().equals("guest")) {
- userInfo = new UserInfo();
- } else {
- userInfo = getUserInfoById(claims.getSubject());
- }
- // }
- } catch (Exception e) {
- logger.error("loginAppToken", e);
- }
- return userInfo;
- }
- @Override
- public List<String> findDepartLeader(String userId) {
- logger.info("findDepartLeader");
- try {
- return userInfoMapper.findDepartLeader(userId);
- } catch (Exception e) {
- logger.error("findDepartLeader", e);
- }
- return null;
- }
- @Override
- public List<String> findUserByRoleName(String roleName) {
- logger.info("findUserByRoleName");
- try {
- return userInfoMapper.findUserByRoleName(roleName);
- } catch (Exception e) {
- logger.error("findUserByRoleName", e);
- }
- return null;
- }
- public class LoginException extends Exception {
- public LoginException(String message) {
- super(message);
- }
- }
- @Override
- public UserInfo loginWechat(String code) {
- try {
- final String APP_ID = PropertiesFileLoader.getProperties("weixinappid");
- final String APP_SECRET = PropertiesFileLoader.getProperties("weixinsecret");
- String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID + "&secret=" + APP_SECRET + "&code=" + code
- + "&grant_type=authorization_code";
- JSONObject data = WeixinUtil.loadJSON(accessTokenUrl);
- logger.debug("微信授权获取access_token:\n" + data.toString(4));
- String openId = data.getString("openid");
- String access_token = data.getString("access_token");
- String userDataUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openId;
- JSONObject userData = WeixinUtil.loadJSON(userDataUrl);
- logger.debug("微信授权获取用户信息:\n" + userData.toString(4));
- UserInfo userInfo = new UserInfo();
- userInfo.setOpenId(openId);
- userInfo = getUserInfo(userInfo);
- if (userInfo != null) {
- return userInfo;
- }
- userInfo = new UserInfo();
- userInfo.setOpenId(openId);
- String nickname = userData.getString("nickname");
- userInfo.setNickname(nickname);
- userInfo.setUsername(nickname);
- try {
- String country = userData.getString("country");
- userInfo.setCountry(country);
- } catch (JSONException ignored) {
- }
- try {
- String province = userData.getString("province");
- userInfo.setProvince(province);
- } catch (JSONException ignored) {
- }
- try {
- String city = userData.getString("city");
- userInfo.setCity(city);
- } catch (JSONException ignored) {
- }
- int sex = 1;
- try {
- sex = userData.getInt("sex");
- } catch (JSONException ignored) {
- }
- userInfo.setSex(sex == 1 ? "男" : "女");
- String headimgurl = null;
- try {
- headimgurl = userData.getString("headimgurl");
- } catch (JSONException ignored) {
- }
- userInfo.setIcon(saveAvatar(headimgurl));
- if (createUserInfo(userInfo)) {
- return userInfo;
- }
- } catch (Exception e) {
- logger.error("loginWechat", e);
- }
- return null;
- }
- private String saveAvatar(String url) {
- String path;
- HttpURLConnection httpUrl = null;
- URL iconUrl = null;
- try {
- iconUrl = new URL(url);
- httpUrl = (HttpURLConnection) iconUrl.openConnection();
- httpUrl.connect();
- Random random = new Random();
- StringBuilder randomCode = new StringBuilder();
- for (int i = 0; i < 8; i++) {
- randomCode.append(Integer.toString(random.nextInt(36), 36));
- }
- String uploadPath = String.format("images/%s-%s.jpg", new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss").format(new Date()), randomCode);
- path = ossFileService.upload(httpUrl.getInputStream(), uploadPath);
- } catch (IOException e) {
- path = "https://microball.oss-cn-hangzhou.aliyuncs.com/huanbaojia/icon_morentouxiang.png";
- e.printStackTrace();
- } finally {
- if (httpUrl != null) {
- httpUrl.disconnect();
- }
- }
- return path;
- }
- /**
- * <p>支付宝支付成功回调接口。充值</p>
- *
- * @param tradeNo
- * @param tradeStatus
- */
- @Override
- public void alipaySuccess(String tradeNo, String tradeStatus) {
- logger.info("alipaySuccess:支付宝支付成功回调接口 tradeNo:" + tradeNo + ", tradeStatus:" + tradeStatus);
- try {
- AlipayTemp alipayTemp = new AlipayTemp();
- alipayTemp.setOutTradeNo(tradeNo);
- alipayTemp = alipayTempMapper.queryAlipayTemp(alipayTemp);
- if (alipayTemp != null) {
- if (!AppConstant.Aliapi.TRADE_SUCCESS.equals(alipayTemp.getTradeStatus())) {
- UserInfo userInfo = this.getUserInfoById(alipayTemp.getOrderId());
- int cashPledge = userInfo.getCashPledge();
- UserInfo updateUser = new UserInfo();
- updateUser.setId(userInfo.getId());
- updateUser.setCashPledge(cashPledge + alipayTemp.getTotalAmount().intValue());
- if (userInfo.getApproveStep() == 3) {
- //如果是交押金状态,更新为完成。
- updateUser.setApproveStep(4);
- }
- this.updateUserInfo(updateUser);
- alipayTemp.setTradeStatus(tradeStatus);
- alipayTempMapper.updateByPrimaryKeySelective(alipayTemp);
- }
- }
- } catch (Exception e) {
- logger.error("alipaySuccess:支付宝支付成功回调接口异常 tradeNo:" + tradeNo + ", tradeStatus:" + tradeStatus, e);
- }
- }
- @Override
- public UserInfo loginMiniApp(String code) {
- try {
- WxMaJscode2SessionResult result = wxMaService.jsCode2SessionInfo(code);
- String openId = result.getOpenid();
- String sessionKey = result.getSessionKey();
- UserInfo userInfo = new UserInfo();
- userInfo.setOpenId(openId);
- userInfo = getUserInfo(userInfo);
- if (userInfo != null) {
- userInfo.setSessionKey(sessionKey);
- updateUserInfo(userInfo);
- return userInfo;
- }
- userInfo = new UserInfo();
- userInfo.setUsername(UUID.randomUUID().toString());
- userInfo.setNickname("用户" + RandomStringUtils.randomAlphabetic(6));
- userInfo.setOpenId(openId);
- userInfo.setIcon("https://microball.oss-cn-hangzhou.aliyuncs.com/awesomeAdmin/user.png");
- userInfo.setSessionKey(sessionKey);
- createUserInfo(userInfo);
- return userInfo;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- @Override
- public Result getMiniAppUserInfo(String sessionKey, String rawData, String signature,
- String encryptedData, String iv) {
- // 用户信息校验
- if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
- return new Result(false, "获取用户信息失败");
- }
- // 解密用户信息
- WxMaUserInfo wxUserInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
- UserInfo userInfo = new UserInfo();
- userInfo.setOpenId(wxUserInfo.getOpenId());
- userInfo = getUserInfo(userInfo);
- String avatarUrl = "https://microball.oss-cn-hangzhou.aliyuncs.com/awesomeAdmin/user.png";
- try {
- avatarUrl = saveAvatar(wxUserInfo.getAvatarUrl());
- } catch (Exception e) {
- logger.error("获取头像失败", e);
- }
- if (userInfo == null) {
- userInfo = new UserInfo();
- userInfo.setUsername(UUID.randomUUID().toString());
- userInfo.setNickname(wxUserInfo.getNickName());
- userInfo.setOpenId(wxUserInfo.getOpenId());
- userInfo.setUnionId(wxUserInfo.getUnionId());
- userInfo.setIcon(avatarUrl);
- userInfo.setSex(Integer.valueOf(wxUserInfo.getGender()) == 1 ? "男" : "女");
- userInfo.setCountry(wxUserInfo.getCountry());
- userInfo.setProvince(wxUserInfo.getProvince());
- userInfo.setCity(wxUserInfo.getCity());
- createUserInfo(userInfo);
- } else {
- userInfo.setIcon(avatarUrl);
- userInfo.setNickname(wxUserInfo.getNickName());
- userInfo.setUnionId(wxUserInfo.getUnionId());
- userInfo.setSex(Integer.valueOf(wxUserInfo.getGender()) == 1 ? "男" : "女");
- userInfo.setCountry(wxUserInfo.getCountry());
- userInfo.setProvince(wxUserInfo.getProvince());
- userInfo.setCity(wxUserInfo.getCity());
- updateUserInfo(userInfo);
- }
- if (userInfo != null) {
- return new Result(true, userInfo);
- }
- return new Result(false, "获取用户信息失败");
- }
- }
|