ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

第三方网站登录微信——保姆级

2021-07-25 18:33:11  阅读:191  来源: 互联网

标签:String 登录 微信 用户 access token 保姆 appid


在这里插入图片描述
上面是官网发布的时序图:(前提是给第三方已经通过了微信的授权)
1、用户对第三方说:我要用微信方式登录你们
2、第三方对微信说:用户要用微信登录我们,我需要这个用户的数据
3、微信问用户:有个第三方要你数据,给不给。用户说给
4、微信对第三方说:用户同意了,你拿着临时证明来取吧
5、第三方带着临时证明和授权时候的信息取用户信息
6、微信核对以上信息后把用户信息交给第三方

第一步:
前端:
1、在页面中先引入如下JS文件(支持https):http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js
2、在需要使用微信登录的地方实例以下JS对象:

 var obj = new WxLogin({
 self_redirect:true,
 id:"login_container", 
 appid: "", 
 scope: "", 
 redirect_uri: "",
  state: "",
 style: "",
 href: ""
 });
参数说明
id页面显示二维码的容器id
appid申请通过的appid
scope应用授权作用域,拥有多个作用域用逗号(,)分隔,网页应用目前仅填写snsapi_login即可
redirect_uri重定向地址

前端整体代码:

mounted() {
    // 注册全局登录事件对象
    window.loginEvent = new Vue(); 
    // 监听登录事件
    loginEvent.$on("loginDialogEvent", function () {
      document.getElementById("loginDialog").click();
    }); 
    // 触发事件,显示登录层:loginEvent.$emit('loginDialogEvent') //初始化微信js
    const script = document.createElement("script");
    script.type = "text/javascript";
    script.src =
      "https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js";
    document.body.appendChild(script); 

    // 微信登录回调处理
    let self = this;
    window["loginCallback"] = (name, token, openid,phone) => {
      self.loginCallback(name, token, openid,phone);
    };
  },
   methods: {
    weixinLogin() {
      this.dialogAtrr.showLoginType = "weixin";
      weixinApi.getLoginParam().then((response) => {//调用后端方法封装数据
          var obj = new WxLogin({
          self_redirect: true,
          id: "weixinLogin", // 需要显示的容器id
          appid: response.data.appid, // 公众号appid wx*******
          scope: response.data.scope, // 网页默认即可
          redirect_uri: response.data.redirectUri, // 授权成功后回调的url
          state: response.data.state, // 可设置为简单的随机数加session用来校验
          style: "black", // 提供"black"、"white"可选。二维码的样式
          href: "", // 外部css文件url,需要https
        });
      }).catch(()=>{
        console.log("出错了")
      });
    },
   }

后端方法:

try {
            String redirectUri = URLEncoder.encode(ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL, "UTF-8");
            Map<String, Object> map = new HashMap<>();
            map.put("appid", ConstantPropertiesUtil.WX_OPEN_APP_ID);
            map.put("scope", "snsapi_login");
            map.put("redirectUri", redirectUri);
            map.put("state", System.currentTimeMillis() + "王木风");//该参数可用于防止csrf攻击(跨站请求伪造攻击),非必须携带
            return R.ok().data(map);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

第二步:
请求:https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

参数说明
secret应用密钥AppSecret,申请通过后获得
appid申请通过的appid
code上一步获取的
grant_type填authorization_code(固定的)

后端被回调方法:

 StringBuffer baseAccessTokenUrl = new StringBuffer().append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantPropertiesUtil.WX_OPEN_APP_ID,//appid
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,//secret密钥
                code);
//            2.2使用工具发送请求
            String accesstokenInfo = HttpClientUtils.get(accessTokenUrl);

返回的accesstokenInfo(JSON串):

参数说明
access_token接口调用凭证
expires_inaccess_token接口调用凭证超时时间,单位(秒)
refresh_token用户刷新access_token
openid授权用户唯一标识
scope用户授权的作用域,使用逗号(,)分隔
unionid当且仅当该网站应用已获得该用户的userinfo授权时,才会出现该字段。

第三步:通过access_token调用接口(根据openid访问微信获取用户信息)
在这里插入图片描述

String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                String resultInfo = HttpClientUtils.get(userInfoUrl);

标签:String,登录,微信,用户,access,token,保姆,appid
来源: https://blog.csdn.net/qq_45672914/article/details/119076600

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有