1.填寫授權回調頁面域名:
1.1獲取微信公眾平臺測試賬號

alt 獲取微信公眾平臺測試賬號
1.2對帳號進行接口配置填寫

alt 對帳號進行接口配置填寫
1.3填寫授權回調頁面域名
-
注意域名填寫不要加?
http://
或者https://
alt 填寫授權回調頁面域名
2授權成功獲得Openid
- 主要是根據(jù)微信公眾平臺技術文檔進行操作。
2.1用戶同意授權,獲取code
在確保微信公眾賬號擁有授權作用域
<scope參數(shù)>
的權限的前提下(服務號獲得高級接口后,默認擁有scope
參數(shù)中的snsapi_base
和snsapi_userinfo
),引導關注者打開如下頁面:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
//若提示“該鏈接無法訪問”,請檢查參數(shù)是否填寫錯誤,是否擁有scope參數(shù)對應的授權作用域權限。
2.1.1封裝普通url成授權url
-
本人是采用過濾器的方式封裝url引導用戶訪問上面授權鏈接:
public class OpenidFilter implements Filter { private static String flag1 = "1"; private static String flag2 = "2"; @Override public void destroy() { } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { //轉換request 和 respond HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; flag1 = request.getRequestURI(); // 判斷是否同一個路徑封裝成微信的路徑再次訪問 System.out.println("是否同一個路徑封裝成微信的路徑再次訪問" + flag1.equals(flag2)); if (!flag1.equals(flag2)) { // 判斷request中是否有openid if (CheckUtil.isNullOrBlank((String) request.getSession().getAttribute("openid"))) { flag2 = request.getRequestURI(); // 修改成微信的url String url = WeixinUtil.AUTHORIZE_URL.replace("APPID", WeixinUtil.APPID) .replace("SCOPE", WeixinUtil.SCOPR) .replace("REDIRECT_URI", WeixinUtil.DOMAIN_NAME + request.getRequestURI()); System.out.println("過濾修改后的url:" + url); //重定向url response.sendRedirect(url); return; } } chain.doFilter(request, response); } @Override public void init(FilterConfig arg0) throws ServletException { } }
-
此過濾器應該為一級調用,web.xml配置:
<filter> <filter-name>openidFilter</filter-name> <filter-class>com.weixin.oauth.filter.OpenidFilter</filter-class> </filter> <filter-mapping> <filter-name>openidFilter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>1</dispatcher> </filter-mapping>
-
直接在微信Web開發(fā)工具輸入需要封裝的url:
alt 使用微信開發(fā)工具輸入url 過濾修改后的url:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9240e5de6afdd7b1&redirect_uri=http://zhixiaoyi.nat300.top/weixinOAuth/OAuthServlet.do&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
2.1.2授權訪問獲得code
- 之后會進入授權頁面:

alt 用戶進行授權
2.2通過code獲得openid
- 在獲得code之后需立即采用WeixinUtil通過code換取網(wǎng)頁授權access_token。
這里通過code換取的是一個特殊的網(wǎng)頁授權
access_token
,與基礎支持中的access_token
(該access_token
用于調用其他接口)不同。公眾號可通過下述接口來獲取網(wǎng)頁授權access_token
。如果網(wǎng)頁授權的作用域為snsapi_base
,則本步驟中獲取到網(wǎng)頁授權access_token
的同時,也獲取到了openid
,snsapi_base
式的網(wǎng)頁授權流程即到此為止。
獲得
access_token
的請求連接:https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
其返回JSON數(shù)據(jù)包如下:
{ "access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE" }
-
獲得code和openid的servlet:
@WebServlet(name = "OAuthServlet.do", urlPatterns = { "/OAuthServlet.do" }) public class OAuthServlet extends HttpServlet { private static final long serialVersionUID = 1L; public OAuthServlet() { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 得到code String code = request.getParameter("code"); //先檢測是否已經(jīng)得到openid String openid = (String) request.getSession().getAttribute("openid"); if(CheckUtil.isNullOrBlank(openid)){ //判斷cede是否為空即是否需要訪問獲得openid if (!CheckUtil.isNullOrBlank(code)) { System.out.println("code:" + code); //采用WeixinUtil通過code換取網(wǎng)頁授權access_token OAuthInfo oauthInfo = WeixinUtil.getAccessToken(WeixinUtil.APPID, WeixinUtil.APPSECRET, code); request.getSession().setAttribute("openid", oauthInfo.getOpenId()); } } request.getRequestDispatcher("index.jsp").forward(request, response); System.out.println("openid:" + openid); } }
WeixinUtil代碼如下:
public class WeixinUtil {
// 公眾號id
public static String APPID = "wx9240e5de6afdd7b1";
// 公眾號密鑰
public static String APPSECRET = "2de51d7fae9cb5f36d5468c15bc288fe";
// 用戶同意授權url,獲取code
public static String AUTHORIZE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
// 通過code換取網(wǎng)頁授權access_token的url
public static String ACCESS_TOKEN_BY_CODE_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
// 授權域名
public static String DOMAIN_NAME = "http://zhixiaoyi.nat300.top";
// url范圍
public static String SCOPR = "snsapi_userinfo";
/**
* Get請求
*
* @param url
* @return
*/
public static JSONObject doGetStr(String url) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
JSONObject jsonObject = null;
try {
HttpResponse httpRequest = httpClient.execute(httpGet);
HttpEntity entity = httpRequest.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, "UTF-8");
jsonObject = JSONObject.fromObject(result);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonObject;
}
/**
* Post請求
*
* @param url
* @param outStr
* @return
*/
public static JSONObject doPostStr(String url, String outStr) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
JSONObject jsonObject = null;
try {
httpPost.setEntity(new StringEntity(outStr, "UTF-8"));
HttpResponse httpRequest = httpClient.execute(httpPost);
HttpEntity entity = httpRequest.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
jsonObject = JSONObject.fromObject(result);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonObject;
}
/**
* 網(wǎng)頁授權獲取openId第2步,根據(jù)code取得openId
*
* @param appid
* 公眾號的唯一標識
* @param secret
* 公眾號的appsecret密鑰
* @param code
* code為換取access_token的票據(jù)
* @return
*/
/**
*
* 通過code獲取access_token
*
* @return
*/
public static OAuthInfo getAccessToken(String appid, String secret, String code) {
OAuthInfo oAuthInfo = new OAuthInfo();
String url = ACCESS_TOKEN_BY_CODE_URL.replace("APPID", appid).replace("SECRET", secret).replace("CODE", code);
JSONObject jsonObject = doGetStr(url);
if (jsonObject != null) {
oAuthInfo.setAccessToken(jsonObject.getString("access_token"));
oAuthInfo.setOpenId(jsonObject.getString("openid"));
oAuthInfo.setExpiresIn(jsonObject.getInt("expires_in"));
oAuthInfo.setRefreshToken(jsonObject.getString("refresh_token"));
oAuthInfo.setScope(jsonObject.getString("scope"));
}
return oAuthInfo;
}
}
-
控制臺輸出結果:
是否同一個路徑封裝成微信的路徑再次訪問false 過濾修改后的url:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9240e5de6afdd7b1&redirect_uri=http://zhixiaoyi.nat300.top/weixinOAuth/OAuthServlet.do&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect 是否同一個路徑封裝成微信的路徑再次訪問true code:051FhwC11h9UfM1y5xE11yjBC11FhwC6 openid:ozlH6v1yu2otJOmT1BsD24d25xBU
頁面展示openid:

alt 頁面展示openid
-
用到的pojo:
public class OAuthInfo { // 網(wǎng)頁授權接口調用憑證 private String accessToken; // access_token接口調用憑證超時時間 private int expiresIn; // 用戶刷新access_token private String refreshToken; // 用戶唯一標識 private String openId; // 用戶授權的作用域 private String scope; public String getAccessToken() { return accessToken; } public int getExpiresIn() { return expiresIn; } public String getRefreshToken() { return refreshToken; } public String getOpenId() { return openId; } public String getScope() { return scope; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public void setExpiresIn(int expiresIn) { this.expiresIn = expiresIn; } public void setRefreshToken(String refreshToken) { this.refreshToken = refreshToken; } public void setOpenId(String openId) { this.openId = openId; } public void setScope(String scope) { this.scope = scope; } @Override public String toString() { return "OAuthInfo [accessToken=" + accessToken + ", expiresIn=" + expiresIn + ", refreshToken=" + refreshToken + ", openId=" + openId + ", scope=" + scope + "]"; } }