소스 검색

:bookmark: 小程序注册时不添加手机号

Twelve615 1 년 전
부모
커밋
bc7b076035

+ 34 - 0
crmeb-common/src/main/java/com/zbkj/common/request/UserBindingPhoneRequest.java

@@ -0,0 +1,34 @@
+package com.zbkj.common.request;
+
+import com.zbkj.common.constants.RegularConstants;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import lombok.EqualsAndHashCode;
+import lombok.experimental.Accessors;
+
+import javax.validation.constraints.NotBlank;
+import javax.validation.constraints.Pattern;
+import java.io.Serializable;
+
+/**
+ * 换绑手机号请求对象
+
+ */
+@Data
+@EqualsAndHashCode(callSuper = false)
+@Accessors(chain = true)
+@ApiModel(value="UserBindingPhoneRequest", description="添加手机号请求对象")
+public class UserBindingPhoneRequest implements Serializable {
+
+    private static final long serialVersionUID=1L;
+
+    @ApiModelProperty(value = "手机号(此处为新手机号)", required = true)
+    @NotBlank(message = "手机号不能为空")
+    @Pattern(regexp = RegularConstants.PHONE_TWO, message = "手机号码格式错误")
+    private String phone;
+
+    @ApiModelProperty(value = "手机号验证码", required = true)
+    @Pattern(regexp = RegularConstants.VALIDATE_CODE_NUM_SIX, message = "验证码格式错误,验证码必须为6位数字")
+    private String captcha;
+}

+ 1 - 0
crmeb-front/src/main/java/com/zbkj/front/config/WebConfig.java

@@ -64,6 +64,7 @@ public class WebConfig implements WebMvcConfigurer {
                 excludePathPatterns("/api/front/login/wechat/public").
                 excludePathPatterns("/api/front/login/wechat/routine").
                 excludePathPatterns("/api/front/login/wechat/register/binding/phone").
+                excludePathPatterns("/api/front/login/wechat/register/binding/openId").
                 excludePathPatterns("/api/front/login/wechat/app/login").
                 excludePathPatterns("/api/front/login/ios/login").
                 excludePathPatterns("/api/front/city/**").

+ 6 - 0
crmeb-front/src/main/java/com/zbkj/front/controller/LoginController.java

@@ -83,6 +83,12 @@ public class LoginController {
         return CommonResult.success(loginService.wechatRegisterBindingPhone(request));
     }
 
+    @ApiOperation(value = "微信注册绑定")
+    @RequestMapping(value = "/wechat/register/binding/openId", method = RequestMethod.POST)
+    public CommonResult<LoginResponse> wechatRegisterBinding(@RequestBody @Validated WxBindingPhoneRequest request) {
+        return CommonResult.success(loginService.wechatRegisterBinding(request));
+    }
+
     @ApiOperation(value = "微信登录App授权登录")
     @RequestMapping(value = "/wechat/app/login", method = RequestMethod.POST)
     public CommonResult<LoginResponse> wechatAppLogin(@RequestBody @Validated RegisterAppWxRequest request) {

+ 19 - 0
crmeb-front/src/main/java/com/zbkj/front/controller/UserController.java

@@ -2,6 +2,7 @@ package com.zbkj.front.controller;
 
 
 import com.zbkj.common.request.PasswordRequest;
+import com.zbkj.common.request.UserBindingPhoneRequest;
 import com.zbkj.common.request.UserBindingPhoneUpdateRequest;
 import com.zbkj.common.request.UserEditInfoRequest;
 import com.zbkj.common.response.UserInfoResponse;
@@ -79,6 +80,24 @@ public class UserController {
         return CommonResult.failed();
     }
 
+    @ApiOperation(value = "添加手机号获取验证码")
+    @RequestMapping(value = "/add/binding/phone/code", method = RequestMethod.POST)
+    public CommonResult<String> addPhoneCode(@RequestBody @Validated UserBindingPhoneRequest request) {
+        if (userService.addPhoneCode(request)) {
+            return CommonResult.success();
+        }
+        return CommonResult.failed();
+    }
+
+    @ApiOperation(value = "添加手机号")
+    @RequestMapping(value = "/add/binding/phone", method = RequestMethod.POST)
+    public CommonResult<String> addPhone(@RequestBody @Validated UserBindingPhoneRequest request) {
+        if (userService.addPhone(request)) {
+            return CommonResult.success();
+        }
+        return CommonResult.failed();
+    }
+
     @ApiOperation(value = "用户注销数据前置")
     @RequestMapping(value = "/logoff/before", method = RequestMethod.GET)
     public CommonResult<UserLogoffBeforeResponse> logoffBefore() {

+ 7 - 0
crmeb-front/src/main/java/com/zbkj/front/service/LoginService.java

@@ -63,6 +63,13 @@ public interface LoginService {
     LoginResponse wechatRegisterBindingPhone(WxBindingPhoneRequest request);
 
     /**
+     * 微信注册绑定
+     * @param request 请求参数
+     * @return 登录信息
+     */
+    LoginResponse wechatRegisterBinding(WxBindingPhoneRequest request);
+
+    /**
      * 获取登录配置
      */
     FrontLoginConfigResponse getLoginConfig();

+ 7 - 0
crmeb-front/src/main/java/com/zbkj/front/service/impl/FrontOrderServiceImpl.java

@@ -8,6 +8,7 @@ import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.github.pagehelper.PageInfo;
+import com.google.common.base.Strings;
 import com.zbkj.common.constants.*;
 import com.zbkj.common.exception.CrmebException;
 import com.zbkj.common.model.cat.Cart;
@@ -318,6 +319,12 @@ public class FrontOrderServiceImpl implements FrontOrderService {
     @Override
     public OrderNoResponse createOrder(CreateOrderRequest orderRequest) {
         User user = userService.getInfo();
+        //if (user ==null) {
+        //    throw new CrmebException("获取用户信息失败无法创建订单");
+        //}
+        //if(Strings.isNullOrEmpty(user.getPhone())){
+        //    throw new CrmebException("请添加手机号");
+        //}
         // 通过缓存获取预下单对象
         String key = OrderConstants.PRE_ORDER_CACHE_PREFIX + orderRequest.getPreOrderNo();
         boolean exists = redisUtil.exists(key);

+ 115 - 0
crmeb-front/src/main/java/com/zbkj/front/service/impl/LoginServiceImpl.java

@@ -6,6 +6,7 @@ import cn.hutool.core.util.StrUtil;
 import cn.hutool.crypto.SecureUtil;
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
+import com.google.common.base.Strings;
 import com.zbkj.common.constants.*;
 import com.zbkj.common.exception.CrmebException;
 import com.zbkj.common.model.user.User;
@@ -20,6 +21,7 @@ import com.zbkj.common.vo.WeChatMiniAuthorizeVo;
 import com.zbkj.common.vo.WeChatOauthToken;
 import com.zbkj.front.service.LoginService;
 import com.zbkj.service.service.*;
+import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang3.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -38,6 +40,7 @@ import java.util.concurrent.TimeUnit;
  * 移动端登录服务类
  */
 @Service
+@Slf4j
 public class LoginServiceImpl implements LoginService {
 
     private static final Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);
@@ -222,6 +225,118 @@ public class LoginServiceImpl implements LoginService {
         return loginResponse;
     }
 
+    @Override
+    public LoginResponse wechatRegisterBinding(WxBindingPhoneRequest request) {
+        log.debug("注册绑定canshu:{}",request);
+        // 检验
+        WeChatMiniAuthorizeVo response = wechatService.miniAuthCode(request.getCode());
+/*        if (response == null || Strings.isNullOrEmpty(response.getOpenId())) {
+            log.debug("获取OpenId失败");
+            throw new CrmebException("获取OpenId失败");
+        }*/
+        log.debug("注册绑定获取的微信数据:{}",response);
+
+        // 进入创建用户绑定手机号流程
+        String value = redisUtil.get(request.getKey());
+        if (StrUtil.isBlank(value)) {
+            throw new CrmebException("用户缓存已过期,请清除缓存重新登录");
+        }
+        RegisterThirdUserRequest registerThirdUserRequest = JSONObject.parseObject(value, RegisterThirdUserRequest.class);
+        log.debug("redis中的数据:{}",registerThirdUserRequest);
+        if (!request.getType().equals(registerThirdUserRequest.getType())) {
+            throw new CrmebException("用户的类型与缓存中的类型不符");
+        }
+
+/*        if (!response.getOpenId().equals(registerThirdUserRequest.getOpenId())) {
+            log.debug("判断openId:“{}”不等与“{}”",response.getOpenId(),registerThirdUserRequest.getOpenId());
+            throw new CrmebException("登陆失败OpenId不一致");
+        }*/
+
+
+        boolean isNew = true;
+        User user = userService.getByAccount(registerThirdUserRequest.getOpenId());
+        // 查询是否用对应得token
+        Integer userTokenType = getUserTokenType(request.getType());
+        if (ObjectUtil.isNotNull(user)) {// 历史用户校验
+            if (request.getType().equals(UserConstants.REGISTER_TYPE_WECHAT) && user.getIsWechatPublic()) {
+                throw new CrmebException("该账号已绑定微信公众号");
+            }
+            if (request.getType().equals(UserConstants.REGISTER_TYPE_ROUTINE) && user.getIsWechatRoutine()) {
+                throw new CrmebException("该账号已绑定微信小程序");
+            }
+            if (request.getType().equals(UserConstants.REGISTER_TYPE_ANDROID_WX) && user.getIsWechatAndroid()) {
+                throw new CrmebException("该账号已绑定微信Android");
+            }
+            if (request.getType().equals(UserConstants.REGISTER_TYPE_IOS_WX) && user.getIsWechatIos()) {
+                throw new CrmebException("该账号已绑定微信IOS");
+            }
+            UserToken userToken = userTokenService.getTokenByUserId(user.getId(), userTokenType);
+            if (ObjectUtil.isNotNull(userToken)) {
+                throw new CrmebException("该账号已被注册");
+            }
+            isNew = false;
+        } else {
+            user = new User();
+            user.setRegisterType(registerThirdUserRequest.getType());
+            // 这里手机号是空的
+            user.setPhone(request.getPhone());
+            user.setAccount(registerThirdUserRequest.getOpenId()); // account数据库由32位改成128位了,因为openId长度是128
+            user.setSpreadUid(0);
+            user.setIsEnterpriseUser(1);
+            // 数据中密码长度由原来的32位改成 256,因为openId长度是128,生成后的密码可能比128长
+            user.setPwd(CommonUtil.createPwd(registerThirdUserRequest.getOpenId()));
+            user.setNickname(randomChar(4));
+            user.setAvatar(systemConfigService.getValueByKey(SysConfigConstants.USER_DEFAULT_AVATAR_CONFIG_KEY));
+            user.setSex(0);
+            user.setIsEnterpriseUser(1);
+            user.setAddress("");
+        }
+        switch (request.getType()) {
+            case UserConstants.REGISTER_TYPE_WECHAT:
+                user.setIsWechatPublic(true);
+                break;
+            case UserConstants.REGISTER_TYPE_ROUTINE:
+                user.setIsWechatRoutine(true);
+                break;
+            case UserConstants.REGISTER_TYPE_IOS_WX:
+                user.setIsWechatIos(true);
+                break;
+            case UserConstants.REGISTER_TYPE_ANDROID_WX:
+                user.setIsWechatAndroid(true);
+                break;
+        }
+        user.setLastLoginTime(CrmebDateUtil.nowDateTime());
+        User finalUser = user;
+        boolean finalIsNew = isNew;
+        Boolean execute = transactionTemplate.execute(e -> {
+            Integer spreadPid = Optional.ofNullable(registerThirdUserRequest.getSpreadPid()).orElse(0);
+            if (finalIsNew) {// 新用户
+                // 分销绑定
+                if (spreadPid > 0 && userService.checkBingSpread(finalUser, registerThirdUserRequest.getSpreadPid(), "new")) {
+                    finalUser.setSpreadUid(registerThirdUserRequest.getSpreadPid());
+                    finalUser.setSpreadTime(CrmebDateUtil.nowDateTime());
+                    userService.updateSpreadCountByUid(registerThirdUserRequest.getSpreadPid(), Constants.OPERATION_TYPE_ADD);
+                }
+                userService.save(finalUser);
+            } else {
+                userService.updateById(finalUser);
+                if (finalUser.getSpreadUid().equals(0) && spreadPid > 0) {
+                    // 绑定推广关系
+                    bindSpread(finalUser, spreadPid);
+                }
+            }
+            userTokenService.bind(registerThirdUserRequest.getOpenId(), userTokenType, finalUser.getId());
+            return Boolean.TRUE;
+        });
+        if (!execute) {
+            log.error(StrUtil.format("微信用户注册生成失败,openid = {}, key = {}", registerThirdUserRequest.getOpenId(), request.getKey()));
+            throw new CrmebException(StrUtil.format("微信用户注册生成失败,openid = {}, key = {}", registerThirdUserRequest.getOpenId(), request.getKey()));
+        }
+        LoginResponse loginResponse = getLoginResponse(finalUser);
+        log.debug("返回数据:{}", loginResponse);
+        return loginResponse;
+    }
+
     /**
      * 微信注册绑定手机号
      *

+ 7 - 0
crmeb-front/src/main/java/com/zbkj/front/service/impl/SeckillServiceImpl.java

@@ -7,6 +7,7 @@ import cn.hutool.core.util.ObjectUtil;
 import cn.hutool.core.util.StrUtil;
 import com.alibaba.fastjson.JSON;
 import com.github.pagehelper.PageInfo;
+import com.google.common.base.Strings;
 import com.zbkj.common.constants.*;
 import com.zbkj.common.exception.CrmebException;
 import com.zbkj.common.model.merchant.Merchant;
@@ -676,6 +677,12 @@ public class SeckillServiceImpl implements SeckillService {
      */
     @Override
     public OrderNoResponse createOrder(CreateOrderRequest orderRequest, PreOrderInfoVo orderInfoVo, User user) {
+        //if (user ==null) {
+        //    throw new CrmebException("获取用户信息失败无法创建订单");
+        //}
+        //if(Strings.isNullOrEmpty(user.getPhone())){
+        //    throw new CrmebException("请添加手机号");
+        //}
         UserAddress userAddress = null;
         OrderMerchantRequest orderMerchantRequest = orderRequest.getOrderMerchantRequestList().get(0);
         if (orderMerchantRequest.getShippingType().equals(OrderConstants.ORDER_SHIPPING_TYPE_EXPRESS)) {

+ 1 - 1
crmeb-front/src/main/resources/application-dev.yml

@@ -17,7 +17,7 @@ crmeb:
 server:
   port: 8012
   servlet:
-    context-path: /guicai         # 访问path
+    context-path: /         # 访问path
   tomcat:
     uri-encoding: UTF-8     # 默认编码格式
     max-threads: 1000       # 最大线程数量 默认200

+ 21 - 0
crmeb-service/src/main/java/com/zbkj/service/service/UserService.java

@@ -110,6 +110,20 @@ public interface UserService extends IService<User> {
     Boolean updatePhone(UserBindingPhoneUpdateRequest request);
 
     /**
+     * 添加手机号获取验证码
+     *
+     * @param request 请求参数
+     */
+    Boolean addPhoneCode(UserBindingPhoneRequest request);
+
+    /**
+     * 添加手机号
+     *
+     * @param request 请求参数
+     */
+    Boolean addPhone(UserBindingPhoneRequest request);
+
+    /**
      * 平台端用户分页列表
      *
      * @param request          查询参数
@@ -331,4 +345,11 @@ public interface UserService extends IService<User> {
      * @return
      */
     List<Integer> getParentId(Integer userId);
+
+    /**
+     * 通过账号获取用户
+     * @param openId
+     * @return
+     */
+    User getByAccount(String openId);
 }

+ 43 - 0
crmeb-service/src/main/java/com/zbkj/service/service/impl/UserServiceImpl.java

@@ -388,6 +388,40 @@ public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserS
     }
 
     /**
+     * 添加手机号获取验证码
+     *
+     * @param request 请求参数
+     *                captcha 为用户原手机号验证码
+     */
+    @Override
+    public Boolean addPhoneCode(UserBindingPhoneRequest request) {
+        User tempUser = getByPhone(request.getPhone());
+        if (ObjectUtil.isNotNull(tempUser)) {
+            throw new CrmebException("手机号已被占用");
+        }
+        return smsService.sendCommonCode(request.getPhone());
+    }
+
+    /**
+     * 添加手机号
+     *
+     * @param request 请求参数
+     */
+    @Override
+    public Boolean addPhone(UserBindingPhoneRequest request) {
+        checkValidateCode(request.getPhone(), request.getCaptcha());
+        User tempUser = getByPhone(request.getPhone());
+        if (ObjectUtil.isNotNull(tempUser)) {
+            throw new CrmebException("手机号已被占用");
+        }
+        User user = getInfo();
+        LambdaUpdateWrapper<User> wrapper = Wrappers.lambdaUpdate();
+        wrapper.set(User::getPhone, request.getPhone());
+        wrapper.eq(User::getId, user.getId());
+        return update(wrapper);
+    }
+
+    /**
      * 分页显示用户表
      *
      * @param request          搜索条件
@@ -1313,6 +1347,15 @@ public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserS
         return dao.getParentId(userId);
     }
 
+    @Override
+    public User getByAccount(String openId) {
+        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
+        lqw.eq(User::getAccount, openId);
+        lqw.eq(User::getIsLogoff, 0);
+        lqw.last(" limit 1");
+        return dao.selectOne(lqw);
+    }
+
     /**
      * 批量清除用户推广人
      *