【云+社区年度征文】2020年小程序开发-云开发技术总结

2020年注定是不平凡的一年,一场冠状疫情的爆发,让人们突然认识到生命的可贵,人们对生命重新有了新的认识。谱写了太多的悲伤,太多难过,太多的眼泪和辛酸。珍惜当下,敬畏生命,敬畏自然。

下面围绕这些规范写内容

  • 文章的创新型
  • 文章的实用性

 - 代码的可借鉴性

  • 代码的规范度

小程序云开发入门到实践:

上面讲到uniCloud,那么什么是uniCloud呢?

uniCloud是Dcloud联合阿里云,腾讯云,为uniapp的开发者提供的基于serverless模式和js编程的云开发平台

uniCloud的好处在于用熟悉的js,轻松搞定前台整体业务。不管用什么服务器运维,弹性扩容,防DDos攻击,全都不需要操心

其实客户端调用云函数,如下:

uniCloud.callFunction()//调用

云开发api-云开发API

wx.cloud
wx.cloud.database()
wx.cloud.database().command
wx.cloud.database().command.aggregate

提前发起权限设置

wx.authorize({
  scope: 'scope.record',
  success () {
    // 用户已经同意小程序使用录音功能,后续调用 wx.startRecord 接口不会弹窗询问
    wx.startRecord()
  }
})

1.云开发api分类

2.云开发api初始化方法

3.云开发api使用注意事项

初始化 服务端
npm install --save wx-server-sdk

const cloud = require('wx-server-sdk')
cloud.init({
 env: 'test-x' // 环境id
})

云开发的初始化选项支持传入一个Object,指定各个服务使用的默认环境

云开发api使用注意事项:

1.云开发api同时支持callback风格和promise风格

2.云开发api初始化时如果没有设置id,默认使用先创建的那个

3.在服务端可以借助云开发sdk内置的getWXContext来获取到用户的身份信息

云开发数组查询

const db = wx.cloud.database();
const _ = db.command;

db.collection("todos")
.where({
 progress: _.in([0,100])
})
.get({
 success: console.log,
 fail: console.error
});

Index.js

const db = wx.cloud.database();
const _ = db.command
Page({
 query: function() {
  console.log('query')
  db.collection('data')
  .where({
   count: _.nin([1,3,4])
  })
  .get().then(console.log)
 }
})

了解网络状态

wx.getNetworkType({
  success(res) {
    console.log(res)
  }
});
所在的手机当前的网络状态是WiFi、3G、4G、5G

获取设备信息

wx.getSystemInfo({
  success (res) {
    console.log("设备的所有信息",res)
    console.log(res.model)
    console.log(res.pixelRatio)
    console.log(res.windowWidth)
    console.log(res.windowHeight)
    console.log(res.language)
    console.log(res.version)
    console.log(res.platform)
  }
})
获取用户手机的微信版本、操作系统及版本、屏幕分辨率、设备的型号与品牌、基础库版本等信息。

页面链接跳转

wx.navigateTo({
  url: '/pxxx'
})

wx.navigateBack({
  delta: 1
})
返回页面的上一层

显示消息提示框

wx.showToast({
  title: '弹出成功',
  icon: 'success',
  duration: 1000
})

设置当前页面的标题

wx.setNavigationBarTitle({
  title: 'xxxx'
})

打开文件选择器上传文件

wx.chooseImage({
  count: 1,
  sizeType: ['original', 'compressed'],
  sourceType: ['album', 'camera'],
  success (res) {
    const tempFilePaths = res.tempFilePaths
  }
})

小程序上获取用户信息的四种模式

wx.login -> 获取code仅可用于获取openid, unionid 和session_key

button -> 用户首次需使用按钮模式,提示用户主动点击按钮,方可获取用户信息

wx.getUserInfo -> 用户首次授权后,调用该接口可以获取用户信息,openid和unionid,需调用session_key解密后方可获得

open-data -> 仅可用于展示用户数据,js逻辑层无法获取

小程序云开发:

云函数:wx.cloud.callFunction;数据库:wx.cloud.database;文件存储:wx.cloud.uploadFile

第一步创建云开发,其目录结构:

云函数: cloudfunctions

前端代码:miniprogram

图片等资源: images

页面目录: pages

全局配置: app.js - app.json

全局样式文件: app.wxss

项目配置文件:project.config.json

项目里使用创建的环境,在app.js文件配置

//app.js
App({
  onLaunch: function () {
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
        // env 参数说明:
        //   env 参数决定接下来小程序发起的云开发调用(wx.cloud.xxx)会默认请求到哪个云环境的资源
        //   此处请填入环境 ID, 环境 ID 可打开云控制台查看
        //   如不填则使用默认环境(第一个创建的环境)
        env: 'my-env-id',
        traceUser: true,
      })
    }

    this.globalData = {}
  }
})

b

其实调用云函数文件:

sum() {
 wx.cloud.callFunction({
  name: 'sum',
  data: {
   a: 2,
   b: 5
  }
 }).then(res=>{
  console.log(res);
 }).catch(err=>{
  console.log(err);
 });
}

获取当前用户openid:

<view>云函数</view>
<button bindtap="getOpenId">获取当前用户openid</button>
getOpenId() {
 wx.cloud.callFunction({
  name: 'login'
 }).then(res=>{
  console.log(res);
 }).catch(err=>{
  console.log(err);
 })
}

批量删除的代码是怎么写的呢,如下:

const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database();

// 云函数入口函数

exports.main = async(event, context) => {
 try{
  return await db.collection('user').where({
   name: 'jeskson'
  }).remove()
 }catch(e){
  console.log(e);
 }
}

getDelete() {
 wx.cloud.callFunction({
  name: 'bataDelete',
 }).then(res=>{
  console.log(res);
 }).catch(err=>{
  console.error(err);
 })
}

云开发模式:

小程序端-》原生接口-》云开发:云数据库,云函数,云存储,云调用,HTTP API

创建数据库:

可以在uniCloud中直接创建,也可以通过node.js的后台代码来创建,在uniapp中,为了安全起见,是不允许客户端直接调用数据库,而是通过客户端调用云函数,元函数调用数据库的形式

数据库和集合的引用:

  const db=uniCloud.database();
  const ban=db.collection('集合名');//集合名就是数据表的名称
  db.createCollection(collectionName)//创建集合

数据库的增删改查

  const db=uniCloud.database();
  const ban=db.collection('集合名');
  
  ban.get().then(res=>{
  console.log(res)
  }).catch(msg=>{
  console.log(msg)
  });
  //获取集合中的数据,promise写法
  
  ban.get({sucess:(res)=>{
  console.log(res)
  },
  fail:(msg)=>{
  console.log(msg)
  }
  });
  //第二种写法
  //这里只简单的介绍,详细的可查看 官方文档
  ban.where({
    name:"查询的name",
    index:查询的下标等  
  }).get().then(res=>{
  console.log(res)
  }).catch(e=>{
  console.log(msg)
  });
  
  //添加
  ban.add({
    data:{
        id:要添加的id,
        name:要添加的name
    }
  }).then(res=>{
  console.log(res)
  }).catch(e=>{
  console.log(msg)
  });
  
//更新
  ban.doc('id').update({
    data:{
      name:'要替换的属性名'
    }
  }).then(res=>{
  console.log(res)
  }).catch(e=>{
  console.log(msg)
  });
  
  ban.doc('id').set({
    data:{
      name:'要替换的属性名',
      id:要替换的id名
    }
  }).then(res=>{console.log(res)}).catch(e=>{console.log(msg)});
  
//删除数据,只能每次删除一条
  ban.doc('id').remove({ }).then(res=>{
  console.log(res)
  }).catch(e=>{
  console.log(msg)
  });

云存储:uploadFile(Object object)

uni.chooseImage({
 count: 1,
 success: (res) => {
  console.log(res);
  var path=res.tempFilePaths[0];//获取当前图片的路径
  uniCloud.uploadFile({
   filePath: path, // 当前图片路径
   cloudPath: 'img', // 文件名
   success: (res1) => {
    console.log(res1);
   }
  })
 }
})

// promise写法
const result = await uniClound.uploadFile({
 filePath: filePath
});

deleteFile(Object object) 删除云端文件

  // promise写法
uniCloud
  .deleteFile({
    fileList: ['云储存的ID'];//字符串类型的数组
  })
  .then(res => {});

// callback写法
uniCloud.deleteFile(
  {
    fileList: ['云储存的ID'],
    success(){},
    fail(){},
    complete(){}
  }
);

客户端调用云函数:

  //index.js云函数文件
  'use strict'; 
  uniCloud.init();
  
  const db=uniCloud.database();
  exports.main = async (event, context) => {
    return new Promise((resolve,reject)=>{
    db.collection('banner').get().then(res=>{
        resolve(res);
    }).catch(msg=>{
        reject(msg);
    })
  })
};

  onLoad() {
          uniCloud.callFunction({//客户端调用云函数,云函数调用数据库
              name:'index',
              success:(res)=> {
                  console.log(res);
                  var ban=res.result.data[0].banner;
                  console.log(ban);
              }
          })
  },

uni-app使用微信小程序云函数的步骤

发订阅消息,需要调用接口wx.requestSubscribeMessage

callPay(){
  wx.cloud.callFunction({
    name: 'pay', 
    success: res => {
      console.log(res)
      const payment = res.result.payment
      wx.requestPayment({
        ...payment,
        success (res) {
          console.log('支付成功', res) 
          this.subscribeMessage()
        },
      })
    },
  })
},
subscribeMessage() {
  wx.requestSubscribeMessage({
    tmplIds: [
      "xxxxxx-xx-x",//订阅消息模板ID
    ],
    success(res) {
      console.log("订阅消息API调用成功:",res)
    },
    fail(res) {
      console.log("订阅消息API调用失败:",res)
    }
  })
},

自动回复文本消息和链接

<button open-type="contact" >进入客服</button>
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
})
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext() 
  try {
    const result = await cloud.openapi.customerServiceMessage.send({
      touser: wxContext.OPENID,
      msgtype: 'text',
      text: {
        content: 'xxxxxxx'
      }
    })
    
    const result2 = await cloud.openapi.customerServiceMessage.send({
      touser: wxContext.OPENID,
      msgtype: 'text',
      text: {
        content: 'xxxxx'
      }
    }) 

    return event    
  } catch (err) {
    console.log(err)
    return err
  }
}

自动回复链接

const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
})
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext() 
  try {
    const result = await cloud.openapi.customerServiceMessage.send({
      touser: wxContext.OPENID,
      msgtype: 'link',
      link: {
        title: 'xxxxxxx',
        description: 'xxxxxx',
        url: 'https://xxxxxxx根据关键词来回复用户t.com/',
        thumbUrl: 'https://xxxxxxxm/love.png'
      }
    }) 
  return event    

  } catch (err) {
    console.log(err)
    return err
  }
}

根据关键词来回复用户

const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
})
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext() 
  const keyword = event.Content
  try {
    if(keyword.search(/xxxx/i)!=-1){
      const result = await cloud.openapi.customerServiceMessage.send({
        touser: wxContext.OPENID,
        msgtype: 'link',
        link: {
          title: 'xxxxx',
          description: 'xxxxx',
          url: 'https://xxx.com/',
          thumbUrl: 'https://xxxx.png'
        }
      })  
    } 
    return event
  } catch (err) {
    console.log(err)
    return err
  }
}

获取微信步数

getWeRunData(){
  wx.getWeRunData({
    success: (result) => {
      console.log(result)
    },
  })
}

订阅消息

subscribeMessage() {
  wx.requestSubscribeMessage({
    tmplIds: [
      "xxxxxxxxxxxx",//模板
      "xxxxxxxxxxxx",
      "xxxxxxxxxx
    ],
    success(res) {
      console.log("订阅消息API调用成功:",res)
    },
    fail(res) {
      console.log("订阅消息API调用失败:",res)
    }
  })
},

云开发登陆

检查是否登录

<script>
	global.isLogin = function() {
		try {
			var openid = uni.getStorageSync('openid');
		} catch (e) {

		}
		if (openid === '') {
			return false
		} else {
			return {
				openid
			}
		}
	};
	export default {
		onLaunch: function() {
			console.log('App Launch')
			wx.cloud.init({
				traceUser: true
			});
		}
	}
</script>

登陆页面

<template>
	<view>
		<!-- #ifdef MP-WEIXIN -->
		<button class='bottom' type='primary' open-type="getUserInfo"
		 withCredentials="true" lang="zh_CN" @getuserinfo="wxGetUserInfo">
			授权登录
		</button>
		<!-- #endif -->
	</view>
</template>
<script>
	const db = wx.cloud.database();
	export default {
		data() {
			return {}
		},
		methods: {
			wxGetUserInfo(msg) {
				console.log(msg)
				
				var that = this;
				if (!msg.detail.iv) {
					uni.showToast({
						title: '您取消了授权,登录失败',
						icon: 'none'
					});
					return false
				}
				
				uni.showLoading({
				    title: '加载中'
				});
				
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
					
						console.log(loginRes)
						that.getOpenid(msg);
					},
					fail: function(r) {
						console.log(r)
					}
				})
				
			},
			getOpenid(msg) {
				var that = this;
				
				wx.cloud.callFunction({
					name: 'getOpenid',
					complete: res => {
						console.log('openid: ', res);
						try {
							uni.setStorageSync('openid', res.result.openId);
						} catch (e) {
						}
						that.saveToDb(msg, res.result.openId)
					},
				});
				
			},
			
			saveToDb(msg, openid) {
				console.log(openid)
				
				db.collection('user').where({
					_openid: openid
				}).get().then(res => {
				
					console.log(res)
					
					if (res.errMsg === 'collection.get:ok') {
					
						if (res.data.length === 0) {
							db.collection('user').add({
								data: {
									...msg.detail.userInfo,
									_openid: res.result.openId
								}
							}).then(res => {
								console.log(res);
							});
						}
						
						uni.hideLoading();
						
						uni.showToast({
							title: '授权成功',
							icon: 'success'
						});
						
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {}
				})

			}
		},
		onLoad() {

		}
	}
</script>

活动链接:

https://cloud.tencent.com/developer/article/1752258

总结

以上就是今天要讲的内容,本文仅仅简单介绍了小程序开发-云开发技术总结,感谢阅读,如果你觉得这篇文章对你有帮助的话,也欢迎把它分享给更多的朋友。感谢转发分享,点赞,收藏哦!

本站文章资源均来源自网络,除非特别声明,否则均不代表站方观点,并仅供查阅,不作为任何参考依据!
如有侵权请及时跟我们联系,本站将及时删除!
如遇版权问题,请查看 本站版权声明
THE END
分享
二维码
海报
【云+社区年度征文】2020年小程序开发-云开发技术总结
2020年注定是不平凡的一年,一场冠状疫情的爆发,让人们突然认识到生命的可贵,人们对生命重新有了新的认识。谱写了太多的悲伤,太多难过,太多的眼泪和辛酸。珍惜当下...
<<上一篇
下一篇>>