UserService.java 30 KB

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