One hour wechat application

Time:2020-11-20

“Applet” this epoch-making product has been released for nearly a week, and Internet technologists are eager to try. But the small program is still in the internal test, the first batch only issued 200 internal test qualification (tearful). I thought that without the appid, I would be out of touch with the applet this month. Fortunately, wechat has released the official version of the developer tool these two days,You don’t need to be invited to have a taste

So there was my first experience with “app”, and my feeling was only one word – Shuang!

Which applet demo to choose?

On GitHub, a well-known gay dating website, there are many demos for “applets”, but most of them are simple API demonstrations. Some even write page data directly into JSON files (there is clearly an API for network requests). What I want to experience is a project that can seamlessly connect the server side and the applet side. Finally, I chose the “small photo album” project officially launched by Tencent cloud.

“Small album” mainly realizes the following functions:

  • Lists a list of pictures in the object store cos.

  • Click the upload picture icon in the upper left corner to call the camera to take photos or select pictures from the mobile phone album, and upload the selected pictures to the object storage cos.

  • Press left and right to switch to picture preview mode.

  • Long press any picture to save it locally or delete it from cos.

One hour wechat application

Effect demonstration diagram (limited by development tools, some functions have not been realized)

Cloud object service is a cloud storage service with high availability, high stability and strong security for enterprises and individual developers launched by Tencent cloud. Any amount and form of unstructured data can be put into cos, and data management and processing can be realized in COS.

The reason why we choose the demo of Tencent cloud is that it isTencent launched its own project, the quality of the project is guaranteedSecond, it is because it isThere are few projects that focus on both small program development and cloud deployment

Programmers with a little experience know that the architecture should be separated from static, and the static files should not be placed on their own server, but on the object storage server cos dedicated for storage, and accelerated with CDN. The back end of the “mini album” is Node.js , nginx as the reverse proxy.

Step 1: build a development environment

First of all, we need to build a local wechat “applet” development environment. Download developer tools. Official wechat has launched the official version of IDE,There’s no need to download the cracked version。 Open the download page of the official website and select according to your own operating system. I use the Mac version.

After installation, it will require wechat to scan the code and log in. After that, you can see the page where you created the project.

One hour wechat application

Select to add an item. If there is no appid, you can select none (if you scribble, an error will be reported, and you may not be able to enter the project at that time). If the project directory you selected is empty, please tick “create quick start project in current directory” as shown in the figure.

One hour wechat application

After clicking “add project”, we will enter the debugging page of the development tool.

Step 2: download the source code of “small photo album”

Next, we’ll download the source code of the album. You can choose to download it directly from the link provided by Tencent cloud official website, or pull it from GitHub warehouse of Tencent cloud team. I recommend pulling from GitHub repository to get the latest code in time.

git clone https://github.com/CFETeam/weapp-demo-album.git

In the end, we’ll get a directory like this.

One hour wechat application

Briefly explain the following directory structure:

  • Applet (or app): the code of “small photo album” application package can be opened as a project directly in wechat developer tool.

  • Server: the built node server code is used as the communication between the server and the app, and provides CGI interface examples for fetching image resources, uploading images, and deleting images.

  • Assets: a screenshot of the demo of “small photo album”.

After the source code download is completed, we open the wechat web developer tool, create a new project “small photo album”, and select the directory applet (or app).

One hour wechat application

Source code analysis of “small photo album”

Before deployment, let’s take a brief analysis of the specific code of “small photo album”. After all, it’s not our goal to just look at the effect, it’s our purposeTake “small photo album” as an example to learn how to develop small programs and interact with the server

One hour wechat application

The “mini photo album” contains an app describing the overall program and multiple pages describing the respective pages. The main program app is mainly composed of three filesapp.js(applet logic)app.json(applet public settings) andapp.wxssThe first two are required files.config.jsThe file contains some settings for the deployment domain name. Don’t worry about it now.

In the pages directory, there are two page pages, index and album. The page structure is relatively simple, in which index is the default page when the applet starts. Under each page, there must be at least. JS (page logic) and. Wxml (page structure), and. Wxss (page style sheet) and. JSON (page configuration) files are optional. You may have noticed,These files have the same file name as the parent directory。 This is an official regulation of wechat, which aims to reduce configuration items and facilitate developers.

Let’s take the index as an example.index.wxmlIs the presentation layer file of this page, the code is very simple, can be divided into two parts.

<view>
    <view class="page-top">
        < text class = "username" > congratulations < / text >
        < text class = "text info" > successfully built a wechat applet < / text >
        <view class="page-btn-wrap">
            < button class = "page BTN" bindtap = "gotoalbum" > Enter album < / button >
        </view>
    </view>
    <view class="page-bottom">
        < text class = "QR TXT" > share QR code and invite friends to write small programs together! </text>
        <image class="qr-img"></image>
        <image class="page-logo"></image>
    </view>
</view>

The results are as follows:

One hour wechat application

We see that there is a “enter album” button on the page. Normal understanding, after clicking the button, we can enter the album. How is the operation implemented behind the applet?

stayindex.wxmlWe found that the corresponding button tag has abindtapProperty, which is bound to agotoAlbumMethods. And this method can be used inindex.jsFile. In fact, only this method is defined in the file, and the specific action to be performed is to jump to the album page.

Page({
    //Go to album page
    gotoAlbum() {
        wx.navigateTo({ url: '../album/album' });
    },
});

album.jsThe main logic of the program is written in the page, including selecting or shooting pictures, previewing pictures, downloading pictures and deleting pictures; album.wxml View, scroll view and swipper are all used, and message prompt box toast is provided. See the source code of the project for the implementation of specific methods and views. All of these functions are written in the page class.

Lib directory provides some auxiliary functions that small programs will use, including asynchronous access and object storage cos API.

Generally speaking, as the official wechat propaganda, the efficiency of developing small programs under developer tools has been greatly improved, and there are many improved components and APIs of wechat. So, the experience on the speed of development is very cool.

In addition, because the “small album” needs many cloud capabilities, such as uploading and downloading images, we also need to deploy and set up the server side. See the next steps for details.

Step 3: deploy server code in the cloud

Although the server-side development is not the focus of this article, in order to fully experience the whole development and deployment process of “small album”, we still need to understand the server-side deployment. Here we use Tencent cloud.

If you want to feel better, you can choose the small app cloud image provided by Tencent cloud. The server running code and configuration of “small album” have been packaged into Tencent cloud CVM image, which can be used directly. It can be said that it is one click deployment of cloud.

If you haven’t used Tencent cloud before, you can choose to try it for free (I’ve collected my personal version server for 8 days) or get a gift bag to buy the services you need at a discount price.

One hour wechat application

You can also choose to upload the server folder in the source code of “small album” to your own server.

Step 4: prepare the domain name and configure the certificate

If you already have Tencent cloud’s server and domain name, and you have configured HTTPS, you can skip steps 4-6.

In the wechat applet, all network requests are strictly restricted, and domain names and protocols that do not meet the conditions cannot be requested. In short, your domain name must follow the HTTPS protocol. So you also need to apply for a certificate for your domain name. If you don’t have a domain name, please register one first. Since we have not received the internal test, we do not need to log in to the wechat public platform to configure the communication domain name.

Step 5: nginx configure HTTPS

Nginx has been deployed in the cloud sample image of wechat applet, but it still needs to be installed in the/etc/nginx/conf.dModify the domain name, certificate and private key in the configuration.

One hour wechat application

Please replace the red box with your own domain name and certificate, andproxy_passSet to Node.js Listening port, mine is 9993.

After the configuration is complete, reload the configuration file and restart nginx.

sudo service nginx reload
sudo service nginx restart

Step 6: domain name resolution

We also need to add a domain name record to resolve the domain name to our cloud server, so that we can use the domain name for the HTTPS service. For domain names registered in Tencent cloud, you can directly use the cloud resolution console to add host records, and directly select the CVM purchased above.

One hour wechat application

After the resolution takes effect, our domain name supports HTTPS access.

Step 7: open and configure cos

Because we want to realize the separation of motion and stillness, we choose to store the image resources of “small album” on cos. To use the cos service, you need to log in to the cos administration console and complete the following operations in it.

  1. Click Create bucket. You will be asked to select the project and fill in the corresponding name. Here, we just need to fill in the bucket name we like.

One hour wechat application

  1. Then, in the bucket list, click the bucket you just created. Then click “get API key” on the new page.

One hour wechat application

The pop-up page contains three information we need: the unique app ID, a pair of secretid and secretkey (used to call cos API). Take care of this information and we’ll use it later.

  1. Finally, create a folder in the new bucket container, named photos. We will also talk about this later.

Step 8: start the “mini album” server

In the official image, the node service code of the small photo album sample has been deployed in the directory/data/release/qcloud-applet-albumNext. Enter the directory. If it is your own server, please enter the corresponding folder.

cd /data/release/qcloud-applet-album

There is a directory namedconfig.jsAs shown below, modify the corresponding cos configuration according to the comments:

module.exports = {
    //Port number monitored by node
    port: '9993',
    ROUTE_BASE_PATH: '/applet',

    Cosappid: 'fill in the app ID assigned when opening cos',
    Cossecretid: 'fill in the key secretid',
    Cossecretkey: 'fill in the secret key',
    Cosfilebucket: 'fill in the created public read private write bucket name',
};

Besides,cd ./routes/album/handlers, modifylist.js, willconst listPathModify the value of to the image storage path under your bucket. If it is the root directory, change to'/'。 The current server code sets the value to'/photos'If you did not create the directory in step 7, you will not be able to debug successfully.

The small album example uses PM2 to manage the node process, and executes the following command to start the node service:

pm2 start process.json

Step 9: domain name configuration

Next, open the “small photo album” project in the wechat web developer tool, and add the source file config.js Modify the communication domain name host in to the domain name you applied for.

One hour wechat application

Change the content in the blue box to your own domain name

Click demo to start debugging.

One hour wechat application

One hour wechat application

Finally, it is suggested that up to now, the upload and download API provided by wechat applet can’t work normally in the debugging tool, so you need to scan and preview the wechat code on your mobile phone. However, due to no internal test qualification, we can not experience it for the time being.

Well, that’s not cool enough. There’s no in-house invitation.

to update:Tencent cloud also wrote another three demo small program tutorial, you can also have a look.