WebApp微信集成登录

把一个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:只能在微信中打开调试,无法看到控制台,需要把接收到的数据输出到页面上查看。


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值