|
|
@@ -0,0 +1,68 @@
|
|
|
+package cn.com.ctop.job.adq.data.service.impl;
|
|
|
+
|
|
|
+import cn.com.ctop.job.adq.data.mapper.AppletTokenRefreshMapper;
|
|
|
+import cn.com.ctop.job.adq.data.service.IAppletTokenRefreshService;
|
|
|
+import cn.com.ctop.job.adq.data.utils.Check;
|
|
|
+import cn.com.ctop.job.adq.data.utils.HttpUtils;
|
|
|
+import com.alibaba.fastjson.JSONObject;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.beans.factory.annotation.Autowired;
|
|
|
+import org.springframework.data.redis.core.RedisTemplate;
|
|
|
+import org.springframework.stereotype.Service;
|
|
|
+
|
|
|
+import javax.annotation.Resource;
|
|
|
+import java.util.HashMap;
|
|
|
+import java.util.List;
|
|
|
+import java.util.Map;
|
|
|
+import java.util.concurrent.TimeUnit;
|
|
|
+
|
|
|
+@Service
|
|
|
+@Slf4j
|
|
|
+public class AppletTokenRefreshServiceImpl implements IAppletTokenRefreshService {
|
|
|
+
|
|
|
+ @Autowired
|
|
|
+ private AppletTokenRefreshMapper tokenRefreshMapper;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private RedisTemplate redis2Template_db5;
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void buildAppletTokens() {
|
|
|
+ List<JSONObject> list = tokenRefreshMapper.queryAppletList();
|
|
|
+ for (JSONObject applet : list) {
|
|
|
+ buildAppletToken(applet, 0);
|
|
|
+ }
|
|
|
+ tokenRefreshMapper.refreshAppletTokens(list);
|
|
|
+ }
|
|
|
+
|
|
|
+ //构建小程序token
|
|
|
+ private void buildAppletToken(JSONObject applet, int count) {
|
|
|
+ String name = applet.getString("name");
|
|
|
+ try {
|
|
|
+ Map<String, Object> param = new HashMap<>();
|
|
|
+ String appId = applet.getString("appId");
|
|
|
+ param.put("appid", appId);
|
|
|
+ param.put("secret", applet.getString("appSecret"));
|
|
|
+ param.put("grant_type", "client_credential");
|
|
|
+ String result = HttpUtils.httpGet("https://api.weixin.qq.com/cgi-bin/token", param, null);
|
|
|
+ JSONObject tokenInfo = JSONObject.parseObject(result);
|
|
|
+ if (!Check.isNull(tokenInfo)) {
|
|
|
+ String accessToken = tokenInfo.getString("access_token");
|
|
|
+ redis2Template_db5.opsForValue().set("wechat-applet-access-token-key-" + applet.getInteger("id"), accessToken, 60, TimeUnit.MINUTES);
|
|
|
+ applet.put("token", accessToken);
|
|
|
+ log.info("小程序:{},更新token完成", name);
|
|
|
+ } else {
|
|
|
+ if (count < 3) {
|
|
|
+ Thread.sleep(5000L);
|
|
|
+ buildAppletToken(applet, count + 1);
|
|
|
+ } else {
|
|
|
+ log.error("小程序:{},更新token失败!,结果:{}", name, tokenInfo);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ } catch (Exception e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ log.error("小程序:{},更新token异常!", name);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+}
|