微信小程序实现用户微信登录操作案例

  • 微信小程序可以通过微信官方提供的登录能力,获取用户信息,建立用户体系。

  • 本人做的登录测试需要用到以下3个东西:

1.小程序

小程序是用户使用的客户端,由于小程序运行在微信之上,所以小程序可以通过微信官方提供的API获取微信用户的身份信息。

2.开发者服务器

小程序的后端服务器,用于为小程序用户提供服务。

3.微信接口服务

作用是为开发者服务器提供的接口。

下面是我的演示:
在这里插入图片描述
打开微信开发者工具,在miniprogram下新建index.js文件,里面的信息如下:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
//处理post请求
app.post('/', (req, res) => {
  console.log(req.body);
  res.json(req.body);
});
//监听3000端口
app.listen(3000, () => {
  console.log(填写自己服务器的地址);
});

里面有关的监听端口和请求本小白还有些不太明白,有待提供,仅供参考。
如果不知道服务器地址console.log(req.body);可以在服务器命令提示符里面输出的。本人用的是node.js
在这里插入图片描述
首先cd自己的微信小程序工程,然后要执行nodemon index.js命令。出现如上图所示说明你的服务器启动成功。

然后在主文件里面写wxml,wxss,js,json:
在这里插入图片描述
index.wxml:

<view class="container">
<view class="userinfo">
<button wx:if="{{!hasUserInfo}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo" class="btn">获取头像昵称</button>
<!--使用wx:else来判断应该渲染什么到页面上去-->
<block wx:else>
<!--头像-->
<image class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
<!--昵称,userInfo.nickName和userInfo.city都是微信官方提供的API,并不是我们自己写的接口-->
<text class="userinfo-nickname">{{userInfo.nickName}}</text>
<!--所在城市-->
<text class="userinfo-nickname">{{userInfo.city}}</text>
<!--性别-->
<open-data type="userGender" lang="zh_CN"></open-data>

<button class="unlogin" bindtap="exit">退出登录</button>
</block>
</view>
</view>

index.wxss设置样式:


.btn{
  border: 2rpx solid#32cd32;
}
.container{
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  padding: 200rpx 0;
  box-sizing: border-box;
}
.userinfo{
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.userinfo-avatar{
  width: 128rpx;
  height: 128rpx;
  border-radius: 8%;
}
.userinfo-nickname{
  color: #aaa;
}
.unlogin{
  background-color: #32cd32;
}

index.js:

Page({

  /**
   * 页面的初始数据
   */
   //首先设置参数userInfo为空,hasUserInfo为false,表示没有登录
  data: {
    userInfo:{},
    hasUserInfo:false
  },

  onLoad: function () {
    
  },
  //getUserInfo函数绑定了按钮
  getUserInfo: function (e) {
    console.log(e.detail.userInfo)
    if(e.detail.userInfo){
      this.setData({
        userInfo:e.detail.userInfo,
        hasUserInfo:true
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
   //绑定了退出登录按钮,通过清空userInfo并且设置hasUserInfo为false来退出登录
  exit: function () {
    console.log('exit ok')
    this.setData({
      userInfo: {},
      hasUserInfo: false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

然后查看效果:
登录前:
在这里插入图片描述
登录后:
在这里插入图片描述
查看控制台输出信息:
在这里插入图片描述
appData登录前:
在这里插入图片描述
登录后:
在这里插入图片描述
至此就完成了登录流程,有问题相互讨论,本小白水平有限啊啊。

  • 7
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值