Browse Source

优化微信授权

zyh
Gao xiaosong 4 years ago
parent
commit
4fb75be4b0
  1. 128
      pages/authorization/index.vue
  2. 217
      pages/user/User/index.vue
  3. 508
      utils/index.js

128
pages/authorization/index.vue

@ -7,7 +7,8 @@
<open-data class="user-avatar" type="userAvatarUrl"></open-data>
<open-data class="user-name" type="userNickName"></open-data>
<view class="login-notice">为了提供更优质的服务需要获取您的头像昵称</view>
<button class="cu-btn author-btn" @getuserinfo="getUserInfo" open-type="getUserInfo">授权并查看</button>
<button class="cu-btn author-btn" v-if="canIUseGetUserProfile" @tap="getUserInfoProfile">授权并查看</button>
<button class="cu-btn author-btn" v-else @getuserinfo="getUserInfo" open-type="getUserInfo">授权并查看</button>
<button class="cu-btn close-btn" @tap="back">暂不授权</button>
</view>
</view>
@ -25,88 +26,123 @@
</template>
<script>
import {
mapState,
mapMutations,
mapActions
} from "vuex";
import {
wxappAuth,
getUser
} from "@/api/user";
import dayjs from "dayjs";
import cookie from "@/utils/store/cookie";
import {
login,
authorize
} from "@/utils";
import { mapState, mapMutations, mapActions } from 'vuex'
import { wxappAuth, getUser } from '@/api/user'
import dayjs from 'dayjs'
import cookie from '@/utils/store/cookie'
import { login, authorize } from '@/utils'
export default {
data() {
return {
authorize: false,
};
canIUseGetUserProfile: false,
}
},
computed: {
...mapState(["isAuthorization", "$deviceType", "token"]),
...mapState(['isAuthorization', '$deviceType', 'token']),
},
onShow() {
onLoad() {
console.log(wx.getUserProfile)
if (wx.getUserProfile) {
console.log(this)
this.canIUseGetUserProfile = true
console.log(this.canIUseGetUserProfile)
}
// //
},
onHide() {
this.updateAuthorizationPage(false);
this.changeAuthorization(false);
this.updateAuthorizationPage(false)
this.changeAuthorization(false)
},
onUnload() {
this.updateAuthorizationPage(false);
this.changeAuthorization(false);
this.updateAuthorizationPage(false)
this.changeAuthorization(false)
},
methods: {
...mapActions(["changeAuthorization", "setUserInfo"]),
...mapMutations(["updateAuthorizationPage"]),
...mapActions(['changeAuthorization', 'setUserInfo']),
...mapMutations(['updateAuthorizationPage']),
toLogin() {
this.$yrouter.push({
path: "/pages/user/Login/index",
path: '/pages/user/Login/index',
query: {},
});
})
},
back() {
this.$yrouter.switchTab({
path: "/pages/home/index",
path: '/pages/home/index',
query: {},
});
})
},
getUserInfo(data) {
if (data.detail.errMsg == "getUserInfo:fail auth deny") {
console.log(data)
console.log('getUserInfo')
if (data.detail.errMsg == 'getUserInfo:fail auth deny') {
uni.showToast({
title: "取消授权",
icon: "none",
title: '取消授权',
icon: 'none',
duration: 2000,
});
return;
})
return
}
uni.showLoading({
title: "登录中",
});
title: '登录中',
})
login()
.then((res) => {
.then(e => {
uni.hideLoading()
console.log('重定向')
this.$yrouter.reLaunch({
path: cookie.get('redirect').replace(/\ /g, ''),
})
})
.catch(error => {
uni.hideLoading()
console.log(error)
uni.showToast({
title: error,
icon: 'none',
duration: 2000,
})
})
},
getUserInfoProfile(data) {
console.log('getUserInfoProfile')
wx.getUserProfile({
lang: 'zh_CN',
desc: '需要获取您的信息用来展示',
success: res => {
console.log(res)
uni.showLoading({
title: '登录中',
})
login(res)
.then(e => {
console.log('重定向')
this.$yrouter.reLaunch({
path: cookie.get("redirect").replace(/\ /g, '')
});
path: cookie.get('redirect').replace(/\ /g, ''),
})
})
.catch((error) => {
console.log(error);
.catch(error => {
console.log(error)
uni.showToast({
title: error,
icon: "none",
icon: 'none',
duration: 2000,
});
});
})
})
},
})
},
},
mounted() {},
};
mounted() {
if (wx.getUserProfile) {
console.log(this)
this.canIUseGetUserProfile = true
console.log(this.canIUseGetUserProfile)
}
},
}
</script>
<style lang="less">

217
pages/user/User/index.vue

@ -64,40 +64,35 @@
<view @click="goMyOrder(0)" class="item">
<view class="pictrue">
<image src="@/static/images/dfk.png" />
<text class="order-status-num"
v-if="userInfo.orderStatusNum.unpaidCount > 0">{{ userInfo.orderStatusNum.unpaidCount }}</text>
<text class="order-status-num" v-if="userInfo.orderStatusNum.unpaidCount > 0">{{ userInfo.orderStatusNum.unpaidCount }}</text>
</view>
<view>待付款</view>
</view>
<view @click="goMyOrder(1)" class="item">
<view class="pictrue">
<image src="@/static/images/dfh.png" />
<text class="order-status-num"
v-if="userInfo.orderStatusNum.unshippedCount > 0">{{ userInfo.orderStatusNum.unshippedCount }}</text>
<text class="order-status-num" v-if="userInfo.orderStatusNum.unshippedCount > 0">{{ userInfo.orderStatusNum.unshippedCount }}</text>
</view>
<view>待发货</view>
</view>
<view @click="goMyOrder(2)" class="item">
<view class="pictrue">
<image src="@/static/images/dsh.png" />
<text class="order-status-num"
v-if="userInfo.orderStatusNum.receivedCount > 0">{{ userInfo.orderStatusNum.receivedCount }}</text>
<text class="order-status-num" v-if="userInfo.orderStatusNum.receivedCount > 0">{{ userInfo.orderStatusNum.receivedCount }}</text>
</view>
<text>待收货</text>
</view>
<view @click="goMyOrder(3)" class="item">
<view class="pictrue">
<image src="@/static/images/dpj.png" />
<text class="order-status-num"
v-if="userInfo.orderStatusNum.evaluatedCount > 0">{{ userInfo.orderStatusNum.evaluatedCount }}</text>
<text class="order-status-num" v-if="userInfo.orderStatusNum.evaluatedCount > 0">{{ userInfo.orderStatusNum.evaluatedCount }}</text>
</view>
<text>待评价</text>
</view>
<view @click="goReturnList()" class="item">
<view class="pictrue">
<image src="@/static/images/sh.png" />
<text class="order-status-num"
v-if="userInfo.orderStatusNum.refundCount > 0">{{ userInfo.orderStatusNum.refundCount }}</text>
<text class="order-status-num" v-if="userInfo.orderStatusNum.refundCount > 0">{{ userInfo.orderStatusNum.refundCount }}</text>
</view>
<text>售后/退款</text>
</view>
@ -132,110 +127,97 @@
</view>
</template>
<script>
import {
mapState,
mapGetters,
mapMutations,
mapActions
} from "vuex";
import {
getUserInfo,
getMenuUser,
bindingPhone
} from "@/api/user";
import {
isWeixin,
VUE_APP_RESOURCES_URL
} from "@/utils";
import cookie from "@/utils/store/cookie";
import SwitchWindow from "@/components/SwitchWindow";
import Authorization from "@/pages/authorization/index";
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
import { getUserInfo, getMenuUser, bindingPhone } from '@/api/user'
import { isWeixin, VUE_APP_RESOURCES_URL } from '@/utils'
import cookie from '@/utils/store/cookie'
import SwitchWindow from '@/components/SwitchWindow'
import Authorization from '@/pages/authorization/index'
const NAME = "User";
const NAME = 'User'
export default {
name: NAME,
components: {
SwitchWindow,
Authorization
Authorization,
},
props: {},
data: function() {
return {
MyMenus: [],
switchActive: false,
isWeixin: false
};
isWeixin: false,
}
},
computed: mapGetters(["userInfo"]),
computed: mapGetters(['userInfo']),
methods: {
...mapMutations(["updateAuthorizationPage"]),
...mapMutations(['updateAuthorizationPage']),
goReturnList() {
this.$yrouter.push("/pages/order/ReturnList/index");
this.$yrouter.push('/pages/order/ReturnList/index')
},
goMyOrder(type) {
this.$yrouter.push({
path: "/pages/order/MyOrder/index",
path: '/pages/order/MyOrder/index',
query: {
type
}
});
type,
},
})
},
goBindPhone() {
this.$yrouter.push({
path: "/pages/user/BindingPhone/index",
});
path: '/pages/user/BindingPhone/index',
})
},
goUserCoupon() {
this.$yrouter.push("/pages/user/coupon/UserCoupon/index");
this.$yrouter.push('/pages/user/coupon/UserCoupon/index')
},
goIntegral() {
this.$yrouter.push("/pages/user/signIn/Integral/index");
this.$yrouter.push('/pages/user/signIn/Integral/index')
},
goUserPromotion() {
this.$yrouter.push("/pages/user/promotion/UserPromotion/index");
this.$yrouter.push('/pages/user/promotion/UserPromotion/index')
},
goUserAccount() {
this.$yrouter.push({
path: "/pages/user/UserAccount/index"
});
path: '/pages/user/UserAccount/index',
})
},
goPersonalData() {
this.$yrouter.push("/pages/user/PersonalData/index");
this.$yrouter.push('/pages/user/PersonalData/index')
},
getPhoneNumber: function(e) {
let thit = this;
let thit = this
console.log(e)
//
if (e.mp.detail.errMsg == "getPhoneNumber:ok") {
if (e.mp.detail.errMsg == 'getPhoneNumber:ok') {
uni.showLoading({
title: "绑定中"
});
bindingPhone({
title: '绑定中',
})
wxappBindingPhone({
encryptedData: e.mp.detail.encryptedData,
iv: e.mp.detail.iv
iv: e.mp.detail.iv,
})
.then(res => {
// this.User();
thit.$store.dispatch("userInfo", true);
uni.hideLoading();
thit.$store.dispatch('userInfo', true)
uni.hideLoading()
uni.showToast({
title: res.msg,
icon: "success",
duration: 2000
});
icon: 'success',
duration: 2000,
})
})
.catch(error => {
uni.hideLoading();
thit.$store.dispatch("userInfo", true);
console.log(error);
uni.hideLoading()
thit.$store.dispatch('userInfo', true)
console.log(error)
uni.showToast({
title: error.msg ||
error.response.data.msg ||
error.response.data.message,
icon: "none",
duration: 2000
});
});
title: error.msg || error.response.data.msg || error.response.data.message,
icon: 'none',
duration: 2000,
})
})
// //
// uni.getProvider({
// service: "oauth",
@ -284,101 +266,94 @@
// });
} else {
uni.showToast({
title: "已拒绝授权",
icon: "none",
duration: 2000
});
title: '已拒绝授权',
icon: 'none',
duration: 2000,
})
}
},
changeswitch: function(data) {
this.switchActive = data;
this.switchActive = data
},
MenuUser: function() {
let that = this;
let that = this
getMenuUser()
.then(res => {
uni.hideLoading();
that.MyMenus = res.data.routine_my_menus;
uni.hideLoading()
that.MyMenus = res.data.routine_my_menus
})
.catch(error => {
uni.hideLoading();
console.log(error);
});
uni.hideLoading()
console.log(error)
})
},
goPages: function(index) {
let url = this.MyMenus[index].uniapp_url;
if (
url === "/pages/user/promotion/UserPromotion/index" &&
this.userInfo.statu === 1
) {
let url = this.MyMenus[index].uniapp_url
if (url === '/pages/user/promotion/UserPromotion/index' && this.userInfo.statu === 1) {
if (!this.userInfo.isPromoter) {
uni.showToast({
title: "您还没有推广权限!!",
icon: "none",
duration: 2000
});
return;
title: '您还没有推广权限!!',
icon: 'none',
duration: 2000,
})
return
}
}
if (
url === "/pages/orderAdmin/OrderIndex/index" &&
!this.userInfo.adminid
) {
if (url === '/pages/orderAdmin/OrderIndex/index' && !this.userInfo.adminid) {
uni.showToast({
title: "您还不是管理员!!",
icon: "none",
duration: 2000
});
return;
title: '您还不是管理员!!',
icon: 'none',
duration: 2000,
})
return
}
console.log(this.userInfo)
if (url === "/pages/orderAdmin/OrderCancellation/index" && !this.userInfo.checkStatus) {
if (url === '/pages/orderAdmin/OrderCancellation/index' && !this.userInfo.checkStatus) {
uni.showToast({
title: "您没有核销权限,请后台店员设置!!",
icon: "none",
duration: 2000
});
return;
title: '您没有核销权限,请后台店员设置!!',
icon: 'none',
duration: 2000,
})
return
}
this.$yrouter.push({
path: this.MyMenus[index].uniapp_url
});
path: this.MyMenus[index].uniapp_url,
})
},
goPages2: function() {
this.$yrouter.push({
path: "/pages/shop/GoodsList/index",
path: '/pages/shop/GoodsList/index',
query: {
// id: 0,
title: '积分商城',
isIntegral: true,
}
});
}
},
})
},
},
watch: {
userInfo() {
this.MenuUser();
}
this.MenuUser()
},
},
onShow() {
if (this.$store.getters.token) {
//
uni.showLoading({
title: "加载中"
});
this.$store.dispatch("getUser", true);
this.MenuUser();
this.isWeixin = isWeixin();
title: '加载中',
})
this.$store.dispatch('getUser', true)
this.MenuUser()
this.isWeixin = isWeixin()
}
},
onHide() {
console.log("离开用户中心");
this.updateAuthorizationPage(false);
console.log('离开用户中心')
this.updateAuthorizationPage(false)
},
}
};
</script>
<style lang="less">

508
utils/index.js

@ -2,117 +2,103 @@ import Vue from 'vue'
// import MpvueRouterPatch from 'mpvue-router-patch'
// Vue.use(MpvueRouterPatch)
import {
wxappAuth,
getUserInfo
} from "@/api/user";
import store from "@/store";
import dayjs from "dayjs";
import cookie from "@/utils/store/cookie";
import stringify from "@/utils/querystring";
import { VUE_APP_API_URL } from "@/config";
import { wxappAuth, getUserInfo } from '@/api/user'
import store from '@/store'
import dayjs from 'dayjs'
import cookie from '@/utils/store/cookie'
import stringify from '@/utils/querystring'
import { VUE_APP_API_URL } from '@/config'
import { wechat, auth, oAuth, toAuth } from '@/libs/wechat'
export function dataFormat(time, option) {
time = +time * 1000;
const d = new Date(time);
const now = new Date().getTime();
time = +time * 1000
const d = new Date(time)
const now = new Date().getTime()
const diff = (now - d) / 1000;
const diff = (now - d) / 1000
if (diff < 30) {
return "刚刚";
return '刚刚'
} else if (diff < 3600) {
// less 1 hour
return Math.ceil(diff / 60) + "分钟前";
return Math.ceil(diff / 60) + '分钟前'
} else if (diff < 3600 * 24) {
return Math.ceil(diff / 3600) + "小时前";
return Math.ceil(diff / 3600) + '小时前'
} else if (diff < 3600 * 24 * 2) {
return "1天前";
return '1天前'
}
if (option) {
// return parseTime(time, option);
} else {
let timeStr = d.getFullYear() + "年" + (d.getMonth() + 1) + "月" + d.getDate() + "日" + d.getHours() + "时" + d.getMinutes() +
"分"
let timeStr = d.getFullYear() + '年' + (d.getMonth() + 1) + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
return timeStr
}
}
// 年月日,时分秒
// "YYYY-mm-dd HH:MM"
export function dateFormatL(fmt, date) {
let ret;
let ret
const opt = {
"Y+": date.getFullYear().toString(), // 年
"m+": (date.getMonth() + 1).toString(), // 月
"d+": date.getDate().toString(), // 日
"H+": date.getHours().toString(), // 时
"M+": date.getMinutes().toString(), // 分
"S+": date.getSeconds().toString() // 秒
'Y+': date.getFullYear().toString(), // 年
'm+': (date.getMonth() + 1).toString(), // 月
'd+': date.getDate().toString(), // 日
'H+': date.getHours().toString(), // 时
'M+': date.getMinutes().toString(), // 分
'S+': date.getSeconds().toString(), // 秒
// 有其他格式化字符需求可以继续添加,必须转化成字符串
};
}
for (let k in opt) {
ret = new RegExp("(" + k + ")").exec(fmt);
ret = new RegExp('(' + k + ')').exec(fmt)
if (ret) {
fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
};
};
return fmt;
fmt = fmt.replace(ret[1], ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0'))
}
}
return fmt
}
export function dateFormatT(time) {
time = +time * 1000;
const d = new Date(time);
return (
d.getFullYear() +
"/" +
(d.getMonth() + parseInt(1)) +
"/" +
d.getDate()
);
time = +time * 1000
const d = new Date(time)
return d.getFullYear() + '/' + (d.getMonth() + parseInt(1)) + '/' + d.getDate()
}
export function trim(str) {
return String.prototype.trim.call(str);
return String.prototype.trim.call(str)
}
export function isType(arg, type) {
return Object.prototype.toString.call(arg) === "[object " + type + "]";
return Object.prototype.toString.call(arg) === '[object ' + type + ']'
}
export function isWeixin() {
if (navigator && navigator.userAgent && navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1) {
if (navigator && navigator.userAgent && navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1) {
return true
}
return false
}
export function parseQuery() {
let res = {};
let res = {}
// #ifdef H5
const query = (location.href.split("?")[1] || "")
.trim()
.replace(/^(\?|#|&)/, "");
const query = (location.href.split('?')[1] || '').trim().replace(/^(\?|#|&)/, '')
if (!query) {
return res;
return res
}
query.split("&").forEach(param => {
const parts = param.replace(/\+/g, " ").split("=");
const key = decodeURIComponent(parts.shift());
const val = parts.length > 0 ? decodeURIComponent(parts.join("=")) : null;
query.split('&').forEach(param => {
const parts = param.replace(/\+/g, ' ').split('=')
const key = decodeURIComponent(parts.shift())
const val = parts.length > 0 ? decodeURIComponent(parts.join('=')) : null
if (res[key] === undefined) {
res[key] = val;
res[key] = val
} else if (Array.isArray(res[key])) {
res[key].push(val);
res[key].push(val)
} else {
res[key] = [res[key], val];
res[key] = [res[key], val]
}
});
})
// #endif
// #ifndef H5
var pages = getCurrentPages() //获取加载的页面
@ -149,20 +135,20 @@ export function getCurrentPageUrlWithArgs() {
}
// 复制到剪切板
export const copyClipboard = (data) => {
export const copyClipboard = data => {
uni.setClipboardData({
data: data,
success: (res) => {
success: res => {
uni.showToast({
title: '复制成功',
icon: 'success',
duration: 2000
duration: 2000,
})
}
},
})
}
export const getProvider = (service) => {
export const getProvider = service => {
return new Promise((resolve, reject) => {
// 获取当前环境的服务商
uni.getProvider({
@ -175,35 +161,33 @@ export const getProvider = (service) => {
},
fail() {
reject('获取环境服务商失败')
}
},
})
}).catch(error => {
console.log(error)
})
}
export const authorize = (authorizeStr) => {
export const authorize = authorizeStr => {
return new Promise((resolve, reject) => {
console.log('检验授权', `scope.${authorizeStr}`)
uni.getSetting({
success(res) {
console.log(res.authSetting)
if (res.authSetting[`scope.${authorizeStr}`]) {
resolve('获取授权成功')
resolve(true)
} else {
reject('获取授权失败')
resolve(false)
}
},
fail() {
reject('获取设置失败')
}
resolve(false)
},
})
})
}
export const login = () => {
export const login = loginInfo => {
return new Promise((resolve, reject) => {
if (Vue.prototype.$deviceType == 'weixin') {
// 微信授权登录
@ -216,24 +200,24 @@ export const login = () => {
if (redirect) {
redirect = redirect.split('/pages')[1]
if (!redirect) {
redirect="/Loading/index";
redirect = '/Loading/index'
}
reLaunch({
path: '/pages' + redirect,
});
cookie.remove('redirect');
})
cookie.remove('redirect')
} else {
reLaunch({
path: '/pages/home/index',
});
})
}
})
.catch(() => {
reject('当前运行环境为微信浏览器')
reLaunch({
path: '/pages/home/index',
});
});
})
})
} else {
}
return
@ -252,7 +236,8 @@ export const login = () => {
console.log('开始登录')
console.log('————————————————————')
console.log('获取环境商')
getProvider().then(provider => {
getProvider()
.then(provider => {
console.log('当前的环境商')
console.log(provider)
if (!provider) {
@ -262,63 +247,105 @@ export const login = () => {
console.log('调用登录接口')
uni.login({
provider: provider,
success: function (loginRes) {
success: async function(loginRes) {
console.log(loginRes)
// 微信登录
console.log('登录接口调用成功')
console.log('开始检查用户信息授权')
let code = loginRes.code;
let code = loginRes.code
cookie.set('wxLoginCode', loginRes.code)
// 检查授权, 检查用户信息授权
authorize('userInfo').then(() => {
console.log('授权通过')
console.log('开始获取用户信息')
let authorizeRes = await authorize('userInfo')
if (!wx.getUserProfile && !authorizeRes) {
reject('用户未授权')
return
}
if (wx.getUserProfile) {
if (loginInfo) {
wxappAuth({
encryptedData: loginInfo.encryptedData,
iv: loginInfo.iv,
code: code,
spread: cookie.get('spread'),
})
.then(({ data }) => {
console.log('登录接口调用成功')
console.log('开始处理登录信息保存,并获取用户详情')
uni.hideLoading()
store.commit('login', data.token, dayjs(data.expires_time))
store.dispatch('userInfo', true)
getUserInfo()
.then(user => {
console.log('获取用户信息成功')
uni.setStorageSync('uid', user.data.uid)
store.dispatch('setUserInfo', user.data)
resolve(user)
})
.catch(error => {
console.log('获取用户信息失败')
reject('获取用户信息失败')
})
})
.catch(error => {
console.log(error)
console.log('登录接口调用失败')
reject('登录接口调用失败')
})
} else {
reject('用户未授权')
return
}
} else {
uni.getUserInfo({
provider: provider,
success: function(user) {
console.log(user)
console.log('获取用户信息成功')
console.log('开始调用登录接口')
wxappAuth({
encryptedData: user.encryptedData,
iv: user.iv,
code: code,
spread: cookie.get("spread")
}).then(({ data }) => {
spread: cookie.get('spread'),
})
.then(({ data }) => {
console.log('登录接口调用成功')
console.log('开始处理登录信息保存,并获取用户详情')
uni.hideLoading();
store.commit("login", data.token, dayjs(data.expires_time));
uni.hideLoading()
store.commit('login', data.token, dayjs(data.expires_time))
store.dispatch('userInfo', true)
getUserInfo().then(user => {
getUserInfo()
.then(user => {
console.log('获取用户信息成功')
uni.setStorageSync('uid', user.data.uid);
uni.setStorageSync('uid', user.data.uid)
store.dispatch('setUserInfo', user.data)
resolve(user)
}).catch(error => {
})
.catch(error => {
console.log('获取用户信息失败')
reject('获取用户信息失败')
});
}).catch(error => {
})
})
.catch(error => {
console.log(error)
console.log('登录接口调用失败')
reject('登录接口调用失败')
});
})
},
fail() {
console.log('获取用户信息失败')
reject('获取用户信息失败')
}
});
}).catch(error => {
console.log('用户未授权')
reject('用户未授权')
},
})
}
},
fail() {
console.log('调用登录接口失败')
reject('调用登录接口失败')
}
});
}).catch(error => {
},
})
})
.catch(error => {
reject('获取环境服务商失败')
})
})
@ -335,14 +362,14 @@ export const handleGetUserInfo = () => {
reLaunch({
path: redirect,
// query
});
})
return
}
reLaunch({
path: '/pages/home/index',
// query
});
})
// var pages = getCurrentPages() //获取加载的页面
// var currentPage = pages[pages.length - 1] //获取当前页面的对象
@ -419,10 +446,7 @@ export const handleGetUserInfo = () => {
export function parseUrl(location) {
if (typeof location === 'string') return location
const {
path,
query
} = location
const { path, query } = location
const queryStr = stringify(query)
@ -443,9 +467,9 @@ export function parseRoute($mp) {
hash: '',
fullPath: parseUrl({
path: `/${path}`,
query: _$mp.query || _$mp.page.options
query: _$mp.query || _$mp.page.options,
}),
name: path && path.replace(/\/(\w)/g, ($0, $1) => $1.toUpperCase())
name: path && path.replace(/\/(\w)/g, ($0, $1) => $1.toUpperCase()),
}
}
@ -464,24 +488,24 @@ export function handleAuth() {
return false
}
export const handleLoginStatus = (location, complete, fail, success) => {
// 不登录可访问的页面
let page = [{
let page = [
{
path: '/pages/Loading/index',
name: 'loading页面'
name: 'loading页面',
},
{
path: '/pages/home/index',
name: '首页'
name: '首页',
},
{
path: '/pages/user/Login/index',
name: '登录页面'
name: '登录页面',
},
{
path: '/pages/authorization/index',
name: '授权页面'
name: '授权页面',
},
]
@ -499,7 +523,7 @@ export const handleLoginStatus = (location, complete, fail, success) => {
// 判断用户是否有token
if (!handleAuth()) {
page.map((item) => {
page.map(item => {
if (item.path == path) {
isAuth = true
}
@ -509,7 +533,6 @@ export const handleLoginStatus = (location, complete, fail, success) => {
}
return new Promise((resolve, reject) => {
if (isAuth) {
// 有token
if (path == '/pages/home/index' || path == '/pages/shop/GoodsClass/index' || path == '/pages/shop/ShoppingCart/index' || path == '/pages/user/User/index') {
@ -523,7 +546,7 @@ export const handleLoginStatus = (location, complete, fail, success) => {
url: parseUrl(location),
complete,
fail,
success
success,
})
} else {
// 没有token,先校验用户是否授权,如果授权了,进行自动登录
@ -558,17 +581,19 @@ export function routerPermissions(url, type) {
console.log('————————')
console.log('开始校验权限')
console.log('————————')
authorize('userInfo').then(() => {
authorize('userInfo')
.then(() => {
// 自动登录
console.log('————————')
console.log('自动登录')
console.log('————————')
login().then(res => {
login()
.then(res => {
// 登录成功,跳转到需要跳转的页面
console.log('————————')
console.log('登录成功,跳转页面')
console.log('————————')
store.commit("updateAuthorizationPage", false);
store.commit('updateAuthorizationPage', false)
if (path == '/pages/shop/ShoppingCart/index' || path == '/pages/user/User/index') {
console.log('————————')
console.log('当前是购物车,或者个人中心')
@ -578,7 +603,6 @@ export function routerPermissions(url, type) {
if (type == 'reLaunch') {
reLaunch({
path,
})
return
}
@ -591,27 +615,29 @@ export function routerPermissions(url, type) {
push({
path,
})
}).catch(error => {
})
.catch(error => {
console.log('————————')
console.log('自动登录失败,跳转到授权页面')
console.log('————————')
uni.showToast({
title: error,
icon: "none",
duration: 2000
});
icon: 'none',
duration: 2000,
})
reLaunch({
path: '/pages/authorization/index',
})
cookie.set('redirect', path)
})
}).catch(error => {
})
.catch(error => {
// 跳转到登录页面或者授权页面
if (path == '/pages/shop/ShoppingCart/index' || path == '/pages/user/User/index') {
switchTab({
path,
})
store.commit("updateAuthorizationPage", false);
store.commit('updateAuthorizationPage', false)
return
}
reLaunch({
@ -620,7 +646,7 @@ export function routerPermissions(url, type) {
cookie.set('redirect', path)
})
} else if (Vue.prototype.$deviceType == 'weixin') {
wechat().then(() => oAuth());
wechat().then(() => oAuth())
if (!type) {
push({
path: url,
@ -634,33 +660,36 @@ export function routerPermissions(url, type) {
path: '/pages/user/Login/index',
})
}
}
export function push(location, complete, fail, success) {
handleLoginStatus(location, complete, fail, success).then(params => {
handleLoginStatus(location, complete, fail, success)
.then(params => {
uni.navigateTo(params)
}).catch(error => {
})
.catch(error => {
// 没有权限
})
}
export function replace(location, complete, fail, success) {
handleLoginStatus(location, complete, fail, success).then(params => {
handleLoginStatus(location, complete, fail, success)
.then(params => {
console.log(params)
uni.redirectTo(params)
}).catch(error => {
})
.catch(error => {
// 没有权限
})
}
export function reLaunch(location, complete, fail, success) {
handleLoginStatus(location, complete, fail, success).then(params => {
handleLoginStatus(location, complete, fail, success)
.then(params => {
console.log(params)
uni.reLaunch(params)
}).catch(error => {
})
.catch(error => {
// 没有权限
console.log(error)
})
@ -668,7 +697,7 @@ export function reLaunch(location, complete, fail, success) {
export function go(delta) {
uni.navigateBack({
delta
delta,
})
}
@ -676,19 +705,20 @@ export function back() {
uni.navigateBack({
delta: 1,
success: function(e) {},
fail: function (e) { }
fail: function(e) {},
})
}
export function switchTab(location, complete, fail, success) {
handleLoginStatus(location, complete, fail, success).then(params => {
handleLoginStatus(location, complete, fail, success)
.then(params => {
uni.switchTab(params)
}).catch(error => {
})
.catch(error => {
// 没有权限
})
}
export const _router = {
mode: 'history',
switchTab,
@ -696,26 +726,25 @@ export const _router = {
replace,
go,
back,
reLaunch
reLaunch,
}
export function handleQrCode() {
var urlSpread = parseQuery()["q"];
var urlSpread = parseQuery()['q']
if (urlSpread) {
if (urlSpread.indexOf('%3F') != -1) {
// 通过海报二维码进来
urlSpread = urlSpread
.split("%3F")[1]
.replace(/%3D/g, ":")
.replace(/%26/g, ",")
.split(",")
.split('%3F')[1]
.replace(/%3D/g, ':')
.replace(/%26/g, ',')
.split(',')
.map((item, index) => {
item = item.split(":");
return `"${item[0]}":"${item[1]}"`;
item = item.split(':')
return `"${item[0]}":"${item[1]}"`
})
.join(",");
urlSpread = JSON.parse("{" + urlSpread + "}");
.join(',')
urlSpread = JSON.parse('{' + urlSpread + '}')
return urlSpread
} else {
return handleUrlParam(urlSpread)
@ -725,19 +754,19 @@ export function handleQrCode() {
}
export function handleUrlParam(path) {
var url = path.split("?")[1]; //获取url中"?"符后的字串
var theRequest = new Object();
if (path.includes("?")) {
var url = path.split("?")[1]; //获取url中"?"符后的字串
let strs = url.split("&");
var url = path.split('?')[1] //获取url中"?"符后的字串
var theRequest = new Object()
if (path.includes('?')) {
var url = path.split('?')[1] //获取url中"?"符后的字串
let strs = url.split('&')
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
}
}
return theRequest;
return theRequest
}
const getImageInfo = (images) => {
const getImageInfo = images => {
return new Promise((resolve, reject) => {
let imageAry = {}
images.map((item, index) => {
@ -754,13 +783,12 @@ const getImageInfo = (images) => {
if (Object.keys(imageAry).length == images.length) {
resolve(imageAry)
}
}
},
})
})
})
}
/**
* 获取分享海报
* @param array store 海报素材
@ -773,39 +801,39 @@ const getImageInfo = (images) => {
export const PosterCanvas = (store, successCallBack) => {
uni.showLoading({
title: '海报生成中',
mask: true
});
mask: true,
})
getImageInfo([store.image, store.code]).then(res => {
let contentHh = 48 * 1.3
const ctx = uni.createCanvasContext('myCanvas')
ctx.clearRect(0, 0, 0, 0);
ctx.clearRect(0, 0, 0, 0)
const WIDTH = 747
const HEIGHT = 1326;
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(0, 0, WIDTH, HEIGHT);
ctx.drawImage(res[0].path, 0, 0, WIDTH, WIDTH);
ctx.drawImage(res[1].path, 40, 1064, 200, 200);
ctx.save();
let r = 90;
let d = r * 2;
let cx = 40;
let cy = 990;
ctx.arc(cx + r, cy + r, r, 0, 2 * Math.PI);
ctx.clip();
ctx.restore();
ctx.setTextAlign('center');
ctx.setFontSize(48);
ctx.setFillStyle('#000');
ctx.fillText(store.title, WIDTH / 2, 810 + contentHh);
const HEIGHT = 1326
ctx.fillStyle = '#FFFFFF'
ctx.fillRect(0, 0, WIDTH, HEIGHT)
ctx.drawImage(res[0].path, 0, 0, WIDTH, WIDTH)
ctx.drawImage(res[1].path, 40, 1064, 200, 200)
ctx.save()
let r = 90
let d = r * 2
let cx = 40
let cy = 990
ctx.arc(cx + r, cy + r, r, 0, 2 * Math.PI)
ctx.clip()
ctx.restore()
ctx.setTextAlign('center')
ctx.setFontSize(48)
ctx.setFillStyle('#000')
ctx.fillText(store.title, WIDTH / 2, 810 + contentHh)
ctx.setTextAlign('center')
ctx.setFontSize(32);
ctx.setFillStyle('red');
ctx.fillText('¥' + store.price, WIDTH / 2, 985);
ctx.setFontSize(32)
ctx.setFillStyle('red')
ctx.fillText('¥' + store.price, WIDTH / 2, 985)
ctx.setTextAlign('center')
ctx.setFontSize(22);
ctx.setFillStyle('#333333');
ctx.fillText('长按识别二维码立即购买', WIDTH / 2, 1167);
ctx.save();
ctx.setFontSize(22)
ctx.setFillStyle('#333333')
ctx.fillText('长按识别二维码立即购买', WIDTH / 2, 1167)
ctx.save()
ctx.draw(true, () => {
uni.canvasToTempFilePath({
canvasId: 'myCanvas',
@ -813,16 +841,14 @@ export const PosterCanvas = (store, successCallBack) => {
destWidth: WIDTH,
destHeight: HEIGHT,
success: function(res) {
uni.hideLoading();
successCallBack && successCallBack(res.tempFilePath);
uni.hideLoading()
successCallBack && successCallBack(res.tempFilePath)
},
fail: function(error) {
console.log(error)
},
})
});
})
})
// uni.getImageInfo({
@ -840,24 +866,21 @@ export const PosterCanvas = (store, successCallBack) => {
// })
}
export const handleLoginFailure = () => {
console.log('————————')
console.log('退出登录,标记当前页面为授权页面,防止多次跳转')
console.log('————————')
store.commit("logout");
store.commit('logout')
// 改为授权取消
store.commit("updateAuthorization", false);
store.commit('updateAuthorization', false)
let currentPageUrl = getCurrentPageUrl()
if (store.state.$deviceType == 'weixin') {
// 如果不是授权页面,
if (!store.getters.isAuthorizationPage) {
// 标识当前为授权页面
store.commit("updateAuthorizationPage", true);
store.commit('updateAuthorizationPage', true)
toAuth()
}
return
@ -870,12 +893,11 @@ export const handleLoginFailure = () => {
}
}
console.log('————————')
console.log('当前是授权页面')
console.log(store.getters)
console.log('————————')
store.commit("updateAuthorizationPage", true);
store.commit('updateAuthorizationPage', true)
let path = '/' + getCurrentPageUrlWithArgs()
@ -894,10 +916,10 @@ export const handleLoginFailure = () => {
path: `/ ${currentPageUrl} `,
query: {
id: qrCode.pinkId,
}
},
})
if (qrCode.spread) {
cookie.set("spread", qrCode.spread || 0);
cookie.set('spread', qrCode.spread || 0)
}
} else {
console.log('————————')
@ -918,11 +940,11 @@ export const handleLoginFailure = () => {
path: `/ ${currentPageUrl} `,
query: {
id: qrCode.bargainId,
partake: qrCode.uid
}
partake: qrCode.uid,
},
})
if (qrCode.spread) {
cookie.set("spread", qrCode.spread || 0);
cookie.set('spread', qrCode.spread || 0)
}
} else {
handleNoParameters()
@ -942,10 +964,10 @@ export const handleLoginFailure = () => {
path: `/ ${currentPageUrl} `,
query: {
id: qrCode.productId,
}
},
})
if (qrCode.spread) {
cookie.set("spread", qrCode.spread || 0);
cookie.set('spread', qrCode.spread || 0)
}
} else {
handleNoParameters()
@ -956,8 +978,6 @@ export const handleLoginFailure = () => {
}
}
console.log('————————')
console.log(path, '重定向页面地址')
console.log('————————')
@ -968,35 +988,34 @@ const handleNoParameters = () => {
uni.showToast({
title: '未获取到必要参数,即将跳转首页',
icon: 'success',
duration: 2000
duration: 2000,
})
setTimeout(() => {
clearTimeout()
switchTab({
path: '/pages/home/index',
});
})
}, 1500)
}
export function chooseImage(callback) {
uni.chooseImage({
count: 1,
sourceType: ["album"],
sourceType: ['album'],
success: res => {
uni.getImageInfo({
src: res.tempFilePaths[0],
success: image => {
console.log(image);
uni.showLoading({ title: "图片上传中", mask: true });
console.log(image)
uni.showLoading({ title: '图片上传中', mask: true })
uni.uploadFile({
url: `${VUE_APP_API_URL}/api/upload`,
file: image,
filePath: image.path,
header: {
Authorization: "Bearer " + store.getters.token
Authorization: 'Bearer ' + store.getters.token,
},
name: "file",
name: 'file',
success: res => {
if (callback) {
callback(JSON.parse(res.data).link)
@ -1004,39 +1023,34 @@ export function chooseImage(callback) {
},
fail: err => {
uni.showToast({
title: "上传图片失败",
icon: "none",
duration: 2000
});
title: '上传图片失败',
icon: 'none',
duration: 2000,
})
},
complete: res => {
uni.hideLoading()
}
});
},
})
},
fail: err => {
uni.showToast({
title: "获取图片信息失败",
icon: "none",
duration: 2000
});
}
});
}
});
title: '获取图片信息失败',
icon: 'none',
duration: 2000,
})
},
})
},
})
}
export function handleErrorMessage(err) {
console.log(err)
uni.hideLoading();
uni.hideLoading()
uni.showToast({
title:
err.msg ||
err.response.data.msg ||
err.response.data.message ||
"创建订单失败",
icon: "none",
title: err.msg || err.response.data.msg || err.response.data.message || '创建订单失败',
icon: 'none',
duration: 2000,
});
})
}

Loading…
Cancel
Save