一、
枯藤老树昏鸦,上班就想回家。
二、
打开官方文档,看一下文档上怎样生成二维码。获取不限制的小程序码
把文档甩给后端、后端摆烂说忙、不给写,我真的****了。好吧,自己动手丰衣足食,我写出来的又不是不能用。
三、
首先要来小程序的appid、secret,然后起个nest项目。
//写个接口
@Get('/getCode')
getCode(@Request() req) {
return this.girlService.getCode(req.query.eid || '',req.query.path||'');//调用service
}
//进入service调用方法
async getCode(eid:number,path:string) {
let access_token = await axios.get(
'https://api.weixin.qq.com/cgi-bin/token',
{
params: {
grant_type: 'client_credential',
appid: ''//小程序的appid,
secret: ''//小程序secret,
},
},
);
access_token = access_token.data.access_token;
let qrcode = await axios.post(
'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' +
access_token,
{
page: path,
scene: 'eid=' + eid,
check_path: false,
env_version: 'develop'//正式版为 "release",体验版为 "trial",开发版为 "develop",
},
{ responseType: 'arraybuffer' },
);
const base64Data = Buffer.from(qrcode.data).toString('base64');
return {
base64: 'data:image/png;base64,' + base64Data,
};
}
四、
npm run start:dev 启动项目,然后访问接口,如果不出意外的话 已经可以生成二维码了。
这里生成的是base64格式的,有没有办法让他直接生成小程序图片呢?
$ pnpm i ejs --save
修改main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
// app.useStaticAssets('public');
app.useStaticAssets(join(__dirname, '..', 'public'), { prefix: '/static/' }); //设置虚拟路径
app.setBaseViewsDir(join(__dirname, '..', 'views')); // 放视图的文件
app.setViewEngine('ejs');
await app.listen(3000);
}
bootstrap();
创建对应模板文件
// views/index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<img src="<%=message%>" />
</body>
</html>
修改controller
@Get('/getCode')
@Render('index')
getCode(@Request() req) {
return this.girlService.getCode(req.query.eid || '',req.query.path||'');//调用service
}
修改service
async getCode(eid:number,path:string) {
let access_token = await axios.get(
'https://api.weixin.qq.com/cgi-bin/token',
{
params: {
grant_type: 'client_credential',
appid: ''//小程序的appid,
secret: ''//小程序secret,
},
},
);
access_token = access_token.data.access_token;
let qrcode = await axios.post(
'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' +
access_token,
{
page: path,
scene: 'eid=' + eid,
check_path: false,
env_version: 'develop'//正式版为 "release",体验版为 "trial",开发版为 "develop",
},
{ responseType: 'arraybuffer' },
);
const base64Data = Buffer.from(qrcode.data).toString('base64');
return {
message: 'data:image/png;base64,' + base64Data,
};
}
启动项目,请求接口
完结!