Browse Source

优化微信授权

master
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-avatar" type="userAvatarUrl"></open-data>
<open-data class="user-name" type="userNickName"></open-data> <open-data class="user-name" type="userNickName"></open-data>
<view class="login-notice">为了提供更优质的服务需要获取您的头像昵称</view> <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> <button class="cu-btn close-btn" @tap="back">暂不授权</button>
</view> </view>
</view> </view>
@ -25,88 +26,123 @@
</template> </template>
<script> <script>
import { import { mapState, mapMutations, mapActions } from 'vuex'
mapState, import { wxappAuth, getUser } from '@/api/user'
mapMutations, import dayjs from 'dayjs'
mapActions import cookie from '@/utils/store/cookie'
} from "vuex"; import { login, authorize } from '@/utils'
import {
wxappAuth,
getUser
} from "@/api/user";
import dayjs from "dayjs";
import cookie from "@/utils/store/cookie";
import {
login,
authorize
} from "@/utils";
export default { export default {
data() { data() {
return { return {
authorize: false, authorize: false,
}; canIUseGetUserProfile: false,
}
}, },
computed: { 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() { onHide() {
this.updateAuthorizationPage(false); this.updateAuthorizationPage(false)
this.changeAuthorization(false); this.changeAuthorization(false)
}, },
onUnload() { onUnload() {
this.updateAuthorizationPage(false); this.updateAuthorizationPage(false)
this.changeAuthorization(false); this.changeAuthorization(false)
}, },
methods: { methods: {
...mapActions(["changeAuthorization", "setUserInfo"]), ...mapActions(['changeAuthorization', 'setUserInfo']),
...mapMutations(["updateAuthorizationPage"]), ...mapMutations(['updateAuthorizationPage']),
toLogin() { toLogin() {
this.$yrouter.push({ this.$yrouter.push({
path: "/pages/user/Login/index", path: '/pages/user/Login/index',
query: {}, query: {},
}); })
}, },
back() { back() {
this.$yrouter.switchTab({ this.$yrouter.switchTab({
path: "/pages/home/index", path: '/pages/home/index',
query: {}, query: {},
}); })
}, },
getUserInfo(data) { 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({ uni.showToast({
title: "取消授权", title: '取消授权',
icon: "none", icon: 'none',
duration: 2000, duration: 2000,
}); })
return; return
} }
uni.showLoading({ uni.showLoading({
title: "登录中", title: '登录中',
}); })
login() 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('重定向') console.log('重定向')
this.$yrouter.reLaunch({ this.$yrouter.reLaunch({
path: cookie.get("redirect").replace(/\ /g, '') path: cookie.get('redirect').replace(/\ /g, ''),
}); })
}) })
.catch((error) => { .catch(error => {
console.log(error); console.log(error)
uni.showToast({ uni.showToast({
title: error, title: error,
icon: "none", icon: 'none',
duration: 2000, duration: 2000,
}); })
}); })
},
})
}, },
}, },
mounted() {}, mounted() {
}; if (wx.getUserProfile) {
console.log(this)
this.canIUseGetUserProfile = true
console.log(this.canIUseGetUserProfile)
}
},
}
</script> </script>
<style lang="less"> <style lang="less">

217
pages/user/User/index.vue

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

508
utils/index.js

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

Loading…
Cancel
Save