import { Toast } from 'vant'; import axios from 'axios' import common from './common' import api from "./api"; const InitLogin = { homeUrl: '',// 登陆后跳转的地址,用于重新登录流程 useOpenId: false, // 是否要绑定openId succFn: null, // 成功回调方法 wappId: '', // 商户主体id loginType: null,//登陆类型 0-企业微信,1-微信公众,2-app appId: '', // 登录主体标识,企业微信为coprId,app为学校id(schoolId),公众号为appId userType: 0, //0-教职工,1-家长 state: '', // 自定义参数,企业微信登录为应用标识 appLoginMsg: {},//登录用户信息 {userMsg:系统用户信息,refreshToken:刷新token,token:,token_expire_date:token过期时间戳,identity:身份信息,openId:用户openId} uniqueCode: '',//当前用户唯一标识(仅适用于app方式) /** * 入口方法 * @param succ_fn 登录成功回调方法 * @param useOpenId 使用openId * @param testMode 是否开发环境 * @param testParam 开发环境登录信息 */ init({loginSuccess, state, userType, useOpenId, uniqueCode, testMode = false, appId, testParam = {}}) { // console.log("初始化") this.useOpenId = useOpenId this.succFn = loginSuccess // 从路径获取登录参数 this.state = state || common.getQueryVariable("state") this.userType = userType || Number(common.getQueryVariable("userType")) this.appId = appId || common.getQueryVariable("appId") || common.getQueryVariable("corpId") || common.getQueryVariable("schoolId") this.loginType = Number(common.getQueryVariable("loginType")) || this.getLoginType() this.uniqueCode = uniqueCode if (testMode === true) { this.appId = 'schoolId2' this.appLoginMsg = { "userMsg": { "userId": testParam.id, "deptId": 2, "identityId": testParam.identityId }, "tokenInfo": { "token": testParam.token }, "identity": { "parentId": testParam.identityId } } localStorage.setItem('appId', this.appId) localStorage.setItem(this.appId, JSON.stringify(this.appLoginMsg)) this.succFn() return } localStorage.setItem('appId', this.appId) this.appLoginMsg = localStorage.getItem(this.appId); try { this.appLoginMsg = JSON.parse(this.appLoginMsg) } catch (e) { // 用户信息不存在进行初始化 this.appLoginMsg = { 'userMsg': {} } } // 初始化用户登录信息 if (!this.appLoginMsg) { this.appLoginMsg = { 'userMsg': {} } } console.log("appLoginMsg", this.appLoginMsg) console.log("uniqueCode", this.uniqueCode) // 已登录进入页面 if (this.appLoginMsg.userMsg && Object.keys(this.appLoginMsg.userMsg).length > 1 && this.appLoginMsg.tokenInfo) { // 获取唯一标识 let getUniqueCode = common.getUniqueCode() if (getUniqueCode && getUniqueCode === this.uniqueCode) { this.afterIn() } else { // 移除缓存后重新登录 let storageAppId = localStorage.getItem("appId") localStorage.removeItem("uniqueCode" + storageAppId) localStorage.removeItem(storageAppId) this.startLogin() } } else { //未登录进入登录流程 if (this.appId == this.wappId && this.useOpenId) { this.wxLogin(this.appId, 0) } else { this.startLogin() } } }, /** * 开始登录 */ startLogin() { console.log("开始登录") // 第一次登录 switch (this.loginType) { case 0: case 1: this.wxLogin(null, 1); break; case 2: this.appLogin() break; default: console.log("1231231") return; } }, /** * app登录 */ appLogin() { let that = this try { $.initGetAppBasicInfo(function (data) { var params = { areaId: data.areaId, mobile: data.userPhone, userId: data.userId, schoolId: that.appId, type: that.userType } that.apiLogin(params) }); } catch (e) { Toast('错误') } }, /** * 微信oauth2授权登录流程 * @param aid 主体id * @param type 0-绑定商户openId,1-登录 */ wxLogin: function (aid, type) { console.log("微信登录") var appid = aid || this.appId if (!aid) { localStorage.setItem('appId', appid) } // 微信方的授权码 var code = common.getQueryVariable('code') // 商户id let a = localStorage.getItem('wappId') if (appid != a) { localStorage.setItem('wappId', appid) } if (!code || appid != a) { //用户第一次进入页面,跳转授权 var url = encodeURIComponent(location.href) window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid + '&redirect_uri=' + url + '&response_type=code&scope=snsapi_base#wechat_redirect'; } else { //授权后跳回页面=》进入登录流程 if (type == 0) { this.bindWxOpenId(code) } else { var params = { corpId: this.appId, code: common.getQueryVariable('code'), state: this.state, type: this.userType } this.apiLogin(params) } } }, /** * 绑定微信公众号下openId * @param code 微信授权码 */ bindWxOpenId(code) { this.appId = localStorage.getItem('appId') var appMsg = localStorage.getItem(this.appId) var userMsg = {} if (appMsg) { appMsg = JSON.parse(appMsg) userMsg = appMsg.userMsg } axios.get(process.env.VUE_APP_BASE_API + '/user/user/bindWxOpenId', { params: { code: code, identityId: userMsg.identityId, type: 0 } }).then(res => { if (res.data.data) { var openId = res.data.data appMsg.identity.wxPublicOpenId = openId this.appLoginMsg = appMsg localStorage.setItem(common.getQueryVariable('corpId'), JSON.stringify(appMsg)) this.succFn(userMsg.identityId) } else { Toast('登录失败') } }) }, /** * 调用系统登录 * @param params 登录参数 */ apiLogin(params) { console.log("api登录") var url = process.env.VUE_APP_BASE_API switch (this.loginType) { case 0: url = url + '/auth/social/qywx/login'; break; case 1: params.appId = this.appId url = url + '/auth/social/wxpublic/login'; break; case 2: url = url + '/auth/social/app/login'; break; } axios.get(url, {params: params}).then(res => { this.afterLogin(res) }).catch(err => { Toast('登录失败,网络错误') }) }, /** * 登陆后数据处理 * @param res * @returns {{this.appLoginMsg: InitLogin.this.appLoginMsg, this.appId: *}} */ afterLogin: function (res) { console.log("登录后数据处理") if (res) { var toekn_info = res.data.data.token var userMsg = res.data.data.user var identity = res.data.data.identity // token信息 if (toekn_info) { var tokenInfo = {} tokenInfo.refreshToken = toekn_info.refresh_token tokenInfo.token = toekn_info.token_type + ' ' + toekn_info.access_token // 计算token有效期限 var token_expire = toekn_info.expires_in let now = new Date().getTime() now = parseInt(now / 1000) let last_date = now - 0 + (token_expire - 0) tokenInfo.tokenExpireDate = last_date this.appLoginMsg.tokenInfo = tokenInfo } // 用户信息 if (identity) { this.appLoginMsg.identity = identity } // 系统用户信息 if (userMsg) { this.appLoginMsg.userMsg = userMsg } } // 保存信息 localStorage.setItem(this.appId, JSON.stringify(this.appLoginMsg)) localStorage.setItem("uniqueCode" + this.appId, this.uniqueCode) this.succFn() }, /** * 刷新token */ refreshToken: function () { // 刷新token var tokenInfo = this.appLoginMsg.tokenInfo; let rtoken = tokenInfo.refreshToken axios.post(process.env.VUE_APP_BASE_API + '/auth/oauth/token?grant_type=refresh_token&refresh_token=' + rtoken, {}, { headers: { 'Authorization': 'Basic YXBwOjEyMzQ1Ng==' } }).then(res => { if (res.data.access_token) { let login_data = res.data tokenInfo.refreshToken = login_data.refresh_token tokenInfo.token = login_data.token_type + ' ' + login_data.access_token var token_expire = login_data.expires_in //过期时间秒 let now = new Date().getTime() now = parseInt(now / 1000) let last_date = now - 0 + (token_expire - 0) tokenInfo.tokenExpireDate = last_date this.appLoginMsg.tokenInfo = tokenInfo localStorage.setItem(this.appId, JSON.stringify(this.appLoginMsg)) this.succFn() } else { this.retryLogin() } }).catch(err => { console.log("使用refresh_token重新获取token信息失败", err) this.retryLogin() }); }, /** * 进入后的逻辑处理 * token过期等判断 */ afterIn: function () { var tokenInfo = this.appLoginMsg.tokenInfo; let last_date = tokenInfo.tokenExpireDate let now_date = parseInt(new Date().getTime() / 1000) if (now_date > last_date) { //已过期,调刷新token this.refreshToken() } else { if (this.useOpenId) { if (this.appLoginMsg.identity.wxPublicOpenId) { this.succFn() } else { //没有openid localStorage.setItem('appId', this.appMsgName) // 根据学校查询正确的openId api.getAppIdBySchool({schoolId: this.appLoginMsg.userMsg.deptId}).then(res => { this.wappId = res.data.data this.wxLogin(this.wappId) }) } } else { this.succFn() } } }, /** * 重新登录 */ retryLogin: function () { var appId = localStorage.getItem("appId"); if (appId) { var appMsg = localStorage.getItem(appId); if (appMsg) { appMsg = JSON.parse(appMsg) } var tokenInfo = appMsg.tokenInfo let last_date = tokenInfo.tokenExpireDate let now_date = parseInt(new Date().getTime() / 1000) if (now_date > last_date) { //已过期,调刷新token this.refreshToken() } localStorage.removeItem(appId) localStorage.removeItem('appId') localStorage.removeItem('wappId') localStorage.removeItem("uniqueCode" + appId) } window.location.reload() }, /** * 微信环境使用微信登录,非微信环境使用app登录 * @param param * @returns {boolean} */ getLoginType(param) { var ua = navigator.userAgent.toLowerCase(); if (ua.match(/MicroMessenger/i) == "micromessenger") { return 0; } else { return 2; } } } export default InitLogin