首页 > 学院 > 开发设计 > 正文

WebApp微信集成登录

2019-11-07 23:57:37
字体:
来源:转载
供稿:网友

把一个WebApp发布在微信公众号上,并且想使用微信用户的信息,以求达到微信集成登录的目的。官方文档讲的也很详细,然而在做的过程中还是遇到很多坑,分享出来希望能对有需要的人有所帮助。实现效果如下:

微信浏览器授权的前提: 

1.拥有微信公众号,即有APPID,APPSecret,并设置了授权回调域 2.必须在手机端的微信浏览器打开方可,目测现在windows PC端的微信浏览器打开也可通过授权。 3.以上条件都具备后参照微信开放文档进行开发。

文档参考:网页授权获取用户基本信息

http://mp.weixin.QQ.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html

weixin.js

var weixin = {    config: {        url:'https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri='+encodeURIComponent("https://...")+'&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect',        userInfo:JSON.parse(localStorage.getItem('MY_USER_INFO'))    },    isweixin: function() {        var ua = window.navigator.userAgent.toLowerCase();        if(ua.match(/MicroMessenger/i) == 'micromessenger'){            return true;        } else {            return false;        }    },    getQueryString: function(name) {        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i");        var r = window.location.search.substr(1).match(reg);        if (r!=null) return unescape(r[2]); return null;    },    getUser : function(code) {        $.Ajax({            type: 'get',            url: "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=APP_SECRET&code="+code+"&grant_type=authorization_code",            cache:false,            async: false,            dataType: 'jsonp',            jsonp: 'jsonpcallback',            success: function(json){                localStorage.setItem('MY_USER_INFO',JSON.stringify(json));                // document.write("<div>"+JSON.stringify(json)+"</div>");                $("#test").html(json[0].openid);            },            error: function(err) {                // console.log(err);                $("#error").html(JSON.stringify(err));            }        })    },    getUserInfo:function(){        if(weixin.config.userInfo != null){            return JSON.parse(localStorage.getItem('MY_USER_INFO'));        }else{            if(weixin.getQueryString('code') != null){                 weixin.getUser(weixin.getQueryString('code'));                return JSON.parse(localStorage.getItem('MY_USER_INFO'));            }else{                window.location.href = weixin.config.url;            }        }    }}ps:只能在微信中打开调试,无法看到控制台,需要把接收到的数据输出到页面上查看。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表