UserService.java 29 KB

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