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

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; let urlData = location.pathname + location.search;
if (!that.$store.getters.isLogin && Auth.isWeixin()) { if (!that.$store.getters.isLogin && Auth.isWeixin()) {
const { code, } = option.query; 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) { && location.pathname.indexOf('/pages/users/wechat_login/index') === -1) {
// code // code
uni.setStorageSync('snsapiCode', code); uni.setStorageSync('snsapiCode', code);

View File

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

View File

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

View File

@ -1,15 +1,11 @@
// #ifdef H5 // #ifdef H5
import WechatJSSDK from "@/plugin/jweixin-module/index.js"; 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 * as WeiXinApi from '@/api/system/weixin.js';
import { import {
WX_AUTH, WX_AUTH,
STATE_KEY, STATE_KEY,
LOGINTYPE,
BACK_URL BACK_URL
} from '@/config/cache'; } from '@/config/cache';
import { import {
@ -156,9 +152,9 @@ class AuthWechat {
*/ */
oAuth(snsapiBase,url) { oAuth(snsapiBase,url) {
// TODO 芋艿:先链式去掉这个逻辑; // TODO 芋艿:先链式去掉这个逻辑;
if (true) { // if (true) {
return; // return;
} // }
if (uni.getStorageSync(WX_AUTH) && store.state.app.token && snsapiBase == 'snsapi_base') return; if (uni.getStorageSync(WX_AUTH) && store.state.app.token && snsapiBase == 'snsapi_base') return;
const { const {
code 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 * 微信公众号的授权登录获取 token
* @param {Object} code *
* 实现逻辑是发起社交登录
*/ */
auth(code) { auth(code, state) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
wechatAuth(code, Cache.get("spread")) // 31 的原因,它是公众号登录的社交类型
.then(({ AuthApi.socialLogin(31, code, state)
data .then((data) => {
}) => { debugger
resolve(data); resolve(data);
Cache.set(WX_AUTH, code); Cache.set(WX_AUTH, code);
Cache.clear(STATE_KEY); Cache.clear(STATE_KEY);
// Cache.clear('spread'); }).catch(reject);
loginType && Cache.clear(LOGINTYPE);
})
.catch(reject);
}); });
} }
@ -218,33 +196,25 @@ class AuthWechat {
*/ */
getAuthUrl(appId,snsapiBase,backUrl) { getAuthUrl(appId,snsapiBase,backUrl) {
let url = `${location.origin}${backUrl}` let url = `${location.origin}${backUrl}`
if(url.indexOf('?') == -1){ if(url.indexOf('?') === -1){
url = url+'?' url = url+'?'
}else{ }else{
url = url+'&' 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`;
// }
} }
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() { isWeixin() {
return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1; return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
} }

View File

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

View File

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