原创声明:本文为本人原创作品,绝非他处转账,转载请联系博主

从接触公众号到现在,开发维护了2个公众号,开发过程中遇到很多问题,现在把部分模块功能在这备案一下,做个总结也希望能给其他人帮助

工欲善其事,必先利其器,先看看开发公众号需要准备或了解什么

  1. web开发工具:官方提供的开发工具,使用自己的微信号来调试微信网页授权、调试、检验页面的 JS-SDK 相关功能与权限,模拟大部分 SDK 的输入和输出。下载地址:web开发工具下载
  2. 开发文档:https://mp.weixin.qq.com/wiki
  3. 登录微信测试公众号,获取公众号的appID、appsecret,登录地址:http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login (一般测试开发阶段,都不拿正式公众号测试,因为存在风险并且你调试时不用担心影响到正式公众号的正常使用,而且有些接口在正式公众号上比较严格,而在测试公众号上可以放开,如模板信息)

下面进入正题,实现微信网页授权,获取微信信息,主要用于以微信帐号作为用户登录,如果你只是需要绑定微信,就可以不用授权,直接请求获取微信OpenId(对当前公众号唯一),进行用户绑定(在下面代码时是写明如何实现),该功能可在开发文档:微信网页开发-》微信网页授权里查看详细信息,下面正式开始。

1.填写授权回调页面域名

进入测试公众号,在体验接口权限表中找到网页帐号,右侧添加自己的域名,测试公众号可填写本地IP,如你是正式公众号只能填写自己的域名,如果未填写,当进行接口调用时,会提示:redirect_uri参数错误!如果还有其他不了解的配置,可以在开发文档里查看详信息,

2.代码展示

1).调用微信接口返回的参数都是JSON格式,封装个Http请求方法
  1. public class WeixinUtil {
  2. /**
  3. * 发起https请求并获取结果
  4. * @param requestUrl 请求地址
  5. * @param requestMethod 请求方式(GET、POST)
  6. * @param outputStr 提交的数据
  7. * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
  8. */
  9. public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
  10. JSONObject jsonObject = null;
  11. StringBuffer buffer = new StringBuffer();
  12. try {
  13. // 创建SSLContext对象,并使用我们指定的信任管理器初始化
  14. TrustManager[] tm = { new MyX509TrustManager() };
  15. SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
  16. sslContext.init(null, tm, new java.security.SecureRandom());
  17. // 从上述SSLContext对象中得到SSLSocketFactory对象
  18. SSLSocketFactory ssf = sslContext.getSocketFactory();
  19. URL url = new URL(requestUrl);
  20. HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
  21. httpUrlConn.setSSLSocketFactory(ssf);
  22. httpUrlConn.setDoOutput(true);
  23. httpUrlConn.setDoInput(true);
  24. httpUrlConn.setUseCaches(false);
  25. // 设置请求方式(GET/POST)
  26. httpUrlConn.setRequestMethod(requestMethod);
  27. if ("GET".equalsIgnoreCase(requestMethod))
  28. httpUrlConn.connect();
  29. // 当有数据需要提交时
  30. if (null != outputStr) {
  31. OutputStream outputStream = httpUrlConn.getOutputStream();
  32. // 注意编码格式,防止中文乱码
  33. outputStream.write(outputStr.getBytes("UTF-8"));
  34. outputStream.close();
  35. }
  36. // 将返回的输入流转换成字符串
  37. InputStream inputStream = httpUrlConn.getInputStream();
  38. InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
  39. BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  40. String str = null;
  41. while ((str = bufferedReader.readLine()) != null) {
  42. buffer.append(str);
  43. }
  44. bufferedReader.close();
  45. inputStreamReader.close();
  46. // 释放资源
  47. inputStream.close();
  48. inputStream = null;
  49. httpUrlConn.disconnect();
  50. jsonObject = JSONObject.fromObject(buffer.toString());
  51. } catch (ConnectException ce) {
  52. log.error("Weixin server connection timed out.");
  53. } catch (Exception e) {
  54. log.error("https request error:{}", e);
  55. }
  56. return jsonObject;
  57. }
  58. }
2).下面展示访问个人中心时,进行用户授权
  1. /**
  2. * 个人中心
  3. * @param request
  4. * @param response
  5. * @return
  6. */
  7. @RequestMapping("/gotoPeopleIndex")
  8. public String gotoPeopleIndex(HttpServletRequest request,HttpServletResponse response){
  9. //判断是否授权过,授权通过时,会保存session“WeixinUserInfo”,这样下次访问时,如果WeixinUserInfo存在,说明已经授权过,用户信息已经存在
  10. WeixinUserInfo WeixinUserInfo = (WeixinUserInfo) session.getAttribute("WeixinUserInfo");
  11. if(WeixinUserInfo==null){//没有授权过,跳转授权页面,如果你不需要授权,则scope为snsapi_base,这是不会弹出授权页面
  12. String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+TimedTask.appid+"&redirect_uri="+TimedTask.websiteAndProject+"/weixinF/getOpenInfo/gotoPeopleIndex&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
  13. return "redirect:"+url;
  14. }else{
  15. return "weixin/customer/userInfo";
  16. }
  17. }
  18. /**
  19. * 微信网页授权获得微信详情
  20. * @param code
  21. * @param state
  22. * @param view 授权后调整的视图
  23. * @param request
  24. * @param appid 公众号appid
  25. * @param appsecret 公众号appsecret
  26. * @param websiteAndProject 请求地址跟工程名,如我当前的为http://192.168.2.113/seafood
  27. * @param response
  28. * @throws ServletException
  29. * @throws IOException
  30. */
  31. @RequestMapping("/getOpenInfo/{view}")
  32. public void getOpenInfo(@RequestParam("code") String code,@RequestParam("state") String state,@PathVariable("view") String view,HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
  33. // 用户同意授权
  34. if (!"authdeny".equals(code)) {
  35. //获取OpenId
  36. OpenIdResult open = WeixinUtil.getOpenId(request, code, TimedTask.appid, TimedTask.appsecret);
  37. //检验授权凭证(access_token)是否有效
  38. int result = WeixinUtil.checkAccessToken(open.getAccess_token(), open.getOpenid());
  39. if(0 != result){
  40. open = WeixinUtil.getNewAccess_Token(open,open.getRefresh_token(),TimedTask.appid);
  41. }
  42. // 网页授权接口访问凭证
  43. String accessToken = open.getAccess_token();
  44. String openId = open.getOpenid();
  45. //获取微信用户详细信息,如果你不需要授权,可跳过该步骤,直接以微信的OpenId,查找是否已经绑定,没有跳转到绑定界面
  46. WeixinUserInfo user = WeixinUtil.getWeixinUserInfo(accessToken, openId);
  47. Customer customer = weixinFirstServer.getCustomerDetailByOpenId(user.getOpenId());
  48. if(customer!=null){
  49. if(customer.getAccountStatus()==2){
  50. response.setContentType("text/html; charset=UTF-8");
  51. try {
  52. response.sendRedirect(TimedTask.websiteAndProject+"/weixin/customer/noAuthority.jsp");
  53. } catch (IOException e) {
  54. e.printStackTrace();
  55. }
  56. return;
  57. }
  58. customer.setHeadPhoto(user.getHeadImgUrl());
  59. }else{
  60. Customer newuser = new Customer();
  61. newuser.setCustomerWeixinId(openId);
  62. newuser.setCustomerWNickname(user.getNickname());
  63. newuser.setSex(user.getSex());
  64. //绑定
  65. result = weixinFirstServer.addCustomerInfo(newuser);
  66. if(result<=0){
  67. response.setContentType("text/html; charset=UTF-8");
  68. try {
  69. response.sendRedirect(TimedTask.websiteAndProject+"/weixin/customer/error.jsp");
  70. } catch (IOException e) {
  71. e.printStackTrace();
  72. }
  73. }else{
  74. customer = weixinFirstServer.getCustomerDetailByOpenId(user.getOpenId());
  75. if(customer.getAccountStatus()==2){
  76. response.setContentType("text/html; charset=UTF-8");
  77. try {
  78. response.sendRedirect(TimedTask.websiteAndProject+"/weixin/customer/noAuthority.jsp");
  79. } catch (IOException e) {
  80. e.printStackTrace();
  81. }
  82. return;
  83. }
  84. }
  85. }
  86. session.setAttribute("customerInfo", customer);
  87. session.setAttribute("WeixinUserInfo", user);
  88. request.setAttribute("state", state);
  89. response.setContentType("text/html; charset=UTF-8");
  90. try {
  91. response.sendRedirect(TimedTask.websiteAndProject+"/weixinF/"+view);
  92. } catch (IOException e) {
  93. e.printStackTrace();
  94. }
  95. }else{
  96. response.setContentType("text/html; charset=UTF-8");
  97. try {
  98. response.sendRedirect(TimedTask.websiteAndProject+"/weixin/customer/error.jsp");
  99. } catch (IOException e) {
  100. e.printStackTrace();
  101. }
  102. }
  103. }
微信工具类代码:
  1. public class WeixinUtil {
  2. public final static String getOpen_id_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
  3. /**
  4. * 检验授权凭证(access_token)是否有效
  5. * @param accessToken 凭证
  6. * @param openid id
  7. * @return
  8. */
  9. public static int checkAccessToken(String accessToken, String openid) {
  10. String requestUrl = "https://api.weixin.qq.com/sns/auth?access_token="+accessToken+"&openid="+openid;
  11. JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
  12. int result = 1;
  13. // 如果请求成功
  14. if (null != jsonObject) {
  15. try {
  16. result = jsonObject.getInt("errcode");
  17. } catch (JSONException e) {
  18. accessToken = null;
  19. // 获取token失败
  20. log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
  21. }
  22. }
  23. return result;
  24. }
  25. /**
  26. * 用户授权,使用refresh_token刷新access_token
  27. * @return
  28. */
  29. public static OpenIdResult getNewAccess_Token(OpenIdResult open,String refresh_token,String openId) {
  30. String requestUrl = getNewAccess_token.replace("REFRESH_TOKEN", refresh_token).replace("APPID", openId);
  31. JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
  32. // 如果请求成功
  33. if (null != jsonObject) {
  34. try {
  35. open.setAccess_token(jsonObject.getString("access_token"));
  36. } catch (JSONException e) {
  37. // 获取token失败
  38. log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
  39. }
  40. }
  41. return open;
  42. }
  43. /**
  44. * 获得用户基本信息
  45. * @param request
  46. * @param code
  47. * @param appid
  48. * @param appsecret
  49. * @return
  50. */
  51. public static OpenIdResult getOpenId(HttpServletRequest request, String code,String appid, String appsecret) {
  52. String requestURI = request.getRequestURI();
  53. String param = request.getQueryString();
  54. if(param!=null){
  55. requestURI = requestURI+"?"+param;
  56. }
  57. String url = getOpen_id_url.replace("APPID",appid).replace("SECRET",appsecret).replace("CODE",code);
  58. JSONObject jsonObject = httpRequest(url, "POST", null);
  59. OpenIdResult result = new OpenIdResult();
  60. if (null != jsonObject) {
  61. Object obj = jsonObject.get("errcode");
  62. if (obj == null) {
  63. result.setAccess_token(jsonObject.getString("access_token"));
  64. result.setExpires_in(jsonObject.getString("expires_in"));
  65. result.setOpenid(jsonObject.getString("openid"));
  66. result.setRefresh_token(jsonObject.getString("refresh_token"));
  67. result.setScope(jsonObject.getString("scope"));
  68. }else{
  69. System.out.println("获取openId回执:"+jsonObject.toString()+"访问路径:"+requestURI);
  70. log.error("访问路径:"+requestURI);
  71. log.error("获取openId失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
  72. }
  73. }
  74. return result;
  75. }
  76. /**
  77. * 通过网页授权获取用户信息
  78. * @param accessToken 网页授权接口调用凭证
  79. * @param openId 用户标识
  80. * @return WeixinUserInfo
  81. */
  82. public static WeixinUserInfo getWeixinUserInfo(String accessToken, String openId) {
  83. WeixinUserInfo user = null;
  84. // 拼接请求地址
  85. String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
  86. requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
  87. // 通过网页授权获取用户信息
  88. JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
  89. if (null != jsonObject) {
  90. try {
  91. user = new WeixinUserInfo();
  92. // 用户的标识
  93. user.setOpenId(jsonObject.getString("openid"));
  94. // 昵称
  95. user.setNickname(jsonObject.getString("nickname"));
  96. // 性别(1是男性,2是女性,0是未知)
  97. user.setSex(jsonObject.getInt("sex"));
  98. // 用户所在国家
  99. user.setCountry(jsonObject.getString("country"));
  100. // 用户所在省份
  101. user.setProvince(jsonObject.getString("province"));
  102. // 用户所在城市
  103. user.setCity(jsonObject.getString("city"));
  104. // 用户头像
  105. user.setHeadImgUrl(jsonObject.getString("headimgurl"));
  106. // 用户特权信息
  107. user.setPrivilegeList(JSONArray.toList(jsonObject.getJSONArray("privilege"), List.class));
  108. } catch (Exception e) {
  109. user = null;
  110. int errorCode = jsonObject.getInt("errcode");
  111. String errorMsg = jsonObject.getString("errmsg");
  112. log.error("获取用户信息失败 errcode:{} errmsg:{},reqUrl{}", errorCode, errorMsg);
  113. }
  114. }
  115. return user;
  116. }
  117. }
下面展示,当用户session失效时,自动登录的代码,这时是不需要授权的
  1. @RequestMapping("/gotoGoodsView")
  2. public String gotoGoodsView(@RequestParam(value="longitude",defaultValue="",required=false) String longitude,@RequestParam(value="latitude",defaultValue="",required=false) String latitude){
  3. String param = request.getQueryString();
  4. String url = request.getServletPath();
  5. if(param!=null){
  6. url = url+"?"+param.replaceAll("&","-");//如果不把&替换成别的,当重新登录成功后调整会参数丢失
  7. }
  8. Customer customerInfo = (Customer) session.getAttribute("customerInfo");
  9. if(customerInfo==null){//session失效,跳转到获取微信详情页面(授权)
  10. return "redirect:/weixinF/getCode?view="+TimedTask.websiteAndProject+"/weixinF/autoLogin&view2="+TimedTask.websiteAndProject+url;
  11. }
  12. return "/weixin/customer/goodsList";
  13. }
  14. @RequestMapping("/getCode")
  15. public void getCode(HttpServletResponse response){
  16. String view = request.getParameter("view");//获取openId的路径
  17. String view2 = request.getParameter("view2");//获取openId成功后跳转的路径
  18. String redirect_url = "";
  19. try {
  20. redirect_url = URLEncoder.encode(view,"UTF-8");
  21. if(view2!=null && !"".equals(view2)){
  22. view2 = view2.replaceAll("-","&");
  23. redirect_url = redirect_url +"?redirect_url="+ URLEncoder.encode(URLEncoder.encode(view2,"UTF-8"),"UTF-8");
  24. }
  25. } catch (UnsupportedEncodingException e1) {
  26. e1.printStackTrace();
  27. }
  28. String url = WeixinUtil.getCode_url.replace("APPID",TimedTask.appid).replace("REDIRECT_URI",redirect_url);
  29. response.setContentType("text/html; charset=UTF-8");
  30. try {
  31. response.sendRedirect(url);
  32. } catch (IOException e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. /**
  37. * 自动登录并跳转
  38. * @param code
  39. * @param appid 公众号appid
  40. * @param appsecret 公众号appsecret
  41. * @param websiteAndProject 请求地址跟工程名,如我当前的为http://192.168.2.113/seafood
  42. * @param url 自动登录后跳转路径
  43. * @return
  44. */
  45. @RequestMapping("/autoLogin")
  46. public String autoLogin(HttpServletResponse response,@RequestParam(value="code",defaultValue="") String code,@RequestParam(value="redirect_url",defaultValue="") String url){
  47. OpenIdResult open = WeixinUtil.getOpenId(request,code,TimedTask.appid,TimedTask.appsecret);//根据Code获取OpenId
  48. //根据OpenId查找是否有该客户,没有进行绑定
  49. Customer customerInfo = weixinFirstServer.getCustomerDetailByOpenId(open.getOpenid());
  50. if(customerInfo!=null){
  51. if(customerInfo.getAccountStatus()==2){//用户账户是否正常
  52. return "redirect:"+TimedTask.websiteAndProject+"/weixin/customer/noAuthority.jsp";
  53. }
  54. session.setAttribute("customerInfo", customerInfo);//把用户信息存在session中
  55. response.setContentType("text/html; charset=UTF-8");
  56. try {
  57. response.sendRedirect(url);
  58. } catch (IOException e) {
  59. e.printStackTrace();
  60. }
  61. return null;
  62. }else{
  63. url= url.replaceAll("&","-");
  64. url = url.replace(TimedTask.websiteAndProject,"");
  65. String redirectUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+TimedTask.appid+"&redirect_uri="+TimedTask.websiteAndProject+"/weixinF/getOpenInfoRedirectAction?actionName="+url+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
  66. response.setContentType("text/html; charset=UTF-8");
  67. try {
  68. response.sendRedirect(redirectUrl);
  69. } catch (IOException e) {
  70. e.printStackTrace();
  71. }
  72. return null;
  73. }
  74. }
到此,微信网页授权认证,与session失效自动登录已经完成,如果有问题欢迎在评论区指出
下一篇将讲解如何发送模板消息,实现消息实时通知,如常见业务:订单通知,消费通知等,参考【http://www.cnblogs.com/zhaixiajiao/p/6760194.html

微信公众号开发《一》OAuth2.0网页授权认证获取用户的详细信息,实现自动登陆的更多相关文章

  1. C#微信公众号开发-高级接口-之网页授权oauth2.0获取用户基本信息(二)

    C#微信公众号开发之网页授权oauth2.0获取用户基本信息(一) 中讲解了如果通过微信授权2.0snsapi_base获取已经关注用户的基本信息,然而很多情况下我们经常需要获取非关注用户的信息,方法 ...

  2. Java微信公众平台开发之OAuth2.0网页授权

    根据官方文档点击查看在微信公众号请求用户网页授权之前,开发者需要先到公众平台官网中的"开发 - 接口权限 - 网页服务 - 网页帐号 - 网页授权获取用户基本信息"的配置选项中,修 ...

  3. PHP微信公众平台OAuth2.0网页授权,获取用户信息代码类封装demo(二)

    一.这个文件微信授权使用的是OAuth2.0授权的方式.主要有以下简略步骤: 第一步:判断有没有code,有code去第三步,没有code去第二步 第二步:用户同意授权,获取code 第三步:通过co ...

  4. php 微信公众平台OAuth2.0网页授权,获取用户信息代码类封装demo

    get_wx_data.php <?php /** * 获取微信用户信息 * @author: Lucky hypo */ class GetWxData{ private $appid = ' ...

  5. 微信公众平台开发 OAuth2.0网页授权认证

    一.什么是OAuth2.0 官方网站:http://oauth.NET/   http://oauth.Net/2/ 权威定义:OAuth is An open protocol to allow s ...

  6. 微信公众平台开发—利用OAuth2.0获取微信用户基本信息

    在借鉴前两篇获取微信用户基本信息的基础下,本人也总结整理了一些个人笔记:如何通过OAuth2.0获取微信用户信息 1.首先在某微信平台下配置OAuth2.0授权回调页面: 2.通过appid构造url ...

  7. 微信公众号开发《三》微信JS-SDK之地理位置的获取,集成百度地图实现在线地图搜索

    本次讲解微信开发第三篇:获取用户地址位置信息,是非常常用的功能,特别是服务行业公众号,尤为需要该功能,本次讲解的就是如何调用微信JS-SDK接口,获取用户位置信息,并结合百度地铁,实现在线地图搜索,与 ...

  8. 微信公众号开发《三》微信JS-SDK之地理位置的获取与在线导航,集成百度地图实现在线地图搜索

    本次讲解微信开发第三篇:获取用户地址位置信息,是非常常用的功能,特别是服务行业公众号,尤为需要该功能,本次讲解的就是如何调用微信JS-SDK接口,获取用户位置信息,并结合百度地铁,实现在线地图搜索,与 ...

  9. 微信公众平台开发(71)OAuth2.0网页授权

    微信公众平台开发 OAuth2.0网页授权认证 网页授权获取用户基本信息 作者:方倍工作室 微信公众平台最近新推出微信认证,认证后可以获得高级接口权限,其中一个是OAuth2.0网页授权,很多朋友在使 ...

随机推荐

  1. Elasticsearch NEST使用指南:映射和分析

    NEST提供了多种映射方法,这里介绍下通过Attribute自定义映射. 一.简单实现 1.定义业务需要的POCO,并指定需要的Attribute [ElasticsearchType(Name = ...

  2. php生成N个不重复的随机数实例

    思路: 将随机数存入数组,再在数组中去除重复的值,即可生成一定数量的不重复随机数. /* * array unique_rand( int $min, int $max, int $num ) * 生 ...

  3. Squid代理服务器(三)——ACL访问控制

    一.ACL概念 Squid提供了强大的代理控制机制,通过合理设置ACL(Access Control List,访问控制列表)并进行限制,可以针对源地址.目标地址.访问的URL路径.访问的时间等各种条 ...

  4. UIViewContentMode-

    图片很小,frame很大 图片很大,frame很小 UIViewContentModeScaleToFill, UIViewContentModeScaleAspectFit, UIViewConte ...

  5. 北京DNS

    202.106.0.20 202.106.196.115 202.106.46.151

  6. 箭头函数中的this和普通函数中的this对比

    ES6中新增了箭头函数这种语法,箭头函数以其简洁性和方便获取this的特性.下面来总结一下他们之间的区别: 普通函数下的this: 在普通函数中的this总是代表它的直接调用者,在默认情况下,this ...

  7. Jenkins Slave Nodes – using the Swarm Plugin

    link: http://www.donaldsimpson.co.uk/2013/03/18/jenkins-slave-nodes-using-the-swarm-plugin/ I’ve bee ...

  8. MVC返回数据流,ajax接受并保存文件

    js代码 <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <ti ...

  9. springboot整合security实现基于url的权限控制

    权限控制基本上是任何一个web项目都要有的,为此spring为我们提供security模块来实现权限控制,网上找了很多资料,但是提供的demo代码都不能完全满足我的需求,因此自己整理了一版. 在上代码 ...

  10. 我的Python升级打怪之路【二】:Python的基本数据类型及操作

    基本数据类型 1.数字 int(整型) 在32位机器上,整数的位数是32位,取值范围是-2**31~2--31-1 在64位系统上,整数的位数是64位,取值范围是-2**63~2**63-1 clas ...