Skip to content

Commit 0d6712f

Browse files
committed
issue binarywang#39 公众号添加oauth2的支持
1 parent 8e4077e commit 0d6712f

11 files changed

Lines changed: 267 additions & 80 deletions

File tree

‎weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpConfigStorage.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ public interface WxMpConfigStorage {
2525

2626
public int getExpiresIn();
2727

28-
public String getOauth2redirectUrl();
28+
public String getOauth2redirectUri();
2929

3030
public String getHttp_proxy_host();
3131

‎weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpInMemoryConfigStorage.java‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ public class WxMpInMemoryConfigStorage implements WxMpConfigStorage {
2020
protected int http_proxy_port;
2121
protected String http_proxy_username;
2222
protected String http_proxy_password;
23-
protected String oauth2redirectUrl;
23+
protected String oauth2redirectUri;
2424

2525
public void updateAccessToken(WxAccessToken accessToken) {
2626
updateAccessToken(accessToken.getAccessToken(), accessToken.getExpiresIn());
@@ -80,12 +80,12 @@ public void setExpiresIn(int expiresIn) {
8080
}
8181

8282
@Override
83-
public String getOauth2redirectUrl() {
84-
return this.oauth2redirectUrl;
83+
public String getOauth2redirectUri() {
84+
return this.oauth2redirectUri;
8585
}
8686

87-
public void setOauth2redirectUrl(String oauth2redirectUrl) {
88-
this.oauth2redirectUrl = oauth2redirectUrl;
87+
public void setOauth2redirectUri(String oauth2redirectUri) {
88+
this.oauth2redirectUri = oauth2redirectUri;
8989
}
9090

9191
public String getHttp_proxy_host() {

‎weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpServiceImpl.java‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,11 @@
2727
import org.apache.http.client.config.RequestConfig;
2828
import org.apache.http.client.methods.CloseableHttpResponse;
2929
import org.apache.http.client.methods.HttpGet;
30-
import org.apache.http.client.utils.URIUtils;
3130
import org.apache.http.impl.client.BasicCredentialsProvider;
3231
import org.apache.http.impl.client.BasicResponseHandler;
3332
import org.apache.http.impl.client.CloseableHttpClient;
3433
import org.apache.http.impl.client.HttpClients;
3534

36-
import javax.print.DocFlavor;
3735
import java.io.File;
3836
import java.io.IOException;
3937
import java.io.InputStream;
@@ -303,7 +301,7 @@ public WxMpSemanticQueryResult semanticQuery(WxMpSemanticQuery semanticQuery) th
303301
public String oauth2buildAuthorizationUrl(String scope, String state) {
304302
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" ;
305303
url += "appid=" + wxMpConfigStorage.getAppId();
306-
url += "&redirect_uri=" + URIUtil.encodeURIComponent(wxMpConfigStorage.getOauth2redirectUrl());
304+
url += "&redirect_uri=" + URIUtil.encodeURIComponent(wxMpConfigStorage.getOauth2redirectUri());
307305
url += "&response_type=code";
308306
url += "&scope=" + scope;
309307
if (state != null) {

‎weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpOAuth2AccessToken.java‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package me.chanjar.weixin.mp.bean.result;
22

33
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
4+
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
45

56
/**
67
* Created by qianjia on 14/11/26.
@@ -58,7 +59,17 @@ public void setExpiresIn(int expiresIn) {
5859
}
5960

6061
public static WxMpOAuth2AccessToken fromJson(String json) {
61-
return WxGsonBuilder.create().fromJson(json, WxMpOAuth2AccessToken.class);
62+
return WxMpGsonBuilder.create().fromJson(json, WxMpOAuth2AccessToken.class);
6263
}
6364

65+
@Override
66+
public String toString() {
67+
return "WxMpOAuth2AccessToken{" +
68+
"accessToken='" + accessToken + '\'' +
69+
", expiresIn=" + expiresIn +
70+
", refreshToken='" + refreshToken + '\'' +
71+
", openId='" + openId + '\'' +
72+
", scope='" + scope + '\'' +
73+
'}';
74+
}
6475
}

‎weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUser.java‎

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
*/
1010
public class WxMpUser {
1111

12-
protected boolean subscribe;
12+
protected Boolean subscribe;
1313
protected String openId;
1414
protected String nickname;
1515
protected String sex;
@@ -18,13 +18,13 @@ public class WxMpUser {
1818
protected String province;
1919
protected String country;
2020
protected String headImgUrl;
21-
protected long subscribeTime;
21+
protected Long subscribeTime;
2222
protected String unionId;
2323

24-
public boolean isSubscribe() {
24+
public Boolean isSubscribe() {
2525
return subscribe;
2626
}
27-
public void setSubscribe(boolean subscribe) {
27+
public void setSubscribe(Boolean subscribe) {
2828
this.subscribe = subscribe;
2929
}
3030
public String getOpenId() {
@@ -75,10 +75,10 @@ public String getHeadImgUrl() {
7575
public void setHeadImgUrl(String headImgUrl) {
7676
this.headImgUrl = headImgUrl;
7777
}
78-
public long getSubscribeTime() {
78+
public Long getSubscribeTime() {
7979
return subscribeTime;
8080
}
81-
public void setSubscribeTime(long subscribeTime) {
81+
public void setSubscribeTime(Long subscribeTime) {
8282
this.subscribeTime = subscribeTime;
8383
}
8484
public String getUnionId() {
@@ -91,5 +91,21 @@ public void setUnionId(String unionId) {
9191
public static WxMpUser fromJson(String json) {
9292
return WxMpGsonBuilder.INSTANCE.create().fromJson(json, WxMpUser.class);
9393
}
94-
94+
95+
@Override
96+
public String toString() {
97+
return "WxMpUser{" +
98+
"subscribe=" + subscribe +
99+
", openId='" + openId + '\'' +
100+
", nickname='" + nickname + '\'' +
101+
", sex='" + sex + '\'' +
102+
", language='" + language + '\'' +
103+
", city='" + city + '\'' +
104+
", province='" + province + '\'' +
105+
", country='" + country + '\'' +
106+
", headImgUrl='" + headImgUrl + '\'' +
107+
", subscribeTime=" + subscribeTime +
108+
", unionId='" + unionId + '\'' +
109+
'}';
110+
}
95111
}

‎weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpGsonBuilder.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import com.google.gson.GsonBuilder;
55
import me.chanjar.weixin.mp.bean.*;
66
import me.chanjar.weixin.mp.bean.result.*;
7+
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
78

89
public class WxMpGsonBuilder {
910

@@ -24,6 +25,7 @@ public class WxMpGsonBuilder {
2425
INSTANCE.registerTypeAdapter(WxMpQrCodeTicket.class, new WxQrCodeTicketAdapter());
2526
INSTANCE.registerTypeAdapter(WxMpTemplateMessage.class, new WxMpTemplateMessageGsonAdapter());
2627
INSTANCE.registerTypeAdapter(WxMpSemanticQueryResult.class, new WxMpSemanticQueryResultAdapter());
28+
INSTANCE.registerTypeAdapter(WxMpOAuth2AccessToken.class, new WxMpOAuth2AccessTokenAdapter());
2729
}
2830

2931
public static Gson create() {
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package me.chanjar.weixin.mp.util.json;
2+
3+
import com.google.gson.*;
4+
import me.chanjar.weixin.common.bean.WxAccessToken;
5+
import me.chanjar.weixin.common.util.json.GsonHelper;
6+
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
7+
8+
import java.lang.reflect.Type;
9+
10+
/**
11+
* Created by qianjia on 14/11/28.
12+
*/
13+
public class WxMpOAuth2AccessTokenAdapter implements JsonDeserializer<WxMpOAuth2AccessToken> {
14+
15+
public WxMpOAuth2AccessToken deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws
16+
JsonParseException {
17+
WxMpOAuth2AccessToken accessToken = new WxMpOAuth2AccessToken();
18+
JsonObject accessTokenJsonObject = json.getAsJsonObject();
19+
20+
if (accessTokenJsonObject.get("access_token") != null && !accessTokenJsonObject.get("access_token").isJsonNull()) {
21+
accessToken.setAccessToken(GsonHelper.getAsString(accessTokenJsonObject.get("access_token")));
22+
}
23+
if (accessTokenJsonObject.get("expires_in") != null && !accessTokenJsonObject.get("expires_in").isJsonNull()) {
24+
accessToken.setExpiresIn(GsonHelper.getAsPrimitiveInt(accessTokenJsonObject.get("expires_in")));
25+
}
26+
if (accessTokenJsonObject.get("refresh_token") != null && !accessTokenJsonObject.get("refresh_token").isJsonNull()) {
27+
accessToken.setRefreshToken(GsonHelper.getAsString(accessTokenJsonObject.get("refresh_token")));
28+
}
29+
if (accessTokenJsonObject.get("openid") != null && !accessTokenJsonObject.get("openid").isJsonNull()) {
30+
accessToken.setOpenId(GsonHelper.getAsString(accessTokenJsonObject.get("openid")));
31+
}
32+
if (accessTokenJsonObject.get("scope") != null && !accessTokenJsonObject.get("scope").isJsonNull()) {
33+
accessToken.setScope(GsonHelper.getAsString(accessTokenJsonObject.get("scope")));
34+
}
35+
return accessToken;
36+
}
37+
38+
}
Lines changed: 110 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,127 @@
11
package me.chanjar.weixin.mp.demo;
22

3+
import me.chanjar.weixin.common.api.WxConsts;
4+
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
5+
import me.chanjar.weixin.common.exception.WxErrorException;
6+
import me.chanjar.weixin.mp.api.*;
7+
import me.chanjar.weixin.mp.bean.WxMpMpXmlOutImageMessage;
8+
import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
9+
import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage;
10+
import me.chanjar.weixin.mp.bean.WxMpXmlOutTextMessage;
311
import org.eclipse.jetty.server.Server;
4-
import org.eclipse.jetty.servlet.ServletHandler;
12+
import org.eclipse.jetty.servlet.*;
13+
14+
import javax.xml.bind.JAXBException;
15+
import java.io.IOException;
16+
import java.io.InputStream;
17+
import java.util.Map;
518

619
/**
720
* @author Daniel Qian
821
*/
922
public class WxMpDemoServer {
23+
24+
private static WxMpConfigStorage wxMpConfigStorage;
25+
private static WxMpService wxMpService;
26+
private static WxMpMessageRouter wxMpMessageRouter;
27+
1028
public static void main(String[] args) throws Exception {
29+
initWeixin();
30+
1131
Server server = new Server(8080);
1232

1333
ServletHandler handler = new ServletHandler();
14-
server.setHandler(handler);
1534

16-
handler.addServletWithMapping(WxMpDemoServlet.class, "/*");
35+
ServletHolder endpointServletHolder = new ServletHolder(new WxMpEndpointServlt(wxMpConfigStorage, wxMpService, wxMpMessageRouter));
36+
handler.addServletWithMapping(endpointServletHolder, "/*");
37+
38+
ServletHolder oauthServletHolder = new ServletHolder(new WxMpOAuth2Servlet(wxMpService));
39+
handler.addServletWithMapping(oauthServletHolder, "/oauth2/*");
40+
41+
server.setHandler(handler);
1742
server.start();
1843
server.join();
1944
}
45+
46+
private static void initWeixin() {
47+
try {
48+
InputStream is1 = ClassLoader.getSystemResourceAsStream("test-config.xml");
49+
WxMpDemoInMemoryConfigStorage config = WxMpDemoInMemoryConfigStorage.fromXml(is1);
50+
51+
wxMpConfigStorage = config;
52+
wxMpService = new WxMpServiceImpl();
53+
wxMpService.setWxMpConfigStorage(config);
54+
55+
WxMpMessageHandler textHandler = new WxMpMessageHandler() {
56+
@Override
57+
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context,
58+
WxMpService wxMpService) {
59+
WxMpXmlOutTextMessage m
60+
= WxMpXmlOutMessage.TEXT().content("测试加密消息").fromUser(wxMessage.getToUserName())
61+
.toUser(wxMessage.getFromUserName()).build();
62+
return m;
63+
}
64+
};
65+
66+
WxMpMessageHandler imageHandler = new WxMpMessageHandler() {
67+
@Override
68+
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context,
69+
WxMpService wxMpService) {
70+
try {
71+
WxMediaUploadResult wxMediaUploadResult = wxMpService
72+
.mediaUpload(WxConsts.MEDIA_IMAGE, WxConsts.FILE_JPG, ClassLoader.getSystemResourceAsStream("mm.jpeg"));
73+
WxMpMpXmlOutImageMessage m
74+
= WxMpXmlOutMessage
75+
.IMAGE()
76+
.mediaId(wxMediaUploadResult.getMediaId())
77+
.fromUser(wxMessage.getToUserName())
78+
.toUser(wxMessage.getFromUserName())
79+
.build();
80+
return m;
81+
} catch (WxErrorException e) {
82+
e.printStackTrace();
83+
} catch (IOException e) {
84+
e.printStackTrace();
85+
}
86+
return null;
87+
}
88+
};
89+
90+
WxMpMessageHandler oauth2handler = new WxMpMessageHandler() {
91+
@Override
92+
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context,
93+
WxMpService wxMpService) {
94+
String href = "<a href=\"" + wxMpService.oauth2buildAuthorizationUrl(WxConsts.OAUTH2_SCOPE_USER_INFO, null)
95+
+ "\">测试oauth2</a>";
96+
return WxMpXmlOutMessage
97+
.TEXT()
98+
.content(href)
99+
.fromUser(wxMessage.getToUserName())
100+
.toUser(wxMessage.getFromUserName()).build();
101+
}
102+
};
103+
104+
wxMpMessageRouter = new WxMpMessageRouter(wxMpService);
105+
wxMpMessageRouter
106+
.rule()
107+
.async(false)
108+
.content("哈哈") // 拦截内容为“哈哈”的消息
109+
.handler(textHandler)
110+
.end()
111+
.rule()
112+
.async(false)
113+
.content("图片")
114+
.handler(imageHandler)
115+
.end()
116+
.rule()
117+
.async(false)
118+
.content("oauth")
119+
.handler(oauth2handler)
120+
.end()
121+
;
122+
123+
} catch (JAXBException e) {
124+
throw new RuntimeException(e);
125+
}
126+
}
20127
}

0 commit comments

Comments
 (0)