Browse Source

修改公众号微信登录授权未保存token的问题

zyh
Gaoxs 5 years ago
parent
commit
48e073d573
  1. 2
      api/public.js
  2. 54
      libs/wechat.js
  3. 31
      main.js
  4. 7
      manifest.json
  5. 6
      pages/Loading/index.vue
  6. 16
      pages/home/index.vue
  7. 2
      store/index.js
  8. 35
      utils/index.js

2
api/public.js

@ -63,7 +63,7 @@ export function getArticleDetails(id) {
export function getWechatConfig() {
return request.get(
"/wechat/config",
{ url: document.location.href },
{ url: location.href },
{ login: false }
);
}

54
libs/wechat.js

@ -57,6 +57,7 @@ const BACK_URL = "login_back_url";
const LOGINTYPE = "loginType";
let instance;
let wechatObj;
let appId
export function wechat() {
console.log('初始化微信配置')
@ -64,8 +65,10 @@ export function wechat() {
if (instance) return resolve(instance);
getWechatConfig()
.then(res => {
console.log(res.data)
const _wx = WechatJSSDK(res.data);
console.log(_wx)
appId = res.data.appId
wechatObj = _wx;
_wx
.initialize()
@ -74,7 +77,10 @@ export function wechat() {
instance.initConfig = res.data;
resolve(instance);
})
.catch(reject);
.catch(error => {
console.log(error)
reject(error)
});
})
.catch(err => {
console.log(err);
@ -90,8 +96,11 @@ export function clearAuthStatus() {
export function oAuth() {
console.log('处理微信授权')
console.log(store)
console.log(store.state)
return new Promise((resolve, reject) => {
if (cookie.has(WX_AUTH) && store.state.app.token) {
// if (cookie.has(WX_AUTH)) {
if (cookie.has(WX_AUTH) && store.state.token) {
reject()
return;
}
@ -101,6 +110,8 @@ export function oAuth() {
return
}
resolve()
}).catch(error => {
console.log(error)
})
}
@ -108,43 +119,42 @@ export function auth(code) {
console.log('获取微信授权')
return new Promise((resolve, reject) => {
let loginType = cookie.get(LOGINTYPE);
debugger
wechatAuth(code, parseInt(cookie.get("spread")), loginType)
.then(({ data }) => {
console.log(data)
const expires_time = dayjs(data.expires_time);
const newTime = Math.round(new Date() / 1000);
store.commit("LOGIN", data.token, expires_time - newTime);
store.commit("login", data.token, expires_time - newTime);
cookie.set(WX_AUTH, code, expires_time);
cookie.remove(STATE_KEY);
loginType && cookie.remove("loginType");
loginType && cookie.remove(LOGINTYPE);
debugger
resolve();
})
.catch(reject);
});
}).catch(error => {
debugger
console.log(error)
})
}
export function toAuth() {
wechat().then(wx => {
location.href = getAuthUrl(wx.initConfig.appId);
});
// wechat().then(wx => {
location.href = getAuthUrl("wxc061dee8806ff712");
// });
}
function getAuthUrl(appId) {
const redirect_uri = encodeURIComponent(
`${location.origin}/auth/` +
encodeURIComponent(
encodeURIComponent(
cookie.has(BACK_URL)
? cookie.get(BACK_URL)
: location.pathname + location.search
)
)
);
const redirect_uri = encodeURIComponent(`${location.origin}/pages/Loading/index`);
// const redirect_uri = encodeURIComponent(`${location.origin}/pages/Loading/index`encodeURIComponent(encodeURIComponent(cookie.has(BACK_URL)? cookie.get(BACK_URL): location.pathname + location.search)));
// const redirect_uri = encodeURIComponent(`${window.location.origin}${window.location.pathname}`)
// const redirect_uri = encodeURIComponent(`${location.origin}`)
cookie.remove(BACK_URL);
const state = encodeURIComponent(
("" + Math.random()).split(".")[1] + "authorizestate"
);
const state = 'STATE'
// const state = encodeURIComponent(("" + Math.random()).split(".")[1] + "authorizestate");
cookie.set(STATE_KEY, state);
return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;
return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
}
function toPromise(fn, config = {}) {

31
main.js

@ -84,17 +84,46 @@ Vue.prototype.$VUE_APP_API_URL = VUE_APP_API_URL
// #ifdef H5
// H5编译的代码
import { wechat, oAuth } from '@/libs/wechat'
import {
wechat,
clearAuthStatus,
oAuth,
auth,
toAuth,
pay,
openAddress,
openShareAll,
openShareAppMessage,
openShareTimeline,
wechatEvevt,
ready,
wxShowLocation,
} from '@/libs/wechat'
import { isWeixin } from '@/utils'
// 判断是否是微信浏览器
if (isWeixin()) {
Vue.prototype.$deviceType = 'weixin'
store.commit('updateDevicetype', 'weixin')
// wechat().then(() => oAuth());
} else {
Vue.prototype.$deviceType = 'weixinh5'
store.commit('updateDevicetype', 'weixinh5')
}
Vue.prototype.wechat = wechat
Vue.prototype.clearAuthStatus = clearAuthStatus
Vue.prototype.oAuth = oAuth
Vue.prototype.auth = auth
Vue.prototype.toAuth = toAuth
Vue.prototype.pay = pay
Vue.prototype.openAddress = openAddress
Vue.prototype.openShareAll = openShareAll
Vue.prototype.openShareAppMessage = openShareAppMessage
Vue.prototype.openShareTimeline = openShareTimeline
Vue.prototype.wechatEvevt = wechatEvevt
Vue.prototype.ready = ready
Vue.prototype.wxShowLocation = wxShowLocation
// #endif
// #ifdef APP-PLUS

7
manifest.json

@ -152,8 +152,11 @@
},
"h5" : {
"title" : "yshop",
"devServer": {
"disableHostCheck": true
"devServer" : {
"disableHostCheck" : true
},
"router" : {
"mode" : "history"
}
}
}

6
pages/Loading/index.vue

@ -52,9 +52,9 @@ export default {
return;
}
login().finally(() => {
this.$yrouter.switchTab({
path: "/pages/home/index"
});
// this.$yrouter.switchTab({
// path: "/pages/home/index"
// });
});
},
methods: {

16
pages/home/index.vue

@ -146,7 +146,6 @@
mapMutations,
mapActions
} from 'vuex';
import GoodList from '@/components/GoodList';
import PromotionGood from '@/components/PromotionGood';
import CouponWindow from '@/components/CouponWindow';
@ -310,7 +309,20 @@
goGoodsPromotion() {
this.$yrouter.push('/pages/shop/GoodsPromotion/index');
},
setOpenShare: function() {},
setOpenShare: function() {
if (this.$deviceType == 'weixin') {
getShare().then(res => {
var data = res.data.data;
var configAppMessage = {
desc: data.synopsis,
title: data.title,
link: location.href,
imgUrl: data.img
};
this.openShareAll(configAppMessage);
})
}
},
startQr: function() {
uni.scanCode({
success: (res) => {

2
store/index.js

@ -80,7 +80,7 @@ const vuexStore = new Vuex.Store({
actions: {
getLocation({ state, commit }, force) {
uni.getLocation({
type: 'wgs84',
type: 'gcj02',
success: function (res) {
console.log(res)
commit("setLocation", {

35
utils/index.js

@ -10,7 +10,7 @@ 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 } from '@/libs/wechat'
import { wechat, auth, oAuth, toAuth } from '@/libs/wechat'
export function dataFormat(time, option) {
@ -158,8 +158,8 @@ export const login = () => {
return new Promise((resolve, reject) => {
if (Vue.prototype.$deviceType == 'weixin') {
// 微信授权登录
wechat().then(() => oAuth().then((code) => {
// const { code } = parseQuery()
const { code } = parseQuery()
if (code) {
auth(code)
.then(() => {
// location.replace(
@ -173,7 +173,34 @@ export const login = () => {
reject('当前运行环境为微信浏览器')
location.replace("/pages/home/index");
});
}));
} else {
wechat().then(() => oAuth());
}
// if (!code) {
// toAuth("wxc061dee8806ff712")
// } else {
// // wechat().then(() => oAuth().then((code) => {
// // // const { code } = parseQuery()
// // debugger
// // auth(code)
// // .then(() => {
// // // location.replace(
// // // decodeURIComponent(decodeURIComponent(this.$route.params.url))
// // // );
// // debugger
// // location.href = decodeURIComponent(
// // decodeURIComponent(this.$route.params.url)
// // );
// // })
// // .catch(() => {
// // reject('当前运行环境为微信浏览器')
// // location.replace("/pages/home/index");
// // });
// // })).catch(error => {
// // console.log(error)
// // reject('自动登录失败')
// // });
// }
return
}
if (Vue.prototype.$deviceType == 'weixinh5') {

Loading…
Cancel
Save