使用nest写一个生成微信小程序码的接口

在这里插入图片描述
一、
枯藤老树昏鸦,上班就想回家。

二、
打开官方文档,看一下文档上怎样生成二维码。获取不限制的小程序码
在这里插入图片描述
把文档甩给后端、后端摆烂说忙、不给写,我真的****了。好吧,自己动手丰衣足食,我写出来的又不是不能用。

三、
首先要来小程序的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,
    };
  }

启动项目,请求接口
在这里插入图片描述

完结!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
1. 安装微信开发者工具和nestjs 首先,需要安装微信开发者工具和nestjs。微信开发者工具用于调试和运行小程序nestjs用于编后端接口。 2. 创建小程序 在微信开发者工具中,创建一个新的小程序,并获取小程序的AppID和AppSecret。 3. 创建nestjs项目 使用nestjs cli工具创建一个新的nestjs项目。在终端中运行以下命令: ``` npm install -g @nestjs/cli nest new my-project ``` 4. 安装依赖 在nestjs项目根目录下运行以下命令安装依赖: ``` npm install @nestjs/common @nestjs/core @nestjs/platform-express @nestjs/swagger @nestjs/passport passport passport-wechat express-session ``` 5. 配置nestjsnestjs项目中,需要配置passport和wechat strategy。 在app.module.ts文件中,添加passport和session模块: ```typescript import { Module } from '@nestjs/common'; import { PassportModule } from '@nestjs/passport'; import { WechatStrategy } from './wechat.strategy'; import * as session from 'express-session'; @Module({ imports: [ PassportModule, session({ secret: 'my-secret', resave: false, saveUninitialized: false, }), ], providers: [WechatStrategy], }) export class AppModule {} ``` 在wechat.strategy.ts文件中,添加wechat strategy: ```typescript import { Injectable } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { Strategy } from 'passport-wechat'; @Injectable() export class WechatStrategy extends PassportStrategy(Strategy, 'wechat') { constructor() { super({ appID: 'YOUR_APP_ID', appSecret: 'YOUR_APP_SECRET', scope: 'snsapi_userinfo', state: 'STATE', }); } async validate(accessToken: string, refreshToken: string, profile: any) { const { openid, nickname, headimgurl } = profile; return { openid, nickname, headimgurl }; } } ``` 在validate方法中,可以获取用户的openid,昵称和头像等信息。这些信息可以保存到数据库中,用于后续的用户验证和业务逻辑。 6. 编接口nestjs中,可以使用@Controller和@Get等装饰器编接口。 在app.controller.ts文件中,添加/login接口: ```typescript import { Controller, Get, Req, Res, UseGuards } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; @Controller() export class AppController { @Get('/login') @UseGuards(AuthGuard('wechat')) async login(@Req() req, @Res() res) { res.redirect('/'); } } ``` 在/login接口中,使用wechat strategy进行授权登录,并重定向到首页。 7. 运行nestjs项目 在nestjs项目根目录下运行以下命令启动nestjs项目: ``` npm run start ``` 8. 配置小程序 在微信开发者工具中,配置小程序的请求域名和授权域名。 在小程序的app.js文件中,添加以下代: ```javascript const app = getApp() App({ onLaunch: function () { // 登录 wx.login({ success: res => { // 发送 res.code 到后台换取 openId, sessionKey, unionId wx.request({ url: 'http://localhost:3000/login', method: 'GET', data: { code: res.code }, success: res => { console.log(res.data) } }) } }) } }) ``` 在onLaunch方法中,调用wx.login方法获取用户的code,并发送请求到nestjs的/login接口进行授权登录。 9. 测试 在微信开发者工具中,启动小程序并查看控制台输出。 如果输出了用户的openid,昵称和头像等信息,则说明授权登录已经成功,可以保存这些信息到数据库中,用于后续的用户验证和业务逻辑。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值