unicloud generates WeChat applet sharing code

1. Program

After reading the official documents, there are three ways to obtain the applet code, and I use the second method: generate an unlimited number of sharing codes.
Corresponding official document: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/qr-code/getUnlimitedQRCode.html
It is divided into https call and cloud development call.
Because I use unicloud cloud development, if I use WeChat cloud development, I need to introduce wx-server-sdk, and then I have to configure a bunch of things, and the documentation is incomplete. After two failed attempts, I gave up this solution.
The last is the way of calling https.

Second, realize the idea

[Step 1] You need to obtain the ACCESS_TOKEN value.
This kind of WeChat interface must be called by the server , and cannot be called directly by https on the front end. Although it can be called successfully during the development stage, it is because the WeChat developer tool - project information - local settings has checked the success caused by not verifying the legal domain name. When you release the trial version and the official version, it is impossible to call.
Therefore, to obtain ACCESS_TOKEN, you must directly call the WeChat interface on the server side to obtain it.
Official document: https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html
Implemented cloud object code:

// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程:https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
module.exports = {
    
    
	_before: function () {
    
     // 通用预处理器

	},
	
	async addCodeInfo(infoObj){
    
    
		//获取access_token
		const APPID='xxx'
		const APPSECRET='xxx'
		const URL = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${
      
      APPID}&secret=${
      
      APPSECRET}`
		const requestOptions = {
    
    
			method: 'GET',
			dataType: 'json'
		}
		const res1 = await uniCloud.httpclient.request(URL,requestOptions)
		const access_token=res1.data.access_token
		return access_token
	}
}

[Step 2] You need to use ACCESS_TOKEN to call the interface of WeChat to generate the sharing code.
This interface is still the interface of WeChat, so it still needs to be initiated on the server.
Therefore, based on the access_token obtained in the previous step, continue to call the interface for obtaining the sharing code:

// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程:https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
module.exports = {
    
    
	_before: function () {
    
     // 通用预处理器

	},
	//数据库中增加wifi信息,增加完毕后返回分享二维码
	async addCodeInfo(infoObj){
    
    
		//获取access_token
		const APPID='wxe0bc57edf31dad80'
		const APPSECRET='7e5f676a5fad20d044434792360c28d4'
		const URL = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${
      
      APPID}&secret=${
      
      APPSECRET}`
		const requestOptions = {
    
    
			method: 'GET',
			dataType: 'json'
		}
		const res1 = await uniCloud.httpclient.request(URL,requestOptions)
		const access_token=res1.data.access_token

		//由此id生成分享码
		const codeUrl=`https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${
      
      access_token}`
		const codeOptions={
    
    
			method:'POST',
			data: JSON.stringify({
    
    
				"scene":'id',
				"page":'pages/index/index',
				"check_path":false,
				"width":500,
				"env_version":'trial'//trial:体验版
			}),
		}
		const res3 = await uniCloud.httpclient.request(codeUrl,codeOptions)
		return res3
	}
}

[Step 3] The result type of the obtained sharing code is the binary format of the buffer, which needs to be transferred to the picture, as shown
in the figure below:
insert image description here
that is, res.data is data of the buffer type, and it has two fields: the data field stores the content, and the type field displays type.
So it needs to be converted to base64 on the server side and then passed to the front end:

const buffer=res3.data
const result=buffer.toString('base64')

Three, complete code implementation

front end

<img :src="shareCode" alt="" >

<script>
	export default {
    
    
		data() {
    
    
			return {
    
    
				shareCode:'',
			}
		},
		onLoad(options) {
    
    
			this.getWeixinCode()
		},
		methods: {
    
    
			//调用后端接口,生成小程序分享码
			async getWeixinCode() {
    
     // 注意异步
				const _this=this
				const wifiCode = uniCloud.importObject('wifiCode') // 导入云对象
				try {
    
    
					const params={
    
    }
					const res=await wifiCode.addCodeInfo(params)
					console.log("++++",res)
					this.shareCode="data:image/png;base64," + res
				} catch (e) {
    
    
					console.log(e)
				}
			}
		}
	}
</script>

Backend:
mainly the cloud object wifiCode:

// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程:https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
module.exports = {
    
    
	_before: function () {
    
     // 通用预处理器

	},
	//数据库中增加wifi信息,增加完毕后返回分享二维码
	async addCodeInfo(infoObj){
    
    
		//获取access_token
		const APPID='xxx'
		const APPSECRET='xxx'
		const URL = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${
      
      APPID}&secret=${
      
      APPSECRET}`
		const requestOptions = {
    
    
			method: 'GET',
			dataType: 'json'
		}
		const res1 = await uniCloud.httpclient.request(URL,requestOptions)
		const access_token=res1.data.access_token
		
		//由此id生成分享码
		const codeUrl=`https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${
      
      access_token}`
		const codeOptions={
    
    
			method:'POST',
			data: JSON.stringify({
    
    
				"scene":"23",
				"page":'pages/index/index',
				"check_path":false,
				"width":500,
				"env_version":'trial'//trial:体验版
			}),
		}
		const res3 = await uniCloud.httpclient.request(codeUrl,codeOptions)
		const buffer=res3.data
		console.log("---响应--",buffer)
		// const buf = new Buffer (buffer)
		console.log("buffer转化",buffer.toString('base64'))
		const result=buffer.toString('base64')
		return result
	}
}

Four, pits

1. The WeChat interface needs to be called by the server.
2. The post interface parameters of the interface to obtain the sharing code need to be processed once by JSON.stringify
. 3. Scenez only supports 32 bits, and some special characters are not yet supported.
4. The access_token parameter of the interface to obtain the sharing code must be placed on the url, which is the same as in my code.
5. After the local development is completed, the cloud objects need to be uploaded and deployed, and the trial version and real machine debugging can be used. In addition, you need to configure the interface whitelist of the applet. https://tcb-api.tencentcloudapi.com and
https://tcb-wbk382fznzzwna3-8chuc14d8e99.service.tcloudbase.com
6. The interface for obtaining the shared code returns the buffer binary stream, so the interface for obtaining the QR code, I did not configure the datatype parameter, but let it use the default value. After the result is obtained, it needs to be converted into base64 before it can be rendered on the page.
insert image description here
All in all, it's quite pitiful, but I didn't cry.
Hey, that's it~
I hope it will be helpful to the friends who will see it later~

Guess you like

Origin blog.csdn.net/weixin_42349568/article/details/128314523