|
|
@@ -1,4 +1,47 @@
|
|
|
-import { Injectable } from '@nestjs/common';
|
|
|
+import { Inject, Injectable } from '@nestjs/common'
|
|
|
+import weixinConfig from './weixin.config'
|
|
|
+import { ConfigType } from '@nestjs/config'
|
|
|
+import { ApiConfig, ApiConfigKit, AccessTokenApi } from 'tnwx'
|
|
|
+import { InjectRepository } from '@nestjs/typeorm'
|
|
|
+import { AccessToken } from './entities/accessToken.entity'
|
|
|
+import { LessThan, Not, Repository } from 'typeorm'
|
|
|
+import { addSeconds } from 'date-fns'
|
|
|
|
|
|
@Injectable()
|
|
|
-export class WeixinService {}
|
|
|
+export class WeixinService {
|
|
|
+ constructor(
|
|
|
+ @Inject(weixinConfig.KEY)
|
|
|
+ private readonly weixinConfiguration: ConfigType<typeof weixinConfig>,
|
|
|
+ @InjectRepository(AccessToken)
|
|
|
+ private readonly accessTokenRepository: Repository<AccessToken>
|
|
|
+ ) {
|
|
|
+ let apiConfig = new ApiConfig(weixinConfiguration.appId, weixinConfiguration.appSecret, '')
|
|
|
+ ApiConfigKit.putApiConfig(apiConfig)
|
|
|
+ // 开启开发模式,方便调试
|
|
|
+ ApiConfigKit.devMode = true
|
|
|
+ // 设置当前应用
|
|
|
+ ApiConfigKit.setCurrentAppId(apiConfig.getAppId)
|
|
|
+ }
|
|
|
+
|
|
|
+ async getAccessToken() {
|
|
|
+ let accessToken = await this.accessTokenRepository.findOneBy({
|
|
|
+ expireAt: LessThan(new Date())
|
|
|
+ })
|
|
|
+ if (accessToken) {
|
|
|
+ if (accessToken.expireAt.getTime() - new Date().getTime() < 600 * 1000) {
|
|
|
+ this.refreshAccessToken()
|
|
|
+ }
|
|
|
+ return accessToken.accessToken
|
|
|
+ }
|
|
|
+ return await this.refreshAccessToken()
|
|
|
+ }
|
|
|
+
|
|
|
+ async refreshAccessToken() {
|
|
|
+ const res = await AccessTokenApi.getAccessToken()
|
|
|
+ const newToken = await this.accessTokenRepository.save(
|
|
|
+ new AccessToken(res.getAccessToken, addSeconds(new Date(), res.getExpiresIn - 300))
|
|
|
+ )
|
|
|
+ await this.accessTokenRepository.delete({ id: Not(newToken.id) })
|
|
|
+ return newToken.accessToken
|
|
|
+ }
|
|
|
+}
|