unicloud获取小程序二维码和使用

首先我的路由,使用的是uni-cloud-router

1.首先导入插件mp-cloud-openapi

从这里直接导入项目中 https://ext.dcloud.net.cn/plugin?id=1810

2.生成二维码 base64

这是我写的 service

const {
	Service
} = require('uni-cloud-router')
const openapi = require('mp-cloud-openapi')
let Duplex = require('stream').Duplex;
module.exports = class appletService extends Service {
	constructor(ctx) {
		super(ctx)
		this.appid = '****'  //小程序appid
		this.secret = '*****'  //小程序秘要

		this.openapiWeixin = openapi.initWeixin({
			appId: this.appid,
			secret: this.secret
		})
	}


	async getQrcode(page, scene = 'aa', width = 430) {

		
	
		const result = await this.openapiWeixin.wxacode.getUnlimited({
			page: page,
			scene: scene,
			width: width,
			accessToken: await this.getToken()  //获取小程序token
		})

		
		return result.buffer.toString('base64');


	}
	
	
	//获取小程序token  这个我是存在表里,你们自行储存
	async getToken(){
		let detail_token = await this.service.setting.get('applet_token')
		let token = ''
		if (!detail_token|| detail_token.endtime < Date.now()) {
			const {
				accessToken,
				expiresIn
			} = await this.openapiWeixin.auth.getAccessToken()
			
			
			await this.service.setting.set('applet_token', {
				accessToken,
				expiresIn,
				endtime: Date.now() + (expiresIn - 1000) * 1000
			})
			
			token = accessToken
		} else {
			token = detail_token.accessToken
		}
		
		return token
	}


}

3.控制器返回给前端二维码

const {
    Controller
} = require('uni-cloud-router')
module.exports = class evalController extends Controller {
    constructor(ctx) {
        super(ctx)
    }
	
	
	
	async qrcode() {
		const data = this.ctx.data
		
	
		let page =  decodeURIComponent(data.page)
		let scene = data.scene ? data.scene : 'aa'
		
		let res_qrcode = await this.service.applet.getQrcode(page, scene)
		
		this.ctx.set('content-type', 'image/png')

		this.ctx.isBase64Encoded = true 

		return res_qrcode

	}
	
	
	
}

4.前端的使用方法

 

这是用云开发开发的小程序,可以参考一下

unicloud获取小程序二维码和使用_第1张图片

你可能感兴趣的:(html5)