nestjs代码实现对接微信小程序授权登录获取用户信息
时间: 2023-09-16 08:10:25 浏览: 1085
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. 配置nestjs
在nestjs项目中,需要配置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,昵称和头像等信息,则说明授权登录已经成功,可以保存这些信息到数据库中,用于后续的用户验证和业务逻辑。
阅读全文
相关推荐














