微信小程序下獲取公衆号openId
發表時(shí)間:2020-11-5
發布人(rén):融晨科技
浏覽次數:248
微信小程序下獲取公衆号openId
一、爲(wéi / wèi)什麽我們需要(yào / yāo)在(zài)小程序下面獲取公衆号的(de)openId呢?
微信公衆号和(hé / huò)微信小程序我們一般都會開發,有一種場景我們經常會遇到(dào),公衆号的(de)消息推送以(yǐ)較成熟,我們希望把小程序那邊的(de)用戶也(yě)同步到(dào)公衆号這(zhè)邊,而(ér)且最好采用靜默方式,所以(yǐ)我們有這(zhè)種需求。
二、方案
從目前來(lái)講,微信沒有給我們提供可直接在(zài)小程序中調用公衆号的(de)接口,當然大(dà)家會想到(dào)union機制,當然這(zhè)個(gè)還是(shì)有一定限制的(de),需要(yào / yāo)用戶主動觸發。那麽我們有沒有其他(tā)可選方案呢,當然我們會想到(dào)是(shì)不(bù)是(shì)可以(yǐ)通過向程序訪問公衆号h5的(de)頁面呢,這(zhè)個(gè)時(shí)候我們會想到(dào)webview組件。
通過webview加載 公衆号的(de)一個(gè)h5頁面,h5頁面隻做公衆号授權處理,例如
小程序
constructor(props) {
super(props)
this.state = {
num: 0
}
}
handleLoad (e) {
let { num } = this.state;
this.setState({num: ++num}, ()=>{
if(num==2){
const url = e.detail.src;
let code = getQueryString(url, 'code')
Taro.redirectTo({
url: `/pages/index/index?code=${code}`
})
}
})
}
handleError () {
Taro.redirectTo({
url: `/pages/index/index`
})
}
render () {
return (
<WebView src='https://xxxx.xxxx.com/#/pages/get-openId/index'>={ this.handleLoad }>={ this.handleError } />
)
}
公衆号
constructor(props) {
super(props);
this.state = {
};
}
componentDidMount() {
Taro.showLoading({ title: '加載中...', mask: true })
let APP_ID = '000000000000'
let urlParams = getAuthUrl(window.location.href, APP_ID)
let code = ''
if(urlParams){
code = getQueryString('code')
}
if(!code){
window.location.href = urlParams
return
}
setTimeout(() => {
Taro.hideLoading()
}, 6000);
}
render() {
return (
<View className='loading-container'>
</View>
)
}
const getAuthUrl = (appId, currentPageUrl ) => {
const authUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri="+ encodeURIComponent(currentPageUrl) +"&response_type=code&scope=snsapi_base&state=TOKEN&connect_redirect=1#wechat_redirect"
return authUrl
}
小程序加載的(de)頁面會請求兩次, 這(zhè)是(shì)和(hé / huò)公衆号授權機制有關,我們隻需要(yào / yāo)在(zài)頁面加載的(de)第二次從detial中拿到(dào)code就(jiù)可以(yǐ)了(le/liǎo)。