Althars123 3 years ago
parent
commit
9fa5b1c67a

+ 2 - 3
twzd-admin/src/main/java/com/miaxis/app/controller/wx/UserInfoController.java

@@ -1,6 +1,5 @@
 package com.miaxis.app.controller.wx;
 
-import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.miaxis.common.constant.Constants;
 import com.miaxis.common.core.controller.BaseController;
 import com.miaxis.common.core.domain.Response;
@@ -33,8 +32,8 @@ public class UserInfoController extends BaseController {
     @GetMapping(value = "/info")
     @ApiOperation("获取用户信息")
     public Response<UserInfo> getInfo(){
-        String openid = SecurityUtils.getLoginUser().getStudent().getOpenid();
-        return Response.success(userInfoService.getOne(new QueryWrapper<UserInfo>().eq("openid",openid)));
+        Long userId  = SecurityUtils.getLoginUser().getStudent().getId();
+        return Response.success(userInfoService.getById(userId));
     }
 
 

+ 33 - 6
twzd-admin/src/main/java/com/miaxis/system/controller/system/SysLoginController.java

@@ -21,6 +21,7 @@ import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.springframework.beans.BeanUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.web.bind.annotation.GetMapping;
@@ -66,12 +67,11 @@ public class SysLoginController
     @Value("${app.appSecret}")
     private String appSecret;
 
+    @Value("${xcx.appId}")
+    private String xcxAppid;
 
-
-
-
-
-
+    @Value("${xcx.secret}")
+    private String xcxSecret;
 
 
     /**
@@ -123,7 +123,7 @@ public class SysLoginController
         }
         String userInfoStr = wxService.getUserInfo("zh_CN", wxResult.getAccess_token(), wxResult.getOpenid());
         WxUserInfo wxUserInfo = JSONObject.parseObject(userInfoStr,WxUserInfo.class);
-
+        ServletUtils.getRequest().setAttribute("openid",wxUserInfo.getOpenid());
         String token = loginService.login(wxUserInfo,null, StudentLoginTypeEnum.AUTHORIZATION_CODE_LOGIN.getCode());
         TokenDTO tokenDTO = new TokenDTO();
         tokenDTO.setToken(token);
@@ -152,6 +152,33 @@ public class SysLoginController
 
     }
 
+    /**
+     * 用户 jscode登录
+     *
+     */
+    @PostMapping("/login/jscode")
+    @ApiOperation("小程序jscode登录")
+    public Response<TokenDTO> getInfo(String jscode){
+        String result = wxService.getWxInfo(xcxAppid, xcxSecret, jscode,"authorization_code");
+        JSONObject jsonString = JSONObject.parseObject(result);
+        WxResult wxResult = JSONObject.toJavaObject(jsonString, WxResult.class);
+        TokenDTO tokenDTO = new TokenDTO();
+        // 生成令牌
+        if (wxResult.getOpenid() != null){
+            // 生成令牌
+            WxUserInfo wxUserInfo = new WxUserInfo();
+            BeanUtils.copyProperties(wxResult,wxUserInfo);
+            ServletUtils.getRequest().setAttribute("xcxOpenid",wxUserInfo.getOpenid());
+            String token = loginService.login(wxUserInfo,null, StudentLoginTypeEnum.AUTHORIZATION_XCX_LOGIN.getCode());
+            tokenDTO.setToken(token);
+            return Response.success(tokenDTO) ;
+        }
+        else{
+            return Response.error(500,wxResult.getErrmsg());
+        }
+
+    }
+
 //
 //    /**
 //     * 用户 jscode登录

+ 4 - 1
twzd-admin/src/main/resources/application-dev.yml

@@ -85,7 +85,10 @@ spring:
 app:
     appId: wx67ca1b8c9816ef28
     appSecret: 8604f2a6eb6338cfa64e7df4ec2c08b3
-
+# 微信小程序
+xcx:
+    appId: wx8f43db501343feab
+    secret: 3509a81880669ffa6fa554b2aa050351
 
 # 微信支付
 wxpay:

+ 5 - 0
twzd-admin/src/main/resources/application-prod.yml

@@ -83,6 +83,11 @@ app:
     appId: wx67ca1b8c9816ef28
     appSecret: 8604f2a6eb6338cfa64e7df4ec2c08b3
 
+# 微信小程序
+xcx:
+    appId: wx8f43db501343feab
+    secret: 3509a81880669ffa6fa554b2aa050351
+
 # 微信支付
 wxpay:
     v3url: https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi

+ 5 - 0
twzd-admin/src/main/resources/application-prodtest.yml

@@ -83,6 +83,11 @@ app:
     appId: wx67ca1b8c9816ef28
     appSecret: 8604f2a6eb6338cfa64e7df4ec2c08b3
 
+# 微信小程序
+xcx:
+    appId: wx8f43db501343feab
+    secret: 3509a81880669ffa6fa554b2aa050351
+
 # 微信支付
 wxpay:
     v3url: https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi

+ 59 - 1
twzd-admin/src/test/java/com/miaxis/test/NormalTest.java

@@ -1,8 +1,13 @@
 package com.miaxis.test;
 
+import com.alibaba.fastjson.JSONObject;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.miaxis.TwzdApplication;
+import com.miaxis.common.core.domain.entity.UserInfo;
+import com.miaxis.feign.dto.WxGzhBatchUser;
 import com.miaxis.feign.service.IWxSendService;
 import com.miaxis.spread.service.impl.WxSpreadRelationServiceImpl;
+import com.miaxis.user.service.IUserInfoService;
 import com.miaxis.wx.service.IWxGzhService;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -11,6 +16,8 @@ import org.springframework.test.context.ActiveProfiles;
 import org.springframework.test.context.junit4.SpringRunner;
 
 import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.List;
 
 @ActiveProfiles("prodtest")
 @SpringBootTest(classes = TwzdApplication.class)
@@ -25,11 +32,62 @@ public class NormalTest {
     IWxSendService wxSendService;
     @Resource
     IWxGzhService wxGzhService;
+    @Resource
+    IUserInfoService userInfoService;
     @Test
     public void test666() throws Exception {
         String gzhToken = wxGzhService.getGzhToken();
-        String res = wxSendService.userInfo(gzhToken, "ovKTX59m65qpQAd-Bh0AIc5KhW3Q", "zh_CN");
+//        String res = wxSendService.userInfo(gzhToken, "ovKTX59m65qpQAd-Bh0AIc5KhW3Q", "zh_CN");
+        List<UserInfo> list = userInfoService.list();
+        int times = (list.size()-1)/100+1;
+        for (int i= 0; i < times-1; i++){
+            WxGzhBatchUser batchUser = new WxGzhBatchUser();
+            List<JSONObject> jlist = new ArrayList<JSONObject>();
+            for(int j=0+i*100;j<99+i*100;j++){
+                JSONObject jo = new JSONObject();
+                jo.put("lang","zh_CN");
+                jo.put("openid",list.get(j).getOpenid());
+                jlist.add(jo);
+            }
+            batchUser.setUser_list(jlist);
+            String res = wxSendService.batchUserInfo(gzhToken,batchUser);
+            System.out.println(res);
+        }
+        WxGzhBatchUser batchUser = new WxGzhBatchUser();
+        List<JSONObject> jlist = new ArrayList<JSONObject>();
+        for(int j=0+(times-1)*100;j<list.size()-1;j++){
+            JSONObject jo = new JSONObject();
+            jo.put("lang","zh_CN");
+            jo.put("openid",list.get(j).getOpenid());
+            jlist.add(jo);
+        }
+        batchUser.setUser_list(jlist);
+        String res = wxSendService.batchUserInfo(gzhToken,batchUser);
+        System.out.println("最后一次");
         System.out.println(res);
+
+
+
+
+    }
+    @Test
+    public void test777() throws Exception {
+        List<UserInfo> list = userInfoService.list(new QueryWrapper<UserInfo>().isNull("union_id"));
+        System.out.println(list.size());
+        int index =1 ;
+        for (UserInfo userInfo : list){
+            String res = wxSendService.userInfo( wxGzhService.getGzhToken(), userInfo.getOpenid(), "zh_CN");
+            JSONObject jsonObject = JSONObject.parseObject(res);
+            if (jsonObject.getString("unionid") ==null){
+                System.out.println( index);
+                index++;
+                continue;
+            }
+            userInfo.setUnionId(jsonObject.getString("unionid"));
+
+            index++;
+        }
+        userInfoService.updateBatchById(list);
     }
 
 

+ 7 - 1
twzd-common/src/main/java/com/miaxis/common/core/domain/entity/UserInfo.java

@@ -62,11 +62,17 @@ public class UserInfo extends BaseBusinessEntity{
 
 
     /** 微信openid */
-    @Excel(name = "微信openid")
+    @Excel(name = "公众号openid")
     @TableField("openid")
     @ApiModelProperty(value = "微信openid")
     private String openid;
 
+    /** 微信openid */
+    @Excel(name = "小程序openid")
+    @TableField("xcx_openid")
+    @ApiModelProperty(value = "小程序openid")
+    private String xcxOpenid;
+
 
 
     /** 0 启用 1禁用 */

+ 2 - 1
twzd-common/src/main/java/com/miaxis/common/enums/StudentLoginTypeEnum.java

@@ -7,7 +7,8 @@ package com.miaxis.common.enums;
  */
 public enum StudentLoginTypeEnum
 {
-    AUTHORIZATION_CODE_LOGIN("1", "授权码登录");
+    AUTHORIZATION_CODE_LOGIN("1", "公众号授权码登录"),
+    AUTHORIZATION_XCX_LOGIN("2", "小程序登录");
 
     private final String code;
     private final String info;

+ 1 - 1
twzd-framework/src/main/java/com/miaxis/framework/config/SecurityConfig.java

@@ -102,7 +102,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter
                 // 对于app 开放页面,允许任意访问
                 .antMatchers("/**/open-api/**").permitAll()
                 // 对于登录login 验证码captchaImage 允许匿名访问
-                .antMatchers("/login", "/login/noCode","/captchaImage","/login/code","/login/code/test","/login/jscode-test").anonymous()
+                .antMatchers("/login", "/login/noCode","/captchaImage","/login/code","/login/jscode","/login/code/test","/login/jscode-test").anonymous()
                 //.antMatchers("/student/open/**").permitAll()
                 .antMatchers("/student/**").hasRole("STUDENT")
                 .antMatchers("/vip/**").hasRole("VIP")

+ 4 - 3
twzd-framework/src/main/java/com/miaxis/framework/web/service/SysLoginService.java

@@ -100,10 +100,11 @@ public class SysLoginService
         ServletUtils.getRequest().setAttribute("loginType",loginType);
         ServletUtils.getRequest().setAttribute("headImage",wxUserInfo.getHeadimgurl());
         ServletUtils.getRequest().setAttribute("nickName",wxUserInfo.getNickname());
-        ServletUtils.getRequest().setAttribute("unionid",wxUserInfo.getUnionid());
+
         // 用户验证
-        if (StudentLoginTypeEnum.AUTHORIZATION_CODE_LOGIN.getCode().equals(loginType)){
-            return authenticate(wxUserInfo.getOpenid(),new OpenIdAuthenticationToken(wxUserInfo.getOpenid()));
+        if (StudentLoginTypeEnum.AUTHORIZATION_CODE_LOGIN.getCode().equals(loginType)
+                ||StudentLoginTypeEnum.AUTHORIZATION_XCX_LOGIN.getCode().equals(loginType)){
+            return authenticate(wxUserInfo.getOpenid(),new OpenIdAuthenticationToken(wxUserInfo.getUnionid()));
         }
         else{
             throw new CustomException("loginType参数错误");

+ 22 - 8
twzd-framework/src/main/java/com/miaxis/framework/web/service/UserDetailsServiceImpl.java

@@ -63,22 +63,35 @@ public class UserDetailsServiceImpl implements UserDetailsService
             return createLoginUser(user);
         } else if (StudentLoginTypeEnum.AUTHORIZATION_CODE_LOGIN.getCode().equals(loginType)){
             {
-                UserInfo userInfo = userService.getStudentByOpenId(identification);
+                UserInfo userInfo = userService.getStudentByUnionid(identification);
                 if (userInfo == null) {
                     userInfo = new UserInfo();
                     userInfo.setHeadImage((String) ServletUtils.getRequest().getAttribute("headImage"));
                     userInfo.setNickName((String) ServletUtils.getRequest().getAttribute("nickName"));
-                    userInfo.setUnionId((String) ServletUtils.getRequest().getAttribute("unionid"));
-                    userInfo.setOpenid(identification);
+                    userInfo.setOpenid((String) ServletUtils.getRequest().getAttribute("openid"));
+                    userInfo.setUnionId(identification);
                     userService.saveUserInfo(userInfo);
-                    userInfo = userService.getStudentByOpenId(identification);
                 }else {
                     userInfo.setHeadImage((String) ServletUtils.getRequest().getAttribute("headImage"));
                     userInfo.setNickName((String) ServletUtils.getRequest().getAttribute("nickName"));
-                    userInfo.setUnionId((String) ServletUtils.getRequest().getAttribute("unionid"));
+                    userInfo.setOpenid((String) ServletUtils.getRequest().getAttribute("openid"));
                     userService.updateStudent(userInfo);
                 }
-                return createLoginUser(userInfo);
+                return createLoginUser(identification);
+            }
+        }else if (StudentLoginTypeEnum.AUTHORIZATION_XCX_LOGIN.getCode().equals(loginType)){
+            {
+                UserInfo userInfo = userService.getStudentByUnionid(identification);
+                if (userInfo == null) {
+                    userInfo = new UserInfo();
+                    userInfo.setXcxOpenid((String) ServletUtils.getRequest().getAttribute("xcxOpenid"));
+                    userInfo.setUnionId(identification);
+                    userService.saveUserInfo(userInfo);
+                }else {
+                    userInfo.setXcxOpenid((String) ServletUtils.getRequest().getAttribute("xcxOpenid"));
+                    userService.updateStudent(userInfo);
+                }
+                return createLoginUser(identification);
             }
         } else{
             throw new CustomException("登录类型不存在");
@@ -88,8 +101,9 @@ public class UserDetailsServiceImpl implements UserDetailsService
 
     }
 
-    private UserDetails createLoginUser(UserInfo student) {
-        return new LoginUser(student);
+    private UserDetails createLoginUser(String identification) {
+        UserInfo userInfo = userService.getStudentByUnionid(identification);
+        return new LoginUser(userInfo);
     }
 
     public UserDetails createLoginUser(SysUser user)

+ 14 - 0
twzd-service/src/main/java/com/miaxis/feign/dto/WxGzhBatchUser.java

@@ -0,0 +1,14 @@
+package com.miaxis.feign.dto;
+
+import com.alibaba.fastjson.JSONObject;
+import lombok.Data;
+
+import java.util.List;
+
+@Data
+public class WxGzhBatchUser {
+
+
+    private List<JSONObject> user_list;
+
+}

+ 10 - 1
twzd-service/src/main/java/com/miaxis/feign/service/IWxSendService.java

@@ -2,11 +2,11 @@ package com.miaxis.feign.service;
 
 import com.alibaba.fastjson.JSONObject;
 import com.miaxis.common.config.FeignConfig;
+import com.miaxis.feign.dto.WxGzhBatchUser;
 import com.miaxis.feign.dto.WxMessageCusom;
 import com.miaxis.feign.dto.WxMessageTemplate;
 import com.miaxis.feign.dto.WxQrTicket;
 import feign.Headers;
-
 import feign.Param;
 import feign.form.FormData;
 import org.springframework.cloud.openfeign.FeignClient;
@@ -100,6 +100,15 @@ public interface IWxSendService {
                     @RequestParam("openid") String openid,
                     @RequestParam("lang") String lang);
 
+
+    /**
+     * 批量获取用户信息
+     * @param token 调用接口凭证
+     * @return
+     */
+    @PostMapping(value = "/user/info/batchget")
+    String batchUserInfo(@RequestParam("access_token") String token, WxGzhBatchUser batchUser);
+
     /**
      * 发送客服消息
      * @param accessToken

+ 16 - 1
twzd-service/src/main/java/com/miaxis/wx/service/WxService.java

@@ -32,7 +32,7 @@ public interface WxService {
 
 
     /**
-     * 获取用户信息
+     * 公众号获取用户信息
      */
     @GetMapping(value = "/sns/userinfo")
     String getUserInfo(
@@ -41,6 +41,21 @@ public interface WxService {
             @RequestParam("openid") String openid
     );
 
+    /**
+     *  小程序获取openid
+     * @param appid
+     * @param secret
+     * @param jsCode
+     * @param grantType
+     * @return
+     */
+    @GetMapping(value = "/sns/jscode2session")
+    String getWxInfo(
+            @RequestParam("appid") String appid,
+            @RequestParam("secret") String secret,
+            @RequestParam("js_code") String jsCode,
+            @RequestParam("grant_type") String grantType);
+
     /**
      * 获取jsapi_ticket
      */

+ 2 - 0
twzd-system/src/main/java/com/miaxis/system/mapper/SysUserMapper.java

@@ -123,4 +123,6 @@ public interface SysUserMapper
     List<AgentVO> getAgentList(@Param("roleId")Long roleId, @Param("userName")String userName);
 
     void updateSysUserByNickName(@Param("schoolName")String schoolName, @Param("total")Integer total);
+
+    UserInfo getStudentByUnionid(String identification);
 }

+ 2 - 0
twzd-system/src/main/java/com/miaxis/system/service/ISysUserService.java

@@ -184,4 +184,6 @@ public interface ISysUserService
     List<AgentVO> getAgentList(Long roleId, String schoolName);
 
     void updateSysUserByNickName(String schoolName, Integer total);
+
+    UserInfo getStudentByUnionid(String identification);
 }

+ 5 - 0
twzd-system/src/main/java/com/miaxis/system/service/impl/SysUserServiceImpl.java

@@ -478,4 +478,9 @@ public class SysUserServiceImpl implements ISysUserService
     public void updateSysUserByNickName(String schoolName, Integer total) {
         userMapper.updateSysUserByNickName(schoolName,total);
     }
+
+    @Override
+    public UserInfo getStudentByUnionid(String identification) {
+        return userMapper.getStudentByUnionid(identification);
+    }
 }

+ 23 - 3
twzd-system/src/main/resources/mapper/system/SysUserMapper.xml

@@ -92,17 +92,37 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 
 	<select id="getStudentByOpenId" parameterType="String" resultType="com.miaxis.common.core.domain.entity.UserInfo">
 		select * from user_info
-		where openid = #{openid}
+		where union_id = #{unionId}
+	</select>
+
+	<select id="getStudentByUnionid" parameterType="String" resultType="com.miaxis.common.core.domain.entity.UserInfo">
+		select * from user_info
+		where union_id = #{unionId}
 	</select>
 	<select id="getStudentByName" parameterType="String" resultType="com.miaxis.common.core.domain.entity.UserInfo">
 		select * from user_info
 		where name = #{name}
 	</select>
 	<insert id="saveUserInfo" parameterType="com.miaxis.common.core.domain.entity.UserInfo" >
-		insert into user_info (head_image,nick_name,openid) values (#{headImage},#{nickName},#{openid})
+		insert into user_info (head_image,nick_name,openid,xcx_openid,union_id)
+		 values (#{headImage},#{nickName},#{openid},#{xcxOpenid},#{unionId})
 	</insert>
 	<insert id="updateStudent" parameterType="com.miaxis.common.core.domain.entity.UserInfo" >
-		update user_info set head_image = #{headImage},nick_name = #{nickName},union_id = #{unionId} where openid = #{openid}
+		update user_info set
+		<if test="headImage != null and headImage != ''">
+			head_image = #{headImage},
+		</if>
+		<if test="nickName != null and nickName != ''">
+			nick_name = #{nickName},
+		</if>
+		<if test="openid != null and openid != ''">
+			openid = #{openid},
+		</if>
+		<if test="xcxOpenid != null and xcxOpenid != ''">
+			xcx_openid = #{xcxOpenid},
+		</if>
+		union_id = #{unionId}
+		where union_id = #{unionId}
 	</insert>