Skip to content

Commit 7b92a14

Browse files
committed
issue binarywang#39 添加oauth2的支持
1 parent 4d8f9ff commit 7b92a14

7 files changed

Lines changed: 273 additions & 0 deletions

File tree

‎weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,4 +128,12 @@ public class WxConsts {
128128
/** 弹出地理位置选择器 */
129129
public static final String LOCATION_SELECT = "location_select";
130130

131+
///////////////////////
132+
// oauth2网页授权的scope
133+
///////////////////////
134+
/** 不弹出授权页面,直接跳转,只能获取用户openid */
135+
public static final String OAUTH2_SCOPE_BASE = "snsapi_base";
136+
/** 弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息 */
137+
public static final String OAUTH2_SCOPE_USER_INFO = "snsapi_userinfo";
138+
131139
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package me.chanjar.weixin.common.util.http;
2+
3+
import me.chanjar.weixin.common.util.StringUtils;
4+
5+
import java.io.UnsupportedEncodingException;
6+
7+
public class URIUtil {
8+
9+
private static final String ALLOWED_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()";
10+
11+
public static String encodeURIComponent(String input) {
12+
if (StringUtils.isEmpty(input)) {
13+
return input;
14+
}
15+
16+
int l = input.length();
17+
StringBuilder o = new StringBuilder(l * 3);
18+
try {
19+
for (int i = 0; i < l; i++) {
20+
String e = input.substring(i, i + 1);
21+
if (ALLOWED_CHARS.indexOf(e) == -1) {
22+
byte[] b = e.getBytes("utf-8");
23+
o.append(getHex(b));
24+
continue;
25+
}
26+
o.append(e);
27+
}
28+
return o.toString();
29+
} catch (UnsupportedEncodingException e) {
30+
e.printStackTrace();
31+
}
32+
return input;
33+
}
34+
35+
private static String getHex(byte buf[]) {
36+
StringBuilder o = new StringBuilder(buf.length * 3);
37+
for (int i = 0; i < buf.length; i++) {
38+
int n = (int) buf[i] & 0xff;
39+
o.append("%");
40+
if (n < 0x10) {
41+
o.append("0");
42+
}
43+
o.append(Long.toString(n, 16).toUpperCase());
44+
}
45+
return o.toString();
46+
}
47+
}

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ public interface WxMpConfigStorage {
2525

2626
public int getExpiresIn();
2727

28+
public String getOauth2redirectUrl();
29+
2830
public String getHttp_proxy_host();
2931

3032
public int getHttp_proxy_port();

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +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;
2324

2425
public void updateAccessToken(WxAccessToken accessToken) {
2526
updateAccessToken(accessToken.getAccessToken(), accessToken.getExpiresIn());
@@ -78,6 +79,15 @@ public void setExpiresIn(int expiresIn) {
7879
this.expiresIn = expiresIn;
7980
}
8081

82+
@Override
83+
public String getOauth2redirectUrl() {
84+
return this.oauth2redirectUrl;
85+
}
86+
87+
public void setOauth2redirectUrl(String oauth2redirectUrl) {
88+
this.oauth2redirectUrl = oauth2redirectUrl;
89+
}
90+
8191
public String getHttp_proxy_host() {
8292
return http_proxy_host;
8393
}

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

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,54 @@ public interface WxMpService {
329329
*/
330330
WxMpSemanticQueryResult semanticQuery(WxMpSemanticQuery semanticQuery) throws WxErrorException;
331331

332+
/**
333+
* <pre>
334+
* 构造oauth2授权的url连接
335+
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=网页授权获取用户基本信息
336+
* </pre>
337+
* @param scope
338+
* @param state
339+
* @return code
340+
*/
341+
public String oauth2buildAuthorizationUrl(String scope, String state);
342+
343+
/**
344+
* <pre>
345+
* 用code换取oauth2的access token
346+
* 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=网页授权获取用户基本信息
347+
* </pre>
348+
* @param code
349+
* @return
350+
*/
351+
public WxMpOAuth2AccessToken oauth2getAccessToken(String code) throws WxErrorException;
352+
353+
/**
354+
* <pre>
355+
* 刷新oauth2的access token
356+
* </pre>
357+
* @param refreshToken
358+
* @return
359+
*/
360+
public WxMpOAuth2AccessToken oauth2refreshAccessToken(String refreshToken) throws WxErrorException;
361+
362+
/**
363+
* <pre>
364+
* 用oauth2获取用户信息, 当前面引导授权时的scope是snsapi_userinfo的时候才可以
365+
* </pre>
366+
* @param oAuth2AccessToken
367+
* @param lang zh_CN, zh_TW, en
368+
*/
369+
public WxMpUser oauth2getUserInfo(WxMpOAuth2AccessToken oAuth2AccessToken, String lang) throws WxErrorException;
370+
371+
/**
372+
* <pre>
373+
* 验证oauth2的access token是否有效
374+
* </pre>
375+
* @param oAuth2AccessToken
376+
* @return
377+
*/
378+
public boolean oauth2validateAccessToken(WxMpOAuth2AccessToken oAuth2AccessToken);
379+
332380
/**
333381
* 当本Service没有实现某个API的时候,可以用这个,针对所有微信API中的GET请求
334382
* @param url

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

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,13 @@
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;
3031
import org.apache.http.impl.client.BasicCredentialsProvider;
3132
import org.apache.http.impl.client.BasicResponseHandler;
3233
import org.apache.http.impl.client.CloseableHttpClient;
3334
import org.apache.http.impl.client.HttpClients;
3435

36+
import javax.print.DocFlavor;
3537
import java.io.File;
3638
import java.io.IOException;
3739
import java.io.InputStream;
@@ -297,6 +299,98 @@ public WxMpSemanticQueryResult semanticQuery(WxMpSemanticQuery semanticQuery) th
297299
return WxMpSemanticQueryResult.fromJson(responseContent);
298300
}
299301

302+
@Override
303+
public String oauth2buildAuthorizationUrl(String scope, String state) {
304+
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" ;
305+
url += "appid=" + wxMpConfigStorage.getAppId();
306+
url += "&redirect_uri=" + URIUtil.encodeURIComponent(wxMpConfigStorage.getOauth2redirectUrl());
307+
url += "&response_type=code";
308+
url += "&scope=" + scope;
309+
if (state != null) {
310+
url += "&state=" + state;
311+
}
312+
url += "#wechat_redirect";
313+
return url;
314+
}
315+
316+
@Override
317+
public WxMpOAuth2AccessToken oauth2getAccessToken(String code) throws WxErrorException {
318+
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?";
319+
url += "appid=" + wxMpConfigStorage.getAppId();
320+
url += "&secret=" + wxMpConfigStorage.getSecret();
321+
url += "&code=" + code;
322+
url += "&grant_type=authorization_code";
323+
324+
try {
325+
RequestExecutor<String, String> executor = new SimpleGetRequestExecutor();
326+
String responseText = executor.execute(getHttpclient(), httpProxy, url, null);
327+
return WxMpOAuth2AccessToken.fromJson(responseText);
328+
} catch (ClientProtocolException e) {
329+
throw new RuntimeException(e);
330+
} catch (IOException e) {
331+
throw new RuntimeException(e);
332+
}
333+
}
334+
335+
@Override
336+
public WxMpOAuth2AccessToken oauth2refreshAccessToken(String refreshToken) throws WxErrorException {
337+
String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?";
338+
url += "appid=" + wxMpConfigStorage.getAppId();
339+
url += "&grant_type=refresh_token";
340+
url += "&refresh_token=" + refreshToken;
341+
342+
try {
343+
RequestExecutor<String, String> executor = new SimpleGetRequestExecutor();
344+
String responseText = executor.execute(getHttpclient(), httpProxy, url, null);
345+
return WxMpOAuth2AccessToken.fromJson(responseText);
346+
} catch (ClientProtocolException e) {
347+
throw new RuntimeException(e);
348+
} catch (IOException e) {
349+
throw new RuntimeException(e);
350+
}
351+
}
352+
353+
@Override
354+
public WxMpUser oauth2getUserInfo(WxMpOAuth2AccessToken oAuth2AccessToken, String lang) throws WxErrorException {
355+
String url = "https://api.weixin.qq.com/sns/userinfo?";
356+
url += "access_token=" + oAuth2AccessToken.getAccessToken();
357+
url += "&openid=" + oAuth2AccessToken.getOpenId();
358+
if (lang == null) {
359+
url += "&lang=zh_CN";
360+
} else {
361+
url += "&lang=" + lang;
362+
}
363+
364+
try {
365+
RequestExecutor<String, String> executor = new SimpleGetRequestExecutor();
366+
String responseText = executor.execute(getHttpclient(), httpProxy, url, null);
367+
return WxMpUser.fromJson(responseText);
368+
} catch (ClientProtocolException e) {
369+
throw new RuntimeException(e);
370+
} catch (IOException e) {
371+
throw new RuntimeException(e);
372+
}
373+
}
374+
375+
@Override
376+
public boolean oauth2validateAccessToken(WxMpOAuth2AccessToken oAuth2AccessToken) {
377+
String url = "https://api.weixin.qq.com/sns/auth?";
378+
url += "access_token=" + oAuth2AccessToken;
379+
url += "&openid=" + oAuth2AccessToken.getOpenId();
380+
381+
try {
382+
RequestExecutor<String, String> executor = new SimpleGetRequestExecutor();
383+
executor.execute(getHttpclient(), httpProxy, url, null);
384+
} catch (ClientProtocolException e) {
385+
throw new RuntimeException(e);
386+
} catch (IOException e) {
387+
throw new RuntimeException(e);
388+
} catch (WxErrorException e) {
389+
return false;
390+
}
391+
return true;
392+
}
393+
300394
public String get(String url, String queryParam) throws WxErrorException {
301395
return execute(new SimpleGetRequestExecutor(), url, queryParam);
302396
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package me.chanjar.weixin.mp.bean.result;
2+
3+
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
4+
5+
/**
6+
* Created by qianjia on 14/11/26.
7+
*/
8+
public class WxMpOAuth2AccessToken {
9+
10+
private String accessToken;
11+
12+
private int expiresIn = -1;
13+
14+
private String refreshToken;
15+
16+
private String openId;
17+
18+
private String scope;
19+
20+
public String getRefreshToken() {
21+
return refreshToken;
22+
}
23+
24+
public void setRefreshToken(String refreshToken) {
25+
this.refreshToken = refreshToken;
26+
}
27+
28+
public String getOpenId() {
29+
return openId;
30+
}
31+
32+
public void setOpenId(String openId) {
33+
this.openId = openId;
34+
}
35+
36+
public String getScope() {
37+
return scope;
38+
}
39+
40+
public void setScope(String scope) {
41+
this.scope = scope;
42+
}
43+
44+
public String getAccessToken() {
45+
return accessToken;
46+
}
47+
48+
public void setAccessToken(String accessToken) {
49+
this.accessToken = accessToken;
50+
}
51+
52+
public int getExpiresIn() {
53+
return expiresIn;
54+
}
55+
56+
public void setExpiresIn(int expiresIn) {
57+
this.expiresIn = expiresIn;
58+
}
59+
60+
public static WxMpOAuth2AccessToken fromJson(String json) {
61+
return WxGsonBuilder.create().fromJson(json, WxMpOAuth2AccessToken.class);
62+
}
63+
64+
}

0 commit comments

Comments
 (0)