思路:openID是在公眾號里識別用戶的唯一標識
通過用戶關注公眾號(用戶關注公眾號有兩種授權,一種是靜默授權,一種是非靜默授權,此時用的是靜默授權),獲取用戶openID,並且把它傳給后端。
import {getUrlParam} from './getUrlParam.js'
getCode () { if (sessionStorage.getItem("openid")&&sessionStorage.getItem("openid")!="undefined") { return false } var code = getUrlParam('code') // 截取路徑中的code,如果沒有就去微信授權,如果已經獲取到了就直接傳code給后台獲取openId var local = window.location.href var APPID = 'xxxxxxxxxx' if (code == null || code === '') { window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + APPID + '&redirect_uri=' + encodeURIComponent(local) + '&response_type=code&scope=snsapi_base&state=1_128b1ff67fdf4192836b1b0f05472f77#wechat_redirect' } else { this.getOpenId(code) //把code傳給后台獲取用戶信息 } }, getOpenId (code) { //把code傳給后台,得到openid console.log(code) },
getUrlParam.js:
export function getUrlParam (name) {
//獲取地址欄的參數
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)")
var r = window.location.hash.substr(1).match(reg)
console.log(location.hash)
if (r != null) return unescape(r[2])
return null
}