本系列文章主要记录基于云开发 的商城小程序的开发过程以及开发过程中遇到的问题
写在之前:正式接触微云开发是在19年10月份,刚开始只是把它当做一个新的知识去了解,偶尔也会写个代码片段测试单个功能。随着了解的深入慢慢的喜欢上了这种新的开发模式,然后就按照商城的需求一点一点的找云开发的替代方案。我记得当时遇到的问题包括:定时发送模板消息 、支付回调地址 、商城后台管理等等这一些列问题,总终这些问题都一一得到解决。故而在新项目开始之际记录开发 过程中的点点滴滴,一来重新梳理思路 逻辑,二来供广大开发者参考以便指点雅正。
- 开发准备
1,新建小程序填入APPID 使用云开发
2,开通 云开发
创建环境,等待初始化
3,回调IDE 删除无用文件
移除多余文件后空白项目
4,添加小程序常用工具了,搭建简单的开发框架
config.js
const userUtils = require("../utils/userUtils.js")
const user = require("../mode/user.js")
module.exports = {
no_data: "cloud://xxxxx/no_data.png",
faild: "cloud://xxxxx/net_error.png",
net_error: "cloud://xxxxx/net_error.png",
no_order: "cloud://xxxxx/res/no_order.png",
pageSize: 10,
minClickTime: 500,
order_out_time: 60 * 1000 * 30,
ok: "cloud.callFunction:ok",
env: "xxxxx",//环境id
tmpid_order_cancel: "xxxxx", //订单取消模板消息id
tmpid_order_send: "xxxxx", //订单发货
}
user .js
module.exports = {
USER_ID: "user_id",
HEIGHT: "height",
MAIN_HEIGHT: "main_height",
USER_NAME: "user_name",
AVATAR: "avatar",
SX: "sx",
}
file.js
let path=""
function setPath(locationPath)
{
path=locationPath
}
function uploadFile(fileList, index, afterUpSu, posi) {
const imgItem = fileList[index]
if (imgItem.is_up) {
toNext(fileList, index, afterUpSu, posi)
} else {
if (!imgItem.location_path) {
toNext(fileList, index, afterUpSu, posi)
} else {
wx.compressImage({
src: imgItem.location_path, // 图片路径
quality: 70, // 压缩质量
success: function(res) {
imgItem.temppath = res.tempFilePath
upImgToCloud(fileList, index, afterUpSu, posi)
},
fail: function(res) {
upImgToCloud(fileList, index, afterUpSu, posi)
},
complete: function(res) {},
})
}
}
}
function upImgToCloud(fileList, index, afterUpSu,posi) {
const imgItem = fileList[index]
const cloudPath = path+ getMadomChart(10) + new Date().getTime() + ".jpg"
wx.cloud.uploadFile({
cloudPath: cloudPath,
filePath: imgItem.temppath || imgItem.location_path, // 文件路径
success: res => {
// get resource ID
console.log("上传图片 success==" + JSON.stringify(res))
const fileID = res.fileID
imgItem.file_id = fileID
imgItem.is_up = true
wx.cloud.getTempFileURL({
fileList: [{
fileID: fileID
}]
}).then(urlRes => {
console.log("getTempFileURL success==" + JSON.stringify(urlRes))
imgItem.url = urlRes.fileList[0].tempFileURL
toNext(fileList, index, afterUpSu, posi)
}).catch(error => {
console.log("getTempFileURL catch==" + JSON.stringify(error))
toNext(fileList, index, afterUpSu, posi)
})
},
fail: err => {
// handle error
console.log("上传图片 err==" + JSON.stringify(err))
toNext(fileList, index, afterUpSu, posi)
}
})
}
function getMadomChart(length) {
const chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
let result = '';
for (let i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
/**
* 下一张
*/
function toNext(fileList, index, afterUpSu, posi) {
let nextIndex = 0
if (index < fileList.length - 1) {
nextIndex = index + 1
uploadFile(fileList, nextIndex, afterUpSu, posi)
} else {
afterUpSu(fileList, posi)
}
}
module.exports = {
setPath: setPath,
uploadFile: uploadFile,
}
userUtils.js
let utils = require("util.js")
const user = require("../mode/user.js")
const log = require("../utils/log.js")
const config = require("../config/config.js")
let userModel = {}
/**
* 获取窗口高度以及 sx(像素与rpx的比)
*/
function getHeight() {
let oldHight
let mainHeight
const that = this
console.log("mainHeight getHeight==")
try {
oldHight = getDataByKey(user.HEIGHT)
mainHeight = getDataByKey(user.MAIN_HEIGHT)
} catch (e) {
oldHight = 0
mainHeight = 0
}
if (oldHight > mainHeight && mainHeight > 0) {
return
}
wx.getSystemInfo({
success: function(res) {
let height = res.windowHeight
console.log("mainHeight==" + mainHeight)
console.log("height==" + height)
if (mainHeight > 0) {
} else {
setDataBykey(user.MAIN_HEIGHT, height)
}
let width = res.windowWidth
let sx = width / 750
setDataBykey("sx", sx)
if (height > oldHight) {
setDataBykey(user.HEIGHT, height)
}
},
})
}
function setDataBykey(key, value) {
userModel[key] = value
try {
wx.setStorageSync(key, value)
} catch (e) {
wx.setStorage({
key: key,
data: value
})
}
}
function getDataByKey(key) {
if (userModel[key]) {
return userModel[key]
} else {
try {
return wx.getStorageSync(key)
} catch (e) {
wx.getStorage({
key: key,
success(res) {
return res.data
}
})
}
return ""
}
}
function saveUserMsg(res, page, doWhat) {
const detail = res.detail
if (detail && detail.errMsg != "getUserInfo:fail auth deny") {
setDataBykey(user.AVATAR, detail.userInfo.avatarUrl || "")
setDataBykey(user.USER_NAME, detail.userInfo.nickName || "")
page.setData({
avatar: detail.userInfo.avatarUrl,
nickName: detail.userInfo.nickName
})
wx.cloud.callFunction({
name: "updata_userinfo",
data: detail.userInfo
})
if (doWhat) {
doWhat()
}
} else {
wx.showToast({
title: '用户信息获取失败',
icon: "none"
})
}
}
function login() {
console.log("login")
const data = {}
data.req_type = "login"
data.data = {}
wx.cloud.callFunction({
name: "user_manage",
data: data
}).then(res => {
if (res.errMsg == config.ok) {
if (res.result.code == 200) {
const openid = res.result.data.openid
const unionid = res.result.data.unionid
userUtils.setDataBykey(user.USER_ID, openid)
userUtils.setDataBykey(user.UNIONID, unionid)
}
}
})
}
module.exports = {
getHeight: getHeight,
saveUserMsg: saveUserMsg,
getDataByKey: getDataByKey,
setDataBykey: setDataBykey,
login: login,
}
utils.js
const config=require("../config/config.js")
let imgPath = ""
function formatNumber(n) {
n = n.toString()
return n[1] ? n : '0' + n
}
function formatTime(date, format) {
var formateArr = ['YY', 'MM', 'DD', 'hh', 'mm', 'ss'];
var returnArr = [];
returnArr.push(date.getFullYear());
returnArr.push(formatNumber(date.getMonth() + 1));
returnArr.push(formatNumber(date.getDate()));
returnArr.push(formatNumber(date.getHours()));
returnArr.push(formatNumber(date.getMinutes()));
returnArr.push(formatNumber(date.getSeconds()));
for (var i in returnArr) {
format = format.replace(formateArr[i], returnArr[i]);
}
return format;
}
/**
* 判断权限
*
* scope 权限名字
* contentMsg 权限被拒绝时提示文字
* doWhat 授权成功后续操作
*
*/
function getAuthorize(scope, contentMsg, doWhat) {
var that = this
if (wx.getSetting) {
wx.getSetting({
success(res) {
if (!res.authSetting[scope]) {
wx.authorize({
scope: scope,
success() {
// 用户已经同意小程序使用录音功能,后续调用 wx.startRecord 接口不会弹窗询问
doWhat()
},
fail: function(error) {
wx.showModal({
title: '提示',
content: contentMsg + "权限未开启",
confirmText: "去打开",
cancelText: "暂不",
success: function(res) {
if (res.confirm) {
wx.navigateTo({
url: '../openAuthorize/index?auth=' + contentMsg,
})
}
}
})
}
})
} else {
doWhat()
}
},
})
}
}
/**
* 设置图片下载地址
*/
function setImgPath(downLoadPath) {
imgPath = downLoadPath
}
function saveImg() {
this.getAuthorize('scope.writePhotosAlbum', "相册", downLoadPhoto)
}
/**
* 下载图片
*/
function downLoadPhoto() {
if (wx.showLoading) {
wx.showLoading({
title: '正在保存',
mask: true
})
}
var that = this
wx.saveImageToPhotosAlbum({
filePath: imgPath,
success: function (res) {
if (wx.hideLoading) {
wx.hideLoading()
}
wx.showModal({
title: '提示',
content: '图片已保存',
confirmText: "我知道了"
})
},
fail: function (error) {
if (wx.hideLoading) {
wx.hideLoading()
}
}
})
}
/**
* 比较两个版本
*/
function compareVersion(v1, v2) {
v1 = v1.split('.')
v2 = v2.split('.')
var len = Math.max(v1.length, v2.length)
while (v1.length < len) {
v1.push('0')
}
while (v2.length < len) {
v2.push('0')
}
for (var i = 0; i < len; i++) {
var num1 = parseInt(v1[i])
var num2 = parseInt(v2[i])
if (num1 > num2) {
return 1
} else if (num1 < num2) {
return -1
}
}
return 0
}
/**
* 检查更新
*/
function checkUpData() {
if (wx.getUpdateManager) {
const updateManager = wx.getUpdateManager()
updateManager.onCheckForUpdate(function(res) {
// 请求完新版本信息的回调
console.log(res.hasUpdate)
})
updateManager.onUpdateReady(function() {
wx.showModal({
title: '更新提示',
content: '新版本已经准备好,是否重启应用?',
success: function(res) {
if (res.confirm) {
// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
updateManager.applyUpdate()
}
}
})
})
updateManager.onUpdateFailed(function() {
// 新的版本下载失败
})
}
}
function isPhone(phone) {
if (!(/^1[3456789]\d{9}$/.test(phone))) {
return false;
}
return true
}
function initCloud()
{
if (!wx.cloud) {
console.error('请使用 2.2.3 或以上的基础库以使用云能力')
} else {
wx.cloud.init({
// env 参数说明:
// env 参数决定接下来小程序发起的云开发调用(wx.cloud.xxx)会默认请求到哪个云环境的资源
// 此处请填入环境 ID, 环境 ID 可打开云控制台查看
// 如不填则使用默认环境(第一个创建的环境)
env: config.env,
traceUser: true,
success:function(res)
{
}
})
}
}
module.exports = {
formatTime: formatTime,
initCloud: initCloud,
getAuthorize: getAuthorize,
compareVersion: compareVersion,
checkUpData: checkUpData,
setImgPath: setImgPath,
saveImg: saveImg,
isPhone: isPhone,
}
5,建立集合
6,小程序初始化
//app.js
const utils = require("utils/util.js")
const userUtils = require("utils/userUtils.js")
const user = require("mode/user.js")
const config = require("config/config.js")
App({
onLaunch: function () {
userUtils.getHeight()
utils.initCloud()
utils.checkUpData()
this.globalData = {}
userUtils.login()
},
})
到此小程序基本框架搭建完毕,下篇聊一下云开发之后台管理
有帮助,第4步 添加小程序常用工具了,搭建简单的开发框架,这个在哪添加,找不到
源码学习一下
先马后看