微信小程序+雲開發實現歡迎登錄註冊

這篇文章主要介紹了微信小程序+雲開發實現歡迎登錄註冊,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨着小編來一起學習學習吧

前段時間和同學一起做了一個小程序,用來參加學校的比賽,完成後把項目內容分割一下,貼到博客上面,算是學習記錄和總結吧。

因爲是學生黨,而且並沒有很大的需要,所以選擇了微信小程序爲開發者提供的“雲開發”選項。

開發者可以使用雲開發開發微信小程序、小遊戲,無需搭建服務器,即可使用雲端能力。
按照微信的說法:

雲開發爲開發者提供完整的雲端支持,弱化後端和運維概念,無需搭建服務器,使用平臺提供的 API 進行核心業務開發,即可實現快速上線和迭代,同時這一能力,同開發者已經使用的雲服務相互兼容,並不互斥。
目前提供三大基礎能力支持:

  • 雲函數:在雲端運行的代碼,微信私有協議天然鑑權,開發者只需編寫自身業務邏輯代碼
  • 數據庫:一個既可在小程序前端操作,也能在雲函數中讀寫的 JSON 數據庫
  • 存儲:在小程序前端直接上傳/下載雲端文件,在雲開發控制檯可視化管理

首先,開通雲開發功能是第一步(默認你已經註冊好了微信小程序賬號而且申請好了一個AppId),經測試,雲開發並不能使用測試號,只能使用真實的AppId。

注:AppID 首次開通雲環境後,需等待大約 10 分鐘方可正常使用雲 API,在此期間官方後臺服務正在做準備服務,如嘗試在小程序中調用雲 API 則會報 cloud init error:{ errMsg: “invalid scope” } 的錯誤

新建一個項目

之後新建就行了。

新建的項目已經包含了一個快速開發的Demo,而且含有云函數示例,初始化函數等等,最好可以先看看,熟悉一下。

自帶Demo

首先看一下app.js這個文件:

//app.js
App({
 onLaunch: function () {
if (!wx.cloud) {
 console.error('請使用 2.2.3 或以上的基礎庫以使用雲能力')
} else {
 wx.cloud.init({
traceUser: true,
 })
}
})

wx.cloud.init()爲雲端環境初始化函數,如果有多個雲開發環境則需要指定env參數,如下:

wx.cloud.init({
 env: 'test-x1dzi'
})

具體可以查看官方文檔:

developers.weixin.qq.com

接下來聲明一些全局數據

//全局數據
globalData: {
  //用戶ID
  userId: '',
  //用戶信息
  userInfo: null,
  //授權狀態
  auth: {
   'scope.userInfo': false
  },
  //登錄狀態
  logged: false
}

最後的樣子是這樣:

//app.js
App({
	//全局數據
	globalData: {
  	//用戶ID
	  userId: '',
	  //用戶信息
	  userInfo: null,
	  //授權狀態
	  auth: {
	   'scope.userInfo': false
	  },
	  //登錄狀態
	  logged: false
	},

	onLaunch: function() {
		if (!wx.cloud) {
			console.error('請使用 2.2.3 或以上的基礎庫以使用雲能力')
		} else {
			wx.cloud.init({
				traceUser: true,
				env: 'winbin-2hand'
			})
		}
	}
})

注意將env參數換成你自己的雲開發環境。

把Pages目錄下的除index外的文件夾刪除。

並且在app.json中的Pages字段中下僅保留index項:

app.json

{
	"pages": [
	"pages/index/index"
	],
	"window": {
		"backgroundColor": "#F6F6F6",
		"backgroundTextStyle": "light",
		"navigationBarBackgroundColor": "#F6F6F6",
		"navigationBarTitleText": "雲開發 QuickStart",
		"navigationBarTextStyle": "black",
		"navigationStyle": "custom"
	},
	"sitemapLocation": "sitemap.json"
}

頁面文件內容如下:

index.wxml

<view class='container'>
 <open-data class="avs" type="userAvatarUrl"></open-data>
 <view class='username'>
  <text>Hello </text>
  <open-data type="userNickName"></open-data>
 </view>
 <button hidden='{{hiddenButton}}' class='moto-container' open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="onGotUserInfo">
  <text class='moto'> 開啓小程序之旅</text>
 </button>
</view> 

因爲微信小程序聲稱wx.getUserInfo(Object object)在以後將不再支持,這裏使用另一種方式來顯示用戶的信息。

標籤<open-data type=""></open-data>可以用來顯示用戶的一些信息

<open-data type="userAvatarUrl"></open-data>顯示用戶的頭像

<open-data type="userNickName"></open-data>顯示用戶的暱稱

詳情可以查看:wx.getUserInfo中的示例代碼部分

頁面樣式如下:

index.wxss

page {
 width: 100%;
 height: 100%;
}

.container {
 background: url('https://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-758991.png');
 background-size: 400vw 100vh;
 width: 100%;
 height: 100%;
 display: flex;
 flex-direction: column;
 align-items: center;
}

.avs {
 opacity: 0.9;
 width: 200rpx;
 height: 200rpx;
 margin-top: 160rpx;
}

.username {
 font-size: 32rpx;
 font-weight: bold;
 margin-top: 200rpx;
}

.moto-container {
 line-height: normal;
 border: 1px solid #450f80;
 width: 200rpx;
 height: 80rpx;
 border-radius: 5px;
 text-align: center;
 margin-top: 200rpx;
 padding: 0px;
 outline: none;
}

.moto {
 font-size: 22rpx;
 font-weight: bold;
 line-height: 80rpx;
 text-align: center;
 color: #450f80;
}

這裏使用了全屏背景

效果如下:

在這裏插入圖片描述

#接下來是js腳本#

首先說一下思路

流程圖如下

在這裏插入圖片描述

接下來是index.js

const app = getApp();
Page({
 /**
  * 頁面的初始數據
  */
 data: {
  hiddenButton: true
 },

 /**
  *從雲端獲取資料
  *如果沒有獲取到則嘗試新建用戶資料
  */
 onGotUserInfo: function(e) {
  var _this = this
  //需要用戶同意授權獲取自身相關信息
  if (e.detail.errMsg == "getUserInfo:ok") {
   //將授權結果寫入app.js全局變量
   app.globalData.auth['scope.userInfo'] = true
   //嘗試獲取雲端用戶信息
   wx.cloud.callFunction({
    name: 'get_setUserInfo',
    data: {
     getSelf: true
    },
    success: res => {
     if (res.errMsg == "cloud.callFunction:ok")
      if (res.result) {
       //如果成功獲取到
       //將獲取到的用戶資料寫入app.js全局變量
       console.log(res)
       app.globalData.userInfo = res.result.data.userData
       app.globalData.userId = res.result.data._id
       wx.switchTab({
        url: '/pages/home/home'
       })
      } else {
       //未成功獲取到用戶信息
       //調用註冊方法
       console.log("未註冊")
       _this.register({
        nickName: e.detail.userInfo.nickName,
        gender: e.detail.userInfo.gender,
        avatarUrl: e.detail.userInfo.avatarUrl,
        region: ['none', 'none', 'none'],
        campus: "none",
        studentNumber: "none",
       })
      }
    },
    fail: err => {
     wx.showToast({
      title: '請檢查網絡您的狀態',
      duration: 800,
      icon: 'none'
     })
     console.error("get_setUserInfo調用失敗", err.errMsg)
    }
   })
  } else
   console.log("未授權")
 },

 /**
  * 註冊用戶信息
  */
 register: function(e) {
  let _this = this
  wx.cloud.callFunction({
   name: 'get_setUserInfo',
   data: {
    setSelf: false,
    userData: e
   },
   success: res => {
    if (res.errMsg == "cloud.callFunction:ok" && res.result) {
     _this.setData({
      hiddenButton: true
     })
     app.globalData.userInfo = e
     app.globalData.userId = res.result._id
     _this.data.registered = true
     app.getLoginState()
     console.log(res)
     wx.navigateTo({
      url: '/pages/mine/info/info'
     })
    } else {
     console.log("註冊失敗", res)
     wx.showToast({
      title: '請檢查網絡您的狀態',
      duration: 800,
      icon: 'none'
     })
    }
   },
   fail: err => {
    wx.showToast({
     title: '請檢查網絡您的狀態',
     duration: 800,
     icon: 'none'
    })
    console.error("get_setUserInfo調用失敗", err.errMsg)
   }
  })
 },

 /**
  * 生命週期函數--監聽頁面加載
  */
 onLoad: function() {
  let _this = this
  //需要用戶同意授權獲取自身相關信息
  wx.getSetting({
   success: function(res) {
    if (res.authSetting['scope.userInfo']) {
     //將授權結果寫入app.js全局變量
     app.globalData.auth['scope.userInfo'] = true
     //從雲端獲取用戶資料
     wx.cloud.callFunction({
      name: 'get_setUserInfo',
      data: {
       getSelf: true
      },
      success: res => {
       if (res.errMsg == "cloud.callFunction:ok" && res.result) {
        //如果成功獲取到
        //將獲取到的用戶資料寫入app.js全局變量
        console.log(res)
        app.globalData.userInfo = res.result.data.userData
        app.globalData.userId = res.result.data._id
        wx.switchTab({
         url: '/pages/home/home'
        })
       } else {
        _this.setData({
         hiddenButton: false
        })
        console.log("未註冊")
       }
      },
      fail: err => {
       _this.setData({
        hiddenButton: false
       })
       wx.showToast({
        title: '請檢查網絡您的狀態',
        duration: 800,
        icon: 'none'
       })
       console.error("get_setUserInfo調用失敗", err.errMsg)
      }
     })
    } else {
     _this.setData({
      hiddenButton: false
     })
     console.log("未授權")
    }
   },
   fail(err) {
    _this.setData({
     hiddenButton: false
    })
    wx.showToast({
     title: '請檢查網絡您的狀態',
     duration: 800,
     icon: 'none'
    })
    console.error("wx.getSetting調用失敗", err.errMsg)
   }
  })
 }
})

下面是雲函數配置

根據傳入的參數:update ,getSelf ,setSelf ,getOthers

分別執行:更新用戶信息,獲取自身信息,設置自身信息,獲取其他用戶信息 四種操作。

此函數需要使用npm添加md5模塊,用來加密用戶openid並將其存放在數據庫中

// clouldfunctions/get_setUserInfo/package.json

{
 "name": "get_setUserInfo",
 "version": "1.0.0",
 "description": "",
 "main": "index.js",
 "scripts": {
  "test": "echo \"Error: no test specified\" && exit 1"
 },
 "author": "",
 "license": "ISC",
 "dependencies": {
  "wx-server-sdk": "latest",
  "md5-node": "latest"
 }
} 
// clouldfunctions/get_setUserInfo/index.js

const cloud = require('wx-server-sdk')
const md5 = require('md5-node')

//cloud.init()
cloud.init({
 traceUser: true,
 env: 'winbin-2hand'
})
const db = cloud.database()
const usersTable = db.collection("users")
const _ = db.command

// 雲函數入口函數
exports.main = async(event, context) => {
 console.log(event)
 const wxContext = cloud.getWXContext()
 //更新當前信息
 if (event.update == true) {
  try {
   return await usersTable.doc(md5(wxContext.OPENID)).update({
    data: {
     userData: _.set(event.userData)
    },
   })
  } catch (e) {
   console.error(e)
  }
 } else if (event.getSelf == true) {
  //獲取當前用戶信息
  try {
   return await usersTable.doc(md5(wxContext.OPENID)).field({
    openid: false
   }).get()
  } catch (e) {
   console.error(e)
  }
 } else if (event.setSelf == true) {
  //添加當前用戶信息
  try {
   return await usersTable.add({
    data: {
     _id: md5(wxContext.OPENID),
     openid: wxContext.OPENID,
     userData: event.userData,
     boughtList: [],
     messageList: [],
     ontransList: []
    }
   })
  } catch (e) {
   console.error(e)
  }
 } else if (event.getOthers == true) {
  //獲取指定用戶信息
  try {
   return await usersTable.doc(event.userId).field({
    userData: true
   }).get()
  } catch (e) {
   console.error(e)
  }
 }
}

數據庫數據形式:

在這裏插入圖片描述

至此就全部完成了。有需要的可以到github上查看:github:john-tito

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章