WeChat applet cloud development

WeChat applet cloud development

1. Register WeChat Mini Program

WeChat applet has a cloud development function, which can save a lot of background development tasks. However, the use of small program cloud development requires registration of small program appid, test and tourists do not have cloud development function. If you haven't registered the applet, you can install the official documentation to register an applet appid first.

After the registration is complete, you can fill in the relevant information of the mini program, and the system will generate the necessary information such as the appid of the mini program for us, as shown in the figure below. Then, we open the WeChat applet development tool and create a new WeChat applet project. If you haven t already, you can click to download the WeChat development tool . Then, fill in the appid when creating the WeChat applet, as shown in the figure below.

Then, we will find a button for cloud development on the development panel of the WeChat development tool. Cloud development allows developers to use all cloud capabilities such as cloud databases, cloud storage, cloud functions, and cloud hosting without having to build a server. Then, we click on it to build the background data environment, as shown in the figure below.

2. Build a cloud development template

We can follow the steps below to quickly start using cloud development.

  1. New cloud development template
  2. Open cloud development
  3. Experience applet
  4. View console

1. Create a new cloud development template

1. create a new project, fill in AppID (AppID must be filled in to use cloud development capabilities), check to create "Cloud Development QuickStart Project", and click Create to get a sample applet that shows the basic capabilities of cloud development. Note the following differences between this applet and the ordinary QuickStart applet.

  • No guest mode, no test number can be used
  • The field cloudbaseRoot is added to project.config.json to specify the directory for storing cloud functions & cloud hosting
  • The directory specified by cloudbaseRoot has a special icon
  • Cloud development capabilities are supported from the basic library 2.2.3 (coverage rate of 97.3%, check compatibility issues)

2. Open cloud development and create environment

After creating the first cloud development applet, you need to enable cloud development before using cloud development capabilities. On the left side of the developer tool toolbar, click the "Cloud Development" button to open the cloud console, follow the prompts to enable cloud development, and create a cloud environment. Two environments can be created under the default quota. Each environment is isolated from each other. Each environment contains independent database instance, storage space, cloud function configuration and other resources. Each environment has a unique environment ID, and the initially created environment automatically becomes the default environment.

3. Experience the mini program

After opening the creation environment, you can start to operate the applet on the simulator to experience part of the basic capability demonstration provided by cloud development.

4. View the console

The cloud development console is a place to manage cloud development resources. The console provides the following capabilities.

  • Operational analysis : View cloud development monitoring, quota usage, and user access
  • Database : Manage database, you can view, add, update, search, delete data, manage index, manage database access authority, etc.
  • Storage management : view and manage storage space
  • Cloud function : view cloud function list, configuration, log

5. Destroy the environment

Of course, developers can log in to the cloud development console in WeChat Developer Tools, click Switch Environment in Settings, and click Manage My Environment in the drop-down box to manage and delete the environment.

3. Cloud development capabilities

WeChat applet cloud development provides functions such as database, cloud storage, cloud function, cloud call, and HTTP API.

3.1 Database

Cloud Development provides a JSON database. As the name suggests, each record in the database is an object in JSON format. A database can have multiple collections. The collection can be regarded as a JSON array. Each object in the array is a record, and the format of the record is a JSON object.

The correspondence between relational databases and JSON databases is shown in the following table.

Relational DatabaseDocument type
DatabaseDatabase
TableCollection
ColumnField

The following is an example collection data, suppose we have a books collection storing book records, as shown below.

[
  {
    "_id": "Wzh76lk5_O_dt0vO",
    "title": "The Catcher in the Rye",
    "author": "J. D. Salinger",
    "characters": [
      "Holden Caulfield",
      "Stradlater",
      "Mr. Antolini"
    ],
    "publishInfo": {
      "year": 1951,
      "country": "United States"
    }
  },
  {
    "_id": "Wzia0lk5_O_dt0vR",
    "_openid": "ohl4L0Rnhq7vmmbT_DaNQa4ePaz0",
    "title": "The Lady of the Camellias",
    "author": "Alexandre Dumas fils",
    "characters": [
      "Marguerite Gautier",
      "Armand Duval",
      "Prudence",
      "Count de Varville"
    ],
    "publishInfo": {
      "year": 1848,
      "country": "France"
    }
  }
]
 

3.2 Storage

Cloud development provides a storage space, provides upload files to the cloud, cloud download capabilities with permission management, developers can use the cloud storage function through API on the applet terminal and cloud function terminal.

You can call wx.cloud.uploadFile and wx.cloud.downloadFile on the applet terminal to complete the upload and download of cloud files. The following simple lines of code can enable users to select a picture in the applet and upload it to the cloud for management.

// 
wx.chooseImage({
  success: chooseResult => {
    // 
    wx.cloud.uploadFile({
      // 
      cloudPath: 'my-photo.png',
      // 
      filePath: chooseResult.tempFilePaths[0],
      // 
      success: res => {
        console.log(' ', res)
      },
    })
  },
})
 

3.3 Cloud function

A cloud function is a piece of code that runs in the cloud. There is no need to manage the server. It can be written in the development tool and uploaded and deployed with one click to run the back-end code.

An API dedicated to cloud function calls is provided in the applet. Developers can use the getWXContext method provided by wx-server-sdk to obtain the context of each call in the cloud function, without maintaining a complicated authentication mechanism, to obtain the natural trusted user login state (openid).

For example, we define a cloud function as follows, named add, the function is to add the two incoming parameters a and b.

const cloud = require('wx-server-sdk')
exports.main = async (event, context) => {
  let { userInfo, a, b} = event
  let { OPENID, APPID } = cloud.getWXContext() //  openId   appId  
  let sum = a + b

  return {
    OPENID,
    APPID,
    sum
  }
}
 

Then, we can use the cloud function by using wx.cloud on the WeChat applet, as shown below.

wx.cloud.callFunction({
  // 
  name: 'add',
  // 
  data: {
    a: 12,
    b: 19,
  },
  // 
  complete: console.log
})
//  promise  
wx.cloud.callFunction({
  name: 'add',
  data: {
    a: 12,
    b: 19
  }
}).then(console.log)
 

If you need to operate the database, manage cloud files, call other cloud functions and other operations in the cloud function, you can use the official npm package wx-server-sdk to operate.

3.4 HTTP API

Cloud development resources can also be accessed through the HTTP interface, that is, outside the applet. For the interface, see the HTTP API documentation .

4. project examples

4.1 Lottery Assistant

Let's take the [ Raffle Assistant Mini Program ] as an example, how to use the WeChat Mini Program cloud development function to provide interface data.

1. open the [Cloud Development] panel, create a collection, and set the collection permissions to [Everyone can read, only the creator can read and write]. Then, import the lottery.json file in the data of the project to the lottery collection, as shown in the figure below.

Then, deploy the cloud function.

Then re-run the project, the final effect is shown in the figure below. Attachment: WeChat applet cloud development actual combat with the source code of the lucky draw assistant

4.2 Rent WeChat Mini Program

The following is another small house rental program developed using cloud technology, open source address: github.com/lx164/house

Directory Structure

|--|-- cloudfunctions  
|--|--|--|-- AdminManage
|--|--|--|-- Entrust
|--|--|--|-- HouseInfo
|--|--|--|-- InitInfo
|--|--|--|-- Manager
|--|--|--|-- PublishEntrust
|--|-- miniprogram  
|--|--|--Adminpackage  
|--|--|--|-- 
|--|--|--CalculatorPackage  
|--|--|--|-- 
|--|--|--Companypackage  
|--|--|--|-- 
|--|--|--dist  
|--|--|--pages  NaviBar 
|--|--|--|-- 
|--|-- 
|--README.md
 

?Configuration process

Use the WeChat developer tool to import the project (please select the APP folder when importing). When importing the project, you need to fill in the APPID to enable the cloud development function. Then, create the following database collections, one for a collection name, as shown below.

AdminStator
Collections
CompanyInfo
ContactList
Entrust
NewHouse
Recommend
RentingHouse
SecondHouse
TempCllection
UserList
 

When setting the permissions of the collection, the AdminStator permissions of the collection are set to [All users cannot read and write], and the rest of the collection permissions are modified to [All users can read and only the creator can read and write].

Next, set the first initial administrator information, create a new record in AdminStator, add the following fields to the record, and fill in the content in () according to your actual situation.

 "level":0,
 "avatarUrl":"( )",
 "updatetime":"(2021/01/12 06:01:18)",
 "_openid":"( openid)",
 "name":"( )",
 "phone":"( )"
 

There are two ways to obtain WeChat openid, which are the use of cloud development methods and non-cloud development methods to obtain WeChat openid .

Then, create a new record in the collection CompanyInfo, and add the following field content to the record, where the content in () is filled in according to your actual situation.

    "_id":"cb37e58c-f634-49d3-93b9-5aebec00a23a ",
    "introduce":"(/)",
    "updatetime":"2020/06/27 14:22:31",
    "editer":" ",
    "phone":" ",
    "notice":"  "
 

Upload all cloud functions in the cloudfunctions folder, select upload and deploy [Cloud Installation Dependency] when uploading, and the following figure will be shown after successful deployment.

Finally, modify the configuration code of app.js as follows.

 wx.cloud.init({
     env: '( ID)',
     traceUser: true,
  })
 

The ID of the cloud environment can be obtained by clicking the [Settings] button on the top right side of the cloud development panel, as shown in the figure below. Compile the project to see the running effect.

running result