1、一个微信公众号上挂的2个页面,(2个页面域名不同)获得的openid是同一个。
这里的appid 用的是公众号的appid,这里就认为是一个app。
如果一个公众号网页,一个小程序, 他的appid是不同的,需要unionid
2、一个成功获取到基本信息的示例
前台js
- var appid = "xxxxxxxxxxxxxx";
- var wxauthurl = "https://open.weixin.qq.com/connect/oauth2/authorize";
- // snsapi_base 只获取openid, snsapi_userinfo 可以获取昵称等基本信息
- let wx_code = getUrlParam("code"); // 截取url中的code
- console.log("wx_code ", wx_code)
- if (!wx_code) {
- const pathStr = window.location.href
- console.log('cururl ', pathStr)
- window.location.href = wxauthurl+'?appid='+appid+'&redirect_uri='
- + encodeURIComponent(pathStr)
- + '&response_type=code&scope=snsapi_userinfo&state=3451#wechat_redirect';
- } else {
- var obj = {
- "code": wx_code
- }
- $.ajax({
- url: baseURL + "weixin/getUserOpenIdAndUserInfo?t="+Date.now(),
- type: 'POST',
- contentType: 'application/json',
- data: JSON.stringify(obj),
- success: function(result) {
- alert("获取到的信息"+JSON.stringify(result));
- window.localStorage.setItem('openId',result.data);
- },
- error: function(jqXHR, textStatus, errorThrown) {
- layer.close(loading);
- }
- });
- }
-
- function getUrlParam( name ) {
- var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
- var r = window.location.search.substr(1).match(reg);
- if (r != null) return unescape(r[2]);
- return null;
- }
-
后台java接口
- @RequestMapping(value = "/getUserOpenIdAndUserInfo", method = RequestMethod.POST)
- public String getUserOpenIdAndUserInfo(@RequestBody Map
param) { - String code=param.get("code");
- System.out.println("----------------------- 测试 -微信用户信息code-------------:" + code);
- logger.info("leave webAuth {}",code);
- // 1 先用code获取到openid和access_token
- // https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
- JSONObject result = WeixinUtil.getOpenIdByCode(weixinProperties, code);
- if (result != null) {
- JSONObject responseJson = new JSONObject();
- String openId = result.getString("openid");
- String accessToken = result.getString("access_token");
- responseJson.put("openid", openId);
- responseJson.put("scope", result.getString("scope"));
- responseJson.put("access_token", accessToken);
- logger.info("success webAuth {}", responseJson.toJSONString());
- // 通过openId, accessToken获取到用户基本信息,主要是昵称和logo。
- // https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
- JSONObject joUserInfo = WeixinUtil.getUserInfo2(openId, accessToken);
- logger.info("getUserInfo2 userinfo {}", joUserInfo==null?"null":joUserInfo.toJSONString());
- System.out.println("getUserInfo2 userinfo "+ joUserInfo==null?"null":joUserInfo.toJSONString());
- /* // 更新登录用户的openid
- if (userId != null) {
- userMapper.updateUserOpenId(userId, openId);
- }*/
- return "认证成功"+ joUserInfo.toJSONString();
- } else {
- return "认证失败";
- }
- }