授權(quán)整體步驟如下
- 引導用戶進入授權(quán)頁面同意授權(quán)后微信跳轉(zhuǎn)回調(diào)地址并傳遞參數(shù)code 獲取code
- 通過code換取網(wǎng)頁授權(quán)access_token(與基礎(chǔ)支持中的access_token不同)
- 如果需要,開發(fā)者可以刷新網(wǎng)頁授權(quán)access_token,避免過期
-
通過網(wǎng)頁授權(quán)access_token和openid獲取用戶基本信息(支持UnionID機制)
其中 本頁例子前端只做第1步,后端程序員做2,3,4包括配置公眾號上的域名
新建一個index.vue的頁面,在此頁面進行授權(quán)
授權(quán)需要先拿到code ,獲取code需要以下參數(shù)
參數(shù)說明
const base_url = 'http://baidu.com'// 前端域名
const wx_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+appid+'&redirect_uri='+base_url+'&response_type=code&scope=snsapi_base&state=123#wechat_redirect'
export default {
components: {
},
data() {
return {
}
},
onLoad() {
// 獲取URL 上code
const code = this.getUrlParam('code')
// 判斷是否存在code
if(code == null || code == '') {
// 重新獲取code
// console.log(code)
window.location.href = wx_url
} else {
// 發(fā)送code
this.postCode(code)
}
},
methods: {
// 解析URL 參數(shù)
getUrlParam(name) {
let reg = new RegExp('(^|&)'+ name + '=([^&]*)(&|$)')
let r = window.location.search.substr(1).match(reg)
if(r!=null){
return unescape(r[2])
}
return null
},
// 發(fā)送code 獲取信息
postCode(code) {
uni.request({
url: 'https://www.example.com/request', //發(fā)送code給后臺。
success: (res)=> {
//res里面包含用戶信息 openid等
}
});
}
}
}
