Rapid development of WeChat applets: from registered accounts to applet shelves

Write before

Since the WeChat applet function was released, I have been following the trend of the applet, but limited to busy school, there is always not much time to learn.As a sophomore, I gradually learned Vuejs and was attracted by its concise design. Then I looked at the development documentation of the applet and found it so similar?Maybe this is the trend of the front end, each frame tends to be similar and excellent design.

Graduates gradually learned the Go language, in order to practice the Go language, but also to aggregate the things they have accumulated over the years, they developed the WeChat applet: WeZhongnan (you can go to WeChat search, although now graduation is no longer planned to maintain), which aggregates common information query functions in the school of Central South University, such as:Items such as results timetable query, school bus calendar query are already open source in my Github: Front end,back-end.

One day this summer vacation, there was a sudden upsurge of heart and soul. Looking at the statistics of Central and South West, We found that it was still useful. Without promotion, We increased the number of visits by hundreds (suddenly moved), and found that applets support cloud function development. That is to say, backend services are not necessary for small programs.Tool, which is developed directly using the nodejs environment it provides.

After these days of groping, I want to share the whole process of registering myself from the applet to the shelf for the reference of students who are ready to learn the applet.

Dead work

1. Register WeChat applet account

click Portal Register the WeChat applet account immediately.When you click in, you will see the following interface. When you select the registration type, you will choose the WeChat applet.

Then complete the registration by filling in the relevant information.

After completing the registration, switch to the development - > development settings to view the developer ID.

2. Download developer tools and create new projects

Get into Portal To download and install the latest version of the developer tools.With developer tools, developers can complete the development and debugging of applet API s and pages, code viewing and editing, applet preview and publishing, and other functions.

For the interface of how IDE is used, you can refer to it in detail Official Documents

Next, open the developer tool, modify the project name, fill in the AppID mentioned above, and choose Applet Cloud Development for back-end services.

As we can see from the new project, IDE has helped us create a new applet template that includes cloud function development, as well as some function testing interfaces.
At this time, we did not turn on cloud development, we need to click on "Cloud Development" in the upper left corner of IDE, and then choose to turn on cloud services.

Develop applets

1. Introduction to project file structure


The project is divided into two subfolders, one is cloudfunctions, which contains the cloud function of the applet, the other is miniprogram, which is the front-end folder of the applet. There is no fixed folder format, so you can customize your own folder by modifying app.json.Specific documents can be referenced Official Documents

2. Modify applet information

Open app.json under the miniprogram folder, which defines the basic information for the applet.
Below is app.json for my applet. I deleted all the irrelevant pages from the example, adding the index home interface and detail details page.

Modifications to the sample project: Pages except index can be deleted directly from the pages directory, and files from the style and images folders can be deleted.

{
  "pages": [
    "pages/index/index",
    "pages/detail/index"
  ],
  "window": {
    "backgroundColor": "#F6F6F6",
    "backgroundTextStyle": "light",
    "navigationBarBackgroundColor": "#F6F6F6",
    "navigationBarTitleText": "SCI IF Journal Impact Factor Query 2019",
    "navigationBarTextStyle": "black"
  },
  "sitemapLocation": "sitemap.json"
}

3. New Cloud Function!

The biggest advantage of Cloud Function is that it really comes out of the box without buying a server, registering a domain name, and configuring an SSL certificate.
See the new nodejs cloud function in the cloudfunctions directory to create a new cloud function that contains two files: package.json, index.js

package.json is a standard npm package, and index.js is the main file of the cloud function.Below is the initial content of the new cloud function, which first introduces wx-server-sdk, which provides applets with the ability to manipulate the cloud database, then initializes the cloud function, export cloud function content.

// Cloud Function Entry File
const cloud = require('wx-server-sdk')

cloud.init()

// Cloud function entry function
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  }
}

It should be noted that cloud functions contain almost complete nodejs environments, so some common nodejs libraries such as requests, chreeio, and so on can be added and used through package.json.

4. Add functionality to cloud functions

This paper's applet is a small program for SCI journal impact factor query. The logic is simple. The back-end only needs to provide a journal query interface to provide the impact factor of the corresponding journal for the front-end.

  1. New Cloud Function http_get
  2. Introduce related class libraries.Open the directory of the cloud function http_get in the terminal and install the dependent libraries.Since this function utilizes third-party query interfaces, it requires the use of the HTTP request library got and the HTTP parsing library cheerio.The specific operation is as follows
cd /path/to/your/cloudfunctions
npm install //Install wx-cloud-server
npm install got --save
npm install cheerio --save
  1. Add functionality to the function.The main purpose here is to load the related class libraries, parse the html, and return the results as json to the client.
// Load related class libraries
const cloud = require('wx-server-sdk')
const got = require('got')
const querystring = require('querystring')
const cheerio = require('cheerio')
cloud.init()
// Cloud function entry function
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  //sci impact factor query interface
  const sci_url = 'some url'
  //Get Journal Name
  let sciname = event.sciname
  let querys = querystring.stringify({ q: sciname, sci: 1 });
  //Request data
  let resp = await got(sci_url + String(querys))
  //Parse html
  const $ = cheerio.load(resp.body)
  const lists = $(".tb1 tr")
  //Determine whether a query journal exists
  if (lists.children().length == 0) {
    return -1
  }else{
    let jounalLists = lists.map((i, item) => {
      return {
        //serial numbers of periodicals
        no: $(item).children().eq(0).text(),
        //Omit some content and parse html parameters
        //Impact Factor Resolution
        if: $(item).children().eq(7).text(),
      }
    }).get()
    return jounalLists //Return parsing results
  }
}
  1. Debug cloud functions.Debugging cloud functions can be done through the cloud: IDE interface - > cloud development - > cloud functions, select the appropriate cloud function to debug.After clicking Debug, you can return to the result of the debugging, and you can modify the function based on the result.



Cloud functions can also be debugged locally by clicking Local Debugging on the corresponding function folder under cloudfunctions, which makes local debugging easier than cloud debugging and eliminates the need to upload cloud functions to the server before each debugging.However, it is important to note that npm install is executed in the Cloud Functions directory to complete the class library installation before you can debug.

5. Add Applet Page

Each page of the applet contains four files:.js,.json,.Wxml, wxss.js is responsible for program logic, json configuration page parameters, wxml definition page structure, wxss definition page style.This is equivalent to splitting html pages into.html,.css,.js.
Since the applet is a web view environment running in WeChat, its syntax is different from html and you can refer to the official documentation: Portal
To facilitate page building, this paper introduces a third-party class library: Vant , which provides an elegant interface element that is ready to use out of the box and detailed usage can be found in the official vant documentation.
The final applet main interface is as follows:

The corresponding code is as follows:

Page structure

<!--index.wxml-->
  <view class='head_img'>
    <van-cell-group custom-class="cell_group">
    <van-field
      custom-class="cell_filed"
      value="{{ sciname }}"
      placeholder="Journal Name/Initials/Abbreviation/ISSN"
      border="{{ false }}"
      focus="true"
      bind:change="onValueChange"
    />
  </van-cell-group>
  </view>
<view class="container">
  <view class="btn-area">
  <van-button type="info" size="large" round="true" bind:click="onClickQuery" loading="{{isQuery}}">query</van-button>
  </view>
  <view wx:if="{{sci.length>0}}">
    <van-cell-group title="Altogether found{{sci.length}}This Journal">
      <view wx:for="{{sci}}"wx:for-index="idx" wx:for-item="item" wx:key="idx">
          <van-cell title="{{item.sciname}}" 
          value="{{item.if}}"  border="false" 
          title-width="80%"
          is-link link-type="navigateTo"
          url="/pages/detail/index?id={{idx}}"/>
      </view>
    </van-cell-group>
  </view>
</view>

Page logic:

//index.js
const app = getApp()
Page({
  data: {
    isQuery:false,
    sciname:'',
    sci:[],
  },
  onValueChange:function(value){
    this.setData({
      sciname:value.detail
    })
  },
  onClickQuery:function(){
    var _this = this
    this.setData({
      isQuery:true
    })
    console.log('begin'+_this.data.sciname)
    wx.cloud.callFunction({
      name: 'http_get',
      data: {
        sciname:_this.data.sciname
      },
      success:res=>{
        //Not found
        if(res.result==-1){
           wx.showModal({
             title: 'Tips',
             content: 'No relevant information was queried, try a different keyword?',
           }) 
        }else{
          wx.setStorageSync('scis', res.result)
          _this.setData({
            sci:res.result
          })
        }
        _this.setData({
          isQuery: false
        })
      },
      fail:err=>{
        _this.setData({
          isQuery: false
        })
        console.log(err)
      },
    })
  },
  onLoad: function() {
  },
//Omit some code
})

In the same way, I added a detail page to show the details of each journal.

deploy

1. Upload project file

First, for each cloud function, right-click and click "Upload and Deploy: Cloud Installation Dependency" (of course, all files can be uploaded and deployed).Then click on the upload in the upper right corner of the IDE and fill in the version information to complete the upload.

Log in to the management interface of the WeChat public platform, switch to version management, and we can see the submitted version.

2. Fill in applet information

In the first page of the management interface, we write the process of applet publishing. We need to first add the basic information of the applet, such as name, icon, description and so on, when the information of the applet.WeChat officially completes its audits within 7 days. It took two days for my newly registered applet to be audited.

3. Submit for review

Once the audit is complete, it can be submitted for review.Switch to the version management interface, submit an audit of the version you just uploaded, and note the version information.It also takes a few days to review.

epilogue

Due to one development experience, this registration and coding work only took one afternoon, but the process audit is really time-consuming and needs patience.

This program is also published on github: Portal

Keywords: node.js JSON npm SDK github

Added by joopeon on Tue, 23 Jul 2019 02:03:53 +0300