package com.zy.asrs.task; import com.alibaba.fastjson.JSONObject; import com.core.common.Cools; import com.zy.asrs.mapper.ErpTokenMapper; import com.zy.common.utils.HttpHandler; import com.zy.system.entity.Config; import com.zy.system.service.ConfigService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.net.URI; import java.util.Date; import java.util.HashMap; import java.util.Map; @Slf4j @Component public class ErpTokenScheduler { @Autowired private ErpTokenMapper erpTokenMapper; @Autowired private ConfigService configService; @Scheduled(fixedDelay = 7200 * 1000) public void refreshToken() { try { String appId = getConfigValue("ErpAppId", "jxlk"); String appSecrect = getConfigValue("ErpAppSecrect", "jxlk123@jxlk"); String url = getConfigValue("ErpTokenUrl", "http://127.0.0.1:8080/thb-cloud/rest"); URI uri = URI.create(url); String host = uri.getHost(); int port = uri.getPort(); String scheme = uri.getScheme(); String path = uri.getRawPath(); if (Cools.isEmpty(host) || Cools.isEmpty(scheme) || Cools.isEmpty(path)) { log.error("ERP token接口地址配置错误:{}", url); return; } String base = host + (port > 0 ? ":" + port : ""); Map params = new HashMap<>(); params.put("funid", "rest_app"); params.put("eventcode", "get_token"); params.put("user_code", appId); params.put("appid", appId); params.put("appsecret", appSecrect); String resp = new HttpHandler.Builder() .setUri(base) .setHttps("https".equalsIgnoreCase(scheme)) .setPath(path) .setParams(params) .build() .doPost(); if (Cools.isEmpty(resp)) { log.error("ERP token获取失败:空响应"); return; } JSONObject result = JSONObject.parseObject(resp); Boolean success = result.getBoolean("success"); if (!Boolean.TRUE.equals(success)) { log.error("ERP token获取失败:{}", result.getString("message")); return; } JSONObject data = result.getJSONObject("data"); String token = data == null ? null : data.getString("access_token"); if (Cools.isEmpty(token)) { log.error("ERP token获取失败:响应未包含access_token"); return; } Date now = new Date(); erpTokenMapper.upsertToken(appId, appSecrect, token, now); log.info("ERP token刷新成功,appId={}, modiTime={}", appId, now); } catch (Exception e) { log.error("ERP token刷新异常", e); } } private String getConfigValue(String code, String defaultValue) { try { Config config = configService.selectConfigByCode(code); if (config != null && !Cools.isEmpty(config.getValue())) { return String.valueOf(config.getValue()).trim(); } } catch (Exception ignored) { } return defaultValue; } }