登录:初步实现微信公众号登录

pull/1/MERGE
YunaiV 2023-09-10 22:46:53 +08:00
parent e8573f42bb
commit 99a6ff2d77
7 changed files with 119 additions and 191 deletions

View File

@ -82,7 +82,8 @@
let urlData = location.pathname + location.search;
if (!that.$store.getters.isLogin && Auth.isWeixin()) {
const { code, } = option.query;
if (code && code != uni.getStorageSync('snsapiCode')
// debugger
if (code && code !== uni.getStorageSync('snsapiCode')
&& location.pathname.indexOf('/pages/users/wechat_login/index') === -1) {
// code
uni.setStorageSync('snsapiCode', code);

View File

@ -18,16 +18,10 @@
const app = getApp();
import sendVerifyCode from "@/mixins/SendVerifyCode";
import {mapGetters} from "vuex";
import {
registerVerify,
getCodeApi,
getUserInfo,
phoneSilenceAuth,
} from "@/api/user";
import {
getUserPhone,
iosBinding
} from '@/api/public';
import * as AuthApi from "@/api/member/auth";
import * as UserApi from "@/api/member/user";
import { getUserInfo, } from "@/api/user";
import { iosBinding } from '@/api/public';
const BACK_URL = "login_back_url";
export default {
name: 'login_mobile',
@ -41,6 +35,14 @@
type: String,
default: '',
},
socialCode: {
type: String,
default: '',
},
socialState: {
type: String,
default: '',
},
isShow: {
type: Boolean,
default: true
@ -60,7 +62,6 @@
},
data() {
return {
keyCode: '',
account: '',
codeNum: '',
isApp: 0
@ -70,34 +71,26 @@
methods: {
//
async code() {
let that = this;
if (!that.account) return that.$util.Tips({
title: '请填写手机号码'
});
if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(that.account)) return that.$util.Tips({
title: '请输入正确的手机号码'
});
await registerVerify(that.account).then(res => {
that.$util.Tips({
title: res.msg
});
that.sendCode();
}).catch(err => {
return that.$util.Tips({
title: err
})
})
},
// api
getCode() {
let that = this
getCodeApi().then(res => {
that.keyCode = res.data.key;
}).catch(res => {
that.$util.Tips({
title: res
});
});
if (!this.account) {
return this.$util.Tips({
title: '请填写手机号码'
});
}
if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(this.account)) {
return this.$util.Tips({
title: '请输入正确的手机号码'
});
}
await AuthApi.sendSmsCode(this.account, 1)
.then(res => {
this.$util.Tips({title:res.message});
this.sendCode();
})
.catch(err => {
return this.$util.Tips({
title: err
});
});
},
close() {
this.$emit('close', false)
@ -105,22 +98,29 @@
//
loginBtn() {
let that = this
if (!that.account) return that.$util.Tips({
title: '请填写手机号码'
});
if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(that.account)) return that.$util.Tips({
title: '请输入正确的手机号码'
});
if (!that.codeNum) return that.$util.Tips({
if (!this.account) {
return this.$util.Tips({
title: '请填写手机号码'
});
}
if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(this.account)) {
return this.$util.Tips({
title: '请输入正确的手机号码'
});
}
if (!this.codeNum) return this.$util.Tips({
title: '请填写验证码'
});
if (!/^[\w\d]+$/i.test(that.codeNum)) return that.$util.Tips({
title: '请输入正确的验证码'
});
if (!/^[\w\d]+$/i.test(this.codeNum)) {
return this.$util.Tips({
title: '请输入正确的验证码'
});
}
uni.showLoading({
title: !this.userInfo.phone && this.isLogin?'正在绑定中':'正在登录中'
});
if (!this.userInfo.phone && this.isLogin) {
// TODO
iosBinding({
captcha: that.codeNum,
phone: that.account
@ -140,16 +140,17 @@
})
})
} else {
getUserPhone({
captcha: that.codeNum,
phone: that.account,
// #ifdef H5
type: 'public',
// #endif
key: that.authKey
AuthApi.smsLogin({
mobile: this.account,
code: this.codeNum,
socialType: 31, // TODO
socialCode: this.socialCode,
socialState: this.socialState
}).then(res => {
that.$store.commit('LOGIN', {
token: res.data.token
// TODO refreshToken
let data = res.data;
that.$store.commit('LOGIN', {
token: data.accessToken
});
that.$store.commit("SETUID", res.data.uid);
that.getUserInfo();
@ -161,25 +162,6 @@
})
}
},
// #ifdef MP
phoneSilenceAuth(code) {
let self = this
phoneSilenceAuth({
code: code,
spid: app.globalData.spid,
phone: this.account,
captcha: this.codeNum
}).then(res => {
this.$store.commit('LOGIN', res.data.token);
this.$store.commit("SETUID", res.data.uid);
this.getUserInfo();
}).catch(error => {
self.$util.Tips({
title: error
})
})
},
// #endif
/**
* 获取个人用户信息
*/

View File

@ -13,8 +13,6 @@ module.exports = {
WX_AUTH: 'WX_AUTH',
//微信授权状态
STATE_KEY: 'wx_authorize_state',
//登录类型
LOGINTYPE: 'loginType',
//登录回调地址
BACK_URL: 'login_back_url',
// 小程序授权状态

View File

@ -14,11 +14,9 @@ class Apps{
resolve(data);
Cache.set(WX_AUTH, code);
Cache.clear(STATE_KEY);
loginType && Cache.clear(LOGINTYPE);
})
.catch(reject);
});
}
}
export default new Apps();
export default new Apps();

View File

@ -1,15 +1,11 @@
// #ifdef H5
import WechatJSSDK from "@/plugin/jweixin-module/index.js";
import * as AuthApi from "@/api/member/auth";
import {
wechatAuth
} from "@/api/public";
import * as WeiXinApi from '@/api/system/weixin.js';
import {
WX_AUTH,
STATE_KEY,
LOGINTYPE,
BACK_URL
} from '@/config/cache';
import {
@ -156,9 +152,9 @@ class AuthWechat {
*/
oAuth(snsapiBase,url) {
// TODO 芋艿:先链式去掉这个逻辑;
if (true) {
return;
}
// if (true) {
// return;
// }
if (uni.getStorageSync(WX_AUTH) && store.state.app.token && snsapiBase == 'snsapi_base') return;
const {
code
@ -174,41 +170,23 @@ class AuthWechat {
})
})
}
// if (uni.getStorageSync(WX_AUTH) && store.state.app.token) return;
// const {
// code
// } = parseQuery();
// if (!code){
// return this.toAuth(snsapiBase,url);
// }else{
// if(Cache.has('snsapiKey'))
// return this.auth(code).catch(error=>{
// uni.showToast({
// title:error,
// icon:'none'
// })
// })
// }
}
/**
* 授权登录获取token
* @param {Object} code
* 微信公众号的授权登录获取 token
*
* 实现逻辑是发起社交登录
*/
auth(code) {
auth(code, state) {
return new Promise((resolve, reject) => {
wechatAuth(code, Cache.get("spread"))
.then(({
data
}) => {
resolve(data);
Cache.set(WX_AUTH, code);
Cache.clear(STATE_KEY);
// Cache.clear('spread');
loginType && Cache.clear(LOGINTYPE);
})
.catch(reject);
// 31 的原因,它是公众号登录的社交类型
AuthApi.socialLogin(31, code, state)
.then((data) => {
debugger
resolve(data);
Cache.set(WX_AUTH, code);
Cache.clear(STATE_KEY);
}).catch(reject);
});
}
@ -218,33 +196,25 @@ class AuthWechat {
*/
getAuthUrl(appId,snsapiBase,backUrl) {
let url = `${location.origin}${backUrl}`
if(url.indexOf('?') == -1){
url = url+'?'
}else{
url = url+'&'
}
const redirect_uri = encodeURIComponent(
`${url}scope=${snsapiBase}&back_url=` +
encodeURIComponent(
encodeURIComponent(
uni.getStorageSync(BACK_URL) ?
uni.getStorageSync(BACK_URL) :
location.pathname + location.search
)
)
);
uni.removeStorageSync(BACK_URL);
const state = encodeURIComponent(
("" + Math.random()).split(".")[1] + "authorizestate"
);
uni.setStorageSync(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`;
// if(snsapiBase==='snsapi_base'){
// return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=${state}#wechat_redirect`;
// }else{
// 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`;
// }
if(url.indexOf('?') === -1){
url = url+'?'
}else{
url = url+'&'
}
const redirect_uri = encodeURIComponent(`${url}scope=${snsapiBase}&back_url=` +
encodeURIComponent(
encodeURIComponent(
uni.getStorageSync(BACK_URL) ? uni.getStorageSync(BACK_URL) : location.pathname + location.search
)
)
);
uni.removeStorageSync(BACK_URL);
const state = encodeURIComponent(
("" + Math.random()).split(".")[1] + "authorizestate"
);
uni.setStorageSync(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`;
}
/**
* 跳转自动登录
@ -294,6 +264,9 @@ class AuthWechat {
});
}
/**
* 判断是否在微信公众号的浏览器中
*/
isWeixin() {
return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
}

View File

@ -66,7 +66,6 @@
const BACK_URL = "login_back_url";
import * as BrokerageAPI from '@/api/trade/brokerage.js'
import Routine from '@/libs/routine.js';
import {weixinMiniAppLogin} from "../../../api/member/auth";
export default {
name: "Login",
mixins: [sendVerifyCode],

View File

@ -27,7 +27,8 @@
</view>
</view>
<block v-if="isUp">
<mobileLogin :isUp="isUp" @close="maskClose" :authKey="authKey" @wechatPhone="wechatPhone"></mobileLogin>
<mobileLogin :isUp="isUp" @close="maskClose" @wechatPhone="wechatPhone"
:social-code="socialCode" :social-state="socialState" />
</block>
<block v-if="isPhoneBox">
<routinePhone :logoUrl="logoUrl" :isPhoneBox="isPhoneBox" @close="bindPhoneClose" :authKey="authKey">
@ -35,7 +36,6 @@
</block>
</view>
</template>
<script>
const app = getApp();
let statusBarHeight = uni.getSystemInfoSync().statusBarHeight + 'px';
@ -61,7 +61,10 @@
authKey: '',
options: '',
userInfo: {},
codeNum: 0
codeNum: 0,
socialCode: '',
socialState: '',
}
},
components: {
@ -72,7 +75,7 @@
getLogo().then(res => {
this.logoUrl = res.data.logoUrl
})
let that = this
// #ifdef H5
document.body.addEventListener("focusout", () => {
setTimeout(() => {
@ -81,23 +84,14 @@
window.scrollTo(0, Math.max(scrollHeight - 1, 0));
}, 100);
});
const {
code,
state,
scope
} = options;
const { code, state, scope } = options;
this.options = options
// code
this.code = code || ''
//if(!code) location.replace(decodeURIComponent(decodeURIComponent(option.query.back_url)));
if (code && this.options.scope !== 'snsapi_base') {
let spread = app.globalData.spid ? app.globalData.spid : 0;
// wechatAuth(code, Cache.get("spread"), loginType)
wechat.auth(code, spread).then(res => {
if (res.type === 'register') {
this.authKey = res.key;
this.isUp = true
}
//
wechat.auth(code, state).then(res => {
if (res.type === 'login') {
this.$store.commit('LOGIN', {
token: res.token
@ -105,19 +99,16 @@
this.$store.commit("SETUID", res.uid);
this.getUserInfo();
this.wechatPhone();
//location.replace(decodeURIComponent(decodeURIComponent(option.query.back_url)));
}
}).catch(error => {});
}).catch(error => {
debugger
//
this.socialCode = code;
this.socialState = state;
this.isUp = true
});
}
// #endif
let pages = getCurrentPages();
// let prePage = pages[pages.length - 2];
// if (prePage.route == 'pages/order_addcart/order_addcart') {
// this.isHome = true
// } else {
// this.isHome = false
// }
},
methods: {
back() {
@ -144,7 +135,6 @@
} else {
this.isPhoneBox = false
}
},
// #ifdef MP
//
@ -273,26 +263,12 @@
});
},
// #endif
// #ifdef H5
// url
getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var reg_rewrite = new RegExp("(^|/)" + name + "/([^/]*)(/|$)", "i");
var r = window.location.search.substr(1).match(reg);
var q = window.location.pathname.substr(1).match(reg_rewrite);
if (r != null) {
return unescape(r[2]);
} else if (q != null) {
return unescape(q[2]);
} else {
return null;
}
},
//
wechatLogin() {
debugger
if (!this.code && this.options.scope !== 'snsapi_base') {
this.$wechat.oAuth('snsapi_userinfo', '/pages/users/wechat_login/index');
} else {
@ -304,6 +280,7 @@
},
//
wechatPhone() {
debugger
this.$Cache.clear('snsapiKey');
if (this.options.back_url) {
let url = uni.getStorageSync('snRouter');