獲取微信公衆号用戶的(de)openid
發表時(shí)間:2020-11-6
發布人(rén):融晨科技
浏覽次數:92
前言:
官方參考連接:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
1、用戶同意授權,獲取code
public void getCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//appid是(shì)公衆号的(de)appid
String redirect_uri=Param.local_url+"wx/openid";
String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri="
+ URLEncoder.encode(redirect_uri, "GBK")
+ "&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect";
response.sendRedirect(url);
}
需要(yào / yāo)注意的(de)是(shì)鏈接需要(yào / yāo)用 URLEncoder.encode(url)進行編碼,在(zài)連接中加入 connect_redirect=1 是(shì)防止網頁授權兩次或多次重定響應問題,我這(zhè)裏的(de)scope=snsapi_base不(bù)會彈出(chū)授權頁面,但隻能拿到(dào)用戶的(de)openid
2、在(zài)回調地(dì / de)址中通過code獲取用戶的(de)openid
public void openid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/xml; charset=UTF-8");
String oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + AppSecret
+ "&code=" + request.getParameter("code") + "&grant_type=authorization_code";
JSONObject jsonObject = JSONObject.fromObject(HttpRequestUtil.sendGet(oauth2Url));
String pubopenid = jsonObject.getString("openid");
System.out.println("獲取的(de)openid"+pubopenid);
}
其中的(de)sendGet()方法如下:
public static String sendGet(String url) {
String result = "";
BufferedReader in = null;
try {
URL realUrl = new URL(url);
// 打開和(hé / huò)URL之(zhī)間的(de)連接
URLConnection connection = realUrl.openConnection();
// 設置通用的(de)請求屬性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立實際的(de)連接
connection.connect();
// 獲取所有響應頭字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍曆所有的(de)響應頭字段
for (String key : map.keySet()) {
}
// 定義 BufferedReader輸入流來(lái)讀取URL的(de)響應
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
//System.out.println("jieguo--------幾萬個(gè)"+result);
result += line;
}
} catch (Exception e) {
System.out.println("發送GET請求出(chū)現異常!" + e);
e.printStackTrace();
}
// 使用finally塊來(lái)關閉輸入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
3、公衆号配置網頁授權域名
在(zài)公衆号的(de)【開發】-【接口權限】-【網頁授權獲取用戶基本信息】-【網頁授權域名】中配置域名
沒有正式公衆号的(de)可以(yǐ)用測試号試用:http://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index