微信公众号开发《一》OAuth2.0网页授权认证获取用户的详细信息,实现自动登陆
原创声明:本文为本人原创作品,绝非他处转账,转载请联系博主
从接触公众号到现在,开发维护了2个公众号,开发过程中遇到很多问题,现在把部分模块功能在这备案一下,做个总结也希望能给其他人帮助
工欲善其事,必先利其器,先看看开发公众号需要准备或了解什么
- web开发工具:官方提供的开发工具,使用自己的微信号来调试微信网页授权、调试、检验页面的 JS-SDK 相关功能与权限,模拟大部分 SDK 的输入和输出。下载地址:web开发工具下载
- 开发文档:https://mp.weixin.qq.com/wiki
- 登录微信测试公众号,获取公众号的appID、appsecret,登录地址:http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login (一般测试开发阶段,都不拿正式公众号测试,因为存在风险并且你调试时不用担心影响到正式公众号的正常使用,而且有些接口在正式公众号上比较严格,而在测试公众号上可以放开,如模板信息)
下面进入正题,实现微信网页授权,获取微信信息,主要用于以微信帐号作为用户登录,如果你只是需要绑定微信,就可以不用授权,直接请求获取微信OpenId(对当前公众号唯一),进行用户绑定(在下面代码时是写明如何实现),该功能可在开发文档:微信网页开发-》微信网页授权里查看详细信息,下面正式开始。
1.填写授权回调页面域名
进入测试公众号,在体验接口权限表中找到网页帐号,右侧添加自己的域名,测试公众号可填写本地IP,如你是正式公众号只能填写自己的域名,如果未填写,当进行接口调用时,会提示:redirect_uri参数错误!如果还有其他不了解的配置,可以在开发文档里查看详信息,
2.代码展示
- public class WeixinUtil {
- /**
- * 发起https请求并获取结果
- * @param requestUrl 请求地址
- * @param requestMethod 请求方式(GET、POST)
- * @param outputStr 提交的数据
- * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
- */
- public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
- JSONObject jsonObject = null;
- StringBuffer buffer = new StringBuffer();
- try {
- // 创建SSLContext对象,并使用我们指定的信任管理器初始化
- TrustManager[] tm = { new MyX509TrustManager() };
- 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();
- jsonObject = JSONObject.fromObject(buffer.toString());
- } catch (ConnectException ce) {
- log.error("Weixin server connection timed out.");
- } catch (Exception e) {
- log.error("https request error:{}", e);
- }
- return jsonObject;
- }
- }
- /**
- * 个人中心
- * @param request
- * @param response
- * @return
- */
- @RequestMapping("/gotoPeopleIndex")
- public String gotoPeopleIndex(HttpServletRequest request,HttpServletResponse response){
- //判断是否授权过,授权通过时,会保存session“WeixinUserInfo”,这样下次访问时,如果WeixinUserInfo存在,说明已经授权过,用户信息已经存在
- WeixinUserInfo WeixinUserInfo = (WeixinUserInfo) session.getAttribute("WeixinUserInfo");
- if(WeixinUserInfo==null){//没有授权过,跳转授权页面,如果你不需要授权,则scope为snsapi_base,这是不会弹出授权页面
- 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";
- return "redirect:"+url;
- }else{
- return "weixin/customer/userInfo";
- }
- }
- /**
- * 微信网页授权获得微信详情
- * @param code
- * @param state
- * @param view 授权后调整的视图
- * @param request
- * @param appid 公众号appid
- * @param appsecret 公众号appsecret
- * @param websiteAndProject 请求地址跟工程名,如我当前的为http://192.168.2.113/seafood
- * @param response
- * @throws ServletException
- * @throws IOException
- */
- @RequestMapping("/getOpenInfo/{view}")
- public void getOpenInfo(@RequestParam("code") String code,@RequestParam("state") String state,@PathVariable("view") String view,HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
- // 用户同意授权
- if (!"authdeny".equals(code)) {
- //获取OpenId
- OpenIdResult open = WeixinUtil.getOpenId(request, code, TimedTask.appid, TimedTask.appsecret);
- //检验授权凭证(access_token)是否有效
- int result = WeixinUtil.checkAccessToken(open.getAccess_token(), open.getOpenid());
- if(0 != result){
- open = WeixinUtil.getNewAccess_Token(open,open.getRefresh_token(),TimedTask.appid);
- }
- // 网页授权接口访问凭证
- String accessToken = open.getAccess_token();
- String openId = open.getOpenid();
- //获取微信用户详细信息,如果你不需要授权,可跳过该步骤,直接以微信的OpenId,查找是否已经绑定,没有跳转到绑定界面
- WeixinUserInfo user = WeixinUtil.getWeixinUserInfo(accessToken, openId);
- Customer customer = weixinFirstServer.getCustomerDetailByOpenId(user.getOpenId());
- if(customer!=null){
- if(customer.getAccountStatus()==2){
- response.setContentType("text/html; charset=UTF-8");
- try {
- response.sendRedirect(TimedTask.websiteAndProject+"/weixin/customer/noAuthority.jsp");
- } catch (IOException e) {
- e.printStackTrace();
- }
- return;
- }
- customer.setHeadPhoto(user.getHeadImgUrl());
- }else{
- Customer newuser = new Customer();
- newuser.setCustomerWeixinId(openId);
- newuser.setCustomerWNickname(user.getNickname());
- newuser.setSex(user.getSex());
- //绑定
- result = weixinFirstServer.addCustomerInfo(newuser);
- if(result<=0){
- response.setContentType("text/html; charset=UTF-8");
- try {
- response.sendRedirect(TimedTask.websiteAndProject+"/weixin/customer/error.jsp");
- } catch (IOException e) {
- e.printStackTrace();
- }
- }else{
- customer = weixinFirstServer.getCustomerDetailByOpenId(user.getOpenId());
- if(customer.getAccountStatus()==2){
- response.setContentType("text/html; charset=UTF-8");
- try {
- response.sendRedirect(TimedTask.websiteAndProject+"/weixin/customer/noAuthority.jsp");
- } catch (IOException e) {
- e.printStackTrace();
- }
- return;
- }
- }
- }
- session.setAttribute("customerInfo", customer);
- session.setAttribute("WeixinUserInfo", user);
- request.setAttribute("state", state);
- response.setContentType("text/html; charset=UTF-8");
- try {
- response.sendRedirect(TimedTask.websiteAndProject+"/weixinF/"+view);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }else{
- response.setContentType("text/html; charset=UTF-8");
- try {
- response.sendRedirect(TimedTask.websiteAndProject+"/weixin/customer/error.jsp");
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- public class WeixinUtil {
- 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";
- /**
- * 检验授权凭证(access_token)是否有效
- * @param accessToken 凭证
- * @param openid id
- * @return
- */
- public static int checkAccessToken(String accessToken, String openid) {
- String requestUrl = "https://api.weixin.qq.com/sns/auth?access_token="+accessToken+"&openid="+openid;
- JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
- int result = 1;
- // 如果请求成功
- if (null != jsonObject) {
- try {
- result = jsonObject.getInt("errcode");
- } catch (JSONException e) {
- accessToken = null;
- // 获取token失败
- log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
- }
- }
- return result;
- }
- /**
- * 用户授权,使用refresh_token刷新access_token
- * @return
- */
- public static OpenIdResult getNewAccess_Token(OpenIdResult open,String refresh_token,String openId) {
- String requestUrl = getNewAccess_token.replace("REFRESH_TOKEN", refresh_token).replace("APPID", openId);
- JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
- // 如果请求成功
- if (null != jsonObject) {
- try {
- open.setAccess_token(jsonObject.getString("access_token"));
- } catch (JSONException e) {
- // 获取token失败
- log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
- }
- }
- return open;
- }
- /**
- * 获得用户基本信息
- * @param request
- * @param code
- * @param appid
- * @param appsecret
- * @return
- */
- public static OpenIdResult getOpenId(HttpServletRequest request, String code,String appid, String appsecret) {
- String requestURI = request.getRequestURI();
- String param = request.getQueryString();
- if(param!=null){
- requestURI = requestURI+"?"+param;
- }
- String url = getOpen_id_url.replace("APPID",appid).replace("SECRET",appsecret).replace("CODE",code);
- JSONObject jsonObject = httpRequest(url, "POST", null);
- OpenIdResult result = new OpenIdResult();
- if (null != jsonObject) {
- Object obj = jsonObject.get("errcode");
- if (obj == null) {
- result.setAccess_token(jsonObject.getString("access_token"));
- result.setExpires_in(jsonObject.getString("expires_in"));
- result.setOpenid(jsonObject.getString("openid"));
- result.setRefresh_token(jsonObject.getString("refresh_token"));
- result.setScope(jsonObject.getString("scope"));
- }else{
- System.out.println("获取openId回执:"+jsonObject.toString()+"访问路径:"+requestURI);
- log.error("访问路径:"+requestURI);
- log.error("获取openId失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
- }
- }
- return result;
- }
- /**
- * 通过网页授权获取用户信息
- * @param accessToken 网页授权接口调用凭证
- * @param openId 用户标识
- * @return WeixinUserInfo
- */
- public static WeixinUserInfo getWeixinUserInfo(String accessToken, String openId) {
- WeixinUserInfo user = null;
- // 拼接请求地址
- String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
- requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
- // 通过网页授权获取用户信息
- JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
- if (null != jsonObject) {
- try {
- user = new WeixinUserInfo();
- // 用户的标识
- user.setOpenId(jsonObject.getString("openid"));
- // 昵称
- user.setNickname(jsonObject.getString("nickname"));
- // 性别(1是男性,2是女性,0是未知)
- user.setSex(jsonObject.getInt("sex"));
- // 用户所在国家
- user.setCountry(jsonObject.getString("country"));
- // 用户所在省份
- user.setProvince(jsonObject.getString("province"));
- // 用户所在城市
- user.setCity(jsonObject.getString("city"));
- // 用户头像
- user.setHeadImgUrl(jsonObject.getString("headimgurl"));
- // 用户特权信息
- user.setPrivilegeList(JSONArray.toList(jsonObject.getJSONArray("privilege"), List.class));
- } catch (Exception e) {
- user = null;
- int errorCode = jsonObject.getInt("errcode");
- String errorMsg = jsonObject.getString("errmsg");
- log.error("获取用户信息失败 errcode:{} errmsg:{},reqUrl{}", errorCode, errorMsg);
- }
- }
- return user;
- }
- }
- @RequestMapping("/gotoGoodsView")
- public String gotoGoodsView(@RequestParam(value="longitude",defaultValue="",required=false) String longitude,@RequestParam(value="latitude",defaultValue="",required=false) String latitude){
- String param = request.getQueryString();
- String url = request.getServletPath();
- if(param!=null){
- url = url+"?"+param.replaceAll("&","-");//如果不把&替换成别的,当重新登录成功后调整会参数丢失
- }
- Customer customerInfo = (Customer) session.getAttribute("customerInfo");
- if(customerInfo==null){//session失效,跳转到获取微信详情页面(授权)
- return "redirect:/weixinF/getCode?view="+TimedTask.websiteAndProject+"/weixinF/autoLogin&view2="+TimedTask.websiteAndProject+url;
- }
- return "/weixin/customer/goodsList";
- }
- @RequestMapping("/getCode")
- public void getCode(HttpServletResponse response){
- String view = request.getParameter("view");//获取openId的路径
- String view2 = request.getParameter("view2");//获取openId成功后跳转的路径
- String redirect_url = "";
- try {
- redirect_url = URLEncoder.encode(view,"UTF-8");
- if(view2!=null && !"".equals(view2)){
- view2 = view2.replaceAll("-","&");
- redirect_url = redirect_url +"?redirect_url="+ URLEncoder.encode(URLEncoder.encode(view2,"UTF-8"),"UTF-8");
- }
- } catch (UnsupportedEncodingException e1) {
- e1.printStackTrace();
- }
- String url = WeixinUtil.getCode_url.replace("APPID",TimedTask.appid).replace("REDIRECT_URI",redirect_url);
- response.setContentType("text/html; charset=UTF-8");
- try {
- response.sendRedirect(url);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * 自动登录并跳转
- * @param code
- * @param appid 公众号appid
- * @param appsecret 公众号appsecret
- * @param websiteAndProject 请求地址跟工程名,如我当前的为http://192.168.2.113/seafood
- * @param url 自动登录后跳转路径
- * @return
- */
- @RequestMapping("/autoLogin")
- public String autoLogin(HttpServletResponse response,@RequestParam(value="code",defaultValue="") String code,@RequestParam(value="redirect_url",defaultValue="") String url){
- OpenIdResult open = WeixinUtil.getOpenId(request,code,TimedTask.appid,TimedTask.appsecret);//根据Code获取OpenId
- //根据OpenId查找是否有该客户,没有进行绑定
- Customer customerInfo = weixinFirstServer.getCustomerDetailByOpenId(open.getOpenid());
- if(customerInfo!=null){
- if(customerInfo.getAccountStatus()==2){//用户账户是否正常
- return "redirect:"+TimedTask.websiteAndProject+"/weixin/customer/noAuthority.jsp";
- }
- session.setAttribute("customerInfo", customerInfo);//把用户信息存在session中
- response.setContentType("text/html; charset=UTF-8");
- try {
- response.sendRedirect(url);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }else{
- url= url.replaceAll("&","-");
- url = url.replace(TimedTask.websiteAndProject,"");
- 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";
- response.setContentType("text/html; charset=UTF-8");
- try {
- response.sendRedirect(redirectUrl);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
- }
微信公众号开发《一》OAuth2.0网页授权认证获取用户的详细信息,实现自动登陆的更多相关文章
- C#微信公众号开发-高级接口-之网页授权oauth2.0获取用户基本信息(二)
C#微信公众号开发之网页授权oauth2.0获取用户基本信息(一) 中讲解了如果通过微信授权2.0snsapi_base获取已经关注用户的基本信息,然而很多情况下我们经常需要获取非关注用户的信息,方法 ...
- Java微信公众平台开发之OAuth2.0网页授权
根据官方文档点击查看在微信公众号请求用户网页授权之前,开发者需要先到公众平台官网中的"开发 - 接口权限 - 网页服务 - 网页帐号 - 网页授权获取用户基本信息"的配置选项中,修 ...
- PHP微信公众平台OAuth2.0网页授权,获取用户信息代码类封装demo(二)
一.这个文件微信授权使用的是OAuth2.0授权的方式.主要有以下简略步骤: 第一步:判断有没有code,有code去第三步,没有code去第二步 第二步:用户同意授权,获取code 第三步:通过co ...
- php 微信公众平台OAuth2.0网页授权,获取用户信息代码类封装demo
get_wx_data.php <?php /** * 获取微信用户信息 * @author: Lucky hypo */ class GetWxData{ private $appid = ' ...
- 微信公众平台开发 OAuth2.0网页授权认证
一.什么是OAuth2.0 官方网站:http://oauth.NET/ http://oauth.Net/2/ 权威定义:OAuth is An open protocol to allow s ...
- 微信公众平台开发—利用OAuth2.0获取微信用户基本信息
在借鉴前两篇获取微信用户基本信息的基础下,本人也总结整理了一些个人笔记:如何通过OAuth2.0获取微信用户信息 1.首先在某微信平台下配置OAuth2.0授权回调页面: 2.通过appid构造url ...
- 微信公众号开发《三》微信JS-SDK之地理位置的获取,集成百度地图实现在线地图搜索
本次讲解微信开发第三篇:获取用户地址位置信息,是非常常用的功能,特别是服务行业公众号,尤为需要该功能,本次讲解的就是如何调用微信JS-SDK接口,获取用户位置信息,并结合百度地铁,实现在线地图搜索,与 ...
- 微信公众号开发《三》微信JS-SDK之地理位置的获取与在线导航,集成百度地图实现在线地图搜索
本次讲解微信开发第三篇:获取用户地址位置信息,是非常常用的功能,特别是服务行业公众号,尤为需要该功能,本次讲解的就是如何调用微信JS-SDK接口,获取用户位置信息,并结合百度地铁,实现在线地图搜索,与 ...
- 微信公众平台开发(71)OAuth2.0网页授权
微信公众平台开发 OAuth2.0网页授权认证 网页授权获取用户基本信息 作者:方倍工作室 微信公众平台最近新推出微信认证,认证后可以获得高级接口权限,其中一个是OAuth2.0网页授权,很多朋友在使 ...
随机推荐
- Elasticsearch NEST使用指南:映射和分析
NEST提供了多种映射方法,这里介绍下通过Attribute自定义映射. 一.简单实现 1.定义业务需要的POCO,并指定需要的Attribute [ElasticsearchType(Name = ...
- php生成N个不重复的随机数实例
思路: 将随机数存入数组,再在数组中去除重复的值,即可生成一定数量的不重复随机数. /* * array unique_rand( int $min, int $max, int $num ) * 生 ...
- Squid代理服务器(三)——ACL访问控制
一.ACL概念 Squid提供了强大的代理控制机制,通过合理设置ACL(Access Control List,访问控制列表)并进行限制,可以针对源地址.目标地址.访问的URL路径.访问的时间等各种条 ...
- UIViewContentMode-
图片很小,frame很大 图片很大,frame很小 UIViewContentModeScaleToFill, UIViewContentModeScaleAspectFit, UIViewConte ...
- 北京DNS
202.106.0.20 202.106.196.115 202.106.46.151
- 箭头函数中的this和普通函数中的this对比
ES6中新增了箭头函数这种语法,箭头函数以其简洁性和方便获取this的特性.下面来总结一下他们之间的区别: 普通函数下的this: 在普通函数中的this总是代表它的直接调用者,在默认情况下,this ...
- 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 ...
- MVC返回数据流,ajax接受并保存文件
js代码 <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <ti ...
- springboot整合security实现基于url的权限控制
权限控制基本上是任何一个web项目都要有的,为此spring为我们提供security模块来实现权限控制,网上找了很多资料,但是提供的demo代码都不能完全满足我的需求,因此自己整理了一版. 在上代码 ...
- 我的Python升级打怪之路【二】:Python的基本数据类型及操作
基本数据类型 1.数字 int(整型) 在32位机器上,整数的位数是32位,取值范围是-2**31~2--31-1 在64位系统上,整数的位数是64位,取值范围是-2**63~2**63-1 clas ...