uniapp 微信登陆操作记录
  • 分类:建站问题
  • 发表:2020-07-24
  • 围观(356)
  • 评论(0)

在Uniapp环境下检测是否为微信浏览器。

// #ifdef H5
let ua = window.navigator.userAgent.toLowerCase()
if (ua.match(/MicroMessenger/i) == 'micromessenger') {
// do something
}
// #endif

获取授权代码

// #ifdef H5
let ua = window.navigator.userAgent.toLowerCase()
console.log(ua);
if (ua.match(/MicroMessenger/i) == 'micromessenger') {
let appid = "wxcafb840cdc3f98f8";
let backurl = encodeURIComponent("http://hbcgs.hebi99.cn/wx/#/pages/loginwx");
let state = "loginwx";
var wxurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+backurl+"&response_type=code&scope=snsapi_userinfo&state="+state+"#wechat_redirect"
window.location.href = wxurl;
}else{
uni.navigateTo({
url: '../login/login'
});
}
// #endif
// #ifndef H5
uni.navigateTo({
url: '../login/login'
});
// #endif

loginwx.vue文件内容

<template>
<view class="content">
登陆中,请稍等。
</view>
</template>

<script>
var api = require('@/common/api.js')
export default {
onLoad(e) {
console.log(window.location.toString());
let that = this;
that.code = this.getUrlParam('code')
that.state = this.getUrlParam('state');
that.login();
},
data() {
return {
loading: false,
code: "",
state:""
};
},
methods: {
// 获取url地址参数
getUrlParam(paraName) {
let url = window.location.toString()
let arrObj = url.split('?')
if (arrObj.length > 1) {
let arrPara = arrObj[1].split('&')
let arr
for (let i = 0; i < arrPara.length; i++) {
arr = arrPara[i].split('=')
if (arr != null && arr[0] == paraName) {
if (arr[1].indexOf('#')) {
let str
str = arr[1].split('#')
return str[0]
}
return arr[1]
}
}
return ''
} else {
return ''
}
},
login() {
this.loading = true;
api.post({
url: 'user/public/uniappcode',
data: {
code: this.code,
state: this.state,
device_type: api.DeviceType
},
success: data => {
//console.log(data);
if (data.code == 1) {
this.loading = false;
//console.log(data);
uni.showToast({
duration: 500,
title: data.msg
});
uni.setStorageSync('upload', 1)
uni.setStorageSync('login', 1)
uni.setStorageSync('token', data.data.token)
uni.setStorageSync('user', data.data.user)
setTimeout((e => {
uni.switchTab({
url: 'index/index'
});
}), 500);
}
if (data.code == 0) {
this.loading = false;
uni.showToast({
duration: 1500,
icon: 'none',
title: data.msg
});
}
}
})
}
}
}
</script>

<style>
</style>

文件资源:

 

服务端处理

待续

Top