Skip to content

Commit c33ee14

Browse files
authored
🆕 binarywang#2998 【小程序】增加获取稳定版接口调用凭据的接口,通过设置WxMaConfig#useStableAccessToken方法去开启使用稳定版接口
1 parent 24c18b8 commit c33ee14

File tree

11 files changed

+213
-10
lines changed

11 files changed

+213
-10
lines changed

weixin-java-miniapp/src/main/java/cn/binarywang/wx/miniapp/api/WxMaService.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ public interface WxMaService extends WxService {
2222
* 获取access_token.
2323
*/
2424
String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
25+
String GET_STABLE_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/stable_token";
26+
2527

2628
/**
2729
* The constant JSCODE_TO_SESSION_URL.

weixin-java-miniapp/src/main/java/cn/binarywang/wx/miniapp/api/impl/BaseWxMaServiceImpl.java

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,13 @@ public String getAccessToken(boolean forceRefresh) throws WxErrorException {
174174
return this.getWxMaConfig().getAccessToken();
175175
}
176176
} while (!locked);
177-
String response = doGetAccessTokenRequest();
177+
178+
String response;
179+
if (getWxMaConfig().isStableAccessToken()) {
180+
response = doGetStableAccessTokenRequest(forceRefresh);
181+
} else {
182+
response = doGetAccessTokenRequest();
183+
}
178184
return extractAccessToken(response);
179185
} catch (IOException | InterruptedException e) {
180186
throw new WxRuntimeException(e);
@@ -193,6 +199,15 @@ public String getAccessToken(boolean forceRefresh) throws WxErrorException {
193199
*/
194200
protected abstract String doGetAccessTokenRequest() throws IOException;
195201

202+
203+
/**
204+
* 通过网络请求获取稳定版接口调用凭据
205+
*
206+
* @return .
207+
* @throws IOException .
208+
*/
209+
protected abstract String doGetStableAccessTokenRequest(boolean forceRefresh) throws IOException;
210+
196211
@Override
197212
public String get(String url, String queryParam) throws WxErrorException {
198213
return execute(SimpleGetRequestExecutor.create(this), url, queryParam);

weixin-java-miniapp/src/main/java/cn/binarywang/wx/miniapp/api/impl/WxMaServiceHttpClientImpl.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package cn.binarywang.wx.miniapp.api.impl;
22

33
import cn.binarywang.wx.miniapp.api.WxMaService;
4+
import cn.binarywang.wx.miniapp.bean.WxMaStableAccessTokenRequest;
45
import cn.binarywang.wx.miniapp.config.WxMaConfig;
56
import lombok.extern.slf4j.Slf4j;
67
import me.chanjar.weixin.common.util.http.HttpType;
@@ -11,6 +12,9 @@
1112
import org.apache.http.client.config.RequestConfig;
1213
import org.apache.http.client.methods.CloseableHttpResponse;
1314
import org.apache.http.client.methods.HttpGet;
15+
import org.apache.http.client.methods.HttpPost;
16+
import org.apache.http.entity.ContentType;
17+
import org.apache.http.entity.StringEntity;
1418
import org.apache.http.impl.client.BasicResponseHandler;
1519
import org.apache.http.impl.client.CloseableHttpClient;
1620

@@ -93,4 +97,40 @@ protected String doGetAccessTokenRequest() throws IOException {
9397
}
9498
}
9599

100+
@Override
101+
protected String doGetStableAccessTokenRequest(boolean forceRefresh) throws IOException {
102+
String url = StringUtils.isNotEmpty(this.getWxMaConfig().getAccessTokenUrl()) ?
103+
this.getWxMaConfig().getAccessTokenUrl() : StringUtils.isNotEmpty(this.getWxMaConfig().getApiHostUrl()) ?
104+
GET_STABLE_ACCESS_TOKEN.replace("https://api.weixin.qq.com", this.getWxMaConfig().getApiHostUrl()) :
105+
GET_STABLE_ACCESS_TOKEN;
106+
107+
HttpPost httpPost = null;
108+
CloseableHttpResponse response = null;
109+
try {
110+
httpPost = new HttpPost(url);
111+
if (this.getRequestHttpProxy() != null) {
112+
RequestConfig config = RequestConfig.custom().setProxy(this.getRequestHttpProxy()).build();
113+
httpPost.setConfig(config);
114+
}
115+
WxMaStableAccessTokenRequest wxMaAccessTokenRequest = new WxMaStableAccessTokenRequest();
116+
wxMaAccessTokenRequest.setAppid(this.getWxMaConfig().getAppid());
117+
wxMaAccessTokenRequest.setSecret(this.getWxMaConfig().getSecret());
118+
wxMaAccessTokenRequest.setGrantType("client_credential");
119+
wxMaAccessTokenRequest.setForceRefresh(forceRefresh);
120+
httpPost.setEntity(new StringEntity(wxMaAccessTokenRequest.toJson(), ContentType.APPLICATION_JSON));
121+
response = getRequestHttpClient().execute(httpPost);
122+
return new BasicResponseHandler().handleResponse(response);
123+
} finally {
124+
if (httpPost != null) {
125+
httpPost.releaseConnection();
126+
}
127+
if (response != null) {
128+
try {
129+
response.close();
130+
} catch (IOException e) {
131+
}
132+
}
133+
}
134+
}
135+
96136
}

weixin-java-miniapp/src/main/java/cn/binarywang/wx/miniapp/api/impl/WxMaServiceJoddHttpImpl.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11
package cn.binarywang.wx.miniapp.api.impl;
22

33
import cn.binarywang.wx.miniapp.api.WxMaService;
4+
import cn.binarywang.wx.miniapp.bean.WxMaStableAccessTokenRequest;
45
import cn.binarywang.wx.miniapp.config.WxMaConfig;
56
import jodd.http.HttpConnectionProvider;
67
import jodd.http.HttpRequest;
78
import jodd.http.ProxyInfo;
89
import jodd.http.net.SocketHttpConnectionProvider;
10+
import jodd.net.MimeTypes;
911
import me.chanjar.weixin.common.util.http.HttpType;
1012
import org.apache.commons.lang3.StringUtils;
1113

1214
import java.io.IOException;
15+
import java.nio.charset.StandardCharsets;
1316

1417
/**
1518
* jodd-http方式实现.
@@ -62,4 +65,30 @@ protected String doGetAccessTokenRequest() throws IOException {
6265
return request.send().bodyText();
6366
}
6467

68+
@Override
69+
protected String doGetStableAccessTokenRequest(boolean forceRefresh) throws IOException {
70+
71+
String url = StringUtils.isNotEmpty(this.getWxMaConfig().getAccessTokenUrl()) ?
72+
this.getWxMaConfig().getAccessTokenUrl() : StringUtils.isNotEmpty(this.getWxMaConfig().getApiHostUrl()) ?
73+
GET_STABLE_ACCESS_TOKEN.replace("https://api.weixin.qq.com", this.getWxMaConfig().getApiHostUrl()) :
74+
GET_STABLE_ACCESS_TOKEN;
75+
76+
WxMaStableAccessTokenRequest wxMaAccessTokenRequest = new WxMaStableAccessTokenRequest();
77+
wxMaAccessTokenRequest.setAppid(this.getWxMaConfig().getAppid());
78+
wxMaAccessTokenRequest.setSecret(this.getWxMaConfig().getSecret());
79+
wxMaAccessTokenRequest.setGrantType("client_credential");
80+
wxMaAccessTokenRequest.setForceRefresh(forceRefresh);
81+
82+
HttpRequest request = HttpRequest.post(url)
83+
.contentType(MimeTypes.MIME_APPLICATION_JSON, StandardCharsets.UTF_8.name())
84+
.body(wxMaAccessTokenRequest.toJson());
85+
if (this.getRequestHttpProxy() != null) {
86+
SocketHttpConnectionProvider provider = new SocketHttpConnectionProvider();
87+
provider.useProxy(getRequestHttpProxy());
88+
89+
request.withConnectionProvider(provider);
90+
}
91+
return request.send().bodyText();
92+
}
93+
6594
}

weixin-java-miniapp/src/main/java/cn/binarywang/wx/miniapp/api/impl/WxMaServiceOkHttpImpl.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package cn.binarywang.wx.miniapp.api.impl;
22

33
import cn.binarywang.wx.miniapp.api.WxMaService;
4+
import cn.binarywang.wx.miniapp.bean.WxMaStableAccessTokenRequest;
45
import cn.binarywang.wx.miniapp.config.WxMaConfig;
56
import me.chanjar.weixin.common.util.http.HttpType;
67
import me.chanjar.weixin.common.util.http.okhttp.DefaultOkHttpClientBuilder;
@@ -74,4 +75,22 @@ protected String doGetAccessTokenRequest() throws IOException {
7475
return Objects.requireNonNull(response.body()).string();
7576
}
7677
}
78+
79+
@Override
80+
protected String doGetStableAccessTokenRequest(boolean forceRefresh) throws IOException {
81+
String url = StringUtils.isNotEmpty(this.getWxMaConfig().getAccessTokenUrl()) ?
82+
this.getWxMaConfig().getAccessTokenUrl() : StringUtils.isNotEmpty(this.getWxMaConfig().getApiHostUrl()) ?
83+
GET_STABLE_ACCESS_TOKEN.replace("https://api.weixin.qq.com", this.getWxMaConfig().getApiHostUrl()) :
84+
GET_STABLE_ACCESS_TOKEN;
85+
WxMaStableAccessTokenRequest wxMaAccessTokenRequest = new WxMaStableAccessTokenRequest();
86+
wxMaAccessTokenRequest.setAppid(this.getWxMaConfig().getAppid());
87+
wxMaAccessTokenRequest.setSecret(this.getWxMaConfig().getSecret());
88+
wxMaAccessTokenRequest.setGrantType("client_credential");
89+
wxMaAccessTokenRequest.setForceRefresh(forceRefresh);
90+
RequestBody body = RequestBody.Companion.create(wxMaAccessTokenRequest.toJson(), MediaType.parse("application/json; charset=utf-8"));
91+
Request request = new Request.Builder().url(url).post(body).build();
92+
try (Response response = getRequestHttpClient().newCall(request).execute()) {
93+
return Objects.requireNonNull(response.body()).string();
94+
}
95+
}
7796
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package cn.binarywang.wx.miniapp.bean;
2+
3+
import cn.binarywang.wx.miniapp.json.WxMaGsonBuilder;
4+
import com.google.gson.annotations.SerializedName;
5+
import lombok.Data;
6+
7+
import java.io.Serializable;
8+
9+
/**
10+
* 小程序码.
11+
*
12+
* @author Element
13+
* created on 2017/7/27
14+
*/
15+
@Data
16+
public class WxMaStableAccessTokenRequest implements Serializable {
17+
18+
private static final long serialVersionUID = 1L;
19+
20+
@SerializedName("grant_type")
21+
private String grantType = "client_credential";
22+
23+
@SerializedName("appid")
24+
private String appid;
25+
@SerializedName("secret")
26+
private String secret;
27+
28+
@SerializedName("force_refresh")
29+
private boolean forceRefresh;
30+
31+
public String toJson() {
32+
return WxMaGsonBuilder.create().toJson(this);
33+
}
34+
}

weixin-java-miniapp/src/main/java/cn/binarywang/wx/miniapp/config/WxMaConfig.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,13 @@ public interface WxMaConfig {
1919
*/
2020
String getAccessToken();
2121

22+
//region 稳定版access token
23+
boolean isStableAccessToken();
24+
25+
void useStableAccessToken(boolean useStableAccessToken);
26+
//endregion
27+
28+
2229
/**
2330
* Gets access token lock.
2431
*

weixin-java-miniapp/src/main/java/cn/binarywang/wx/miniapp/config/impl/WxMaDefaultConfigImpl.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import cn.binarywang.wx.miniapp.config.WxMaConfig;
44
import cn.binarywang.wx.miniapp.json.WxMaGsonBuilder;
5+
import lombok.AccessLevel;
56
import lombok.Getter;
67
import me.chanjar.weixin.common.bean.WxAccessToken;
78
import me.chanjar.weixin.common.util.http.apache.ApacheHttpClientBuilder;
@@ -19,6 +20,13 @@
1920
public class WxMaDefaultConfigImpl implements WxMaConfig {
2021
protected volatile String appid;
2122
protected volatile String token;
23+
24+
/**
25+
* 是否使用稳定版获取accessToken接口
26+
*/
27+
@Getter(value = AccessLevel.NONE)
28+
private boolean useStableAccessToken;
29+
2230
/**
2331
* 小程序原始ID
2432
*/
@@ -81,6 +89,19 @@ public void setAccessToken(String accessToken) {
8189
this.accessToken = accessToken;
8290
}
8391

92+
//region 使用稳定版接口获取accessToken
93+
@Override
94+
public boolean isStableAccessToken() {
95+
return this.useStableAccessToken;
96+
}
97+
98+
@Override
99+
public void useStableAccessToken(boolean useStableAccessToken) {
100+
this.useStableAccessToken = useStableAccessToken;
101+
}
102+
//endregion
103+
104+
84105
@Override
85106
public Lock getAccessTokenLock() {
86107
return this.accessTokenLock;

weixin-java-miniapp/src/test/java/cn/binarywang/wx/miniapp/api/impl/WxMaServiceImplTest.java

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ public class WxMaServiceImplTest {
3333

3434
@Inject
3535
private WxMaService wxService;
36+
@Inject
37+
private WxMaServiceOkHttpImpl wxMaServiceOkHttp;
3638

3739
public void testRefreshAccessToken() throws WxErrorException {
3840
WxMaConfig configStorage = this.wxService.getWxMaConfig();
@@ -44,6 +46,16 @@ public void testRefreshAccessToken() throws WxErrorException {
4446
assertTrue(StringUtils.isNotBlank(after));
4547
}
4648

49+
public void testStableRefreshAccessToken() throws WxErrorException {
50+
WxMaConfig configStorage = this.wxMaServiceOkHttp.getWxMaConfig();
51+
configStorage.useStableAccessToken(true);
52+
String before = configStorage.getAccessToken();
53+
this.wxMaServiceOkHttp.getAccessToken(false);
54+
String after = configStorage.getAccessToken();
55+
assertNotEquals(before, after);
56+
assertTrue(StringUtils.isNotBlank(after));
57+
}
58+
4759
@Test(expectedExceptions = {WxErrorException.class})
4860
public void testGetPaidUnionId() throws WxErrorException {
4961
final String unionId = this.wxService.getPaidUnionId("1", null, "3", "4");
@@ -134,7 +146,7 @@ public String getAccessToken(boolean forceRefresh) throws WxErrorException {
134146
});
135147
try {
136148
Object execute = service.execute(re, "http://baidu.com", new HashMap<>());
137-
Assert.assertTrue(false, "代码应该不会执行到这里");
149+
Assert.fail("代码应该不会执行到这里");
138150
} catch (WxErrorException e) {
139151
Assert.assertEquals(WxMpErrorMsgEnum.CODE_40001.getCode(), e.getError().getErrorCode());
140152
Assert.assertEquals(2, counter.get());

weixin-java-miniapp/src/test/java/cn/binarywang/wx/miniapp/test/ApiTestModule.java

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
package cn.binarywang.wx.miniapp.test;
22

3-
import java.io.IOException;
4-
import java.io.InputStream;
5-
import java.util.concurrent.locks.ReentrantLock;
6-
7-
import me.chanjar.weixin.common.error.WxRuntimeException;
8-
import org.slf4j.Logger;
9-
import org.slf4j.LoggerFactory;
10-
113
import cn.binarywang.wx.miniapp.api.WxMaService;
4+
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceOkHttpImpl;
125
import cn.binarywang.wx.miniapp.config.WxMaConfig;
136
import com.google.inject.Binder;
147
import com.google.inject.Module;
8+
import me.chanjar.weixin.common.error.WxRuntimeException;
9+
import org.slf4j.Logger;
10+
import org.slf4j.LoggerFactory;
11+
12+
import java.io.IOException;
13+
import java.io.InputStream;
14+
import java.util.concurrent.locks.ReentrantLock;
1515

1616
/**
1717
* @author <a href="https://github.com/binarywang">Binary Wang</a>
@@ -34,6 +34,11 @@ public void configure(Binder binder) {
3434

3535
binder.bind(WxMaService.class).toInstance(wxService);
3636
binder.bind(WxMaConfig.class).toInstance(config);
37+
38+
WxMaServiceOkHttpImpl wxMaServiceOkHttp = new cn.binarywang.wx.miniapp.api.impl.WxMaServiceOkHttpImpl();
39+
wxMaServiceOkHttp.setWxMaConfig(config);
40+
binder.bind(WxMaServiceOkHttpImpl.class).toInstance(wxMaServiceOkHttp);
41+
3742
} catch (IOException e) {
3843
this.log.error(e.getMessage(), e);
3944
}

0 commit comments

Comments
 (0)