1、H5頁(yè)面是運(yùn)行在微信瀏覽器的
2、需要與公眾號(hào)關(guān)聯(lián)(即需要openid)
3、判斷需求是否需要彈窗告知用戶授權(quán)操作
4、獲取地址欄參數(shù)判斷是否有'code',有的話直接傳給后臺(tái)換取openid,沒有就跳轉(zhuǎn)微信提供的獲取code的鏈接
5、獲取到的openid做本地存儲(chǔ),判斷沒有openid進(jìn)行獲取openid操作
6、這邊的操作是不需要彈出授權(quán)框,且code不能重復(fù)使用,所以做了關(guān)注二維碼彈窗且不能關(guān)閉彈窗操作
// 強(qiáng)制關(guān)注公眾號(hào),獲取openid
getCode = function () {
if (sessionStorage.getItem("openid")&&sessionStorage.getItem("openid")!="undefined") {
return false;
}
var code = getUrlParam('code') // 截取路徑中的code,如果沒有就去微信授權(quán),如果已經(jīng)獲取到了就直接傳code給后臺(tái)獲取openId
var local = window.location.href;
var APPID = 'xxx';
if (code == null || code === '') {
window.location. + APPID + '&redirect_uri=' + encodeURIComponent(local) + '&response_type=code&scope=snsapi_base&state=#wechat_redirect'
} else {
getOpenId(code) //把code傳給后臺(tái)獲取用戶信息
}
}
//把code傳給后臺(tái),得到openid
getOpenId = function (code) {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'xxx',
data: { code: code },
success: function (res) {
if (res.status == -1) {
// 提示沒有關(guān)注公眾號(hào) 沒有關(guān)注公眾號(hào)跳轉(zhuǎn)到關(guān)注公眾號(hào)頁(yè)面
console.log('您還未關(guān)注公眾號(hào)喔');
//二維碼彈窗
$('.openPopup').click();
return;
} else {
// 本地存儲(chǔ)這個(gè)openid,并刷新頁(yè)面
sessionStorage.setItem("openid", res.data.openid);
location.reload();
}
}
});
}
//獲取地址欄的參數(shù)
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;
}
//頁(yè)面執(zhí)行調(diào)用
getCode();
到此這篇關(guān)于Html5頁(yè)面獲取微信公眾號(hào)的openid的方法的文章就介紹到這了,更多相關(guān)Html5獲取公眾號(hào)的openid內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持腳本之家!