Generate Mini Program QR Code and Mini Program Code

Use WeChat cloud development to generate custom QR codes and small program codes

Not much to say, let's look at the final display effect first

insert image description here
This one is the final result of generating the QR code. Click Save to Album, and the QR code will be saved to the mobile phone album. When debugging the WeChat developer tool, the picture will be saved to the computer. This is what I saved to the desktop
insert image description here
. The two-dimensional code of
insert image description here
this is the preview function of the two-dimensional code

There are three ways to generate code

  • Generate a QR code (permanently valid, with a limited number): cloud.openapi.wxacode.createQRCode
  • Generate applet code (permanently valid, with a limited number): cloud.openaapi.wxacode.get
  • Generate unlimited small program codes (permanently valid, unlimited): cloud.openaapi.wxacode.getUnlimited

Steps

1. Initialization of the cloud environment

// 云环境的初始化 app.js文件
        wx.cloud.init({
    
    
            env:'cloud1-9gmt6vpx11d9ced0',   // 环境ID
            traceUser:true
        })
// project.config.json文件
		"cloudfunctionRoot": "cloudFn/",  // 与第三步云函数文件夹名一致即可

Click on the cloud development in the WeChat developer tools , an interface will appear, directly copy the environment ID , and then put the copied ID in env
insert image description here
insert image description here

2. Open up a container on the page to display the QR code (including buttons to preview and save to album)

<view class="img-cloud">
	<button bindtap='getQrCode'>生成小程序二维码</button>
	<image class="img" src='{
     
     {image}}' bindtap='previewed' data-filepath='{
     
     {image}}'></image>
	<button bindtap='saved'>保存到相册</button>
</view>

3. Create a cloud function

insert image description here

  1. Create a folder cloudFn in the root directory of the WeChat developer tool, right-click the folder, select New Node.js cloud function , the function name is createQRCode, and three files will be automatically generated
    insert image description here

  2. Code in index.js file

// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
    
     env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

// 云函数入口函数
exports.main = async (event, context) => {
    
    
    try{
    
    
        const result = await cloud.openapi.wxacode.createQRCode({
    
    
        // 扫码后进入的页面路径和携带的参数
            path:'pages/indexv2/index?discount=' + event.discount +'&endDate=' + event.endDate,     
            width:300
        })
        return result
    }catch(err){
    
    
        return err
    }
}
  1. config.json file code
{
    
    
    "permissions": {
    
    
        "openapi": [
            "wxacode.createQRCode"
        ]
    }
}
  1. After the above steps are completed, right-click on the createQRCode folder, select the third upload and deploy: cloud installation dependencies (do not upload node_modules) , and there will be a prompt after the upload is successful.
    insert image description here

4. The method getQrCode to generate a QR code

// 生成二维码
    getQrCode(){
    
    
        wx.showLoading({
    
    
            titel:"生成中..."
        });
        let that = this;
        wx.cloud.callFunction({
    
    
            name:'createQRCode',   // 小程序二维码
            // name:'wxacode',   // 小程序码,有限制
            // name:'getUnlimited',   // 小程序码,无限制
            data:{
    
       // 二维码传递的参数,可自定义,需要与第3步index.js文件的path参数相同
                discount:'0.91',
                endDate:'2023-11-07'
            },
            success(res){
    
    
                console.log(res);
                let fileManager = wx.getFileSystemManager();
                console.log(wx.env,'env');
                let filePath = wx.env.USER_DATA_PATH + '/qr.jpg';   // 二维码的一个本地地址,图片名称可随意起
                console.log(filePath);
                fileManager.writeFile({
    
    
                    filePath,
                    encoding:'binary',
                    data:res.result.buffer,
                    success:(result)=>{
    
    
                        console.log(result);
                        let codeImg = filePath;  
                        that.setData({
    
        // 将二维码渲染到页面上
                            image:codeImg
                        })
                        wx.hideLoading({
    
    })
                    }
                })
            }
        })
    },

5. Save the QR code method saved

// 保存二维码到手机上
    saved(){
    
    
        wx.saveImageToPhotosAlbum({
    
    
          filePath: this.data.image,
          success:res=>{
    
    
            console.log(res);
            wx.showToast({
    
    
                title:'保存成功',
            })
          }
        })
    },

6. Preview QR code method previewed

// 预览二维码
    previewed(e){
    
    
        const {
    
    filepath} = e.currentTarget.dataset;
        wx.previewImage({
    
    
          urls: [filepath],   // 可传多个地址
        })
    }

7. Obtain the parameters passed by the QR code

In Step 2 of Step 3, the page we entered by scanning the code is pages/indexv2/index , so we can get the parameters in the onLoad of this file

onLoad(options) {
    
    
		console.log(options,'options');
		const {
    
    discount,endDate} = options;
		if(discount){
    
    
			// 书写业务逻辑
			xxx
		}
		if(endDate){
    
    
			// 书写业务逻辑
			xxx
		}
	},

If it is helpful to you, please triple ❤, meme~

Guess you like

Origin blog.csdn.net/x_XDGS/article/details/132150027