浏览代码

add(operation-backend & SQL )
[增加标签表]

wangxiao 4 年之前
父节点
当前提交
76c7f1e36d

+ 39 - 6
operation-backend/src/main/java/com/idiot/operationbackend/controller/WeChatController.java

@@ -1,15 +1,13 @@
 package com.idiot.operationbackend.controller;
 
-import com.idiot.operationbackend.config.PlatformProperties;
+import com.alibaba.fastjson.JSONObject;
+import com.idiot.operationbackend.entity.Account;
+import com.idiot.operationbackend.service.facade.AccountService;
 import com.idiot.operationbackend.service.facade.WeChatService;
 import com.idiot.operationbackend.support.Constants;
 import com.idiot.operationbackend.support.JsonResult;
-import com.idiot.operationbackend.support.wechat.WXBizMsgCrypt;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
-import org.dom4j.Document;
-import org.dom4j.Element;
-import org.dom4j.io.SAXReader;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -38,6 +36,8 @@ public class WeChatController {
     private WeChatService weChatService;
 
 
+
+
     @GetMapping("preAuth")
     @ApiOperation(value = "获取预授权码地址,微信认证公众号")
     public ResponseEntity<JsonResult<String>> getPreAuthUrl ()   {
@@ -81,7 +81,40 @@ public class WeChatController {
     @ApiOperation(value = "授权地址回调")
     public String authCallBack(@RequestParam(name = "auth_code") String authCode,
                                @RequestParam(name = "expires_in") String expiresIn)  {
-        return "";
+        logger.info("微信授权回调 ------->start,authCode is :{},expiresIn:{}",authCode,expiresIn);
+        try {
+            String authorizationInfoStr =  weChatService.getAuthorizationInfo(authCode);
+            JSONObject authorizationInfoObj = JSONObject.parseObject(authorizationInfoStr);
+            JSONObject authorizationInfo = authorizationInfoObj.getJSONObject("authorization_info");
+
+            String authorizerAppId = authorizationInfo.getString("authorizer_appid");
+            String authorizerInfoStr = weChatService.getAuthorizerInfo(authorizerAppId);
+            JSONObject authorizerInfoObj = JSONObject.parseObject(authorizerInfoStr);
+
+            Account account = new Account(authorizerAppId);
+            String authorizerAccessToken = authorizationInfo.getString("authorizer_access_token");
+            account.setAuthorizerAccessToken(authorizerAccessToken);
+            account.setExpiresIn(authorizationInfo.getInteger("expires_in"));
+            account.setAuthorizerRefreshToken(authorizationInfo.getString("authorizer_refresh_token"));
+
+            JSONObject authorizerInfo = authorizerInfoObj.getJSONObject("authorizer_info");
+            account.setHeadImg(authorizerInfo.getString("head_img"));
+            account.setNickName(authorizerInfo.getString("nick_name"));
+            account.setServiceTypeInfo(authorizerInfo.getJSONObject("service_type_info").toJSONString());
+            account.setVerifyTypeInfo(authorizerInfo.getJSONObject("verify_type_info").toJSONString());
+            account.setNickName(authorizerInfo.getString("user_name"));
+            account.setPrincipalName(authorizerInfo.getString("principal_name"));
+            account.setBusinessInfo(authorizerInfo.getJSONObject("business_info").toJSONString());
+            account.setAlias(authorizerInfo.getString("alias"));
+            account.setQrcodeUrl(authorizerInfo.getString("qrcode_url"));
+            boolean ifResult = weChatService.saveOrUpdateWechatAcc(account);
+            weChatService.cacheAuthorizerAccessToken(account.getId(),authorizerAccessToken);
+        }catch (Exception e) {
+            logger.error("微信授权回调 ------->失败,authCode is :{},expiresIn:{},error message is :{}",authCode,expiresIn,e.getMessage());
+            return Constants.SUCCESS;
+        }
+
+        return Constants.SUCCESS;
     }
 
 

+ 32 - 2
operation-backend/src/main/java/com/idiot/operationbackend/entity/Account.java

@@ -16,6 +16,14 @@ public class Account {
     @TableId
     private String id;
 
+    private String authorizerAppId;
+
+    private String authorizerAccessToken;
+
+    private String authorizerRefreshToken;
+
+    private int expiresIn;
+
     private String nickName;
 
     private String headImg;
@@ -38,9 +46,7 @@ public class Account {
 
     private String createUserId;
 
-    private String authorizerAppId;
 
-    private String authorizerAccessToken;
 
     /**
      * 粉丝数量
@@ -54,6 +60,14 @@ public class Account {
     @TableField(exist = false)
     private Integer interactFansNum;
 
+
+    public Account() {
+    }
+
+    public Account(String authorizerAppId) {
+        this.authorizerAppId = authorizerAppId;
+    }
+
     public String getId() {
         return id;
     }
@@ -62,6 +76,22 @@ public class Account {
         this.id = id;
     }
 
+    public String getAuthorizerRefreshToken() {
+        return authorizerRefreshToken;
+    }
+
+    public void setAuthorizerRefreshToken(String authorizerRefreshToken) {
+        this.authorizerRefreshToken = authorizerRefreshToken;
+    }
+
+    public int getExpiresIn() {
+        return expiresIn;
+    }
+
+    public void setExpiresIn(int expiresIn) {
+        this.expiresIn = expiresIn;
+    }
+
     public String getNickName() {
         return nickName;
     }

+ 9 - 0
operation-backend/src/main/java/com/idiot/operationbackend/service/facade/AccountService.java

@@ -8,4 +8,13 @@ import com.idiot.operationbackend.entity.Account;
  * @date Created in 17:56 2020/9/10
  */
 public interface AccountService extends IService<Account> {
+
+    /**
+     *  根据授权方appId 保存或更新
+     * @author wangxiao
+     * @date 14:49 2020/9/12
+     * @param account
+     * @return int
+     */
+    boolean saveOrUpdateAccount(Account account);
 }

+ 56 - 1
operation-backend/src/main/java/com/idiot/operationbackend/service/facade/WeChatService.java

@@ -1,7 +1,7 @@
 package com.idiot.operationbackend.service.facade;
 
+import com.idiot.operationbackend.entity.Account;
 import com.idiot.operationbackend.support.Constants;
-import com.idiot.operationbackend.support.wechat.AesException;
 import org.dom4j.Document;
 import org.dom4j.Element;
 import org.dom4j.io.SAXReader;
@@ -52,6 +52,19 @@ public interface WeChatService {
   String getComponentAccessToken ();
 
 
+  /**
+   *  获取授权方令牌
+   * @author wangxiao
+   * @date 16:00 2020/9/12 
+   * @param accountId 公众号列表id
+   * @return java.lang.String
+   */
+  String getAuthorizerAccessToken (String accountId);
+
+
+
+
+
   /**
    *  获取预授权码
    * @author wangxiao
@@ -95,6 +108,48 @@ public interface WeChatService {
   String encryptMsg(String data);
 
 
+  /**
+   *  获取微信授权信息
+   * @author wangxiao
+   * @date 10:52 2020/9/12
+   * @param authCode
+   * @return String
+   */
+  String  getAuthorizationInfo(String authCode);
+
+
+  /**
+   *  获取授权方信息
+   * @author wangxiao
+   * @date 13:14 2020/9/12
+   * @param authorizerAppId 授权方appId
+   * @return java.lang.String
+   */
+  String getAuthorizerInfo(String authorizerAppId);
+
+
+
+  /**
+   *  保存或更新 微信公众号
+   * @author wangxiao
+   * @date 16:15 2020/9/12
+   * @param account 公众号信息
+   * @return boolean
+   */
+  boolean saveOrUpdateWechatAcc(Account account);
+
+
+
+  /**
+   *  缓存authorizerAccessToken
+   * @author wangxiao
+   * @date 16:40 2020/9/12
+   * @param accountId
+   * @param authorizerAccessToken
+   * @return void
+   */
+  void cacheAuthorizerAccessToken(String accountId,String authorizerAccessToken);
+
 
   /**
    *  微信消息转换成map(非加密)

+ 14 - 0
operation-backend/src/main/java/com/idiot/operationbackend/service/impl/AccountServiceImpl.java

@@ -1,11 +1,14 @@
 package com.idiot.operationbackend.service.impl;
 
+import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.idiot.operationbackend.entity.Account;
 import com.idiot.operationbackend.mappers.AccountMapper;
 import com.idiot.operationbackend.service.facade.AccountService;
 import org.springframework.stereotype.Service;
 
+import java.util.Objects;
+
 /**
  * @author wang xiao
  * @date Created in 17:56 2020/9/10
@@ -13,4 +16,15 @@ import org.springframework.stereotype.Service;
 @Service
 public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account>
         implements AccountService {
+
+    @Override
+    public boolean saveOrUpdateAccount(Account account) {
+        Account temp = getOne(Wrappers.<Account>lambdaQuery().eq(Account::getAuthorizerAppId,account.getAuthorizerAppId()));
+        if (Objects.isNull(temp)) {
+            return save(account);
+        }else {
+            account.setId(temp.getId());
+            return saveOrUpdate(account);
+        }
+    }
 }

+ 108 - 14
operation-backend/src/main/java/com/idiot/operationbackend/service/impl/WeChatServiceImpl.java

@@ -3,6 +3,8 @@ package com.idiot.operationbackend.service.impl;
 import com.alibaba.fastjson.JSONObject;
 import com.google.common.cache.*;
 import com.idiot.operationbackend.config.PlatformProperties;
+import com.idiot.operationbackend.entity.Account;
+import com.idiot.operationbackend.service.facade.AccountService;
 import com.idiot.operationbackend.service.facade.WeChatService;
 import com.idiot.operationbackend.support.Constants;
 import com.idiot.operationbackend.support.wechat.AesException;
@@ -52,6 +54,9 @@ public class WeChatServiceImpl implements WeChatService, InitializingBean {
     @Autowired
     private PlatformProperties properties;
 
+    @Autowired
+    private AccountService accountService;
+
 
     @Override
     public String notice(Map<String, String> param) {
@@ -59,10 +64,10 @@ public class WeChatServiceImpl implements WeChatService, InitializingBean {
             return Constants.SUCCESS;
         }
         String infoType = param.get("InfoType");
-        String appId = param.get("AppId");
+        String componentAppId = param.get("AppId");
         String ticket = param.get("ComponentVerifyTicket");
-        logger.info("接受微信验证票据数据,infoType:{},appId:{},ticket:{}",infoType,appId,ticket);
-        cache.put(String.format("component_verify_ticket_%s",appId),ticket);
+        logger.info("接受微信验证票据数据,infoType:{},第三方平台appId:{},ticket:{}",infoType,componentAppId,ticket);
+        cache.put(String.format("component_verify_ticket_%s",componentAppId),ticket);
         return Constants.SUCCESS;
     }
 
@@ -90,10 +95,21 @@ public class WeChatServiceImpl implements WeChatService, InitializingBean {
         }
     }
 
+    @Override
+    public void cacheAuthorizerAccessToken(String accountId, String authorizerAccessToken) {
+        cache.put(String.format("authorizer_access_token_%s",accountId),authorizerAccessToken);
+    }
+
+    @Override
+    public boolean saveOrUpdateWechatAcc(Account account) {
+        return accountService.saveOrUpdateAccount(account);
+    }
+
     @Override
     public String getComponentAccessToken() {
-        String appId = properties.getAppId();
-        String componentAccessToken = cache.getIfPresent(String.format("component_access_token_%s",appId));
+        logger.info("获取第三方平台令牌 component_access_token start");
+        String componentAppId = properties.getAppId();
+        String componentAccessToken = cache.getIfPresent(String.format("component_access_token_%s",componentAppId));
         if ( !StringUtils.isEmpty(componentAccessToken)) {
             return componentAccessToken;
         }
@@ -101,34 +117,74 @@ public class WeChatServiceImpl implements WeChatService, InitializingBean {
         HttpHeaders headers = new HttpHeaders();
         MultiValueMap<String,String> params = new LinkedMultiValueMap<>(3);
         headers.setContentType(MediaType.APPLICATION_JSON);
-        String ticket = cache.getIfPresent(String.format("component_verify_ticket_%s",appId));
-        params.add("component_appid",appId);
+        String ticket = cache.getIfPresent(String.format("component_verify_ticket_%s",componentAppId));
+        params.add("component_appid",componentAppId);
         params.add("component_appsecret",properties.getAppSecret());
         params.add("component_verify_ticket",ticket);
         HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
         ResponseEntity<String> response = restTemplate.exchange(requestUrl, HttpMethod.POST, requestEntity, String.class);
         String  jsonStr = response.getBody();
-        logger.info("请求微信获取令牌component_access_token 请求appId:{},ticket:{},微信返回结果:{}",appId,ticket,jsonStr);
+        logger.info("请求微信获取令牌component_access_token 第三方平台appId:{},ticket:{},微信返回结果:{}",componentAppId,ticket,jsonStr);
         JSONObject jsonObject = JSONObject.parseObject(jsonStr);
         componentAccessToken = jsonObject.getString("component_access_token");
-        cache.put(String.format("component_access_token_%s",appId),componentAccessToken);
+        cache.put(String.format("component_access_token_%s",componentAppId),componentAccessToken);
         return componentAccessToken;
     }
 
+    @Override
+    public String getAuthorizerAccessToken(String accountId) {
+
+        logger.info("获取授权方令牌 authorizer_access_token start");
+        String authorizerAccessToken = cache.getIfPresent(String.format("authorizer_access_token_%s",accountId));
+        if ( !StringUtils.isEmpty(authorizerAccessToken)) {
+            return authorizerAccessToken;
+        }
+        Account account = accountService.getById(accountId);
+        if (Objects.isNull(account)) {
+            logger.error("获取授权方令牌 authorizer_access_token 发生异常===> 公众号id:{}为空",accountId);
+            return null;
+        }
+        String requestUrl = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=COMPONENT_TOKEN";
+        String componentAccessToken = getComponentAccessToken();
+        String componentAppId = properties.getAppId();
+        requestUrl = requestUrl.replace("COMPONENT_TOKEN",componentAccessToken);
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.APPLICATION_JSON);
+        MultiValueMap<String,String> params = new LinkedMultiValueMap<>(4);
+        params.add("component_appid",componentAppId);
+        params.add("component_access_token",componentAccessToken);
+        params.add("authorizer_appid",account.getAuthorizerAppId());
+        params.add("authorizer_refresh_token",account.getAuthorizerRefreshToken());
+        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
+        ResponseEntity<String> response = restTemplate.exchange(requestUrl, HttpMethod.POST, requestEntity, String.class);
+        String  jsonStr = response.getBody();
+        logger.info("获取授权方令牌 authorizer_access_token 第三方平台appId:{},公众号id:{},授权方appId:{},微信返回结果:{}",
+                componentAppId,accountId,account.getAuthorizerAppId(),jsonStr);
+        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
+        authorizerAccessToken = jsonObject.getString("authorizer_access_token");
+        String authorizerRefreshToken  = jsonObject.getString("authorizer_refresh_token");
+        account.setAuthorizerAccessToken(authorizerAccessToken);
+        account.setAuthorizerRefreshToken(authorizerRefreshToken);
+        cache.put(String.format("authorizer_access_token_%s",accountId),authorizerAccessToken);
+        accountService.saveOrUpdate(account);
+        return authorizerAccessToken;
+    }
+
     @Override
     public String getPreAuthCode() {
-        String appId = properties.getAppId();
+        String componentAppId = properties.getAppId();
+        logger.info("请求微信获取预授权码 第三方平台appId:{} start",componentAppId);
         String requestUrl =  "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=COMPONENT_ACCESS_TOKEN";
         String componentAccessToken = getComponentAccessToken();
         requestUrl = requestUrl.replace("COMPONENT_ACCESS_TOKEN",componentAccessToken);
         HttpHeaders headers = new HttpHeaders();
         MultiValueMap<String,String> params = new LinkedMultiValueMap<>(1);
-        params.add("component_appid",appId);
+        params.add("component_appid",componentAppId);
         headers.setContentType(MediaType.APPLICATION_JSON);
         HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
         ResponseEntity<String> response = restTemplate.exchange(requestUrl, HttpMethod.POST, requestEntity, String.class);
         String  jsonStr = response.getBody();
-        logger.info("请求微信获取预授权码 请求appId:{},微信返回结果:{}",appId,jsonStr);
+        logger.info("请求微信获取预授权码 第三方平台appId:{},微信返回结果:{}",componentAppId,jsonStr);
         JSONObject jsonObject = JSONObject.parseObject(jsonStr);
         return jsonObject.getString("pre_auth_code");
     }
@@ -136,9 +192,9 @@ public class WeChatServiceImpl implements WeChatService, InitializingBean {
     @Override
     public String getPreAuthUrl() {
         String preAuthUrl = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=APPID&pre_auth_code=PREAUTHCODE&redirect_uri=URI&auth_type=1";
-        String appId = properties.getAppId();
+        String componentAppId = properties.getAppId();
         String preAuthCode = getPreAuthCode();
-        preAuthUrl = preAuthUrl.replace("APPID",appId).replace("PREAUTHCODE",preAuthCode);
+        preAuthUrl = preAuthUrl.replace("APPID",componentAppId).replace("PREAUTHCODE",preAuthCode);
         logger.info("生成预授权地址, preAuthUrl is {}",preAuthUrl);
         return preAuthUrl;
     }
@@ -153,4 +209,42 @@ public class WeChatServiceImpl implements WeChatService, InitializingBean {
     }
 
 
+    @Override
+    public String getAuthorizationInfo(String authCode) {
+        String componentAppId = properties.getAppId();
+        logger.info("请求微信获取授权信息 第三方平台appId:{} start",componentAppId);
+        String requestUrl = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=COMPONENT_TOKEN";
+        String componentToken = getComponentAccessToken();
+        requestUrl = requestUrl.replace("COMPONENT_TOKEN",componentToken);
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.APPLICATION_JSON);
+        MultiValueMap<String,String> multiValueMap = new LinkedMultiValueMap<>(2);
+        multiValueMap.add("component_appid",componentAppId);
+        multiValueMap.add("authorization_code",authCode);
+        HttpEntity<MultiValueMap<String, String>>  entity = new HttpEntity<> (multiValueMap,headers);
+        ResponseEntity<String> response = restTemplate.exchange(requestUrl,HttpMethod.POST,entity,String.class);
+        String jsonStr = response.getBody();
+        logger.info("请求微信获取授权信息 第三方平台appId:{},微信返回结果:{}",componentAppId,jsonStr);
+        return jsonStr;
+    }
+
+    @Override
+    public String getAuthorizerInfo(String authorizerAppId) {
+        String componentAppId = properties.getAppId();
+        logger.info("请求微信获取授权方信息 第三方平台appId:{},授权方appId:{},start",componentAppId,authorizerAppId);
+        String requestUrl = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=COMPONENT_TOKEN";
+        String componentToken = getComponentAccessToken();
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.APPLICATION_JSON);
+        requestUrl = requestUrl.replace("COMPONENT_TOKEN",componentToken);
+        MultiValueMap<String,String> params = new LinkedMultiValueMap<>(4);
+        params.add("component_access_token",componentToken);
+        params.add("component_appid",componentAppId);
+        params.add("authorizer_appid",authorizerAppId);
+        HttpEntity<MultiValueMap<String, String>>  entity = new HttpEntity<> (params,headers);
+        ResponseEntity<String> response = restTemplate.exchange(requestUrl,HttpMethod.POST,entity,String.class);
+        String jsonStr = response.getBody();
+        logger.info("请求微信获取授权方信息 第三方平台appId:{},授权方appId:{},微信返回结果:{}",componentAppId,authorizerAppId,jsonStr);
+        return jsonStr;
+    }
 }

+ 5 - 2
sql/dataBase.sql

@@ -22,8 +22,10 @@ CREATE TABLE `t_auth_user`  (
 DROP TABLE IF EXISTS `t_account`;
 CREATE TABLE `t_account`  (
   `id` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '主键',
-  `authorizer_app_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
-  `authorizer_access_token` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
+  `authorizer_app_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '授权方appid',
+  `authorizer_access_token` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '授权方accessToken',
+  `authorizer_refresh_token` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '授权方刷新token',
+  `expires_in` int(0) NULL DEFAULT NULL COMMENT 'token过期时间',
   `nick_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '昵称',
   `head_img` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '头像',
   `service_type_info` json NULL COMMENT '公众号类型',
@@ -38,6 +40,7 @@ CREATE TABLE `t_account`  (
   `create_user_id` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '创建人',
   PRIMARY KEY (`id`) USING BTREE
 ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin COMMENT = '公众号' ROW_FORMAT = Dynamic;
+
 -- ----------------------------
 -- Table structure for 公众号粉丝
 -- ----------------------------