把一個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:只能在微信中打開調試,無法看到控制臺,需要把接收到的數據輸出到頁面上查看。
新聞熱點
疑難解答