<template>
<view>
<!-- #ifdef MP-WEIXIN -->
<button type="default" open-type="getUserInfo" @getuserinfo="getUserInfo" withCredentials="true">小程序登录</button>
<!-- #endif -->
<image :src="userUrl" mode=""></image>
<h3>{{userName}}</h3>
<h3>{{openId}}</h3>
</view>
</template>
<script>
export default {
data() {
return {
userName: '',
userUrl: '',
openId: ''
}
},
onLoad(options) {
console.log(options);
this.appLogin()
},
methods: {
// app
appLogin() {
uni.getProvider({
service: 'oauth',
success: (res) => {
console.log(res.provider);
//支持微信、qq和微博等
if (~res.provider.indexOf('weixin')) {
uni.login({
provider: 'weixin',
success: (loginRes) => {
// 获取用户信息
uni.getUserInfo({
provider: 'weixin',
success: (infoRes) => {
this.nickName = infoRes.userInfo.nickName
this.avatarUrl = infoRes.userInfo.avatarUrl
this.openId = infoRes.userInfo.openId
}
});
}
});
}
}
});
},
// 微信
getUserInfo(res) {
uni.showModal({
content: '将获取你的个人信息',
success: (res) => {
//如果用户点击了确定按钮
if (res.confirm) {
wx.getUserProfile({
desc: '获取你的昵称、头像、地区及性别',
success: res => {
console.log(res)
this.userName = res.userInfo.nickName
this.userUrl = res.userInfo.avatarUrl
uni.login({
success: (loginRes) => {
let appid = 'xxxx'
let secret ='xxxx'
let url ='https://api.weixin.qq.com/sns/jscode2session?appid=' +appid + '&secret=' +secret + '&js_code=' + loginRes.code +'&grant_type=authorization_code';
uni.request({
url:url,
success: (res) => {
this.openId = res.data.openid
}
})
}
})
},
fail: res => {
//拒绝授权
wx.showToast({
title: '您拒绝了请求',
icon: 'error',
duration: 2000
});
return;
}
});
} else if (res.cancel) {
//如果用户点击了取消按钮
console.log(3);
wx.showToast({
title: '您拒绝了请求',
icon: 'error',
duration: 2000
});
return;
}
}
});
},
}
}
</script>
<style>
</style>