Browse Source

Merge branch 'mp-server-test' into 'master'

Mp server test

See merge request quanshu/mp-server!664
zhong chunping 2 years ago
parent
commit
3a77aa20d8

+ 20 - 0
mp-admin/src/main/java/com/qs/mp/web/controller/common/WxServerController.java

@@ -4,6 +4,8 @@ import com.alibaba.fastjson.JSONObject;
 import com.qs.mp.channel.domain.Channel;
 import com.qs.mp.common.core.domain.AjaxResult;
 import com.qs.mp.common.core.domain.AjaxResult.Type;
+import com.qs.mp.common.enums.ErrorCodeEnum;
+import com.qs.mp.framework.service.IAppTokenService;
 import com.qs.mp.framework.service.IWxUrlLinkService;
 import com.qs.mp.utils.SecurityUtils;
 import io.swagger.annotations.Api;
@@ -30,6 +32,9 @@ public class WxServerController extends BaseApiController {
 	@Autowired
 	private IWxUrlLinkService wxUrlLinkService;
 
+	@Autowired
+	private IAppTokenService appTokenService;
+
 	@Value("${wx-user.appId}")
 	private String userAppId;
 
@@ -57,4 +62,19 @@ public class WxServerController extends BaseApiController {
 		String rst = wxUrlLinkService.generateCode("pages/lucky/index", "id=" + id, userAppId);
 		return new AjaxResult(Type.SUCCESS, "", rst);
 	}
+
+	/**
+	 * 获取小程序access_token
+	 *
+	 * @return
+	 */
+	@PostMapping("getAccessToken")
+	public AjaxResult getAccessToken(@RequestBody  JSONObject jsonObject) {
+		String appId = jsonObject.getString("appId");
+		if (StringUtils.isBlank(appId)) {
+			return AjaxResult.error(ErrorCodeEnum.ERROR_CODE_1001);
+		}
+		String rst = appTokenService.getAccessToken(appId);
+		return new AjaxResult(Type.SUCCESS, "", rst);
+	}
 }

+ 2 - 20
mp-admin/src/test/java/com/qs/mp/common/BaseControllerTest.java

@@ -1,5 +1,6 @@
 package com.qs.mp.common;
 
+import com.qs.mp.common.utils.http.MpHttpRequestUtils;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.Map;
@@ -18,26 +19,7 @@ import com.qs.mp.common.utils.sign.Md5Utils;
 public class BaseControllerTest {
 
   protected String request(String url, String params) {
-    String nonce = RandomUtils.generateString(20);
-    Date nowTime = new Date();
-    String timestamp = String.valueOf(nowTime.getTime());
-
-    String md5key = "3Jr8S1K18rcC1wAfv8";
-    String l = params + "nonce" + timestamp + md5key;
-    System.out.println("sign str:" + l);
-    String sign = Md5Utils.hash(l);
-    System.out.println("sign rst:" + sign);
-    Map<String, String> headers = new HashMap<String, String>();
-    headers.put("content-type", "application/json; charset=UTF-8");
-    headers.put("x-zz-timestamp", timestamp);
-    // 本地登录状态
-    String token = "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6Ijg3ZWM0OGMwLWQ4ZWYtNDcwYS05ZTQ5LThhOWI0NWMzOWM3MSJ9.q3l1Q0xoWBvXY6eZKfEAKXHZclb2ssMdGO4xd5IjvSNnIRdOLT8kA9jsGo8iR2KZOXjaEfN_DBxPfD6vGZpemg";
-
-    if (!StringUtils.isBlank(token)) {
-      headers.put("Authorization", "Bearer "+token);
-    }
-    String reqUrl = url + "sign=" + sign + "&nonce=" + nonce;
-    return OkHttpUtil.post(reqUrl, params, headers);
+    return MpHttpRequestUtils.request(url, params);
   }
 
   protected String upload(String url, String params, String filePath, String fileName) {

+ 38 - 0
mp-common/src/main/java/com/qs/mp/common/utils/http/MpHttpRequestUtils.java

@@ -0,0 +1,38 @@
+package com.qs.mp.common.utils.http;
+
+import com.qs.mp.common.utils.RandomUtils;
+import com.qs.mp.common.utils.sign.Md5Utils;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+import org.apache.commons.lang3.StringUtils;
+
+/**
+ * @author zhongcp
+ * @Date 2022/6/2
+ */
+public class MpHttpRequestUtils {
+  public static String request(String url, String params) {
+    String nonce = RandomUtils.generateString(20);
+    Date nowTime = new Date();
+    String timestamp = String.valueOf(nowTime.getTime());
+
+    String md5key = "3Jr8S1K18rcC1wAfv8";
+    String l = params + "nonce" + timestamp + md5key;
+    System.out.println("sign str:" + l);
+    String sign = Md5Utils.hash(l);
+    System.out.println("sign rst:" + sign);
+    Map<String, String> headers = new HashMap<String, String>();
+    headers.put("content-type", "application/json; charset=UTF-8");
+    headers.put("x-zz-timestamp", timestamp);
+    // 本地登录状态
+    String token = "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6Ijg3ZWM0OGMwLWQ4ZWYtNDcwYS05ZTQ5LThhOWI0NWMzOWM3MSJ9.q3l1Q0xoWBvXY6eZKfEAKXHZclb2ssMdGO4xd5IjvSNnIRdOLT8kA9jsGo8iR2KZOXjaEfN_DBxPfD6vGZpemg";
+
+    if (!StringUtils.isBlank(token)) {
+      headers.put("Authorization", "Bearer "+token);
+    }
+    String reqUrl = url + "sign=" + sign + "&nonce=" + nonce;
+    return OkHttpUtil.post(reqUrl, params, headers);
+  }
+
+}

+ 1 - 0
mp-framework/src/main/java/com/qs/mp/framework/config/SecurityConfig.java

@@ -132,6 +132,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter
                         HttpMethod.POST,
                     "/api/v1/mp/wx/urlschema/generate",
                     "/api/v1/mp/wx/code/generate",
+                    "/api/v1/mp/wx/getAccessToken",
                     "/api/v1/mp/user/ticket/queryLuckyNum",
                     "/api/v1/mp/user/ticket/hitPrizeBarrage",
                     "/api/v1/mp/user/mall/ticket/detail",

+ 62 - 42
mp-service/src/main/java/com/qs/mp/framework/service/impl/AppTokenServiceImpl.java

@@ -2,20 +2,25 @@ package com.qs.mp.framework.service.impl;
 
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
+import com.qs.mp.common.core.redis.RedisCache;
+import com.qs.mp.common.enums.ServerEnvEnum;
 import com.qs.mp.common.exception.ServiceException;
 import com.qs.mp.common.utils.DateUtils;
 import com.qs.mp.common.utils.LogUtil;
 import com.qs.mp.common.utils.StringUtils;
 import com.qs.mp.common.utils.http.HttpUtils;
+import com.qs.mp.common.utils.http.MpHttpRequestUtils;
 import com.qs.mp.framework.domain.AppToken;
 import com.qs.mp.framework.mapper.AppTokenMapper;
 import com.qs.mp.framework.redis.RedisKey;
 import com.qs.mp.framework.redis.RedisUtil;
 import com.qs.mp.framework.service.IAppTokenService;
 import java.util.Date;
+import java.util.concurrent.TimeUnit;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
 
 @Service
@@ -28,7 +33,10 @@ public class AppTokenServiceImpl implements IAppTokenService {
 
 
   @Autowired
-  private RedisUtil redis;
+  private RedisCache redisCache;
+
+  @Value(value = "${server.env}")
+  private String env;
 
   @Override
   public AppToken selectByPrimaryKey(String appId) {
@@ -37,56 +45,60 @@ public class AppTokenServiceImpl implements IAppTokenService {
 
   @Override
   public String getAccessToken(String appId) {
-//    String cacheKey = RedisKey.build(RedisKey.WX_APP_TOKEN_KEY, appId);
+    String cacheKey = RedisKey.build(RedisKey.WX_APP_TOKEN_KEY, appId);
 
-//    boolean updateCache = false;
+    String resToken = "";
+    Object object = redisCache.getCacheObject(cacheKey);
+    if (null != object && object instanceof String) {
+      resToken = String.valueOf(object);
+    }
+    if (StringUtils.isNotBlank(resToken)) {
+      return resToken;
+    }
 
-//    String appInfo = redis.get(cacheKey);
-    AppToken token = null;
-//    if (StringUtils.isBlank(appInfo)) {
-      token = selectByPrimaryKey(appId);
-    /*  if (null == token) {
+    if (ServerEnvEnum.PROD.getCode().equals(env)) {
+      AppToken token = selectByPrimaryKey(appId);
+      if (null == token) {
         LogUtil.error(logger, "app_token记录不存在,appId:{0}", appId);
         throw new ServiceException();
       }
-      updateCache = true;
-    } else {
-      token = JSON.parseObject(appInfo, AppToken.class);
-    }
-*/
+
    // LogUtil.info(logger, "token: {0}", JSON.toJSONString(token));
-   // if (token.getExpireTimestamp().getTime() < System.currentTimeMillis()) {
-      String res = wxGetAccessToken(appId, token.getAppSecret());
-      if (StringUtils.isEmpty(res)) {
-        LogUtil.error(logger, "获取access_token为空,appId:{0}, res:{1}", appId,
-            res);
-        throw new ServiceException();
+    if (new Date().after(token.getExpireTimestamp())) {
+        String res = wxGetAccessToken(appId, token.getAppSecret());
+        if (StringUtils.isEmpty(res)) {
+          LogUtil.error(logger, "获取access_token为空,appId:{0}, res:{1}", appId,
+              res);
+          throw new ServiceException();
+        }
+        JSONObject jsonObject = JSONObject.parseObject(res);
+        String accessToken = jsonObject.getString("access_token");
+
+        Integer expiresIn = jsonObject.getInteger("expires_in");
+        if (StringUtils.isEmpty(accessToken)) {
+          LogUtil.error(logger, "获取access_token为空,appId:{0}, res:{1}",
+              appId, res);
+          throw new ServiceException("access_token获取为空");
+        }
+        token.setAccessToken(accessToken);
+        // 防止时间不同步,此处提前600s超时
+        token.setExpireTimestamp(DateUtils.addSeconds(new Date(), expiresIn - 600));
+        appTokenMapper.updateByPrimaryKeySelective(token);
       }
+      resToken = token.getAccessToken();
+    } else {
+      // 线下环境,从生产环境获取
+      String res = getAccessTokenFromProd(appId);
       JSONObject jsonObject = JSONObject.parseObject(res);
-      String accessToken = jsonObject.getString("access_token");
-      return accessToken;
-      /*Integer expiresIn = jsonObject.getInteger("expires_in");
-      if (StringUtils.isEmpty(accessToken)) {
-        LogUtil.error(logger, "获取access_token为空,appId:{0}, res:{1}",
-            appId, res);
-        throw new ServiceException();
+      int code = jsonObject.getInteger("code");
+      if (code != 0) {
+        LogUtil.error(logger, "获取accessToken失败,appId:{0},res:{1}",new Object[]{appId, res});
+        throw new ServiceException("获取accessToken失败");
       }
-      token.setAccessToken(accessToken);
-      // 防止时间不同步,此处提前100s超时
-      token.setExpireTimestamp(DateUtils.addSeconds(new Date(), expiresIn - 100));
-      appTokenMapper.updateByPrimaryKeySelective(token);*/
- //     updateCache = true;
-
-   // }
-/*
-    if (updateCache) {
-      boolean result = redis.set(cacheKey, JSON.toJSONString(token));
-      if (!result) {
-        LogUtil.error(logger, "appsecret key set error.cacheKey:", cacheKey);
-      }
-    }*/
-
-   // return token.getAccessToken();
+      resToken = jsonObject.getString("data");
+    }
+    redisCache.setCacheObject(cacheKey, resToken, 1, TimeUnit.MINUTES);
+    return resToken;
   }
 
   private String wxGetAccessToken(String appId, String appSecret) {
@@ -96,4 +108,12 @@ public class AppTokenServiceImpl implements IAppTokenService {
 
   }
 
+  private String getAccessTokenFromProd(String appId) {
+    String params = "{\"appId\":\"" + appId + "\"}";
+    String url = "https://mp-api.51jiazhu.com/api/v1/mp/wx/getAccessToken?";
+    String res = MpHttpRequestUtils.request(url, params);
+    LogUtil.info(logger, "获取accessToken结果:" + res);
+    return res;
+  }
+
 }