A brief analysis of how to dynamically create mini program codes

青灯夜游
Release: 2021-11-03 11:09:32
forward
2813 people have browsed it

This article will introduce to you how to dynamically create mini program codes through WeChat mini program cloud development. I hope it will be helpful to you!

A brief analysis of how to dynamically create mini program codes

1. Foreword

Due to many things at school and work, I have given up "farming" for a long time. During this period of time, I learned a lot and worked on nearly 10 projects, large and small. During this process, I became more and more aware of the importance of recording, so I thought of taking time out of my busy schedule to write a blog and record. Let’s talk about some knowledge points in the development process. It’s a cliché, not only so that I can look back on it next time, but also in the hope that I can help those in need. [Related learning recommendations:Mini Program Development Tutorial]

2. Requirements Analysis

In daily WeChat mini program projects, we often need to use some promotional posters, Invitation posters and other functions, such as a poster to invite friends, allow users to post to friends or forward friend invitations after being generated. At this time, we need to know which users you invited, so that we can easily issue rewards and so on. These are very common requirements. So how to achieve similar needs?

3. Idea Analysis

In fact, the most critical one of these posters is the QR code with parameters (mini program code) recognized by long pressing and scanning the code.

By consulting the WeChat applet development documentation, we can know that in general there are two ways to generate this kind of QR code with parameters (mini program code). When this kind of QR code with parameters is drawn When on the poster, you can use the parameters of this QR code to identify which user generated the poster. When other users scan the code to enter the mini program, the identified ID can be stored in the database to determine who invited the poster. of people.

It’s been too long since I’ve written any code, so it might be a bit cumbersome to say it.

To summarize: To determine whose poster is based on the parameters of the QR code, this parameter must be able to locate the user. Generally speaking, the user's openid can be used as the identification parameter. .

A simple example (cloud development):

Define a collection:user

There are two users

U1

##_id 123456789 You can use the id automatically generated by the cloud database, you don’t need to generate it yourself _openid 112233 It will be included when inserting data, and it is also a system field superiorId 445566 Superior openid field
Field name Value Description
U2

Field name Value Description _id 987654321 Just use the id automatically generated by the cloud database, you don’t need to generate it yourself _openid 556677 It will be included when inserting data, and it is also a system field superiorId 112233 Superior openid field
In the above data table, it is obvious that U2 came in by scanning the QR code (mini program code) of U1, so U2 The value of the superiorId field is U1's openid


. Then when we need to count how many people U1 has invited, we can query how many users in the data whose superiorId value is equal to U1's openid. .

4. Two major implementation methods

As mentioned earlier, there are roughly two ways to achieve this demand, so let's analyze the characteristics of these two implementation methods. It is convenient for us to choose the appropriate method during the development process.

Path One: Mini Program Code

WeChat provides us with three ways to dynamically generate mini program code. Here I will only talk about cloud The calling method is developed by traditional servers and can be operated according to the documentation. The principle is roughly the same.

1,A interface: wxacode.createQRCode

2,C interface: wxacode.get

3,B interface: wxacode.getUnlimited

Make a table to analyze these three interfaces. For a detailed introduction, click on the title Direct access to official documents.

As you can see, the AC interfaces are actually the same, and the actual usage methods are similar, but the parameters will be different.

The difference between AC interface and B interface lies inthe number limit of generation and the length of carried parameters. Therefore, when choosing, you must consider the two conditions of the number of generated and the length of the parameters carried.

Method 2: Ordinary QR code

After briefly comparing the three interfaces of the mini program code, let’s look at it again Look at the characteristics of this ordinary QR code. If the above three interfaces cannot meet the business needs, for example, if the parameters are long and the number of generated items is extremely large, you can try to achieve it through this ordinary QR code.

Compared with the interface, this QR code has no limit on the number of generated parameters. The parameter theory can be very long (I have not tried the specific length, but it is definitely longer than 128), and the timeliness is also long-term. From this point of view, it seems that no matter what the business scenario is, this method is the right choice?

Of course not, at least these two aspects need to be considered for ordinary QR codes.

1. Open scope: small programs for enterprises, media, governments and other organizations.In other words, it does not support the use of individual developer accounts.

2. It is relatively complicated to develop and requires a server and domain name for configuration. There will be many pitfalls.

Since the implementation of this method is a bit complicated, I won’t go into details here. Friends who have needs in this regard can send me private messages to communicate and learn from each other.

One last thing to note is: No matter which way it is implemented, the mini program must be released before it can be scanned and used normally.

5. AC interface implementation code example (cloud development)

The B interface is similar to the AC interface. You can go directly to the official website to see the code example. It should be possible to draw parallels. So here I only use one of the AC interfaces. The main thing is to raise some common questions.

1. After creating a new cloud function, configure permissions in the config.json file (take createQRCode as an example)

A brief analysis of how to dynamically create mini program codes

2. index.js code

const cloud = require('wx-server-sdk') cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV, }) exports.main = async (event) => { try { const result = await cloud.openapi.wxacode.createQRCode({ path: event.path, width: event.width }) return result } catch (err) { return err } }
Copy after login

3. Call (if not local debugging, remember to submit the cloud function)

if (posterType == 1) { // 配置页面路径以及参数 path = "pages/indexStudent1/indexStudent1?superiorId1=" + superiorId1 + "&superiorId2=" + superiorId2 } else if (posterType == 2) { path = "pages/teacherSubmit/teacherSubmit?superiorId=" + superiorId2 } // 调用云函数,请求生成小程序码 buffer 数据 const QRCodeObj = await wx.cloud.callFunction({ name: 'createQRCode', data: { path: path, width: 430 } }) // 需要注意的是返回来的数据是Buffer格式 // 需要转换成为base64格式(为了方便存储复用,毕竟次数有限) const base64 = "data:image/jpeg;base64," + wx.arrayBufferToBase64(QRCodeObj.result.buffer.data) // 将数据直接扔进image组件的src参数里面即可 this.setData({ imgUrl: base64 })
Copy after login

4.wxml

A brief analysis of how to dynamically create mini program codes

5. Effect

A brief analysis of how to dynamically create mini program codes

6. Description and optimization

Just intercepted part of the key code. The small program code has also been processed.

The code that triggers the function and implements reuse is not posted (for safety reasons, it is inconvenient to post it).

When optimizing, the first thing to consider is reuse. That is, a new user calls the cloud function to generate it for the first time. Next time, it will be directly read from the database and generated.

Of course, the premise is that the parameters are consistent.

Why do we need to reuse it? The main reason is that even if it is the same QR code, the parameters are the same. If you call the function ten times to generate it, it is still counted as ten codes, not one code. Therefore, when the number is limited, consider reuse as much as possible.

If this article helped you, please give it a like.

For more programming related knowledge, please visit:Programming Video! !

Interface Generation quantity limit Timeliness Carried parameter length Interface A The total number of AC interfaces does not exceed 10W Long-term 128 bytes Interface C AC interfaces add up to no more than 10W Long term 128 bytes Interface B Unlimited Long term 32 visible characters

The above is the detailed content of A brief analysis of how to dynamically create mini program codes. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!