package com.xcgl.weixin.service; import cn.com.lzt.common.util.HttpClientUtils; import com.alibaba.fastjson.JSONObject; import org.apache.log4j.Logger; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import javax.annotation.PostConstruct; import java.util.*; /** * 微信全局 token 服务 */ @Service @EnableScheduling public class WxTokenServiceImpl implements WxTokenService { private Logger logger = Logger.getLogger(this.getClass()); private final static String wxmpid = "gh_53113f0bc7d4"; private String accessToken = null; private long expireTime = 0; private boolean isLocal = false; // accessToken是否来自本地生产 private String wxTokenUrl = "http://www.shenqin.work/api/wx/getAccessToken"; @PostConstruct private void init() { if (StringUtils.isEmpty(wxTokenUrl)) { isLocal = true; } } public String getSkey() { return this.accessToken; } private boolean isNeedRefresh() { long now = Calendar.getInstance().getTimeInMillis() / 1000; return expireTime - now <= 10; } // @Scheduled(fixedRate = 1000 * 10) private void checkRemoteAccessToken() { logger.debug("checkRemoteAccessToken"); if (this.isLocal) { return; } if (!isNeedRefresh()) { return; } Map params = new HashMap<>(); params.put("wxmpid", wxmpid); try { String ret = HttpClientUtils.sendHttpPost(wxTokenUrl, params); JSONObject jsonObject = JSONObject.parseObject(ret); JSONObject data = jsonObject.getJSONObject("data"); this.accessToken = data.getString("accessToken"); this.expireTime = data.getLong("expireTime"); logger.info("refreshed accessToken=" + this.accessToken + " expireTime=" + this.expireTime); } catch (Exception e) { e.printStackTrace(); } } }