11package com .pingplusplus .util ;
22
33import com .google .gson .*;
4+ import com .pingplusplus .exception .ChannelException ;
5+ import com .pingplusplus .model .Channel ;
46
57import java .io .BufferedReader ;
68import java .io .IOException ;
1820/**
1921 * 用于微信公众号OAuth2.0鉴权,用户授权后获取授权用户唯一标识openid
2022 * WxpubOAuth中的方法都是可选的,开发者也可根据实际情况自行开发相关功能,
21- * 详细内容可参考http ://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
23+ * 详细内容可参考 https ://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
2224 */
2325public class WxpubOAuth {
2426
@@ -37,14 +39,18 @@ public class WxpubOAuth {
3739 * @throws UnsupportedEncodingException
3840 */
3941 public static String getOpenId (String appId , String appSecret , String code )
40- throws UnsupportedEncodingException {
42+ throws UnsupportedEncodingException , ChannelException {
4143 String url = WxpubOAuth .createOauthUrlForOpenid (appId , appSecret , code );
4244
4345 String ret = WxpubOAuth .httpGet (url );
4446 OAuthResult oAuthResult = new GsonBuilder ()
4547 .setFieldNamingPolicy (FieldNamingPolicy .LOWER_CASE_WITH_UNDERSCORES )
4648 .create ().fromJson (ret , OAuthResult .class );
4749
50+ if (oAuthResult .getErrmsg () != null ) {
51+ throw new ChannelException (oAuthResult .getErrmsg (), oAuthResult .getErrcode ().toString (), null );
52+ }
53+
4854 return oAuthResult .getOpenid ();
4955 }
5056
@@ -95,7 +101,7 @@ private static String createOauthUrlForOpenid(String appId, String appSecret, St
95101 return "https://api.weixin.qq.com/sns/oauth2/access_token?" + queryString ;
96102 }
97103
98- private static String httpBuildQuery (Map <String , String > queryString ) throws UnsupportedEncodingException {
104+ protected static String httpBuildQuery (Map <String , String > queryString ) throws UnsupportedEncodingException {
99105 StringBuilder sb = new StringBuilder ();
100106 for (Map .Entry <String , String > e : queryString .entrySet ()) {
101107 if (sb .length () > 0 ) {
@@ -112,7 +118,7 @@ private static String httpBuildQuery(Map<String, String> queryString) throws Uns
112118 * @param urlString
113119 * @return responseString
114120 */
115- private static String httpGet (String urlString ) {
121+ protected static String httpGet (String urlString ) {
116122 String result = "" ;
117123 try {
118124 URL url = new URL (urlString );
@@ -221,6 +227,8 @@ class OAuthResult {
221227 String refreshToken ;
222228 String openid ;
223229 String scope ;
230+ Integer errcode ;
231+ String errmsg ;
224232
225233 public String getAccessToken () {
226234 return accessToken ;
@@ -241,5 +249,13 @@ public String getOpenid() {
241249 public String getScope () {
242250 return scope ;
243251 }
252+
253+ public Integer getErrcode () {
254+ return errcode ;
255+ }
256+
257+ public String getErrmsg () {
258+ return errmsg ;
259+ }
244260 }
245261}
0 commit comments