当前位置:   article > 正文

微信小程序实现用户登录和新增/更新用户表_微信小程序用户表

微信小程序用户表

需求:

1. 用户打开小程序,在user表中记录用户的相关信息,可以导出在别的地方做记录

2. 在页面中也需要能够显示用户姓名头像等信息

3. 由于用户的昵称可以随时改,需要每次登录的时候更新一下信息,否则的话,导出来的用户表和微信里的用户名称对不上

基本逻辑:

1. 打开小程序阶段,onload的时候,通过云函数自动获取openid,并在user表中匹配,如果已经注册过,将hasRegistered设置为true

2. 用户点击按钮登录,调用bindgetuserinfo="getUserInfo"方法,获取用户信息

3. 然后根据1的判断结果,决定是新增用户,还是更新用户信息

4. 之后继续别的业务逻辑

index.js代码如下:

  1. const app = getApp()
  2. const DB = wx.cloud.database()
  3. wx.cloud.init()
  4. Page({
  5. data:{
  6. hasRegistered: false
  7. },
  8. onLoad: function(){
  9. //onLoad过程中,判断用户是否已经注册
  10. let that = this
  11. //获取openid,存入storage
  12. wx.cloud.callFunction({
  13. name:"getOpenId",
  14. success(res){
  15. wx.setStorageSync('openid', res.result.openid)
  16. }
  17. }),
  18. //使用openid判断是否已经注册过
  19. DB.collection('user').where({
  20. _openid: wx.getStorageSync('openid')
  21. }).get({
  22. success(res){
  23. if(res.data.length > 0){
  24. that.setData({
  25. hasRegistered: true //将hasRegistered更新为true
  26. })
  27. }
  28. }
  29. })
  30. },
  31. //bindgetuserinfo调用此函数,获取userInfo,存入storage,新增或者更新时使用
  32. getUserInfo: function(e){
  33. wx.setStorageSync('userInfo', e.detail.userInfo)
  34. //已注册,更新用户信息;没注册,新增用户
  35. let that = this
  36. if(that.data.hasRegistered){
  37. this.updateUser()
  38. }else{
  39. this.addUser()
  40. }
  41. },
  42. //新增用户,并将hasReigstered设置为true
  43. addUser(){
  44. let that = this
  45. DB.collection('user').add({
  46. data:{
  47. name: wx.getStorageSync('userInfo').nickName,
  48. gender: wx.getStorageSync('userInfo').gender,
  49. city: wx.getStorageSync('userInfo').city,
  50. province: wx.getStorageSync('userInfo').province,
  51. country: wx.getStorageSync('userInfo').country,
  52. avatarUrl: wx.getStorageSync('userInfo').avatarUrl
  53. },
  54. success(res){
  55. that.setData({
  56. hasRegistered: true
  57. })
  58. console.log("新增用户成功",res)
  59. }
  60. })
  61. },
  62. //更新用户数据
  63. updateUser(){
  64. DB.collection('user').where({
  65. _openid: wx.getStorageSync('openid')
  66. }).update({
  67. data:{
  68. name: wx.getStorageSync('userInfo').nickName,
  69. gender: wx.getStorageSync('userInfo').gender,
  70. city: wx.getStorageSync('userInfo').city,
  71. province: wx.getStorageSync('userInfo').province,
  72. country: wx.getStorageSync('userInfo').country,
  73. avatarUrl: wx.getStorageSync('userInfo').avatarUrl
  74. },
  75. success(res){
  76. console.log("更新用户信息成功",res)
  77. }
  78. })
  79. }
  80. })

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/131785
推荐阅读
相关标签
  

闽ICP备14008679号