H5實現(xiàn)微信授權登錄的流程不在過多贅述官方文檔傳送門,下面直接上如何在開發(fā)狀態(tài)下實現(xiàn)授權登錄調(diào)試。
1.準備工作。
- 微信公眾號的開發(fā)權限,配置后續(xù)會講。
- 內(nèi)網(wǎng)穿透工具。
- 一個node服務點這里koa2快速搭建,傳送門。
2.公眾號配置
如圖所示點擊網(wǎng)頁授權域名設置
將這個文件txt下載到本地,下面的域名就是回調(diào)域名,可以為http協(xié)議。
3.node服務配置
const Router = require('koa-router');
const router = new Router({
prefix: '/',
});
router.get('這個就是下載的文件名包括文件格式名', async (ctx, next) => {
ctx.type = 'text';
ctx.body = '文件里面的內(nèi)容';
});
router.get('call_back', (ctx) => {
//重定向到code獲取頁面
ctx.redirect(`H5項目穿透外網(wǎng)地址/#/H5項目空白頁面路由?code=${ctx.query.code}`);
});
module.exports = router;
4.H5登錄實現(xiàn)
- 點擊登錄跳轉(zhuǎn)微信授權頁面,利用window.location.href,代碼如下:
window.location.href =
'https://open.weixin.qq.com/connect/oauth2/authorize?appid=公眾號appid&redirect_uri=自己起的node服務穿透后的外網(wǎng)地址/call_back&response_type=code&scope=snsapi_userinfo&state=STATE%23wechat_redirect';
- 跳轉(zhuǎn)到空白頁面獲取的邏輯,代碼如下:
<template>
<view></view>
</template>
<script>
export default {
data() {
return {};
},
methods: {
loginForH5(code) {
//微信登錄H5
auth.H5login({ code})
.then(res => {
if (res.accessToken) {
this.$store.commit('SET_LOGIN', true);
uni.setStorageSync('accessToken', res.accessToken);
}
})
.catch(({ data, status }) => {
console.log('h5err-------->', status, data);
uni.showToast({
icon: 'error',
title: '出現(xiàn)未知錯誤!',
duration: 1000,
success: () => {
uni.switchTab({
url: '/pages/home/index',
fail: e => {
console.error(e);
}
});
}
});
});
},
//獲取鏈接參數(shù)
urlPamras() {
let url = window.document.location.href.toString(); //獲取的完整url
let u = url.split('?');
if (typeof u[1] == 'string') {
u = u[1].split('&');
let get = {};
for (let i in u) {
let j = u[i].split('=');
get[j[0]] = j[1];
}
return get;
} else {
return {};
}
}
},
onLoad() {
const code = this.urlPamras()['code'];
console.log('授權回調(diào)--------------', code);
if (code) {
this.loginForH5(code);
} else {
uni.showToast({
icon: 'error',
title: '出現(xiàn)未知錯誤!',
duration: 1000,
success: () => {
uni.switchTab({
url: '/pages/home/index',
fail: e => {
console.error(e);
}
});
}
});
}
}
};
</script>
5.外網(wǎng)穿透
文章來源:http://www.zghlxwxcb.cn/news/detail-600555.html
最后
總的思路就是:
H5穿透拿到本地服務的外網(wǎng)地址——>node本地服務穿透外網(wǎng)地址——>node服務接收TX授權code——>重定向到H5外網(wǎng)地址主要不想一天老發(fā)布測試H5,然后把后端惹毛了。無奈之舉,原創(chuàng)不易,點贊加收藏。文章來源地址http://www.zghlxwxcb.cn/news/detail-600555.html
到了這里,關于H5使用微信OAuth2.0授權登錄,并實現(xiàn)內(nèi)網(wǎng)調(diào)試。的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!