小程序获取执行login方法获取到code,把code发送给后台接口服务器,后台接口服务器访问微信服务器获取openid,做完成登录业务操作,把登录完成的信息返回给我们的小程序完成登录。
我这里使用uniapp开发的小程序,代码如下:
<template>
<view class="container">
<view class="intro">本项目已包含uni ui组件,无需import和注册,可直接使用。在代码区键入字母u,即可通过代码助手列出所有可用组件。光标置于组件名称处按F1,即可查看组件文档。</view>
<text class="intro">详见:</text>
<uni-link :href="href" :text="href"></uni-link>
<button v-on:click="login">微信登录</button>
</view>
</template>
<script>
export default {
data() {
return {
href: 'https://uniapp.dcloud.io/component/README?id=uniui'
}
},
methods: {
login(){
console.log("点击登录了")
//检查登录状态是否过期
uni.checkSession({
success() {
console.log("checkSession成功");
},
fail() {
console.log("checkSession失败");
}
})
//重新登录
uni.login({
provider: 'weixin',
success: function (loginRes) {
console.log(loginRes);
},
fail() {
console.log("login 失败")
}
});
//获取用户信息
uni.getUserProfile({
desc: '微信登录',
success(res) {
console.log(res)
console.log(res.rawData)
},
fail() {
console.log("获取用户信息失败")
}
})
}
}
}
</script>
<style>
.container {
padding: 20px;
font-size: 14px;
line-height: 24px;
}
</style>