当前位置: 首页 > news >正文

微信小程序云开发用户身份登录_微信小程序+云开发实现欢迎登录注册

前段时间和同学一起做了一个小程序,用来参加学校的比赛,完成后把项目内容分割一下,贴到博客上面,算是学习记录和总结吧。

因为是学生党,而且并没有很大的需要,所以选择了微信小程序为开发者提供的“云开发”选项。

开发者可以使用云开发开发微信小程序、小游戏,无需搭建服务器,即可使用云端能力。

按照微信的说法:

云开发为开发者提供完整的云端支持,弱化后端和运维概念,无需搭建服务器,使用平台提供的 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'

})

具体可以查看官方文档:

接下来声明一些全局数据

//全局数据

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

Hello

开启小程序之旅

因为微信小程序声称wx.getUserInfo(Object object)在以后将不再支持,这里使用另一种方式来显示用户的信息。

标签可以用来显示用户的一些信息

显示用户的头像

显示用户的昵称

详情可以查看: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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章:

  • pandas提取时间里面的年月日_pandas进行时间数据的转换和计算时间差并提取年月日...
  • iserdese2接口详解_Xilinx Notes
  • postman启动没反应_高压软起动通电没反应维修控制器烧毁
  • python策略模式包含以下哪些角色_python---策略模式
  • mybatis 插件_建议收藏,mybatis插件原理详解
  • h5引入json_Html5页面内使用JSON动画的实现
  • bootstrap列表加序号_用vue.js做一个列表,类似于百度的搜索排名,用v-for来循环...
  • 中将2个map的值合并_如果是我,不纠结卫生间留1个还是2个,主卫次卫大合并,宽敞舒适...
  • 宋佳机器人_丝路电影节|宋佳专访:特殊时期用电影抚慰人心 是很温暖的事
  • ipv4的地址位数_网络基础之IP地址和子网掩码
  • 城市运行一网统管_民主监督 | 城市运行“一网统管”,“啄木鸟”在行动
  • 能够编辑excel的python 软件有哪些_平面设计包括哪些软件,常用的设计软件都有哪些...
  • rs232串口防雷电路_【ZYNQ Ultrascale+ MPSOC FPGA教程】第十一章 RS232实验
  • 无偿献血机器人_广州首家有机器人的献血屋开业啦!快来体验吧!
  • go 标准错误输出_Linux入门-标准输出和错误输出
  • 2017 年终总结 —— 在路上
  • Angular4 模板式表单用法以及验证
  • AWS实战 - 利用IAM对S3做访问控制
  • GraphQL学习过程应该是这样的
  • IDEA常用插件整理
  • JSDuck 与 AngularJS 融合技巧
  • Js基础知识(四) - js运行原理与机制
  • Laravel深入学习6 - 应用体系结构:解耦事件处理器
  • macOS 中 shell 创建文件夹及文件并 VS Code 打开
  • Spring技术内幕笔记(2):Spring MVC 与 Web
  • V4L2视频输入框架概述
  • 订阅Forge Viewer所有的事件
  • 普通函数和构造函数的区别
  • 前嗅ForeSpider教程:创建模板
  • 设计模式走一遍---观察者模式
  • 首页查询功能的一次实现过程
  • 数组的操作
  • 小程序button引导用户授权
  • 学习笔记:对象,原型和继承(1)
  • No resource identifier found for attribute,RxJava之zip操作符
  • Mac 上flink的安装与启动
  • #define
  • #stm32驱动外设模块总结w5500模块
  • (12)Linux 常见的三种进程状态
  • (C语言)求出1,2,5三个数不同个数组合为100的组合个数
  • (java版)排序算法----【冒泡,选择,插入,希尔,快速排序,归并排序,基数排序】超详细~~
  • (笔记)Kotlin——Android封装ViewBinding之二 优化
  • (黑马出品_高级篇_01)SpringCloud+RabbitMQ+Docker+Redis+搜索+分布式
  • (原創) 博客園正式支援VHDL語法著色功能 (SOC) (VHDL)
  • (终章)[图像识别]13.OpenCV案例 自定义训练集分类器物体检测
  • (转)jdk与jre的区别
  • .NET Remoting Basic(10)-创建不同宿主的客户端与服务器端
  • .Net 高效开发之不可错过的实用工具
  • .NET/C# 在 64 位进程中读取 32 位进程重定向后的注册表
  • .net6 webapi log4net完整配置使用流程
  • .NetCore实践篇:分布式监控Zipkin持久化之殇
  • .net反编译工具
  • .NET微信公众号开发-2.0创建自定义菜单
  • .Net中wcf服务生成及调用
  • .net中我喜欢的两种验证码