微信网页授权获取openid(微信公众号点击菜单直接跳转获取openid)第十六课

2017年08月13日 15:38 | 4929次浏览 作者原创 版权保护

在技术群里有人根据第十四课 还是问微信如何获取openid,我仔细看了下这章内容,可能说的有点啰里啰嗦,所以今天特意用自己公司的公众号写了一段实现代码来获取openid。

第一 、菜单设置json代码

{
                    "name": "网页授权", 
                    "type": "view", 
                    "url": "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx148d7ereee8d2b9c&redirect_uri=http://www.xxx.com/xxx/weixin/gotestauth.do&response_type=code&scope=snsapi_base&state=1#wechat_redirect"
                }

把上述json代码中的appid 和 redirect_uri的值更换为自己的值即可,其他不用修改

第二、 跳转地址的方法,也就是上面redirect_uri地址请求方法的实现

//www.vxzsk.com V型知识库 
@RequestMapping(value="/gotestauth")
public ModelAndView testAuth(HttpServletRequest request,HttpServletResponse response){
		
		try{
		System.out.println("获取的code::::"+request.getParameter("code"));
		System.out.println("开始调用网页授权");
		String openid = WeixinUtil.getWeChat(request.getParameter("code"));
		System.out.println("结束调用网页授权");
		System.out.println("网页授权获取到的openid:"+openid);
		}catch(Exception e){
			e.printStackTrace();
			System.out.println("调用网页授权异常:"+e);
		}
		
		return new ModelAndView("/weixin/bug/openidException");
	}

第三、WeixinUtil.getWeChat()方法的实现

/***
	 * 获取微信号
	 * @param code V型知识库 www.vxzsk.com
	 * @return
	 */
	public static String getWeChat(String code){
		
		String appid = "应用id";
		String secret = "应用秘钥";
		String weiUserJson=HttpUtil.sendGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code", "utf-8", 30000);
		JSONObject jsonOuth = JSONObject.fromObject(weiUserJson);
        return jsonOuth.getString("openid");
	}

上述方法用到了解析jsonjar包,读者自行下载,appid 和 secret请读者登录公众管理平台查询。

好了 只要跟着上面三个步骤完成,立马就能实现获取openid,上述代码都是经过测试的,还有就是如果想了解如何实现自定义菜单的创建,请访问https://www.vxzsk.com/46.html

HttpUtil的get方法:

 public static String sendGet(String url, String charset, int timeout)
	  {
	    String result = "";
	    try
	    {
	      URL u = new URL(url);
	      try
	      {
	        URLConnection conn = u.openConnection();
	        conn.connect();
	        conn.setConnectTimeout(timeout);
	        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
	        String line="";
	        while ((line = in.readLine()) != null)
	        {
	        
	          result = result + line;
	        }
	        in.close();
	      } catch (IOException e) {
	        return result;
	      }
	    }
	    catch (MalformedURLException e)
	    {
	      return result;
	    }
	    
	    return result;
	  }


小说《我是全球混乱的源头》
此文章本站原创,地址 https://www.vxzsk.com/103.html   转载请注明出处!谢谢!

感觉本站内容不错,读后有收获?小额赞助,鼓励网站分享出更好的教程