微信中H5页面如何获取用户openid呢?
下文笔者讲述微信开发时,web页面获取用户openid的方法分享,如下所示
实现思路: 通过获取回调页面上的code和appid 然后去请求微信API,即可获取用户的openid例:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.net.URLEncoder"%> <%@ page import="com.geong.util.HttpUtil"%> <%@ page import="com.geong.util.PropertiesUtil"%> <%@ page import="com.geong.util.GetWechatParmas"%> <%@ page import="javax.xml.ws.Response"%> <%@ page import="net.sf.json.JSONObject" %> <% //需要配置跳转地址 String jumpUrl =request.getContextPath()+"/page/index.jsp"; //以下为自动处理,不需要更改 String code = request.getParameter("code"); String rpath = PropertiesUtil.getProperty("backurl")+request.getRequestURI(); String oauth2Url = "https://open.weixin.qq.com/connect/oauth2 /authorize?appid="+PropertiesUtil.getProperty("appid") +"&redirect_uri="+URLEncoder.encode(rpath,"UTF-8")+"&response_type=code&scope=snsapi_userinfo& state=123#wechat_redirect"; if(code==null){ response.sendRedirect(oauth2Url); }else{ String url = "https://api.weixin.qq.com/sns /oauth2/access_token?appid="+PropertiesUtil.getProperty("appid") +"&secret="+PropertiesUtil.getProperty("secret")+"& code="+code+"&grant_type=authorization_code"; String openidResult = HttpUtil.get(url,true); JSONObject fromObjectopenid = JSONObject.fromObject(openidResult.toString()); if(fromObjectopenid.toString().indexOf("openid")>-1){ String openid = fromObjectopenid.get("openid").toString(); session.setAttribute("openid",openid); response.sendRedirect(jumpUrl); }else{ response.sendRedirect(oauth2Url); } } %>
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。