微信公众平台开发教程第5篇-----网页授权获取用户基本信息
欢迎加入群:347245650 345531810 进行讨论相互交流 我的微信号:572839485
网页授权获取用户基本信息此接口是通过OAuth2.0来完成网页授权的,是安全可靠的。
一、什么是OAuth2.0
OAuth是一个开放协议,允许用户让第三方应用以安全且标准的方式获取该用户在某一网站、移动或桌面应用上存储的私密的资源(如用户个人信息、照片、视频、联系人列表),而无需将用户名和密码提供给第三方应用。
OAuth 2.0是OAuth协议的下一版本,但不向后兼容OAuth 1.0。 OAuth 2.0关注客户端开发者的简易性,同时为Web应用,桌面应用和手机,和起居室设备提供专门的认证流程。
OAuth允许用户提供一个令牌,而不是用户名和密码来访问他们存放在特定服务提供者的数据。每一个令牌授权一个特定的网站(例如,视频编辑网站)在特定的时段(例如,接下来的2小时内)内访问特定的资源(例如仅仅是某一相册中的视频)。这样,OAuth允许用户授权第三方网站访问他们存储在另外的服务提供者上的信息,而不需要分享他们的访问许可或他们数据的所有内容。(来自于网络)
二、微信公众平台OAuth2.0授权详细步骤
1. 用户关注微信公众账号。
2. 微信公众账号提供用户请求授权页面URL。
3. 用户点击授权页面URL,将向服务器发起请求
4. 服务器询问用户是否同意授权给微信公众账号(scope为snsapi_base时无此步骤)
5. 用户同意(scope为snsapi_base时无此步骤,不弹出授权页面,直接跳转,只能获取用户openid)
6. 服务器将code参数通过回调传给微信公众账号
7. 微信公众账号获得code参数
8. 微信公众账号通过code参数向服务器请求Access Token
9. 服务器返回Access Token和OpenID给微信公众账号
10. 微信公众账号通过Access Token向服务器请求用户信息(scope为snsapi_base时无此步骤)
11. 服务器将用户信息回送给微信公众账号(scope为snsapi_base时无此步骤)
三、配置授权回调页面域名
点击右边的修改
填写授权页面需要注意:
这里我们填写自己的域名www.wechat68.com
这样我的授权页面的域名配置成功了
四、用户授权并获取code 使用code换取access_token 使用access_token获取用户信息 Java代码如下
授权访问的URL:https://open.weixin.qq.com/connect/oauth2/auth9orize?appid=wx614c453e0d1dcd12&redirect_uri=http://www.wechat68.com/Javen/OauthTest&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect
package com.javen.course.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import com.javen.course.entity.UserInfo_weixin; import com.javen.course.util.HttpUtil; /** * * @author 简爱微萌 * @Email zyw205@gmail.com * 接口权限中设置OAuth2.0网页授权 域名 如:www.wechat68.com * 授权访问的URL:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx614c453e0d1dcd12&redirect_uri=http://www.wechat68.com/Javen/OauthTest&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect */ public class Oauth2Servlet extends HttpServlet { private String get_access_token_url="https://api.weixin.qq.com/sns/oauth2/access_token?" + "appid=APPID" + "&secret=SECRET&" + "code=CODE&grant_type=authorization_code"; private String get_userinfo="https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN"; private static final long serialVersionUID = -644518508267758016L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 将请求、响应的编码均设置为UTF-8(防止中文乱码) request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String code=request.getParameter("code"); get_access_token_url=get_access_token_url.replace("APPID", "wx614c453e0d1dcd12"); get_access_token_url=get_access_token_url.replace("SECRET", "fd00642f7a2fea32c5a7b060d9c37db1"); get_access_token_url=get_access_token_url.replace("CODE", code); String json=HttpUtil.getUrl(get_access_token_url); JSONObject jsonObject=JSONObject.fromObject(json); String access_token=jsonObject.getString("access_token"); String openid=jsonObject.getString("openid"); get_userinfo=get_userinfo.replace("ACCESS_TOKEN", access_token); get_userinfo=get_userinfo.replace("OPENID", openid); String userInfoJson=HttpUtil.getUrl(get_userinfo); JSONObject userInfoJO=JSONObject.fromObject(userInfoJson); String user_openid=userInfoJO.getString("openid"); String user_nickname=userInfoJO.getString("nickname"); String user_sex=userInfoJO.getString("sex"); String user_province=userInfoJO.getString("province"); String user_city=userInfoJO.getString("city"); String user_country=userInfoJO.getString("country"); String user_headimgurl=userInfoJO.getString("headimgurl"); // UserInfo_weixin userInfo=new UserInfo_weixin(user_openid, user_nickname, user_sex, user_province, user_city, user_country, user_headimgurl); response.setContentType("text/html; charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method \n"); out.println("openid:"+user_openid+"\n\n"); out.println("nickname:"+user_nickname+"\n\n"); out.println("sex:"+user_sex+"\n\n"); out.println("province:"+user_province+"\n\n"); out.println("city:"+user_city+"\n\n"); out.println("country:"+user_country+"\n\n"); out.println("<img src=/"+user_headimgurl+"/"); out.println(">"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
public static String getUrl(String url){ String result = null; try { // 根据地址获取请求 HttpGet request = new HttpGet(url); // 获取当前客户端对象 HttpClient httpClient = new DefaultHttpClient(); // 通过请求对象获取响应对象 HttpResponse response = httpClient.execute(request); // 判断网络连接状态码是否正常(0--200都数正常) if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { result= EntityUtils.toString(response.getEntity()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; }
/** * 发起https请求并获取结果 * * @param requestUrl 请求地址 * @param requestMethod 请求方式(GET、POST) * @param outputStr 提交的数据 * */ public static String httpRequest(String requestUrl, String requestMethod, String outputStr) { StringBuffer buffer = new StringBuffer(); try { // 创建SSLContext对象,并使用我们指定的信任管理器初始化 TrustManager[] tm = { new MyTrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // 从上述SSLContext对象中得到SSLSocketFactory对象 SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl); HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection(); httpUrlConn.setSSLSocketFactory(ssf); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); // 设置请求方式(GET/POST) httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect(); // 当有数据需要提交时 if (null != outputStr) { OutputStream outputStream = httpUrlConn.getOutputStream(); // 注意编码格式,防止中文乱码 outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); } // 将返回的输入流转换成字符串 InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); // 释放资源 inputStream.close(); inputStream = null; httpUrlConn.disconnect(); return buffer.toString(); } catch (ConnectException ce) { log.error("Weixin server connection timed out."); } catch (Exception e) { log.error("https request error:{}", e); } return null; }
package com.javen.weixin.util; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; /** * 证书信任管理器(用于https请求) */ public class MyTrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }
如果对你有帮助请我喝杯咖啡 左微信 右支付宝 个人微信公众号javenlife