通過java方式獲取微信用戶openId
0.先熟悉微信網(wǎng)頁授權(quán)流程
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
1.內(nèi)網(wǎng)穿透
目的:使本地的服務(wù)能在微信客戶端進行訪問
1.購買隧道
https://natapp.cn/tunnel/buy
2.進行配置
配置域名,ip和端口。在這里配本地可以訪問的服務(wù)的ip和端口。
3 下載客戶端
3 打開命令行在客戶端同級目錄執(zhí)行:natapp -authtoken=xxxxxxxxxx,使隧道服務(wù)上線
2.注冊微信公眾平臺測試賬號
1.進入系統(tǒng)注冊測試賬號
2.掃碼關(guān)注
3.綁定域名
填寫上一步綁定的域名
到這里就可以實現(xiàn)在微信端對本地服務(wù)進行調(diào)用
3.代碼實現(xiàn)
@RequestMapping("/getCodeAndOpenId")
public WxInfo getCodeAndOpenId(@RequestParam("code") String code) {
log.info("==> 先獲取code,再獲取openid 。code={}", code);
Map params = new HashMap();
params.put("appid", "wxb00b277049d87059");
params.put("secret", "4f407849f4b50854ff6fbec3cc3d28a6");
params.put("grant_type", "authorization_code");
params.put("code", code);
String result = HttpGetUtil.httpRequestToString(
"https://api.weixin.qq.com/sns/oauth2/access_token", params);
WxInfo wxInfo = new WxInfo();
if (result != null) {
JSONObject jsonObject = JSONObject.parseObject(result);
String openid = jsonObject.get("openid").toString();
log.info("==> 獲取的 openid={}", openid);
wxInfo.setCode(code);
wxInfo.setOpenid(openid);
}
return wxInfo;
}
說明:用戶在微信端點擊鏈接:
https://open.weixin.qq.com/connect/oauth2/authorize?redirect_uri=http://niki.nat300.top/getCodeAndOpenId&appid=wxb00b277049d87059&response_type=code&scope=snsapi_base&state=1#wechat_redirect
后,會攜帶code跳轉(zhuǎn)到 http://niki.nat300.top/getCodeAndOpenId,即執(zhí)行g(shù)etCodeAndOpenId方法
這個方法會根據(jù)code去獲取openid
3.在微信端訪問授權(quán)頁面
在微信端任意一個窗口打開
4.返回結(jié)果
微信頁面上返回了openid
5.總結(jié)
根據(jù)開發(fā)文檔描述https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect,在訪問這個授權(quán)頁面后,需要跳轉(zhuǎn)到最終真是訪問的頁面,實際上不需要,只需要是一個方法就行,而如果這個方法正好是獲取openid的,那么正好順勢獲取code,只需要通過一個方法就能獲得openid。文章來源:http://www.zghlxwxcb.cn/news/detail-673966.html
6.工具類
public class HttpGetUtil {
public static String httpRequestToString(String url, Map<String, String> params) {
String result = null;
try {
InputStream is = httpRequestToStream(url, params);
BufferedReader in = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null) {
buffer.append(line);
}
result = buffer.toString();
} catch (Exception e) {
return null;
}
return result;
}
private static InputStream httpRequestToStream(String url, Map<String, String> params) {
InputStream is = null;
try {
if (!(params == null)) {
String parameters = "";
boolean hasParams = false;
for (String key : params.keySet()) {
String value = URLEncoder.encode(params.get(key), "UTF-8");
parameters += key + "=" + value + "&";
hasParams = true;
}
if (hasParams) {
parameters = parameters.substring(0, parameters.length() - 1);
}
url += "?" + parameters;
}
URL u = new URL(url);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setConnectTimeout(50000);
conn.setReadTimeout(50000);
conn.setDoInput(true);
//設(shè)置請求方式,默認為GET
conn.setRequestMethod("GET");
is = conn.getInputStream();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
}
7.后續(xù)改進
1.需要在中間(虛擬)頁面判斷訪問渠道
2.如果是微信則需要通過授權(quán)鏈接跳轉(zhuǎn)到明細保存接口
3.否則直接跳轉(zhuǎn)到明細保存接口文章來源地址http://www.zghlxwxcb.cn/news/detail-673966.html
@RequestMapping("/share/middle")
public String middle(HttpServletRequest request, HttpServletResponse response) throws IOException {
String userAgent = request.getHeader("user-agent").toLowerCase();
if (userAgent.indexOf("micromessenger") != -1) {
log.info("==>用戶訪問的方式是微信渠道");
response.sendRedirect("https://open.weixin.qq.com/connect/oauth2/authorize?redirect_uri=http://niki.nat300.top/saveAccessDetail&appid=wxb00b277049d87059&response_type=code&scope=snsapi_base&state=1#wechat_redirect");
} else {
log.info("==>用戶訪問的方式是其他渠道");
response.sendRedirect("http://niki.nat300.top/saveAccessDetail?code=123");
}
return "";
}
@RequestMapping("/saveAccessDetail")
public WxInfo saveAccessDetail(HttpServletRequest request, @RequestParam("code") String code) {
String userAgent = request.getHeader("user-agent").toLowerCase();
WxInfo wxInfo = new WxInfo();
if (userAgent.indexOf("micromessenger") != -1) {
log.info("==>用戶訪問的方式是微信");
log.info("==> 先獲取code,再獲取openid 。code={}", code);
Map params = new HashMap();
params.put("appid", "wxb00b277049d87059");
params.put("secret", "4f407849f4b50854ff6fbec3cc3d28a6");
params.put("grant_type", "authorization_code");
params.put("code", code);
String result = HttpGetUtil.httpRequestToString(
"https://api.weixin.qq.com/sns/oauth2/access_token", params);
if (result != null) {
JSONObject jsonObject = JSONObject.parseObject(result);
String openid = jsonObject.get("openid").toString();
log.info("==> 獲取的 openid={}", openid);
wxInfo.setCode(code);
wxInfo.setOpenid(openid);
}
}
log.info("==>執(zhí)行存入redis操作");
response.sendRedirect("https://www.apache.org/");
log.info("==>跳轉(zhuǎn)到最終實際訪問的頁面。。。。。。。。。。。。。。");
return wxInfo;
}
到了這里,關(guān)于通過java方式獲取微信用戶openId的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!