UserService.java 30 KB

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