springboot 微信授权网页登录操作流程

操作流程

假设你已经有自己的域名,因为微信公众号和微信回调都需要域名

先看看官方给的文档

根据官方文档,主要流程如下:

(1)引导用户进入授权页面同意授权,获取code

(2)通过code换取网页授权access_token(与基础支持中的access_token不同)

(3)刷新access_token(如果有需要)

(3)通过网页授权access_token和openid获取用户基本信息

提示:以下是本篇文章正文内容,下面案例可供参考

编写微信授权方法和获取用户信息方法

二、使用步骤

获取微信二维码信息

代码如下(示例):

/**
  * 公众号微信登录授权
  */
 @RequestMapping("/wxLogin")
 public void wxLogin(HttpServletResponse response) throws IOException {
  //这个url的域名必须在公众号中进行注册验证,这个地址是成功后的回调地址
  String backUrl = "http://7ca0c439f61c.ngrok.io/callback";//使用自己的域名
  // 第一步:用户同意授权,获取code
  //请求地址 snsapi_base snsapi_userinfo
  String url = "https://open.weixin.qq.com/connect/oauth2/authorize" +
    "?appid=" + HttpClientUtil.APPID +
    "&redirect_uri=" + URLEncoder.encode(backUrl,"utf-8") +
    "&response_type=code" +
    "&scope=snsapi_userinfo" +
    "&state=STATE#wechat_redirect";
  logger.info("forward重定向地址{" + url + "}");
  //必须重定向,否则不能成功
  response.sendRedirect(url);
 }

备注:在前端页面直接加载url 就可以出现二维码界面了。直接用的微信的页面,也可以根据自己的爱好进行设计页面
 /**
  * 公众号微信登录授权回调函数
  */
 @RequestMapping("/callback")
 public UserLoginRes callback(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  UserLoginRes userLoginRes = new UserLoginRes();
  try{
   WXUserInfoReq weixinUserInfo = new WXUserInfoReq();
   /*start 获取微信用户基本信息*/
   String code = req.getParameter("code");
   //第二步:通过code换取网页授权access_token
   String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
     + "appid=" + HttpClientUtil.APPID
     + "&secret=" + HttpClientUtil.APPSECRET
     + "&code=" + code
     + "&grant_type=authorization_code";
   System.out.println(url);

   String result = HttpClientUtil.doGet(url);
   JSONObject jsonObject = JSON.parseObject(result);

   /*
   { "access_token":"ACCESS_TOKEN",
   "expires_in":7200,
   "refresh_token":"REFRESH_TOKEN",
   "openid":"OPENID",
   "scope":"SCOPE"
   }
   */
    String openid = jsonObject.getString("openid");
    String access_token = jsonObject.getString("access_token");

   //第三步验证access_token是否失效;
   String chickUrl = "https://api.weixin.qq.com/sns/auth?access_token="
     + access_token + "&openid=" + openid;
   String resultInfo = HttpClientUtil.doGet(chickUrl);
   JSONObject chickuserInfo = JSON.parseObject(resultInfo);
   System.out.println(chickuserInfo.toString());
   if (!"0".equals(chickuserInfo.getString("errcode"))) {
    String refreshInfo1 = HttpClientUtil.doGet(chickUrl);
    JSONObject refreshInfo = JSON.parseObject(refreshInfo1);
    /*
    { "access_token":"ACCESS_TOKEN",
    "expires_in":7200,
    "refresh_token":"REFRESH_TOKEN",
    "openid":"OPENID",
    "scope":"SCOPE" }
    */
    access_token = refreshInfo.getString("access_token");
   }

   // 第四步:拉取用户信息
   String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token
     + "&openid=" + openid
     + "&lang=zh_CN";
   JSONObject userInfo = JSON.parseObject(HttpClientUtil.doGet(infoUrl));
   /*
   { "openid":" OPENID",
   "nickname": NICKNAME,
   "sex":"1",
   "province":"PROVINCE"
   "city":"CITY",
   "country":"COUNTRY",
   "headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
   "privilege":[ "PRIVILEGE1" "PRIVILEGE2"  ],
   "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
   }
   */
   System.out.println(userInfo.getString("openid") + ":" + userInfo.getString("nickname") +":" + userInfo.getString("sex"));
  }catch (Exception e){
   e.printStackTrace();
   userLoginRes.setResult("NO");
   userLoginRes.setRtnErrId("ERROR");
   userLoginRes.setRtnErrMsg(e.getMessage());
  }
  return userLoginRes;
 }

使用到的HttpClientUtil工具类

代码如下(示例):

public class HttpClientUtil {
 //appid、secret为自己公众号平台的appid和secret
 public static final String APPID="xxxxxxx";
 public static final String APPSECRET ="xxxxxxx"; 

 public static String doGet(String url, Map<String, String> param) {
  // 创建Httpclient对象
  CloseableHttpClient httpclient = HttpClients.createDefault();

  String resultString = "";
  CloseableHttpResponse response = null;
  HttpGet httpGet = null;
  try {
   // 创建uri
   URIBuilder builder = new URIBuilder(url);
   if (param != null) {
    for (String key : param.keySet()) {
     builder.addParameter(key, param.get(key));
    }
   }
   URI uri = builder.build();
   // 创建http GET请求
   httpGet = new HttpGet(uri);
   httpGet.setHeader("Host", "api.weixin.qq.com");
   httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko");
   httpGet.setHeader("Accept", "text/html, application/xhtml+xml, */*");
   httpGet.setHeader("Accept-Encoding", "gzip, deflate, br");
   httpGet.setHeader("Connection", "keep-alive");
   httpGet.setHeader("Accept-Language", "zh-CN");
   httpGet.setHeader("Cache-Control", "no-cache");

   // 执行请求
   response = httpclient.execute(httpGet);
   // 判断返回状态是否为200
   if (response.getStatusLine().getStatusCode() == 200) {
    resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
   }
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    if (response != null) {
     response.close();
    }
    httpGet.releaseConnection();
    httpclient.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  return resultString;
 }

 public static String doGet(String url) {
  return doGet(url, null);
 }

 public static String doPost(String url, Map<String, String> param) {
  // 创建Httpclient对象
  CloseableHttpClient httpClient = HttpClients.createDefault();
  CloseableHttpResponse response = null;
  String resultString = "";
  try {
   // 创建Http Post请求
   HttpPost httpPost = new HttpPost(url);
   // 创建参数列表
   if (param != null) {
    List<NameValuePair> paramList = new ArrayList<>();
    for (String key : param.keySet()) {
     paramList.add(new BasicNameValuePair(key, param.get(key)));
    }
    // 模拟表单
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
    httpPost.setEntity(entity);
   }
   // 执行http请求
   response = httpClient.execute(httpPost);
   resultString = EntityUtils.toString(response.getEntity(), "utf-8");
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    response.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }

  return resultString;
 }

 public static String doPost(String url) {
  return doPost(url, null);
 }

 public static String doPostJson(String url, String json) {
  // 创建Httpclient对象
  CloseableHttpClient httpClient = HttpClients.createDefault();
  CloseableHttpResponse response = null;
  String resultString = "";
  try {
   // 创建Http Post请求
   HttpPost httpPost = new HttpPost(url);
   // 创建请求内容
   StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
   httpPost.setEntity(entity);
   // 执行http请求
   response = httpClient.execute(httpPost);
   resultString = EntityUtils.toString(response.getEntity(), "utf-8");
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    response.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  return resultString;
 }

 public static String doGetStr(String httpurl) {
  HttpURLConnection connection = null;
  InputStream is = null;
  BufferedReader br = null;
  String result = null;// 返回结果字符串
  try {
   // 创建远程url连接对象
   URL url = new URL(httpurl);
   // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
   connection = (HttpURLConnection) url.openConnection();
   // 设置连接方式:get
   connection.setRequestMethod("GET");
   // 设置连接主机服务器的超时时间:15000毫秒
   connection.setConnectTimeout(15000);
   // 设置读取远程返回的数据时间:60000毫秒
   connection.setReadTimeout(60000);
   //设置请求头
   connection.setRequestProperty("Host", "api.weixin.qq.com");
   connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko");
   connection.setRequestProperty("Accept", "text/html, application/xhtml+xml, */*");
   connection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
   connection.setRequestProperty("Connection", "keep-alive");
   connection.setRequestProperty("Accept-Language", "zh-CN");
   connection.setRequestProperty("Cache-Control", "no-cache");

   // 发送请求
   connection.connect();
   // 通过connection连接,获取输入流
   if (connection.getResponseCode() == 200) {
    is = connection.getInputStream();
    // 封装输入流is,并指定字符集
    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    // 存放数据
    StringBuffer sbf = new StringBuffer();
    String temp = null;
    while ((temp = br.readLine()) != null) {
     sbf.append(temp);
     sbf.append("\r\n");
    }
    result = sbf.toString();
   }
  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   // 关闭资源
   if (null != br) {
    try {
     br.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   if (null != is) {
    try {
     is.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   connection.disconnect();// 关闭远程连接
  }
  return result;
 }

}

最后根据实际业务处理用户登录

//3.根据uuid查询用户是否存在,如果存在直接登录。如果不存在则自动注册,在登录
   UserInfoModel userInfoByWechat = iUserDao.getUserInfoByWechat(userInfoStr.get("unionid").toString());
   if (userInfoByWechat != null) {
    return ReturnMessage.success(0,"获取成功",userInfoByWechat);
   }
   //4.数据库添加用户信息
   String username = userInfoStr.get("nickname").toString();
   String unionid = userInfoStr.get("unionid").toString();
   UserInfoBean userInfoBean = new UserInfoBean();
   userInfoBean.setUuid(unionid);
   userInfoBean.setUsername(username);
   // 微信登录
   userInfoBean.setStatus(2);
   iUserDao.insertUser(userInfoBean);
   //5.根据uuid查询新注册的用户信息
   UserInfoModel userInfoModel= iUserDao.getUserInfoByWechat(unionid);
   if (userInfoModel == null) {
    return ReturnMessage.fail(400,"用户添加失败,请重新操作");
   }

到此这篇关于springboot 微信授权网页登录操作流程的文章就介绍到这了,更多相关springboot 微信授权登录内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 基于springboot实现整合shiro实现登录认证以及授权过程解析

    这篇文章主要介绍了基于springboot实现整合shiro实现登录认证以及授权过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.添加shiro的依赖 <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring-boot-web- starter</artifactId> <version&g

  • SpringBoot Shiro授权实现过程解析

    这篇文章主要介绍了SpringBoot Shiro授权实现过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 使用Shiro过滤器实现授权 设置好授权拦截跳转的请求地址 /** * 创建ShiroFilterFactoryBean */ @Bean public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") Defaul

  • Springboot如何实现Web系统License授权认证

    在我们做系统级框架的时候,我们要一定程度上考虑系统的使用版权,不能随便一个人拿去在任何环境都能用,所以我们需要给我们系统做一个授权认证机制,只有上传了我们下发的lic文件并验证通过,才能正常使用,下面就开始一步一步实现这个功能 1.生成机器码 我们首先要做的就是对软件部署的环境的唯一性进行限制,这里使用的是macadderss,当然你也可以换成cpu序列编号,并无太大影响,先上代码 private static String getMac() { try { Enumeration<Networ

  • SpringBoot Security整合JWT授权RestAPI的实现

    本教程主要详细讲解SpringBoot Security整合JWT授权RestAPI. 基础环境 技术 版本 Java 1.8+ SpringBoot 2.x.x Security 5.x JWT 0.9.0 创建项目 初始化项目 mvn archetype:generate -DgroupId=com.edurt.sli.slisj -DartifactId=spring-learn-integration-security-jwt -DarchetypeArtifactId=maven-ar

  • springboot2.x实现oauth2授权码登陆的方法

    一 进行授权页 浏览器输入 http://localhost:8081/oauth/authorize?response_type=code&redirect_uri=http://localhost:8081/callback&client_id=android1&scop=all 二 使用资源站用户登陆 自动跨到资源登陆页,先登陆 三 授权资源类型 登陆成功后,去授权你的资源,这些资源是在AuthorizationServerConfig.configure方法里配置的 @Ov

  • springboot 微信授权网页登录操作流程

    操作流程 假设你已经有自己的域名,因为微信公众号和微信回调都需要域名 先看看官方给的文档 根据官方文档,主要流程如下: (1)引导用户进入授权页面同意授权,获取code (2)通过code换取网页授权access_token(与基础支持中的access_token不同) (3)刷新access_token(如果有需要) (3)通过网页授权access_token和openid获取用户基本信息 提示:以下是本篇文章正文内容,下面案例可供参考 编写微信授权方法和获取用户信息方法 二.使用步骤 获取微

  • 利用Spring Social轻松搞定微信授权登录的方法示例

    微信第三方登录有两种方式:扫码登录(微信开放平台)和公众号登录(微信公众平台) 扫码登录可以用于PC等跨平台应用,而公众平台必须在微信app内使用,且必须关注公众号. 下面以公众平台为例,介绍如何基于Spring Social实现微信用户授权并获取到用户信息.(微信开放平台类似) 第一步:到微信公众平台后台注册应用并进行相关设置 微信公众平台后台地址: https://mp.weixin.qq.com/ 也可以先注册一个测试号: https://mp.weixin.qq.com/debug/cg

  • php微信授权登录实例讲解

    要使用微信授权登录功能需要先在微信开发平台创建应用.然后会获取微信提供给你的appId和AppSecret,然后就可以进行开发了. 当然现有很多大佬封装的微信类库非常齐全,而且还很好用,可以去试试,下面讲解一下基本实现方法. 流程 用户同意授权后获取code,code有效期10分钟 使用code获取access_token调用接口凭证,有效期2小时 refresh_token当access_token过期可以使用这个进行刷新,有效期30天 openid普通用户的标识 刷新token 通过toke

  • Vue3项目中优雅实现微信授权登录的方法

    目录 前言 准备 实现思路 上代码 总结 前言 微信授权登录是做微信公众号开发一直绕不开的话题,而且整个授权登录流程的实现,是需要前后端配合一起完成的.在过去前后端还未分离的年代,也许我们前端并不需要太过关心授权的具体实现.然而现在都2021年了,前后端分离的架构大行其道,如何在前后端分离的情况下实现微信授权登录就成了今天要探讨的重点问题. 准备 首先,我们还是需要先梳理下微信授权整个流程是怎样的,这里我就直接将官方文档搬来: 如果用户在微信客户端中访问第三方网页,公众号可以通过微信网页授权机制

  • 企业微信扫码登录网页功能实现代码

    企业微信扫码登录网页功能,代码如下所示: //jq写法完善版 <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <title>信息平台</title> <script src="http://res

  • IOS实现微信授权登录功能

    微信是一个在开发中经常会使用到的平台,比如微信登录.授权.支付.分享.今天我们来看看如何在自己的应用里面集成微信授权. 1.微信授权的定义 微信OAuth2.0授权登录让微信用户使用微信身份安全登录第三方应用或网站,在微信用户授权登录已接入微信OAuth2.0的第三方应用后,第三方可以获取到用户的接口调用凭证(access_token),通过access_token可以进行微信开放平台授权关系接口调用,从而可实现获取微信用户基本开放信息和帮助用户实现基础开放功能等. 2.微信授权的步骤 第三方发

  • Android开发:微信授权登录与微信分享完全解析

    前言 在移动互联网浪潮中,联网APP已经把单机拍死在沙滩上,很多公司都希望自家应用能够有一套帐号系统,可是许多用户却并不一定买账:我凭啥注册你家应用的帐号?微博,微信,QQ几乎成了每个人手机中的必装应用,于是微信,微博,QQ说了:来来来,你们都可以用我家的帐号登录你家应用,只要你遵循OAuth2.0协议标准就行.于是第三方社交帐号登陆成为了许多新兴应用的选择,由于腾讯官方微信开放平台的在线文档相对最新的SDK有些出入,并且登录相关的文档结构次序有些紊乱,今天就把我的一些经验记录在此,对微信开放平

  • 微信小程序获取手机号授权用户登录功能

    小程序中有很多地方都会用到注册用户信息的地方,用户需要填写手机号等,有了这个组件可以快速获取微信绑定手机号码,无须用户填写. 1.getPhoneNumber这个组件通过button来实现(别的标签无效).将button中的open-type="getPhoneNumber",并且绑定bindgetphonenumber事件获取回调. <span style="font-size:14px;"><button open-type="get

  • vue 微信授权登录解决方案

    背景 vue前后端分离开发微信授权 场景 app将商品分享到微信朋友圈或者分享给微信好友,用户点击页面时进行微信授权登陆,获取用户信息. 问题:没有固定的h5应用首页.授权后重定向url带参数并且很长 本人愚钝,开发过程中,尝试过很多方法,踩坑不足以形容我的心情,可以说每一次都是一次跳井的体验啊. 1.一开始是前端请求微信连接,返回code,然后code作为再去请求后台接口获取token,后面看到别人的博客说这个方法不好,最好就是直接请求后台接口,然后后台返回url做跳转,所以就采用了最传统的方

  • vue移动端微信授权登录插件封装的实例

    1.新建wechatAuth.js文件 const queryString = require('query-string') //应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称.性别.所在地.并且,即使在未关注的情况下,只要用户授权,也能获取其信息) const SCOPES = ['snsapi_base', 'snsapi_userinfo'] class VueWe

随机推荐