生活随笔
收集整理的這篇文章主要介紹了
uni-app—微信公众号授权登录(截取code)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
uni-app獲取code發送到服務器上獲取信息
- 首先先獲取code,公眾號分為靜默授權(即無需用戶點擊)和非靜默授權(彈出提示框,用戶點擊確認)
methods: {getCode() { // 非靜默授權,第一次有彈框this.code = ''var local = window.location.href // 獲取頁面urlvar appid = '自己的appid'this.code = this.getUrlCode() // 截取codeurlEncodeif (JSON.stringify(this.code) == "{}") { // 如果沒有code,則去請求window.location.href =`https://open.weixin.qq.com/connect/oauth2/authorize?appid=自己的appid&redirect_uri=https%3a%2f%2f自己的地址%2fh5&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`;}},getUrlCode() { // 截取url中的code方法var url = location.searchvar theRequest = new Object()if (url.indexOf("?") != -1) {var str = url.substr(1)var strs = str.split("&");for (var i = 0; i < strs.length; i++) {theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1])}}return theRequest},//將code傳給后臺sss() {uni.request({url: '接口',method: 'POST',data: {code: getUrl('code'),},success: (res) => {if(res.data.code==1){uni.setStorageSync('token', res.data.data.token);uni.setStorageSync('openid', res.data.data.openid);}else if(res.data.code!=1){this.getCode()}}})},
}
這里需要運行到微信開發者工具 ,換成公眾號網頁開發調試 ,然后就能獲取code了
function getUrl(variable) {var query = window.location.search.substring(1);var vars = query.split("&");for (var i = 0; i < vars.length; i++) {var pair = vars[i].split("=");if (pair[0] == variable) {return pair[1];}}return (false);}
這樣就能放到服務器上了!
總結
以上是生活随笔為你收集整理的uni-app—微信公众号授权登录(截取code)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。