//import request from '../../utils/network.js'
export const host = ''; // 域名
let lock =true
export default function request(opt){
return new Promise((resolve,reject)=>{
if (opt.isLock) {
if (!lock) return;
lock = false;
}
// 默认开启loading
if (!opt.isLocking) {
wx.showLoading({
title: '加载中...'
});
}
wx.request({
url: `${host}${opt.url}`,
method:opt.method||'post',
data:opt.data||{},
header:{
'content-type': opt.hedaer || 'application/json', // 默认值
'token': wx.getStorageSync('token')
},
success:function(res){
resolve(res)
},
fail:function(res){
reject(res)
},
complete:function(res){
if (opt.isLock) {
setTimeout(()=>{
lock=true
}, 5000)
}
if (!opt.isLocking) {
wx.hideLoading();
}
}
})
})
}
//import {authorizeUser} from '../../utils/login.js'
//import {isSession} from '../../utils/login.js'
import request from '/network.js'
export function login(callback) {
wx.login({
success(res) {
let code = res.code
if (res.code) {
getUserInfo((res) => {
let rawData = res.rawData
request({
url: '/api/Auth/Register',
data: {
code: code
}
}).then(res => {
let token = res.data.data.token
wx.setStorageSync('token', token);
request({
url: '/api/Auth/Login',
data: {
rawData: rawData
}
}).then(res => {
console.log(res)
})
}).catch(res=>{
console.log(res)
})
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
}
// 用户授权
export function authorizeUser(ev, callback, logFn) {
wx.getSetting({
success: function (res) {
if (res.authSetting['scope.userInfo']) {
// 用户授权之后将用户信息存入缓存
const userInfo = ev.detail;
wx.setStorageSync('userInfo', JSON.stringify(userInfo));
// 已授权
callback(true);
login(() => {
// 登录成功
if (logFn) {
logFn();
}
});
} else {
callback(false);
wx.showModal({
title: '提示',
content: '请允许授权,否则将会影响小程序的部分功能!',
success(res1) {
}
})
console.log('用户没有授权')
}
},
fail: function () {
console.log('失败');
}
});
}
// 获取用户信息
export function getUserInfo(callback) {
const userInfo = wx.getStorageSync('userInfo');
if (userInfo) {
callback(JSON.parse(userInfo));
} else {
wx.getUserInfo({
success(res) {
wx.setStorageSync('userInfo', JSON.stringify(res));
callback(res);
}
})
}
}
export function isSession(callback, logFn) {
wx.getSetting({
success(res) {
if (res.authSetting['scope.userInfo']) {
callback(true);
// 已授权
const userSession = wx.getStorageSync('token'); // 这里是token
console.log(userSession)
// 没有token就登录获取,反之则不需要登录,直接返回回调
if (!userSession) {
login(() => {
if (logFn) {
logFn();
}
});
} else {
if (logFn) {
logFn();
}
}
} else {
// 未授权
callback(false);
}
},
fail() {}
});
}