Quellcode durchsuchen

小程序登录,获取手机号码,等接口

lyhzzz vor 2 Jahren
Ursprung
Commit
5075b0e0aa

+ 1 - 0
src/main/java/com/fdkankan/tk/common/FilePath.java

@@ -5,4 +5,5 @@ public class FilePath {
     public static final String LOCAL_QRCODE_PATH = System.getProperty("user.dir")+"/"+"images/%s/%s.jpg";
 
     public static final String OSS_QRCODE_PATH = "take-look/images/%s/%s.jpg";
+    public static final String OSS_IMAGES_PATH = "take-look/images/other/";
 }

+ 9 - 0
src/main/java/com/fdkankan/tk/common/ResultCode.java

@@ -10,6 +10,15 @@ public enum ResultCode {
     ROOM_ING(4004,"房间直播中,请先关闭直播再修改!"),
     USER_NOT_LOGIN(4008,"用户未登录"),
     SCENE_STATUS_ERROR(5001,"房间中场景重算中或封存"),
+    WX_LOGIN_ERROR(6001,"微信登录失败,请重新授权登录"),
+    WX_OPENID_ERROr(6002,"微信登录失败,存在重复openid"),
+    WX_PHONE_ERROR(6003,"微信获取手机号码失败"),
+    UPLOAD_ERROR(7001,"文件上传失败"),
+    UPLOAD_FILE_NO_EXIST(7002,"上传文件不存在"),
+    UPLOAD_FILE_TO_LONG(7003,"文件上传过大"),
+    UPLOAD_FILE_TYPE_ERROR(7005,"文件类型错误"),
+    UPLOAD_FILE_MSG_ERROR(7006,"文件内容错误"),
+
 
     ;
     public int code;

+ 1 - 1
src/main/java/com/fdkankan/tk/config/WebAppConfig.java

@@ -18,7 +18,7 @@ public class WebAppConfig implements WebMvcConfigurer {
 	@Override
 	public void addInterceptors(InterceptorRegistry registry) {
 		registry.addInterceptor(tokenInterceptor).addPathPatterns("/**")
-				.excludePathPatterns("/test/**","/roomList/**","/_inner/**");
+				.excludePathPatterns("/test/**","/roomList/**","/_inner/**","wxApi");
 		WebMvcConfigurer.super.addInterceptors(registry);
 	}
 

+ 0 - 2
src/main/java/com/fdkankan/tk/controller/TestController.java

@@ -17,8 +17,6 @@ import java.io.File;
 @RestController
 public class TestController {
 
-    @Autowired
-    IWxService wxService;
 
     @GetMapping("/test")
     public ResultData test(){

+ 26 - 0
src/main/java/com/fdkankan/tk/controller/UploadController.java

@@ -0,0 +1,26 @@
+package com.fdkankan.tk.controller;
+
+import com.fdkankan.tk.common.FilePath;
+import com.fdkankan.tk.common.ResultData;
+import com.fdkankan.tk.service.impl.UploadService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+
+@RestController
+@RequestMapping("/upload")
+public class UploadController {
+
+    @Autowired
+    UploadService uploadService;
+
+    @PostMapping("/file")
+    public ResultData file(@RequestParam(required = false) MultipartFile file) throws Exception {
+
+        return ResultData.ok( uploadService.uploadFile(file,true,FilePath.OSS_IMAGES_PATH));
+    }
+}

+ 35 - 0
src/main/java/com/fdkankan/tk/controller/WxApiController.java

@@ -0,0 +1,35 @@
+package com.fdkankan.tk.controller;
+
+import com.fdkankan.tk.common.ResultData;
+import com.fdkankan.tk.response.WxUserVo;
+import com.fdkankan.tk.service.IWxService;
+import com.fdkankan.tk.service.IWxUserService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.*;
+
+@RequestMapping("/wxApi")
+@RestController
+public class WxApiController {
+
+    @Autowired
+    IWxUserService wxUserService;
+
+    @GetMapping("/wxLogin")
+    public ResultData wxLogin(@RequestParam(required = false) String code){
+
+        return ResultData.ok(wxUserService.wxLogin(code));
+    }
+
+    @GetMapping("/getPhone")
+    public ResultData getPhone(@RequestParam(required = false) String code){
+        return ResultData.ok(wxUserService.getPhone(code));
+    }
+
+    @PostMapping("/updateUser")
+    public ResultData updateUser(@RequestBody WxUserVo param){
+        wxUserService.updateByVo(param);
+        return ResultData.ok();
+    }
+
+
+}

+ 71 - 0
src/main/java/com/fdkankan/tk/entity/WxUser.java

@@ -0,0 +1,71 @@
+package com.fdkankan.tk.entity;
+
+import com.baomidou.mybatisplus.annotation.TableField;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableLogic;
+import com.baomidou.mybatisplus.annotation.TableName;
+import java.io.Serializable;
+import java.util.Date;
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * <p>
+ * 
+ * </p>
+ *
+ * @author 
+ * @since 2022-12-19
+ */
+@Getter
+@Setter
+@TableName("t_wx_user")
+public class WxUser implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * 微信用户id
+     */
+    @TableId("wx_user_id")
+    private String wxUserId;
+
+    @TableField("openid")
+    private String openid;
+
+    @TableField("unionid")
+    private String unionid;
+
+    @TableField("session_key")
+    private String sessionKey;
+
+    /**
+     * 昵称
+     */
+    @TableField("nick_name")
+    private String nickName;
+
+    /**
+     * 头像链接
+     */
+    @TableField("image_url")
+    private String imageUrl;
+
+    /**
+     * 手机号码
+     */
+    @TableField("phone")
+    private String phone;
+
+    @TableField("tb_status")
+    @TableLogic
+    private Integer tbStatus;
+
+    @TableField("create_time")
+    private Date createTime;
+
+    @TableField("update_time")
+    private Date updateTime;
+
+
+}

+ 1 - 1
src/main/java/com/fdkankan/tk/generate/AutoGenerate.java

@@ -18,7 +18,7 @@ public class AutoGenerate {
         String path =System.getProperty("user.dir") ;
 
         generate(path,"tk", getTables(new String[]{
-                "t_tencent_yun",
+                "t_wx_user",
         }));
 
 //        generate(path,"goods", getTables(new String[]{

+ 13 - 0
src/main/java/com/fdkankan/tk/httpClient/client/WxClient.java

@@ -4,9 +4,11 @@ import com.alibaba.fastjson.JSONObject;
 import com.dtflys.forest.annotation.*;
 import com.fdkankan.tk.httpClient.address.FdkkAddressSource;
 import com.fdkankan.tk.httpClient.request.FdkkLoginRequest;
+import com.fdkankan.tk.httpClient.request.WxGetPhoneParam;
 import com.fdkankan.tk.httpClient.request.WxGetQrCodeParam;
 import com.fdkankan.tk.httpClient.response.FdkkLoginVo;
 import com.fdkankan.tk.httpClient.response.FdkkResponse;
+import com.fdkankan.tk.httpClient.response.WxOpenIdVo;
 import com.fdkankan.tk.request.SceneParam;
 
 /**
@@ -16,6 +18,17 @@ import com.fdkankan.tk.request.SceneParam;
 public interface WxClient {
 
     /**
+     * 获取 getOpenIdUrl
+     */
+    @Get("https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type=authorization_code")
+    WxOpenIdVo getOpenIdUrl(@Query("appid") String app_id, @Query("secret") String app_secret, @Query("code")String code);
+    /**
+     * 获取 getOpenIdUrl
+     */
+    @Post("https://api.weixin.qq.com/wxa/business/getuserphonenumber")
+    JSONObject getPhone(@Query("access_token") String access_token, @JSONBody WxGetPhoneParam param);
+
+    /**
      * 获取 access_token
      */
     @Get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential")

+ 10 - 0
src/main/java/com/fdkankan/tk/httpClient/request/WxGetPhoneParam.java

@@ -0,0 +1,10 @@
+package com.fdkankan.tk.httpClient.request;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+
+@Data
+@AllArgsConstructor
+public class WxGetPhoneParam {
+    private String code;
+}

+ 14 - 0
src/main/java/com/fdkankan/tk/httpClient/response/WxOpenIdVo.java

@@ -0,0 +1,14 @@
+package com.fdkankan.tk.httpClient.response;
+
+import lombok.Data;
+import lombok.ToString;
+
+@Data
+@ToString
+public class WxOpenIdVo {
+    private String openId;
+    private String session_key;
+    private String unionid;
+    private Integer errcode;
+    private String errmsg;
+}

+ 18 - 0
src/main/java/com/fdkankan/tk/mapper/IWxUserMapper.java

@@ -0,0 +1,18 @@
+package com.fdkankan.tk.mapper;
+
+import com.fdkankan.tk.entity.WxUser;
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import org.apache.ibatis.annotations.Mapper;
+
+/**
+ * <p>
+ *  Mapper 接口
+ * </p>
+ *
+ * @author 
+ * @since 2022-12-19
+ */
+@Mapper
+public interface IWxUserMapper extends BaseMapper<WxUser> {
+
+}

+ 40 - 0
src/main/java/com/fdkankan/tk/response/WxUserVo.java

@@ -0,0 +1,40 @@
+package com.fdkankan.tk.response;
+
+import com.baomidou.mybatisplus.annotation.TableField;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableLogic;
+import lombok.Data;
+
+import java.util.Date;
+
+@Data
+public class WxUserVo {
+    /**
+     * 微信用户id
+     */
+    private String wxUserId;
+
+
+    private String sessionKey;
+
+    /**
+     * 昵称
+     */
+    private String nickName;
+
+    /**
+     * 头像链接
+     */
+    private String imageUrl;
+
+    /**
+     * 手机号码
+     */
+    private String phone;
+
+    private Integer tbStatus;
+
+    private Date createTime;
+
+    private Date updateTime;
+}

+ 2 - 0
src/main/java/com/fdkankan/tk/service/IWxService.java

@@ -5,5 +5,7 @@ import java.io.IOException;
 
 public interface IWxService {
 
+    String getToken();
+
     void getWxQRCode(String path, String targetTmpPath,Integer reCount);
 }

+ 28 - 0
src/main/java/com/fdkankan/tk/service/IWxUserService.java

@@ -0,0 +1,28 @@
+package com.fdkankan.tk.service;
+
+import com.fdkankan.tk.entity.WxUser;
+import com.baomidou.mybatisplus.extension.service.IService;
+import com.fdkankan.tk.httpClient.response.WxOpenIdVo;
+import com.fdkankan.tk.response.WxUserVo;
+
+/**
+ * <p>
+ *  服务类
+ * </p>
+ *
+ * @author 
+ * @since 2022-12-19
+ */
+public interface IWxUserService extends IService<WxUser> {
+
+    Object wxLogin(String code);
+
+
+    WxUser addUser(WxOpenIdVo wxOpenIdVo);
+
+    WxUser getByOpenId(String openId);
+
+    void updateByVo(WxUserVo param);
+
+    Object getPhone(String code);
+}

+ 73 - 0
src/main/java/com/fdkankan/tk/service/impl/UploadService.java

@@ -0,0 +1,73 @@
+package com.fdkankan.tk.service.impl;
+
+import com.fdkankan.tk.common.ResultCode;
+import com.fdkankan.tk.common.util.UploadToOssUtil;
+import com.fdkankan.tk.exception.BusinessException;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.annotation.Resource;
+import java.io.File;
+import java.util.UUID;
+
+@Service
+public class UploadService {
+
+    @Resource
+    private UploadToOssUtil uploadToOssUtil;
+
+    @Value("${upload.query-path}")
+    private String queryPath;
+
+    public String uploadFile(MultipartFile file, boolean newName, String filePathAdd) {
+        if(file.isEmpty()){
+            throw new BusinessException(ResultCode.UPLOAD_FILE_NO_EXIST);
+        }
+        if(file.getSize()>10 * 1024 * 1024 * 100){
+            System.out.println(file.getSize());
+            throw new BusinessException(ResultCode.UPLOAD_FILE_TO_LONG);
+        }
+        //获取文件名
+        String fileName = file.getOriginalFilename();
+        if(StringUtils.isEmpty(fileName)){
+            throw new BusinessException(ResultCode.UPLOAD_FILE_NO_EXIST);
+        }
+        File localFile = null;
+        try {
+            //获取文件后缀名
+            String suffixName = fileName.substring(fileName.lastIndexOf("."));
+            //重新生成文件名
+            if(newName){
+                fileName = UUID.randomUUID().toString().replace("-","") ;
+            }else {
+                fileName= fileName.substring(0,fileName.lastIndexOf("."));
+            }
+            localFile = File.createTempFile(fileName + suffixName,suffixName);
+            file.transferTo(localFile);
+            String path = localFile.getPath();
+            uploadToOssUtil.uploadOss(path,filePathAdd+ fileName + suffixName);
+            if(!uploadToOssUtil.existKey(filePathAdd + fileName + suffixName)){
+                throw new BusinessException(ResultCode.UPLOAD_ERROR.code,ResultCode.UPLOAD_ERROR.msg);
+            }
+            return queryPath +filePathAdd+ fileName + suffixName;
+        }catch (Exception e){
+            throw new BusinessException(ResultCode.UPLOAD_ERROR.code,ResultCode.UPLOAD_ERROR.msg);
+        }finally {
+            if(localFile!=null){
+                localFile.delete();
+            }
+        }
+
+    }
+
+    public void deleteOssUrl(String path) {
+        try {
+            String replace = path.replace(queryPath, "");
+            uploadToOssUtil.delete(replace);
+        }catch (Exception e){
+            e.printStackTrace();
+        }
+    }
+}

+ 10 - 1
src/main/java/com/fdkankan/tk/service/impl/WxConfigServiceImpl.java

@@ -28,7 +28,16 @@ public class WxConfigServiceImpl extends ServiceImpl<IWxConfigMapper, WxConfig>
 
     @PostConstruct
     public void initWxConfig(){
-        wxConfig = this.getById(1);
+        List<WxConfig> list = this.list();
+        if(list.size() <=0){
+            log.info("项目未配置Wxconfig,请于数据库中配置");
+            return;
+        }
+        if(list.size() >1){
+            log.info("项目配置Wxconfig,存在多个配置,请确保有且只有一个");
+            return;
+        }
+        wxConfig = list.get(0);
         log.info("项目启动加载Wxconfig:{}",wxConfig);
     }
 }

+ 7 - 1
src/main/java/com/fdkankan/tk/service/impl/WxServiceImpl.java

@@ -1,4 +1,5 @@
 package com.fdkankan.tk.service.impl;
+import java.util.Date;
 
 import cn.hutool.core.io.FileUtil;
 import com.alibaba.fastjson.JSONObject;
@@ -8,11 +9,15 @@ import com.fdkankan.tk.common.ResultCode;
 import com.fdkankan.tk.common.util.RedisKeyUtil;
 import com.fdkankan.tk.common.util.UploadToOssUtil;
 import com.fdkankan.tk.entity.Room;
+import com.fdkankan.tk.entity.WxUser;
 import com.fdkankan.tk.exception.BusinessException;
 import com.fdkankan.tk.httpClient.client.WxClient;
+import com.fdkankan.tk.httpClient.response.WxOpenIdVo;
+import com.fdkankan.tk.response.WxUserVo;
 import com.fdkankan.tk.service.IRoomService;
 import com.fdkankan.tk.service.IWxConfigService;
 import com.fdkankan.tk.service.IWxService;
+import com.fdkankan.tk.service.IWxUserService;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.io.IOUtils;
 import org.apache.commons.lang3.StringUtils;
@@ -21,6 +26,7 @@ import org.apache.http.client.methods.HttpPost;
 import org.apache.http.entity.StringEntity;
 import org.apache.http.impl.client.CloseableHttpClient;
 import org.apache.http.impl.client.HttpClients;
+import org.springframework.beans.BeanUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.http.HttpStatus;
@@ -53,7 +59,7 @@ public class WxServiceImpl implements IWxService {
     //太阳码
     static String getWxSunCodeUrl ="https://api.weixin.qq.com/wxa/getwxacode?access_token=%s";
 
-
+    @Override
     public String getToken(){
         String redisKey = RedisKeyUtil.AccessToken + WxConfigServiceImpl.wxConfig.getAppId();
         if(redisUtil.hasKey(redisKey)){

+ 111 - 0
src/main/java/com/fdkankan/tk/service/impl/WxUserServiceImpl.java

@@ -0,0 +1,111 @@
+package com.fdkankan.tk.service.impl;
+
+import com.alibaba.fastjson.JSONObject;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.fdkankan.tk.common.ResultCode;
+import com.fdkankan.tk.common.util.RoomUtil;
+import com.fdkankan.tk.entity.WxUser;
+import com.fdkankan.tk.exception.BusinessException;
+import com.fdkankan.tk.httpClient.client.WxClient;
+import com.fdkankan.tk.httpClient.request.WxGetPhoneParam;
+import com.fdkankan.tk.httpClient.response.WxOpenIdVo;
+import com.fdkankan.tk.mapper.IWxUserMapper;
+import com.fdkankan.tk.response.WxUserVo;
+import com.fdkankan.tk.service.IWxService;
+import com.fdkankan.tk.service.IWxUserService;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.fdkankan.tk.util.MD5Utils;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.BeanUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.security.spec.ECField;
+
+/**
+ * <p>
+ *  服务实现类
+ * </p>
+ *
+ * @author 
+ * @since 2022-12-19
+ */
+@Service
+@Slf4j
+public class WxUserServiceImpl extends ServiceImpl<IWxUserMapper, WxUser> implements IWxUserService {
+
+    @Resource
+    WxClient wxClient;
+    @Autowired
+    IWxService wxService;
+
+    @Override
+    public Object wxLogin(String code) {
+        WxOpenIdVo wxOpenIdVo = wxClient.getOpenIdUrl(WxConfigServiceImpl.wxConfig.getAppId(), WxConfigServiceImpl.wxConfig.getAppSecret(), code);
+        log.info("wxLogin-微信获取openid:{}",wxOpenIdVo);
+        if(wxOpenIdVo.getErrcode() == 0){
+            WxUser wxUser = this.addUser(wxOpenIdVo);
+            WxUserVo vo = new WxUserVo();
+            BeanUtils.copyProperties(wxUser,vo);
+            return vo;
+        }
+        throw new BusinessException(ResultCode.WX_LOGIN_ERROR);
+    }
+
+    @Override
+    public WxUser addUser(WxOpenIdVo wxOpenIdVo) {
+        WxUser wxUser = this.getByOpenId(wxOpenIdVo.getOpenId());
+        if(wxUser != null){
+            return wxUser;
+        }
+        wxUser = new WxUser();
+        wxUser.setWxUserId(RoomUtil.ev + wxOpenIdVo.getOpenId());
+        wxUser.setOpenid(wxOpenIdVo.getOpenId());
+        wxUser.setUnionid(wxOpenIdVo.getUnionid());
+        wxUser.setSessionKey(wxOpenIdVo.getSession_key());
+        this.save(wxUser);
+        return wxUser;
+    }
+
+    @Override
+    public WxUser getByOpenId(String openId) {
+        try {
+            LambdaQueryWrapper<WxUser> wrapper = new LambdaQueryWrapper<>();
+            wrapper.eq(WxUser::getOpenid,openId);
+            return this.getOne(wrapper);
+        }catch (Exception e){
+            e.printStackTrace();
+        }
+       throw new BusinessException(ResultCode.WX_OPENID_ERROr);
+    }
+
+    @Override
+    public void updateByVo(WxUserVo param) {
+        if(StringUtils.isBlank(param.getWxUserId())){
+            throw new BusinessException(ResultCode.PARAM_MISS);
+        }
+        WxUser wxUser = new WxUser();
+        BeanUtils.copyProperties(param,wxUser);
+        wxUser.setCreateTime(null);
+        wxUser.setUpdateTime(null);
+        this.updateById(wxUser);
+    }
+
+    @Override
+    public Object getPhone(String code) {
+        try {
+            JSONObject jsonObject = wxClient.getPhone(wxService.getToken(), new WxGetPhoneParam(code));
+            JSONObject phoneObj = (JSONObject) jsonObject.get("phone_info");
+            if(phoneObj==null){
+                throw new BusinessException(ResultCode.WX_PHONE_ERROR);
+            }
+            //return phoneObj.getString("phoneNumber");
+            return phoneObj;
+        } catch (Exception e){
+            e.printStackTrace();
+        }
+        throw new BusinessException(ResultCode.WX_PHONE_ERROR);
+    }
+}

+ 45 - 0
src/main/java/com/fdkankan/tk/util/MD5Utils.java

@@ -0,0 +1,45 @@
+package com.fdkankan.tk.util;
+
+import java.security.MessageDigest;
+
+public class MD5Utils {
+
+    public static String getPWD( String strs ){
+        /*
+         * 加密需要使用JDK中提供的类
+         */
+        StringBuffer sb = new StringBuffer();
+        try{
+            MessageDigest digest = MessageDigest.getInstance("MD5");
+
+            byte[] bs = digest.digest(strs.getBytes());
+
+            /*
+             *  加密后的数据是-128 到 127 之间的数字,这个数字也不安全。
+             *   取出每个数组的某些二进制位进行某些运算,得到一个具体的加密结果
+             *
+             *   0000 0011 0000 0100 0010 0000 0110 0001
+             *  &0000 0000 0000 0000 0000 0000 1111 1111
+             *  ---------------------------------------------
+             *   0000 0000 0000 0000 0000 0000 0110 0001
+             *   把取出的数据转成十六进制数
+             */
+
+            for (byte b : bs) {
+                int x = b & 255;
+                String s = Integer.toHexString(x);
+                if( x > 0 && x < 16 ){
+                    sb.append("0");
+                    sb.append(s);
+                }else{
+                    sb.append(s);
+                }
+            }
+
+        }catch( Exception e){
+            System.out.println("加密失败");
+        }
+        return sb.toString();
+    }
+
+}

+ 5 - 0
src/main/resources/mapper/tk/WxUserMapper.xml

@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.fdkankan.tk.mapper.IWxUserMapper">
+
+</mapper>