|
17 | 17 | import org.apache.hc.core5.http.HttpHost; |
18 | 18 |
|
19 | 19 | import java.io.IOException; |
| 20 | +import java.util.concurrent.locks.Lock; |
20 | 21 |
|
21 | 22 | /** |
22 | 23 | * The type Wx cp service apache http client. |
@@ -75,6 +76,51 @@ public String getAccessToken(boolean forceRefresh) throws WxErrorException { |
75 | 76 | return this.configStorage.getAccessToken(); |
76 | 77 | } |
77 | 78 |
|
| 79 | + @Override |
| 80 | + public String getMsgAuditAccessToken(boolean forceRefresh) throws WxErrorException { |
| 81 | + if (!this.configStorage.isMsgAuditAccessTokenExpired() && !forceRefresh) { |
| 82 | + return this.configStorage.getMsgAuditAccessToken(); |
| 83 | + } |
| 84 | + |
| 85 | + Lock lock = this.configStorage.getMsgAuditAccessTokenLock(); |
| 86 | + lock.lock(); |
| 87 | + try { |
| 88 | + // 拿到锁之后,再次判断一下最新的token是否过期,避免重刷 |
| 89 | + if (!this.configStorage.isMsgAuditAccessTokenExpired() && !forceRefresh) { |
| 90 | + return this.configStorage.getMsgAuditAccessToken(); |
| 91 | + } |
| 92 | + // 使用会话存档secret获取access_token |
| 93 | + String msgAuditSecret = this.configStorage.getMsgAuditSecret(); |
| 94 | + if (msgAuditSecret == null || msgAuditSecret.trim().isEmpty()) { |
| 95 | + throw new WxErrorException("会话存档secret未配置"); |
| 96 | + } |
| 97 | + String url = String.format(this.configStorage.getApiUrl(WxCpApiPathConsts.GET_TOKEN), |
| 98 | + this.configStorage.getCorpId(), msgAuditSecret); |
| 99 | + |
| 100 | + try { |
| 101 | + HttpGet httpGet = new HttpGet(url); |
| 102 | + if (this.httpProxy != null) { |
| 103 | + RequestConfig config = RequestConfig.custom() |
| 104 | + .setProxy(this.httpProxy).build(); |
| 105 | + httpGet.setConfig(config); |
| 106 | + } |
| 107 | + String resultContent = getRequestHttpClient().execute(httpGet, BasicResponseHandler.INSTANCE); |
| 108 | + WxError error = WxError.fromJson(resultContent, WxType.CP); |
| 109 | + if (error.getErrorCode() != 0) { |
| 110 | + throw new WxErrorException(error); |
| 111 | + } |
| 112 | + |
| 113 | + WxAccessToken accessToken = WxAccessToken.fromJson(resultContent); |
| 114 | + this.configStorage.updateMsgAuditAccessToken(accessToken.getAccessToken(), accessToken.getExpiresIn()); |
| 115 | + } catch (IOException e) { |
| 116 | + throw new WxRuntimeException(e); |
| 117 | + } |
| 118 | + } finally { |
| 119 | + lock.unlock(); |
| 120 | + } |
| 121 | + return this.configStorage.getMsgAuditAccessToken(); |
| 122 | + } |
| 123 | + |
78 | 124 | @Override |
79 | 125 | public void initHttp() { |
80 | 126 | HttpComponentsClientBuilder apacheHttpClientBuilder = DefaultHttpComponentsClientBuilder.get(); |
|
0 commit comments