UserService.java 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. package com.izouma.nineth.service;
  2. import cn.binarywang.wx.miniapp.api.WxMaService;
  3. import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
  4. import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
  5. import com.alibaba.fastjson.JSON;
  6. import com.alibaba.fastjson.serializer.SerializerFeature;
  7. import com.huifu.adapay.core.exception.BaseAdaPayException;
  8. import com.huifu.adapay.model.AdapayCommon;
  9. import com.huifu.adapay.model.SettleAccount;
  10. import com.izouma.nineth.config.AdapayProperties;
  11. import com.izouma.nineth.config.Constants;
  12. import com.izouma.nineth.domain.Follow;
  13. import com.izouma.nineth.domain.IdentityAuth;
  14. import com.izouma.nineth.domain.Invite;
  15. import com.izouma.nineth.domain.User;
  16. import com.izouma.nineth.dto.*;
  17. import com.izouma.nineth.enums.AuthStatus;
  18. import com.izouma.nineth.enums.AuthorityName;
  19. import com.izouma.nineth.exception.BusinessException;
  20. import com.izouma.nineth.repo.*;
  21. import com.izouma.nineth.security.Authority;
  22. import com.izouma.nineth.security.JwtTokenUtil;
  23. import com.izouma.nineth.security.JwtUserFactory;
  24. import com.izouma.nineth.service.sms.SmsService;
  25. import com.izouma.nineth.service.storage.StorageService;
  26. import com.izouma.nineth.utils.BankUtils;
  27. import com.izouma.nineth.utils.JpaUtils;
  28. import com.izouma.nineth.utils.ObjUtils;
  29. import com.izouma.nineth.utils.SecurityUtils;
  30. import lombok.AllArgsConstructor;
  31. import lombok.extern.slf4j.Slf4j;
  32. import me.chanjar.weixin.common.error.WxErrorException;
  33. import me.chanjar.weixin.mp.api.WxMpService;
  34. import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
  35. import me.chanjar.weixin.mp.bean.result.WxMpUser;
  36. import org.apache.commons.collections.MapUtils;
  37. import org.apache.commons.lang3.RandomStringUtils;
  38. import org.apache.commons.lang3.StringUtils;
  39. import org.springframework.beans.BeanUtils;
  40. import org.springframework.cache.annotation.CacheEvict;
  41. import org.springframework.data.domain.Page;
  42. import org.springframework.data.domain.PageImpl;
  43. import org.springframework.data.jpa.domain.Specification;
  44. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  45. import org.springframework.stereotype.Service;
  46. import javax.persistence.criteria.Predicate;
  47. import java.text.SimpleDateFormat;
  48. import java.util.*;
  49. import java.util.regex.Pattern;
  50. import java.util.stream.Collectors;
  51. @Service
  52. @Slf4j
  53. @AllArgsConstructor
  54. public class UserService {
  55. private UserRepo userRepo;
  56. private WxMaService wxMaService;
  57. private WxMpService wxMpService;
  58. private SmsService smsService;
  59. private StorageService storageService;
  60. private JwtTokenUtil jwtTokenUtil;
  61. private CaptchaService captchaService;
  62. private FollowService followService;
  63. private FollowRepo followRepo;
  64. private IdentityAuthRepo identityAuthRepo;
  65. private SysConfigService sysConfigService;
  66. private CollectionService collectionService;
  67. private AdapayService adapayService;
  68. private UserBankCardRepo userBankCardRepo;
  69. private CacheService cacheService;
  70. private InviteRepo inviteRepo;
  71. private AdapayProperties adapayProperties;
  72. @CacheEvict(value = "user", key = "#user.username")
  73. public User update(User user) {
  74. User orig = userRepo.findById(user.getId()).orElseThrow(new BusinessException("无记录"));
  75. ObjUtils.merge(orig, user);
  76. orig = userRepo.save(orig);
  77. userRepo.updateAssetMinter(orig.getId());
  78. userRepo.updateAssetOwner(orig.getId());
  79. userRepo.updateCollectionMinter(orig.getId());
  80. userRepo.updateCollectionOwner(orig.getId());
  81. userRepo.updateOrderMinter(orig.getId());
  82. userRepo.updateHistoryFromUser(orig.getId());
  83. userRepo.updateHistoryToUser(orig.getId());
  84. cacheService.clearCollection();
  85. return orig;
  86. }
  87. @CacheEvict(value = "user", allEntries = true)
  88. public void clearCache() {
  89. }
  90. public Page<User> all(PageQuery pageQuery) {
  91. Specification<User> specification = JpaUtils.toSpecification(pageQuery, User.class);
  92. specification = specification.and((Specification<User>) (root, criteriaQuery, criteriaBuilder) -> {
  93. List<Predicate> and = new ArrayList<>();
  94. and.add(criteriaBuilder.equal(root.get("del"), false));
  95. if (!pageQuery.getQuery().containsKey("admin")) {
  96. and.add(criteriaBuilder.equal(root.get("admin"), false));
  97. }
  98. if (pageQuery.getQuery().containsKey("hasRole")) {
  99. String roleName = (String) pageQuery.getQuery().get("hasRole");
  100. and.add(criteriaBuilder
  101. .isMember(Authority.get(AuthorityName.valueOf(roleName)), root.get("authorities")));
  102. }
  103. return criteriaBuilder.and(and.toArray(new Predicate[0]));
  104. });
  105. return userRepo.findAll(specification, JpaUtils.toPageRequest(pageQuery));
  106. }
  107. public User create(UserRegister userRegister) {
  108. if (StringUtils.isNoneEmpty(userRegister.getPhone()) && userRepo.findByPhoneAndDelFalse(userRegister.getPhone())
  109. .orElse(null) != null) {
  110. throw new BusinessException("该手机号已注册");
  111. }
  112. User user = new User();
  113. BeanUtils.copyProperties(userRegister, user);
  114. user.setShareRatio(sysConfigService.getBigDecimal("share_ratio"));
  115. user.setAuthStatus(AuthStatus.NOT_AUTH);
  116. if (StringUtils.isNotBlank(userRegister.getPassword())) {
  117. user.setPassword(new BCryptPasswordEncoder().encode(userRegister.getPassword()));
  118. }
  119. return userRepo.save(user);
  120. }
  121. public User phoneRegister(String phone, String code, String password) {
  122. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  123. User user = create(UserRegister.builder()
  124. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  125. .username(name)
  126. .nickname(name)
  127. .password(password)
  128. .avatar(Constants.DEFAULT_AVATAR)
  129. .phone(phone)
  130. .build());
  131. return user;
  132. }
  133. public User phoneRegister(String phone, String code, String password, String inviteCode, Long invitor) {
  134. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  135. Invite invite = null;
  136. if (StringUtils.isNotBlank(inviteCode)) {
  137. invite = inviteRepo.findFirstByCode(inviteCode).orElse(null);
  138. }
  139. smsService.verify(phone, code);
  140. User user = create(UserRegister.builder()
  141. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  142. .username(name)
  143. .nickname(name)
  144. .password(password)
  145. .avatar(Constants.DEFAULT_AVATAR)
  146. .phone(phone)
  147. .invitorPhone(Optional.ofNullable(invite).map(Invite::getPhone).orElse(null))
  148. .invitorName(Optional.ofNullable(invite).map(Invite::getName).orElse(null))
  149. .inviteCode(Optional.ofNullable(invite).map(Invite::getCode).orElse(null))
  150. .invitor(invitor)
  151. .build());
  152. if (invite != null) {
  153. inviteRepo.increaseNum(invite.getId());
  154. }
  155. return user;
  156. }
  157. public void del(Long id) {
  158. User user = userRepo.findById(id).orElseThrow(new BusinessException("用户不存在"));
  159. user.setDel(true);
  160. if (StringUtils.isNoneEmpty(user.getOpenId())) {
  161. user.setOpenId(user.getOpenId() + "###" + RandomStringUtils.randomAlphabetic(8));
  162. }
  163. if (StringUtils.isNoneEmpty(user.getPhone())) {
  164. user.setPhone(user.getPhone() + "###" + RandomStringUtils.randomAlphabetic(8));
  165. }
  166. userRepo.save(user);
  167. }
  168. public User loginByPhone(String phone, String code) {
  169. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("该手机未注册"));
  170. smsService.verify(phone, code);
  171. if (user == null) {
  172. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  173. user = create(UserRegister.builder()
  174. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  175. .username(name)
  176. .nickname(name)
  177. .avatar(Constants.DEFAULT_AVATAR)
  178. .phone(phone)
  179. .build());
  180. }
  181. return user;
  182. }
  183. public User loginByPhonePwd(String phone, String password) {
  184. if (StringUtils.isEmpty(phone)) {
  185. throw new BusinessException("手机号错误");
  186. }
  187. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("账号或密码错误"));
  188. if (StringUtils.isEmpty(user.getPassword())) {
  189. throw new BusinessException("账号或密码错误");
  190. }
  191. if (StringUtils.isNoneEmpty(user.getPassword()) &&
  192. !new BCryptPasswordEncoder().matches(password, user.getPassword())) {
  193. throw new BusinessException("账号或密码错误");
  194. }
  195. return user;
  196. }
  197. public User loginMp(String code) throws WxErrorException {
  198. WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
  199. WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(accessToken, null);
  200. User user = userRepo.findByOpenIdAndDelFalse(wxMpUser.getOpenId()).orElse(null);
  201. if (user == null) {
  202. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  203. user = User.builder()
  204. .username(name)
  205. .nickname(name)
  206. .avatar(wxMpUser.getHeadImgUrl())
  207. .sex(wxMpUser.getSexDesc())
  208. .country(wxMpUser.getCountry())
  209. .province(wxMpUser.getProvince())
  210. .city(wxMpUser.getCity())
  211. .openId(wxMpUser.getOpenId())
  212. .language(wxMpUser.getLanguage())
  213. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  214. .authStatus(AuthStatus.NOT_AUTH)
  215. .build();
  216. userRepo.save(user);
  217. }
  218. return user;
  219. }
  220. public String code2openId(String code) throws WxErrorException {
  221. WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
  222. return wxMpService.oauth2getUserInfo(accessToken, null).getOpenId();
  223. }
  224. public User loginMa(String code) {
  225. try {
  226. WxMaJscode2SessionResult result = wxMaService.jsCode2SessionInfo(code);
  227. String openId = result.getOpenid();
  228. String sessionKey = result.getSessionKey();
  229. User userInfo = userRepo.findByOpenIdAndDelFalse(openId).orElse(null);
  230. ;
  231. if (userInfo != null) {
  232. return userInfo;
  233. }
  234. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  235. userInfo = User.builder()
  236. .username(name)
  237. .nickname(name)
  238. .openId(openId)
  239. .avatar(Constants.DEFAULT_AVATAR)
  240. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  241. .authStatus(AuthStatus.NOT_AUTH)
  242. .build();
  243. userInfo = userRepo.save(userInfo);
  244. return userInfo;
  245. } catch (WxErrorException e) {
  246. e.printStackTrace();
  247. }
  248. throw new BusinessException("登录失败");
  249. }
  250. public User getMaUserInfo(String sessionKey, String rawData, String signature,
  251. String encryptedData, String iv) {
  252. // 用户信息校验
  253. if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
  254. throw new BusinessException("获取用户信息失败");
  255. }
  256. // 解密用户信息
  257. WxMaUserInfo wxUserInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
  258. User user = userRepo.findByOpenIdAndDelFalse(wxUserInfo.getOpenId()).orElse(null);
  259. String avatarUrl = Constants.DEFAULT_AVATAR;
  260. try {
  261. String path = "image/avatar/" +
  262. new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) +
  263. RandomStringUtils.randomAlphabetic(8) +
  264. ".jpg";
  265. avatarUrl = storageService.uploadFromUrl(wxUserInfo.getAvatarUrl(), path);
  266. } catch (Exception e) {
  267. log.error("获取头像失败", e);
  268. }
  269. if (user == null) {
  270. user = User.builder()
  271. .username(UUID.randomUUID().toString())
  272. .nickname(wxUserInfo.getNickName())
  273. .openId(wxUserInfo.getOpenId())
  274. .avatar(avatarUrl)
  275. .sex(wxUserInfo.getGender())
  276. .country(wxUserInfo.getCountry())
  277. .province(wxUserInfo.getProvince())
  278. .city(wxUserInfo.getCity())
  279. .authorities(Collections.singleton(Authority.builder().name("ROLE_USER").build()))
  280. .build();
  281. user = userRepo.save(user);
  282. } else {
  283. user.setAvatar(avatarUrl);
  284. user.setNickname(wxUserInfo.getNickName());
  285. user.setSex(wxUserInfo.getGender());
  286. user.setCountry(wxUserInfo.getCountry());
  287. user.setProvince(wxUserInfo.getProvince());
  288. user.setCity(wxUserInfo.getCity());
  289. user = userRepo.save(user);
  290. }
  291. return user;
  292. }
  293. public String setPassword(Long userId, String password) {
  294. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  295. user.setPassword(new BCryptPasswordEncoder().encode(password));
  296. user = userRepo.save(user);
  297. return jwtTokenUtil.generateToken(JwtUserFactory.create(user));
  298. }
  299. public String setPassword(Long userId, String code, String password) {
  300. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  301. smsService.verify(user.getPhone(), code);
  302. return setPassword(userId, password);
  303. }
  304. public String forgotPassword(String phone, String password, String code) {
  305. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("手机号未注册"));
  306. smsService.verify(user.getPhone(), code);
  307. return setPassword(user.getId(), password);
  308. }
  309. public void bindPhone(Long userId, String phone) {
  310. User user = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("用户不存在"));
  311. if (StringUtils.isNoneEmpty(user.getPhone())) {
  312. throw new BusinessException("该账号已绑定手机");
  313. }
  314. userRepo.findByPhoneAndDelFalse(phone).ifPresent(user1 -> {
  315. if (!user1.getId().equals(userId)) {
  316. throw new BusinessException("该手机号已绑定其他账号");
  317. }
  318. });
  319. user.setPhone(phone);
  320. userRepo.save(user);
  321. }
  322. public UserDTO toDTO(User user) {
  323. return toDTO(user, true);
  324. }
  325. public UserDTO toDTO(User user, boolean join) {
  326. UserDTO userDTO = new UserDTO();
  327. BeanUtils.copyProperties(user, userDTO);
  328. if (user.getAuthorities() != null) {
  329. userDTO.setAuthorities(new HashSet<>(user.getAuthorities()));
  330. }
  331. if (join) {
  332. if (SecurityUtils.getAuthenticatedUser() != null) {
  333. userDTO.setFollow(followService.isFollow(SecurityUtils.getAuthenticatedUser().getId(), user.getId()));
  334. }
  335. }
  336. return userDTO;
  337. }
  338. public List<UserDTO> toDTO(List<User> users) {
  339. List<Follow> follows = new ArrayList<>();
  340. if (SecurityUtils.getAuthenticatedUser() != null) {
  341. follows.addAll(followRepo.findByUserId(SecurityUtils.getAuthenticatedUser().getId()));
  342. }
  343. return users.stream().parallel().map(user -> {
  344. UserDTO dto = toDTO(user, false);
  345. if (!follows.isEmpty()) {
  346. dto.setFollow(follows.stream().anyMatch(f -> f.getFollowUserId().equals(user.getId())));
  347. }
  348. return dto;
  349. }).collect(Collectors.toList());
  350. }
  351. public Page<UserDTO> toDTO(Page<User> users) {
  352. List<UserDTO> userDTOS = toDTO(users.getContent());
  353. return new PageImpl<>(userDTOS, users.getPageable(), users.getTotalElements());
  354. }
  355. @CacheEvict(value = "user", allEntries = true)
  356. public void setTradeCode(Long userId, String token, String tradeCode) {
  357. String phone = smsService.verifyToken(token);
  358. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  359. if (!StringUtils.equals(phone, user.getPhone())) {
  360. throw new BusinessException("验证码无效");
  361. }
  362. user.setTradeCode(new BCryptPasswordEncoder().encode(tradeCode));
  363. userRepo.save(user);
  364. }
  365. public void verifyTradeCode(Long userId, String tradeCode) {
  366. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  367. if (!new BCryptPasswordEncoder().matches(tradeCode, user.getTradeCode())) {
  368. throw new BusinessException("校验失败");
  369. }
  370. }
  371. public Map<String, Object> searchByPhone(String phone) {
  372. if (AuthStatus.SUCCESS != SecurityUtils.getAuthenticatedUser().getAuthStatus()) {
  373. throw new BusinessException("实名认证后才能赠送");
  374. }
  375. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("用户不存在或未认证"));
  376. if (AuthStatus.SUCCESS != user.getAuthStatus()) {
  377. throw new BusinessException("用户不存在或未认证");
  378. }
  379. String realName = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(
  380. user.getId(), AuthStatus.SUCCESS)
  381. .map(IdentityAuth::getRealName).orElse("").replaceAll(".*(?=.)", "**");
  382. Map<String, Object> map = new HashMap<>();
  383. map.put("id", user.getId());
  384. map.put("avatar", user.getAvatar());
  385. map.put("phone", user.getPhone().replaceAll("(?<=.{3}).*(?=.{4})", "**"));
  386. map.put("realName", realName);
  387. return map;
  388. }
  389. public Map<String, Object> searchByPhoneAdmin(String phoneStr) {
  390. List<String> phone = Arrays.stream(phoneStr.replaceAll("\n", " ")
  391. .replaceAll("\r\n", " ")
  392. .split(" "))
  393. .map(String::trim)
  394. .filter(s -> !StringUtils.isEmpty(s))
  395. .collect(Collectors.toList());
  396. List<User> users = userRepo.findByPhoneInAndDelFalse(phone);
  397. Map<String, Object> map = new HashMap<>();
  398. map.put("users", users);
  399. List<String> notFound = phone.stream().filter(p -> users.stream().noneMatch(u -> p.equals(u.getPhone())))
  400. .collect(Collectors.toList());
  401. map.put("notFound", notFound);
  402. return map;
  403. }
  404. public void addBankCard(Long userId, String bankNo, String phone, String code) throws BaseAdaPayException {
  405. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  406. IdentityAuth identityAuth = identityAuthRepo
  407. .findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(userId, AuthStatus.SUCCESS)
  408. .orElseThrow(new BusinessException("用户未认证"));
  409. if (identityAuth.isOrg()) {
  410. //throw new BusinessException("企业认证用户请绑定对公账户");
  411. }
  412. if (!StringUtils.isBlank(user.getSettleAccountId())) {
  413. throw new BusinessException("此账号已绑定");
  414. }
  415. BankValidate bankValidate = BankUtils.validate(bankNo);
  416. if (!bankValidate.isValidated()) {
  417. throw new BusinessException("暂不支持此卡");
  418. }
  419. if (StringUtils.isEmpty(user.getMemberId())) {
  420. user.setMemberId(adapayService.createMember(userId, user.getPhone(), identityAuth.getRealName(),
  421. identityAuth.getIdNo()));
  422. userRepo.save(user);
  423. }
  424. smsService.verify(phone, code);
  425. String accountId = adapayService.createSettleAccount(user.getMemberId(), identityAuth.getRealName(),
  426. identityAuth.getIdNo(), phone, bankNo);
  427. user.setSettleAccountId(accountId);
  428. userRepo.save(user);
  429. userBankCardRepo.save(UserBankCard.builder()
  430. .bank(bankValidate.getBank())
  431. .bankName(bankValidate.getBankName())
  432. .bankNo(bankNo)
  433. .cardType(bankValidate.getCardType())
  434. .cardTypeDesc(bankValidate.getCardTypeDesc())
  435. .userId(userId)
  436. .phone(phone)
  437. .build());
  438. }
  439. public void removeBankCard(Long userId) throws BaseAdaPayException {
  440. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  441. if (StringUtils.isNotBlank(user.getSettleAccountId()) && StringUtils.isNotBlank(user.getMemberId())) {
  442. adapayService.delSettleAccount(user.getMemberId(), user.getSettleAccountId());
  443. user.setSettleAccountId(null);
  444. userRepo.save(user);
  445. userBankCardRepo.deleteByUserId(userId);
  446. } else {
  447. throw new BusinessException("未绑定");
  448. }
  449. }
  450. public Map<String, Object> batchRegister(String phones, String defaultPassword) {
  451. List<String> exist = new ArrayList<>();
  452. List<String> err = new ArrayList<>();
  453. List<String> success = new ArrayList<>();
  454. Arrays.stream(phones.replaceAll(",", " ")
  455. .replaceAll(",", " ")
  456. .replaceAll("\n", " ")
  457. .replaceAll("\r\n", " ")
  458. .split(" ")).forEach(phone -> {
  459. if (userRepo.findByPhoneAndDelFalse(phone).isPresent()) {
  460. exist.add(phone);
  461. } else {
  462. if (!Pattern.matches("^1[3-9]\\d{9}$", phone)) {
  463. err.add(phone);
  464. } else {
  465. try {
  466. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  467. User user = create(UserRegister.builder()
  468. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  469. .username(name)
  470. .nickname(name)
  471. .password(defaultPassword)
  472. .avatar(Constants.DEFAULT_AVATAR)
  473. .phone(phone)
  474. .build());
  475. success.add(phone);
  476. } catch (Exception e) {
  477. log.error("注册失败", e);
  478. err.add(phone);
  479. }
  480. }
  481. }
  482. });
  483. Map<String, Object> map = new HashMap<>();
  484. map.put("exist", exist);
  485. map.put("error", err);
  486. map.put("success", success);
  487. return map;
  488. }
  489. public void switchAccount() {
  490. switchAccount(adapayProperties.getAppId());
  491. }
  492. public void switchAccount(String appId) {
  493. userRepo.findBySettleAccountIdIsNotNull().parallelStream().forEach(user -> {
  494. try {
  495. IdentityAuth identityAuth = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(user.getId(), AuthStatus.SUCCESS)
  496. .orElseThrow(new BusinessException("用户未认证"));
  497. UserBankCard userBankCard = userBankCardRepo.findByUserId(user.getId()).stream().findAny()
  498. .orElseThrow(new BusinessException("未绑卡"));
  499. createMember(appId, user.getId().toString(), Optional.ofNullable(userBankCard.getPhone())
  500. .orElse(user.getPhone()), identityAuth.getRealName(), identityAuth.getIdNo());
  501. createSettleAccount(appId, user.getId()
  502. .toString(), identityAuth.getRealName(), identityAuth.getIdNo(), Optional.ofNullable(userBankCard.getPhone())
  503. .orElse(user.getPhone()), userBankCard.getBankNo());
  504. userBankCard.setPhone(Optional.ofNullable(userBankCard.getPhone()).orElse(user.getPhone()));
  505. userBankCardRepo.save(userBankCard);
  506. } catch (Exception e) {
  507. try {
  508. adapayService.delSettleAccount(user.getMemberId(), user.getSettleAccountId());
  509. } catch (Exception ex) {
  510. ex.printStackTrace();
  511. }
  512. user.setSettleAccountId(null);
  513. userRepo.save(user);
  514. userBankCardRepo.deleteByUserId(user.getId());
  515. }
  516. });
  517. }
  518. public void createMember(String appId, String memberId, String tel, String realName, String idno) throws BaseAdaPayException {
  519. Map<String, Object> memberParams = new HashMap<>();
  520. memberParams.put("adapay_func_code", "members.realname");
  521. memberParams.put("member_id", memberId);
  522. memberParams.put("app_id", appId);
  523. memberParams.put("tel_no", tel);
  524. memberParams.put("user_name", realName);
  525. memberParams.put("cert_type", "00");
  526. memberParams.put("cert_id", idno);
  527. Map<String, Object> res = AdapayCommon.requestAdapay(memberParams);
  528. log.info("createMember\n{}", JSON.toJSONString(res, SerializerFeature.PrettyFormat));
  529. if (!("succeeded".equals(MapUtils.getString(res, "status"))
  530. || "member_id_exists".equals(MapUtils.getString(res, "error_code")))) {
  531. String errMsg = MapUtils.getString(res, "error_msg");
  532. String errCode = MapUtils.getString(res, "error_code");
  533. throw new BusinessException(errMsg + "(" + errCode + ")");
  534. }
  535. }
  536. public String createSettleAccount(String appId, String memberId, String realName, String idNo, String phone, String bankNo) throws BaseAdaPayException {
  537. Map<String, Object> settleCountParams = new HashMap<>();
  538. Map<String, Object> accountInfo = new HashMap<>();
  539. accountInfo.put("card_id", bankNo);
  540. accountInfo.put("card_name", realName);
  541. accountInfo.put("cert_id", idNo);
  542. accountInfo.put("cert_type", "00");
  543. accountInfo.put("tel_no", phone);
  544. accountInfo.put("bank_acct_type", "2");
  545. settleCountParams.put("member_id", memberId);
  546. settleCountParams.put("app_id", appId);
  547. settleCountParams.put("channel", "bank_account");
  548. settleCountParams.put("account_info", accountInfo);
  549. Map<String, Object> res = SettleAccount.create(settleCountParams);
  550. log.info("createSettleAccount\n{}", JSON.toJSONString(res, SerializerFeature.PrettyFormat));
  551. if (!("succeeded".equals(MapUtils.getString(res, "status"))
  552. || "account_exists".equals(MapUtils.getString(res, "error_code")))) {
  553. String errMsg = MapUtils.getString(res, "error_msg");
  554. String errCode = MapUtils.getString(res, "error_code");
  555. throw new BusinessException(errMsg + "(" + errCode + ")");
  556. }
  557. return MapUtils.getString(res, "id");
  558. }
  559. }