App
<view @click="onLogin"></view>
<script>
let weixinAuthService;
export default {
components: {},
data() {
return {
hasWeixinAuth: false,
};
},
onLoad() {
// #ifdef APP
plus.oauth.getServices(services => {
weixinAuthService = services.find(service => {
console.log('service===', service);
return service.id === 'weixin';
});
if (weixinAuthService) {
this.hasWeixinAuth = true;
}
});
// #endif
},
methods: {
// 微信登录
async onLogin() {
if (!this.hasWeixinAuth) return;
this.getWeixinCode().then(code => {
console.log('codelogin====', code);
this.wxLoginApi(code);
});
},
// 获取微信code
getWeixinCode() {
return new Promise((resolve, reject) => {
// #ifdef MP-WEIXIN
uni.login({
provider: 'weixin',
success(res) {
resolve(res.code);
},
fail(err) {
reject(new Error('微信登录失败'));
}
});
// #endif
// #ifdef APP-PLUS
weixinAuthService.authorize(
function(res) {
resolve(res.code);
},
function(err) {
console.log(err);
reject(new Error('微信登录失败'));
}
);
// #endif
});
},
// app微信登录接口
async wxLoginApi(value) {
var res = await this.$post('登录接口地址', {
code: value,
type:1
});
if (res.errcode != 0) {
this.$toast(res.errmsg);
return;
}
this.$toast('登录成功');
this.$store.set('jwt', res.data.jwt);
setTimeout(() => {
this.$replaceAllTo('登陆之后跳转页面地址', {});
}, 1000);
},
}
};
</script>
H5
<view @click="onLogin"></view>
export default {
data() {
return {
}
},
onLoad(options) {
let result = this.getAllParams()
if (result.id) { //如果跳转来的链接有参数存到缓存里
this.$store.set('match_id', parseInt(result.id));
}
if (result.code) { //onLogin()回调之后会返回code参数
this.wxLoginApi(result.code);
}
},
methods: {
getAllParams() { //获取url地址上的key,value的方法
let href = window.location.href;
let query = href.substring(href.indexOf("?") + 1);
let vars = query.split("&");
let obj = {};
for (let i = 0; i < vars.length; i++) {
let pair = vars[i].split("=");
// 将参数名和参数值分别作为对象的属性名和属性值
obj[pair[0]] = pair[1];
}
return obj
},
// 获取微信授权
async onLogin() {
let appid = 'appid' //微信公众号的appid
let redirect_uri = '当前项目地址(需要配置)' // 授权登录成功回调的地址,一般为当前页// 授权操作是直接访问腾讯开放平台的一个授权地址,授权成功后会回调 需要在公众平台配置
window.location = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+ appid+'&redirect_uri='+redirect_uri+'&response_type=code&scope=snsapi_userinfo&state=abcdefghigklmnopqrstuvwxyz#wechat_redirect' //引导用户授权
},
// 微信登录
async wxLoginApi(value) {
var res = await this.$post('微信登录的接口地址', {
code: value,
type: 2
});
if (res.errcode != 0) {
this.$toast(res.errmsg);
return;
}
this.$toast('登录成功');
this.$store.set('jwt', res.data.jwt);
setTimeout(() => {
uni.redirectTo({
url: '登陆之后跳转页面地址'
})
}, 1000);
},
}
}
</script>