Pārlūkot izejas kodu

add 微信网页授权登录

zoujiajian 3 gadi atpakaļ
vecāks
revīzija
02d657a104

+ 0 - 1
netflix-dao/src/main/java/com/cyksj/model/dto/AuthRedirect.java

@@ -37,5 +37,4 @@ public class AuthRedirect {
      * 推广id
      */
     private Long pid;
-
 }

+ 1 - 0
netflix-service/src/main/java/com/cyksj/service/authorization/AuthorizationService.java

@@ -20,4 +20,5 @@ public interface AuthorizationService {
 
     JsSdkTicket getJsTicket(String appId, String url) throws Exception;
 
+    String createWxAuthLoginUrl(String state);
 }

+ 11 - 0
netflix-service/src/main/java/com/cyksj/service/authorization/impl/AuthorizationServiceImpl.java

@@ -2,6 +2,7 @@ package com.cyksj.service.authorization.impl;
 
 import com.cyksj.common.util.Codec;
 import com.cyksj.config.WeChatConfig;
+import com.cyksj.config.wxlogin.WxOpenPlatYHLXLoginConfig;
 import com.cyksj.enums.WeChatAuthRedirectUrl;
 import com.cyksj.model.dto.JsSdkTicket;
 import com.cyksj.service.authorization.AuthorizationService;
@@ -10,6 +11,9 @@ import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Service;
 
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+
 /**
  * @author chan
  * @className AuthorizationServiceImpl
@@ -25,6 +29,8 @@ public class AuthorizationServiceImpl implements AuthorizationService {
 
     private final WeChatConfig weChatConfig;
 
+    private final WxOpenPlatYHLXLoginConfig wxOpenPlatYHLXLoginConfig;
+
 
     @Override
     public String createUrl(String state, String authType) {
@@ -55,4 +61,9 @@ public class AuthorizationServiceImpl implements AuthorizationService {
         return jsSdkTicket;
     }
 
+    @Override
+    public String createWxAuthLoginUrl(String state) {
+        return weChatService.createWxAuthLoginUrl(state, wxOpenPlatYHLXLoginConfig.getAppId(), URLEncoder.encode(wxOpenPlatYHLXLoginConfig.getRedirectUri(), StandardCharsets.UTF_8));
+    }
+
 }

+ 4 - 5
netflix-service/src/main/java/com/cyksj/service/gzh/factory/EventMsgService.java

@@ -20,7 +20,6 @@ import com.cyksj.model.dto.MsgEvent;
 import com.cyksj.model.entity.User;
 import com.cyksj.model.entity.UserGzhRelation;
 import com.cyksj.model.entity.WxApp;
-import com.cyksj.model.entity.WxSyncLog;
 import com.cyksj.redis.RedisService;
 import com.cyksj.service.distribute.DistributeService;
 import com.cyksj.service.distribute.equipment.EquipmentDistributeService;
@@ -109,9 +108,9 @@ public class EventMsgService implements GzhMsgService {
 		}
 		//迁移公众号之后同步授权后信息
 		//是否是迁移用户
-		WxSyncLog wxSyncLog = wxSyncLogMapper.selectOne(Wrappers.lambdaQuery(WxSyncLog.class)
-				.eq(WxSyncLog::getToAppid, weChatConfig.getAppid())
-				.eq(WxSyncLog::getNewOpenid, openId).last("limit 1"));
+//		WxSyncLog wxSyncLog = wxSyncLogMapper.selectOne(Wrappers.lambdaQuery(WxSyncLog.class)
+//				.eq(WxSyncLog::getToAppid, weChatConfig.getAppid())
+//				.eq(WxSyncLog::getNewOpenid, openId).last("limit 1"));
 
 		WxApp wxApp = wxAppMapper.selectOne(Wrappers.lambdaQuery(WxApp.class)
 				.eq(WxApp::getGzhOriginalId, msgEvent.getToUserName()).last("limit 1"));
@@ -119,7 +118,7 @@ public class EventMsgService implements GzhMsgService {
 			return false;
 		}
 		GzhUnionidUserinfo info = weChatService.getUserInfo2(weChatService.getAccessToken(wxApp.getAppId()), openId);
-		User user = userService.getSyncUser(info.getOpenid(), info.getUnionid(), wxSyncLog);
+		User user = userService.getSyncUser(info.getOpenid(), info.getUnionid(), null);
 
 		String state = redisService.getStr(RedisService.key.WX_GZH_QRCODE_SHARED_LOGIN.getNameFormat(sceneKey));
 		GzhBodyDto gzhDto = null;

+ 1 - 18
netflix-service/src/main/java/com/cyksj/service/user/impl/UserServiceImpl.java

@@ -72,11 +72,8 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
         if (StrUtil.isEmpty(unionid)) {
             throw BusinessRuntimeException.getInstance("授权操作异常,请刷新页面");
         }
-        WxSyncLog wxSyncLog = wxSyncLogMapper.selectOne(Wrappers.lambdaQuery(WxSyncLog.class)
-                .eq(WxSyncLog::getToAppid, weChatConfig.getAppid())
-                .eq(WxSyncLog::getNewOpenid, info.getOpenid()).last("limit 1"));
 
-		User user = getSyncUser(info.getOpenid(), info.getUnionid(), wxSyncLog);
+		User user = getSyncUser(info.getOpenid(), info.getUnionid(), null);
 
 		user = Optional.ofNullable(user).orElseGet(() -> new User()
 				.setUnionid(unionid));
@@ -90,20 +87,6 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
 		if (StrUtil.isEmpty(user.getHeadimgurl())) {
 			user.setHeadimgurl(info.getHeadimgurl());
 		}
-		if (!user.getUnionid().equals(unionid)) {
-			UserTransferLog log = new UserTransferLog();
-			if (wxSyncLog != null) {
-				log.setType("公众号迁移");
-			} else {
-				log.setType("绑定开发者账号");
-			}
-			log.setOldAppId(weChatConfig.getOldAppid());
-			log.setNewAppId(weChatConfig.getAppid());
-			log.setUserId(user.getId());
-			log.setOldUnionid(user.getUnionid());
-			log.setNewUnionid(info.getUnionid());
-			userTransferLogMapper.insert(log);
-		}
 		user.setUnionid(unionid);
 		user.setOpenId(info.getOpenid());
 		Boolean isNewUser = false;

+ 5 - 0
netflix-service/src/main/java/com/cyksj/service/wechat/WeChatService.java

@@ -88,4 +88,9 @@ public interface WeChatService {
      * 获取微信订单信息 校验订单是否已支付
      */
     Map<String, String> getWxOrderDetail(String shopId, String orderNo) throws Exception;
+
+    /**
+     * 获取微信网页授权url
+     */
+    String createWxAuthLoginUrl(String state, String appId, String redirectUri);
 }

+ 7 - 0
netflix-service/src/main/java/com/cyksj/service/wechat/impl/WeChatServiceImpl.java

@@ -578,6 +578,13 @@ public class WeChatServiceImpl implements WeChatService {
         return orderSearch;
     }
 
+    @Override
+    public String createWxAuthLoginUrl(String state, String appId, String redirectUri) {
+        String authLoginUrl = String.format("https://open.weixin.qq.com/connect/qrconnect?" +
+                "appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_login&state=%s#wechat_redirect", appId, redirectUri, state);
+        return authLoginUrl;
+    }
+
     /**
      * sha256_HMAC加密
      * @param message 消息

+ 52 - 44
netflix-web/src/main/java/com/cyksj/web/controller/user/AuthorizationController.java

@@ -35,10 +35,10 @@ import com.cyksj.redis.RedisService;
 import com.cyksj.service.authorization.AuthorizationService;
 import com.cyksj.service.distribute.DistributeService;
 import com.cyksj.service.distribute.equipment.EquipmentDistributeService;
+import com.cyksj.service.mail.MailService;
 import com.cyksj.service.template.TemplateCommonService;
 import com.cyksj.service.user.UserService;
 import com.cyksj.service.wechat.WeChatService;
-import com.cyksj.service.mail.MailService;
 import com.cyksj.web.util.StpUserUtil;
 import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
@@ -49,8 +49,6 @@ import org.springframework.web.bind.annotation.*;
 import javax.servlet.http.Cookie;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import java.net.URLEncoder;
-import java.nio.charset.StandardCharsets;
 import java.util.Date;
 
 /**
@@ -119,42 +117,9 @@ public class AuthorizationController {
      */
     @GetMapping(value = "/weChat/baseRedirect")
     public void redirect(String code, String state, HttpServletResponse response) throws Exception {
-
-        // 转跳参数
-        String json = Codec.DoBase64.custom().setData(state).decodeAsText();
-        AuthRedirect re = Jsons.parseObject(json, AuthRedirect.class);
-
         AuthToken token = weChatService.getAuthToken(code,weChatConfig.getAppid());
 
-        // 根据openid 与 access_token 获取用户信息
-        GzhOAuth2UserInfo userinfo = weChatService.getUserInfo(token.getAccessToken(), token.getOpenid());
-
-        //保存用户信息
-        User user = userService.saveAuth(userinfo, re.getSharedId(), re.getDsType(), re.getPid());
-        if (user == null) {
-            throw BusinessRuntimeException.getInstance("系统错误,请重新授权");
-        }
-
-        //写回登陆信息
-        StpUserUtil.login(user.getId());
-        response.addHeader("satoken-user",StpUserUtil.getTokenValue());
-
-        Cookie cookie = new Cookie("satoken-user",StpUserUtil.getTokenValue());
-        cookie.setMaxAge(31536000);
-        cookie.setPath("/");
-        response.addCookie(cookie);
-        JSONObject jsonObject = new JSONObject();
-        jsonObject.putOpt("uid",user.getId());
-        jsonObject.putOpt("nickName",user.getNickname());
-
-        Cookie userInfo = new Cookie("info",Base64.encode(jsonObject.toString()));
-        cookie.setMaxAge(31536000);
-        cookie.setPath("/");
-        response.addCookie(userInfo);
-        String url = redisService.getStr(re.getMappingId().toString());
-        redisService.del(re.getMappingId().toString());
-        log.info("微信授权转跳.url: {}",url);
-        response.sendRedirect(url.contains("?") ? url + "&t=" + StpUserUtil.getTokenValue() : url + "?t=" + StpUserUtil.getTokenValue());
+        baseRedirect(token, state, response);
     }
 
     /**
@@ -233,22 +198,30 @@ public class AuthorizationController {
     /**
      * 网页微信授权登录
      */
-    @GetMapping("/wx/login/authUrl")
-    public Result<String> wxAuthorize() throws Exception {
+    @GetMapping("/wx/authLogin")
+    public Result<String> wxAuthorize(Long sharedId, Integer dsType, Long popularizeId) throws Exception {
         String wxAuthUrl = redisService.getStr(RedisService.key.WX_LOGIN_AUTH_URI.getNameFormat(wxOpenPlatYHLXLoginConfig.getAppId()));
         Long mappingId = SEQUENCE.nextId();
         redisService.set(mappingId.toString(), wxOpenPlatYHLXLoginConfig.getLoginUrl(), 60 * 60 * 24L);
-        AuthRedirect redirect = new AuthRedirect().setMappingId(mappingId);
+        AuthRedirect redirect = new AuthRedirect().setMappingId(mappingId).setSharedId(sharedId).setDsType(dsType).setPid(popularizeId);
         String state = Codec.DoBase64.custom().setData(Jsons.toJson(redirect)).encodeAsText();
         if (StrUtil.isEmpty(wxAuthUrl)) {
-            wxAuthUrl = String.format("https://open.weixin.qq.com/connect/qrconnect?" +
-                            "appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_login&state=%s#wechat_redirect",
-                    wxOpenPlatYHLXLoginConfig.getAppId(),
-                    URLEncoder.encode(wxOpenPlatYHLXLoginConfig.getRedirectUri(), StandardCharsets.UTF_8), state);
+            wxAuthUrl = authorizationService.createWxAuthLoginUrl(state);
         }
         return GatewayResponse.SUCCESS.newBuilder().toResult(wxAuthUrl);
     }
 
+    /**
+     * 网页微信授权后跳转
+     */
+    @GetMapping("/wx/authLogin/baseRedirect")
+    public void wxAuthLoginRedirect(String code, String state, HttpServletResponse response) throws Exception {
+
+        AuthToken token = weChatService.getAuthToken(code, wxOpenPlatYHLXLoginConfig.getAppId());
+        //重定向
+        baseRedirect(token, state, response);
+    }
+
     /**
      * 网页扫描微信公众号二维码 临时凭证ticket  关注后登录
      */
@@ -438,4 +411,39 @@ public class AuthorizationController {
         LoginPhoneRep loginPhoneRep = new LoginPhoneRep(StpUserUtil.getTokenValue(), user.getId(), user.getNickname(), user.getHeadimgurl());
         return GatewayResponse.SUCCESS.newBuilder().toResult(loginPhoneRep);
     }
+
+    public void baseRedirect(AuthToken token, String state, HttpServletResponse response) throws Exception {
+        // 根据openid 与 access_token 获取用户信息
+        GzhOAuth2UserInfo userinfo = weChatService.getUserInfo(token.getAccessToken(), token.getOpenid());
+
+        // 转跳参数
+        String json = Codec.DoBase64.custom().setData(state).decodeAsText();
+        AuthRedirect re = Jsons.parseObject(json, AuthRedirect.class);
+        //保存用户信息
+        User user = userService.saveAuth(userinfo, re.getSharedId(), re.getDsType(), re.getPid());
+        if (user == null) {
+            throw BusinessRuntimeException.getInstance("系统错误,请重新授权");
+        }
+
+        //写回登陆信息
+        StpUserUtil.login(user.getId());
+        response.addHeader("satoken-user", StpUserUtil.getTokenValue());
+
+        Cookie cookie = new Cookie("satoken-user", StpUserUtil.getTokenValue());
+        cookie.setMaxAge(31536000);
+        cookie.setPath("/");
+        response.addCookie(cookie);
+        JSONObject jsonObject = new JSONObject();
+        jsonObject.putOpt("uid", user.getId());
+        jsonObject.putOpt("nickName", user.getNickname());
+
+        Cookie userInfo = new Cookie("info", Base64.encode(jsonObject.toString()));
+        cookie.setMaxAge(31536000);
+        cookie.setPath("/");
+        response.addCookie(userInfo);
+        String url = redisService.getStr(re.getMappingId().toString());
+        redisService.del(re.getMappingId().toString());
+        log.info("微信授权转跳.url: {}", url);
+        response.sendRedirect(url.contains("?") ? url + "&t=" + StpUserUtil.getTokenValue() : url + "?t=" + StpUserUtil.getTokenValue());
+    }
 }

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 0 - 0
netflix-web/src/main/resources/application-dev.yml


Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 0 - 0
netflix-web/src/main/resources/application-prd.yml


Daži faili netika attēloti, jo izmaiņu fails ir pārāk liels