Project background

The last article mainly introduces the background of the blog project, technology selection, development framework and system design part of the content, to continue the last, the following mainly introduces the small program login configuration, sharing and subscription message function is how to achieve.

The development of cloud console entry: console.cloud.tencent.com/tcb

What is CloudBase

Cloud Development (TCB) is a cloud native integrated development environment and tool platform provided by Tencent Cloud. It provides developers with highly available, automatic and flexible expansion of back-end cloud services, including computing, storage, hosting and other serverless capabilities, which can be used for cloud integrated development of various end applications (small programs, Public account, Web application, Flutter client, etc.) to help developers build and manage back-end services and cloud resources in a unified manner, avoiding tedious server construction, operation and maintenance during application development. Developers can focus on the implementation of business logic, with lower development threshold and higher efficiency.

System implementation

1 database

Article:

sync_posts = [ { _id: String, createTime: String, slug: String, title: String, tags: Array, description: String, cover: String, // url content: String, // HTML}] // Security rules {"read": true, // public read" write": "Get ('database.user_info.${auth.openID}').ismanager ",Copy the code

User favorites:

User_favorite = [{_id:String, userId:String,// openId postId: String,// Add redundant data to the table createTime: Date}] {"read": "doc. _openID == auth.openid",// Private read" write": "doc. _openID == auth.openid"// private write}Copy the code

User Information:

User_info = [{_id: String, _openID: String,...userInfo, isManager: Boolean,}] // Security rule {"read": "Doc. _openID == auth.openid", // Private read "write": "doc._openid == auth.openid"// private write}Copy the code

2 the login

2.1 Common Login

After cloud development, there is no need to obtain the login certificate (code) through wx.login to exchange the user login status information, because each time the cloud function is called, the caller OpenID has been attached.

Because the user information can be displayed directly through open-data (whether authorized or not), some applets can bypass user login. Some small programs are saved to the database after the user information is authorized. The database information is used for subsequent operations and cannot be updated after the user changes the information. If the user takes the initiative to cancel authorization through the Settings page, but the user’s information is still displayed after the return (showing login), this is because the user mode information is obtained through onLoad, and the return operation is onShow, so there will be conflicts. When a user chooses to use another nickname or profile picture when reauthorizing the login, some applets will consider the user as a new user. There are also some small programs, whether the business needs user information, all require authorization to use.

Based on the principle of “come and go as you please “[1], visitors can browse as tourists, but when it comes to some functions that need to collect and input user information or save user records, users are required to jump to the login page and authorize to obtain information, and save it in the database with openID in the context through cloud functions. At the same time, the custom login state generated by the user id is cached locally in the callback and will be null if the user clicks exit.

// cloudfunction/login const openid = wxContext.OPENID db.collection('user_info').where({ _openid: openid }).get().then(async (res)=> { if (res.data.length === 0) { db.collection('user_info').add({ data: { _openid: openid, ... event.userInfo, createTime: db.serverDate(), } }) }Copy the code

When opening the small program next time, it will check the custom login state in the cache to determine whether the user is logged in or not, and also call the cloud function to update the user information and usage information (such as opening time and opening times for subsequent user analysis). If monitored in onShow, logic duplicates with normal onLaunch. In fact, opening the Settings page inevitably leads to onHide, which can be monitored as follows:

// app.js
onHide:function() {
  wx.onAppShow(()=> {
    if(this.globalData.hasLogin) {
      wx.getSetting({
        success: res => {
          if (!res.authSetting['scope.userInfo']) { // 取消了授权
            this.logout() // 返回后直接登出
          }
        }
      })
    }
    wx.offAppShow();
  })
},
Copy the code

2.2 Administrator Authentication

The administrator is the author of the article. For the administrator identity, consider:

  • Mobile phone number: at present, this interface is for non-individual developers, and has completed the certification of small program open;
  • Openid: it is unknown before it is used and cannot be bound in advance;
  • User information is mutable and unbinding;
  • Password mode exposes the management portal.

For the time being, the simplest and most straightforward data field tag isMaganer: True is adopted, which will also be used for database security rules.

3 share

There are two ways of sharing: directly sharing to chat or generating posters and guiding sharing to moments.

For the former, consider that the image size is 5:4, and any other ratio will produce white space or crop. The latter is mainly analyzed here. It is slow to export pictures through canvas drawing on the small program side. Since the sharing content of each article is basically fixed, pre-generation can be considered. But if you share the QR code and the sharer association, it still needs to be generated locally. The component Mini-share is used here. For the small program code, the cloud call method is currently used, which can only be triggered from the small program end, so it cannot be pre-generated.

Const path = page +'? ' + Object.keys(param).map(function (key) { return encodeURIComponent(key) + "=" + encodeURIComponent(param[key]); }).join("&"); Const fileName = 'wxacode/limitA-' + crypto.createHash('md5').update(path).digest('hex'); Let getFileRes = await cloud.gettempFileurl ({fileList: [fileID]}); / / if not found to regenerate the const wxacodeRes = await cloud. Openapi. Wxacode. Get ({path, Const uploadRes = await cloud.uploadFile({cloudPath: fileName + fileSuffix, fileContent: wxacodeRes.buffer, }); GetFileRes = await cloud.getTempFileurl ({fileList: [uploadres.fileid]});Copy the code

The characteristics of the method of generating TWO-DIMENSIONAL code can be summarized as:

Here, class A (wxacode.get) is used because the default database _id of the article is 32 bits, which reaches the limit of class B, and other information needs to be associated.

4 Subscribe Message

For individual subjects, users can only send messages once after initiating subscription (obtaining the right to send messages) through the small program. Here, when users leave messages, they will subscribe a reply notification, but they cannot send messages to the author (unless the author subscribes for a long time). Since you also need to save to the database, the cloud call is used here.

// post.js wx.requestSubscribeMessage({ tmplIds: [TEMPLATE.REPLY] }) // cloudfunction/sengMsg let sendRes = await db.collection('user_msg').add({ data: { _openid: wxContext.OPENID, msg:inputMsg, createTime:Date.parse(new Date()) } }); Await cloud. Openapi. SubscribeMessage. Send ({data: the format (data), / / because of the various types of information format length limitation, need to deal with touser: wxContext.OPENID, templateId: TEMPLATE.REPLY });Copy the code

May the open source

Open source address: sorted by the author, will be uploaded to github.com/makergyt, please pay attention.

Static site: blog.makergyt.com

Alternate link: github.blog.makergyt.com

Small program: “source create wisdom”, which access to some tools.

References:

[1] : Tencent WeChat little programming guide developers.weixin.qq.com/miniprogram… 2019.

Cloud CloudBase information development Open cloud development: console.cloud.tencent.com/tcb?tdl_anc… The product documentation: cloud.tencent.com/product/tcb… From =10004 Technical exchange plus Q group: 601134960 Latest news follow wechat public account