溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

微信小程序+云開發實現歡迎登錄注冊的示例分析

發布時間:2021-07-07 11:39:03 來源:億速云 閱讀:180 作者:小新 欄目:web開發

這篇文章將為大家詳細講解有關微信小程序+云開發實現歡迎登錄注冊的示例分析,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

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

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

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

  • 云函數:在云端運行的代碼,微信私有協議天然鑒權,開發者只需編寫自身業務邏輯代碼

  • 數據庫:一個既可在小程序前端操作,也能在云函數中讀寫的 JSON 數據庫

  • 存儲:在小程序前端直接上傳/下載云端文件,在云開發控制臺可視化管理

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

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

微信小程序+云開發實現歡迎登錄注冊的示例分析

之后新建就行了。

新建的項目已經包含了一個快速開發的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)
  }
 }
}

數據庫數據形式:

微信小程序+云開發實現歡迎登錄注冊的示例分析

關于“微信小程序+云開發實現歡迎登錄注冊的示例分析”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女