1、H5頁面是運行在微信瀏覽器的
2、需要與公眾號關聯(即需要openid)
3、判斷需求是否需要彈窗告知用戶授權操作
4、獲取地址欄參數判斷是否有'code',有的話直接傳給后台換取openid,沒有就跳轉微信提供的獲取code的鏈接
5、獲取到的openid做本地存儲,判斷沒有openid進行獲取openid操作
6、這邊的操作是不需要彈出授權框,且code不能重復使用,所以做了關注二維碼彈窗且不能關閉彈窗操作
// 強制關注公眾號,獲取openid getCode = function () { if (sessionStorage.getItem("openid")&&sessionStorage.getItem("openid")!="undefined") { return false; } var code = getUrlParam('code') // 截取路徑中的code,如果沒有就去微信授權,如果已經獲取到了就直接傳code給后台獲取openId var local = window.location.href; var APPID = 'xxx'; if (code == null || code === '') { window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + APPID + '&redirect_uri=' + encodeURIComponent(local) + '&response_type=code&scope=snsapi_base&state=#wechat_redirect' } else { getOpenId(code) //把code傳給后台獲取用戶信息 } } //把code傳給后台,得到openid getOpenId = function (code) { $.ajax({ type: 'POST', dataType: 'json', url: 'xxx', data: { code: code }, success: function (res) { if (res.status == -1) { // 提示沒有關注公眾號 沒有關注公眾號跳轉到關注公眾號頁面 console.log('您還未關注公眾號喔'); //二維碼彈窗 $('.openPopup').click(); return; } else { // 本地存儲這個openid,並刷新頁面 sessionStorage.setItem("openid", res.data.openid); location.reload(); } } }); } //獲取地址欄的參數 getUrlParam= function (name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if (r != null) return unescape(r[2]); return null; } //頁面執行調用 getCode();