A Java programmer to share the worst.

The fervent of small procedure believe need not I say more, at the beginning of the year when wife goes pudong certain reach interview, even be asked to have small procedure test experience. Small programs have become an indispensable entry point for Internet companies after PC, WAP, Android and IOS. At this time the company is also doing a small program, so incidentally also learn a. Of course, because I am a Javaer, naturally is the perspective of the back-end to talk about, and the front-end of the students are certainly not comparable.

Learning small programs, I think it is more advantageous for back-end students, because back-end students are familiar with the basic front-end knowledge of HTML, CSS and JS, while front-end students may not know so much about the back-end. Next, with my practice experience to a simple chat about small procedures, is a summary is also a share.

What do applets do?

It’s within reach. Feel these two words to describe the characteristics of the small program is really incisively and vividly. With the number of wechat users, small programs save users from having to install an APP. And after use, there is no need to deliberately exit, directly leave, the next time at a point in time to think of, turn out again on the line. This could be disruptive for many industries. From my personal point of view, small program is suitable for some simple business, performance requirements are not high, use frequency is relatively low applications. For example, vertical e-commerce industry is a typical beneficiary, we-media e-commerce and fresh e-commerce. If users download such an APP, the cost is very high, and the use of small programs can quietly avoid the problem of attracting new customers. For example, if I make my blog into an APP, I believe that almost no students to download, and the use of small programs but occasionally some students will point in to see, ha ha.

Entry applets

First of all, the development of small programs, need a special tool [wechat developer tools], this we can go directly to the wechat public platform to download.

So let’s first create a quick launch template and let’s see, if you have a registered account and you have an appID you can fill it in, if you don’t, it doesn’t matter. Click the program in the picture to use the test account.

As shown above, you can see these files once you enter.

That’s all you can say about a simple little program.

  • App.js is basically the file where the global public JS method declarations and calls are located
  • App. json is a global configuration file for applets, so some pages are required to register this, otherwise access is not allowed
  • App.wxss is the applet global CSS file
  • Under Pages, there are four types of files:.json,.wxss,.wxml,.js

In addition to these four types of files, small program pages basically under each folder equivalent to a page, each folder under the same name but different types of files, these four constitute the entire page.

  • .jsonThe suffixJSONThe configuration file
  • .wxmlThe suffixWXMLTemplate files, similar to HTML for Web development
  • .wxssThe suffixWXSSStyle files, similar to CSS for Web development
  • .jsThe suffixJSScript logic file, it is a JS ah, but small program JS can not operate dom, is based on data binding oh

Then we look at the structure of the JS file, the comment is very clear:

Page ({/ * * * * / data Page of the initial data: {}, function / * * * life cycle - listening Page load * / onLoad:function(options) {}, /** * lifecycle functions -- listen to the page's first rendering complete */ onReady:function() {}, /** * lifecycle function -- listen page display */ onShow:function() {}, /** * lifecycle function -- listen page hide */ onHide:function() {}, /** * lifecycle functions -- listen for page unloads */ onUnload:function() {}, /** * page related event handler -- listen to user pull */ onPullDownRefresh:function() {}, /** ** onReachBottom:function() {}, /** * Users click on the upper right corner to share */ onShareAppMessage:function() {}})Copy the code

Understanding these basic small program development is no problem, the rest is left to turn over the documentation. I recommend reading the document like a dictionary. After reading the easy tutorial and framework, you can look up anything else you need. You don’t have to read it word for word like a textbook.

Because the wechat developer tool is still relatively initial, before each page, I first built a folder, and then built four files respectively. Here’s a tip. You can register your new page with app.json, and the tool will automatically create the folder and four files for you. To tell you the truth, it is very strange that I have not seen this method in the official document, I do not know whether IT is my imagination or the official really did not write.

{
  "pages": ["pages/index/index"."pages/logs/logs"]."window": {"backgroundTextStyle":"light"."navigationBarBackgroundColor": "#fff"."navigationBarTitleText": "WeChat"."navigationBarTextStyle":"black"}}Copy the code

When we register in app.json file, [pages/index/index] will load the four files of the index.xx page instead of writing them one by one. Also, folder names and file names can be different. For example, [pages/index/launch] loads all launch files in the index folder. But the advice remains the same, otherwise it looks awkward.

Finally, in more words, the small program domain name whitelist problem, I found that many students do not know, including colleagues around, has been using Intranet penetration to develop.

First, the applet has restrictions on the domain name the application requests.

  1. The requested domain name must be configured in the background. The request cannot be made without the configured domain name.
  2. The domain name protocol must be HTTPS. HTTP requests will fail

Of course, this is for the online version. If it is our local development, small program provides a very human function. You can ignore this limitation and even request the local IP address + port number without having to use the tedious Intranet traversal method.

The specific operation method is to click “Settings” – “Project Settings” – “check” not to verify the legitimate domain name, Web-view (business domain name), TLS version and HTTPS certificate in the wechat developer tool, as shown below

The following is combined with my practice of small procedures to a simple chat, more information we can refer to the document

Open source practices

It happened that some time ago to do a practice YYblog open source project, this time to take this project to do a simple small program client. So, again, I’m going to show you the picture.

Simple HTML, CSS, JS implementation, no application of any front-end framework, or more suitable for reference learning. PPPS: anyway I won’t say because I won’t just don’t whoop ~~~ shed no technical tears ┭┮﹏┭┮.

In general, although wechat mini program has been online for so long, it is not so stable compared with the development language in the traditional sense, and the official is also in constant adjustment.

I believe many of you have encountered such a scenario, when you enter a small program for the first time, will pop up a user information authorization window. At the beginning, I did the same when I wrote, but later when I uploaded the code, I saw that wechat sent an announcement on September 12.

The main reason is that the callback of the sharing listening interface is cancelled, the getUserInfo interface for obtaining user information is changed to be triggered only when the user clicks relevant authorization components, and the openSetting interface is also changed to be triggered only when the user clicks. So do micro channel small program development or do pay attention to the official dynamic, so as not to do a good function can not be used normally embarrassing.

Global configuration

The related file of app.xx is the global configuration file of the small program. Here, the file of app.js is said separately. When some of our parameters are needed globally, we can write relevant parameters in this file, such as the base URL of our request, or user information, user ID, and other parameters that must be carried in the request. At the same time, we can write the code of version verification here. Here I would like to add that wechat supports version verification. When there is a new version code, users can be prompted to update it. The relevant code is as follows:

App({

  onLaunch() {
    this.checkUpdate();
  },

  globalData: {
    userInfo: {},
    apiBase: "https://www.laoyeye.net",
    userId: ""
  },

  checkUpdate() {
    const updateManager = wx.getUpdateManager();
    updateManager.onCheckForUpdate(function(res) {/ / request of the new version information callback. The console log (res) hasUpdate)}) updateManager. OnUpdateReady (function () {
      wx.showModal({
        title: 'Update Prompt',
        content: 'The new version is ready. Do you want to restart the application? ',
        success: function (res) {
          if(res. Confirm) {/ / download the new version of good, call applyUpdate application. The new version and restart updateManager applyUpdate ()}}})}) updateManager. OnUpdateFailed (function() {// New version download failed console.log()'Update failed! ')})}})Copy the code

Start page

When users first enter the applet, they first display a launch page. In the beginning, I didn’t design it like this. Basically, the user would go directly to the home page and pop up user authorization. However, due to the adjustment of 9.12, I had to make some changes. Let the user enter the start page authorization first, after authorization jump to the home page. Authorized users hide the authorization button and wait 1.5 seconds to return to the home page. In this process, in addition to obtaining user authorization, I also requested the background server to create user data in the background, and finally returned the userId to the applet. In the future, users will carry userId for comments, likes, favorites and other operations, which is convenient to distinguish specific users.

This page actually has two important knowledge points, which are highlighted here.

First, we need to obtain each user’s openId for the current application, so as to avoid the repeated operation of re-authorization the next time the user accesses.

Call the wx.login() interface to obtain the login certificate (code) and then obtain the login state information of the user, including the unique id of the user (OpenID) and the session key of this login(session_key), etc. However, it should be noted that the operation of exchanging OpenID with code needs to be done in the server background. If the exchange is done on js, you will see that login can be obtained normally in the development version, but not in the production, because of the security limitation of the small program, the official domain name cannot be set in the whitelist.

The code is as follows:

login(auth) {
    letthat = this; Wx. login({success:function(res) {
        wx.request({
          url: app.globalData.apiBase + '/api/wx/login? code=' + res.code + '&nickname=' + app.globalData.userInfo.nickName +
            '&avatar=' + app.globalData.userInfo.avatarUrl,
          header: {
            'content-type': 'application/json'
          },
          success: function(res) {
            //userId
            if (res.data.code == 200) {
              app.globalData.userId = res.data.data;
              console.log('Get user information =' + res.data.data);
              if (auth == 'auth') {
                that.direct();
              } else {
                let timer = setTimeout(() => {
                  clearTimeout(timer)
                  that.direct()
                }, 1500)
              }
            }
          }
        })
      }
    })
  },Copy the code

Second, the getUserInfo interface, because of the new restrictions, if the user is not authorized, it will pop up the authorization window. However, if you call this interface without the user’s authorization, it will go directly to the fail callback. So you have to get the user’s authorization from the component and then call this method in the callback that the user clicks.

The code is as follows:

 <button class="show-btn" wx:if="{{userInfo.length == 0}}" type="primary" open-type="getUserInfo" bindgetuserinfo="onGetUserInfo"</button>Copy the code

onGetUserInfo() {
    var that = this;
    wx.getSetting({
      success: function(res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function(res) {
              app.globalData.userInfo = res.userInfo;
              that.login('auth');
            },
            fail: function() {
              console.log('System error')}}}else {
          wx.showToast({
            title: "Authorization failed",
            duration: 1000,
            icon: "none"
          })
        }
      },
      fail: function() {
        console.log('Failed to obtain user information'); }})},Copy the code

Finally, there’s a little problem here, and I don’t know if it’s my problem, but I use it when I do page data assignment

this.data.requestUrl = requestUrl;
or

this.setData({
postList: totalData
});

Methods. In the asynchronous case, you must use method two to fetch data on the page. However, there are some cases in which non-asynchronous methods do not fetch data using method 1, but I can clearly see that the data was successfully assigned in the breakpoint. And this time method two was successful again. It’s really unclear, so try to use method two.

Home page, technical page

Put these two pages together, the reason is that although the two pages show different forms, but the technical characteristics still want to be the same. The only difference may be that LATER I will adjust the data interface of the two pages and request different data.

This page is mainly two knowledge points, pull up to load more and pull down to refresh.

The first thing I do is slide up to load more data, and this is actually an onReachBottom method provided by the applets, which is triggered as soon as the user slides up a certain distance, so I’ve done paginating here. Enter the display of five data for the first time, when the event is triggered after the request of the second page of data. Of course, the data requested to the second page cannot cover the previous data oh, otherwise when the user is sliding, the data just lost, which is not in line with the user’s habits.

The distance triggered by the slide up event can also be achieved via onReachBottomDistance, which defaults to 50px

The specific implementation code is as follows:

// Load more data onReachBottom:function (event) {
    var nextUrl = this.data.requestUrl +
      "? page=" + this.data.page + "&limit=5";
    util.ajax(nextUrl, "get", null, this.processData)
    wx.showNavigationBarLoading()
  },Copy the code

  processData: function(indexData) { var totalData = {}; // If you want to bind the newly loaded data, you need to merge it with the old dataif(! this.data.isEmpty) { totalData = this.data.postList.concat(indexData); }else {
      totalData = indexData;
      this.data.isEmpty = false;
    }
    this.setData({
      postList: totalData
    });

    this.data.page += 1;
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
  },Copy the code

The pull-down refresh is disabled by default and requires enablePullDownRefresh in the *. Json configuration (false by default).

If the drop-down refresh function is enabled globally in app.json, it is enabled for the current page in a specific page.

The relevant codes are as follows:

{
  "navigationBarTitleText":"The old man from the shop."."enablePullDownRefresh": true
}Copy the code

  onPullDownRefresh: function (event) {
    var refreshUrl = this.data.requestUrl +
      "? page=0&limit=5";
    this.data.techList = {};
    this.data.isEmpty = true;
    this.data.page = 1;
    util.ajax(refreshUrl, "get", null, this.processData);
    wx.showNavigationBarLoading();
  },Copy the code

In fact, these two methods, when you look at the official document global configuration will see. I also mentioned above that learning applets, official documentation of easy tutorials and frameworks is a must see, the rest is not so important.

Details page

The detail page is actually a rich text parsing.

Since wechat applet does not support HTML, it needs to be converted to WXML supported by wechat.

In general, wechat’s support for rich text is not good, and there is no official rich text parsing component to use. This time I used wxParse, github’s most popular widget rich text component. Although it is relatively complete, there are still a lot of bugs, and the author doesn’t seem to maintain them. But there’s really no good alternative to this. If you have any other components, please let me know.

WxParse use of projects already speak clearly, everyone convenient to: https://github.com/icindy/wxParse to view.

I have made some minor changes to wxParse, mainly to solve the problem that some mobile phones reported errors that could not be resolved. The reason is that wechat applet does not support console.dir(). This applet has been officially explained in the community.

share

When you define the onShareAppMessage function in the js file of the page, then the page has the sharing function and can be forwarded to your wechat friends.

/** * Users click on the upper right corner to share */ onShareAppMessage:function () {
    return {
      title: this.data.postData.title,
      path: '/pages/post-detail/post-detail? id=' + this.data.id + "&title=" + 'The old man of the shop' + "&share=1"}},Copy the code

Above, is my share code, set the share title, as well as jump path and so on. Here I parameterize the path so THAT I can tell where the user is coming from. Why do you want to distinguish the source of the user, because the small program to share the page after entering a very strange problem, there is no back home button. So I made a separate distinction here, showing a floating back to home page icon when the user comes from share.

The relevant codes are as follows:

<! --> <image wx:if="{{share}}" bindtap='onBackHome' class='back-home' src='/images/icon/home-page.png' lazy-load></image>Copy the code

*/ onBackHome:function () {
    wx.reLaunch({
      url: '/pages/launch/launch? share=1"'})}Copy the code

my

Finally talking about my page, in fact, this page is nothing important. It’s just a jump to a static page.

In the future, I will make personal information into a form that can be bound to a PC account.

My collection has been realized, but maybe there is no entry for specific collection on the details page, I will add it later. Specific renderings are as follows.

There is also a reward sponsorship page, at the beginning of the preparation of small program association, the use of access to the like API. But recently the small program official jump between a number of small programs also want to increase restrictions, too lazy to get.

A direct jump to the details page, details page posted a piece of praise code. It should be noted that the small program page does not support direct long press scan oh, you need to click on the picture, in the pop-up picture in the long press recognition of the two-dimensional code in the figure.

PPPS: After writing the article, I realized that I forgot to say one thing on this page. Small procedures can use Ali icon library, the specific use of online we see it. Say no, interested also can look at my source code implementation.

The last

Attached small program wechat preview address:

I said before that this project is based on my previous open source project YYblog to write, so the PC side of the project is completed. All requested interfaces have been implemented in YYblog.

Small program source has also been uploaded in YYblog, the specific address: github.com/allanzhuo/y…

If this article is helpful to you, or the project can inspire you, I hope to help yyblog project point a Star, github.com/allanzhuo/y…

I’m running out of space, so I’ll stop there. Generally speaking, the technical difficulty is not great, but there are many small pits. If you have any ideas, please feel free to communicate with me in the comments