Table of Contents
1. Foreword
2. Requirements Analysis
3. Idea Analysis
5. AC interface implementation code example (cloud development)
6. Description and optimization
If this article helped you, please give it a like.
Home WeChat Applet Mini Program Development A brief analysis of how to dynamically create mini program codes

A brief analysis of how to dynamically create mini program codes

Nov 03, 2021 am 11:09 AM
Applets WeChat applet

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

##_id123456789You can use the id automatically generated by the cloud database, you don’t need to generate it yourself_openid112233It will be included when inserting data, and it is also a system fieldsuperiorId445566Superior openid field
Field name Value Description
U2

Field nameValueDescription_id987654321Just use the id automatically generated by the cloud database, you don’t need to generate it yourself_openid556677It will be included when inserting data, and it is also a system fieldsuperiorId112233Superior 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.

InterfaceGeneration quantity limitTimelinessCarried parameter lengthInterface AThe total number of AC interfaces does not exceed 10WLong-term128 bytesInterface CAC interfaces add up to no more than 10WLong term128 bytesInterface B UnlimitedLong term32 visible characters

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 in the 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! !

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Xianyu WeChat mini program officially launched Xianyu WeChat mini program officially launched Feb 10, 2024 pm 10:39 PM

Xianyu's official WeChat mini program has quietly been launched. In the mini program, you can post private messages to communicate with buyers/sellers, view personal information and orders, search for items, etc. If you are curious about what the Xianyu WeChat mini program is called, take a look now. What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3. If you want to use it, you must activate WeChat payment before you can purchase it;

Implement card flipping effects in WeChat mini programs Implement card flipping effects in WeChat mini programs Nov 21, 2023 am 10:55 AM

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: <!--index.wxml-->&l

Alipay launched the 'Chinese Character Picking-Rare Characters' mini program to collect and supplement the rare character library Alipay launched the 'Chinese Character Picking-Rare Characters' mini program to collect and supplement the rare character library Oct 31, 2023 pm 09:25 PM

According to news from this site on October 31, on May 27 this year, Ant Group announced the launch of the "Chinese Character Picking Project", and recently ushered in new progress: Alipay launched the "Chinese Character Picking-Uncommon Characters" mini program to collect collections from the society Rare characters supplement the rare character library and provide different input experiences for rare characters to help improve the rare character input method in Alipay. Currently, users can enter the "Uncommon Characters" applet by searching for keywords such as "Chinese character pick-up" and "rare characters". In the mini program, users can submit pictures of rare characters that have not been recognized and entered by the system. After confirmation, Alipay engineers will make additional entries into the font library. This website noticed that users can also experience the latest word-splitting input method in the mini program. This input method is designed for rare words with unclear pronunciation. User dismantling

WeChat applet implements image upload function WeChat applet implements image upload function Nov 21, 2023 am 09:08 AM

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

Implement the drop-down menu effect in WeChat applet Implement the drop-down menu effect in WeChat applet Nov 21, 2023 pm 03:03 PM

To implement the drop-down menu effect in WeChat Mini Programs, specific code examples are required. With the popularity of mobile Internet, WeChat Mini Programs have become an important part of Internet development, and more and more people have begun to pay attention to and use WeChat Mini Programs. The development of WeChat mini programs is simpler and faster than traditional APP development, but it also requires mastering certain development skills. In the development of WeChat mini programs, drop-down menus are a common UI component, achieving a better user experience. This article will introduce in detail how to implement the drop-down menu effect in the WeChat applet and provide practical

Implement image filter effects in WeChat mini programs Implement image filter effects in WeChat mini programs Nov 21, 2023 pm 06:22 PM

Implementing picture filter effects in WeChat mini programs With the popularity of social media applications, people are increasingly fond of applying filter effects to photos to enhance the artistic effect and attractiveness of the photos. Picture filter effects can also be implemented in WeChat mini programs, providing users with more interesting and creative photo editing functions. This article will introduce how to implement image filter effects in WeChat mini programs and provide specific code examples. First, we need to use the canvas component in the WeChat applet to load and edit images. The canvas component can be used on the page

What is the name of Xianyu WeChat applet? What is the name of Xianyu WeChat applet? Feb 27, 2024 pm 01:11 PM

The official WeChat mini program of Xianyu has been quietly launched. It provides users with a convenient platform that allows you to easily publish and trade idle items. In the mini program, you can communicate with buyers or sellers via private messages, view personal information and orders, and search for the items you want. So what exactly is Xianyu called in the WeChat mini program? This tutorial guide will introduce it to you in detail. Users who want to know, please follow this article and continue reading! What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3.

Use WeChat applet to achieve carousel switching effect Use WeChat applet to achieve carousel switching effect Nov 21, 2023 pm 05:59 PM

Use the WeChat applet to achieve the carousel switching effect. The WeChat applet is a lightweight application that is simple and efficient to develop and use. In WeChat mini programs, it is a common requirement to achieve carousel switching effects. This article will introduce how to use the WeChat applet to achieve the carousel switching effect, and give specific code examples. First, add a carousel component to the page file of the WeChat applet. For example, you can use the <swiper> tag to achieve the switching effect of the carousel. In this component, you can pass b

See all articles