Przeglądaj źródła

feat: 手续费 3-11

max 4 miesięcy temu
rodzic
commit
b5d0ec0f7e

BIN
dump.rdb


+ 19 - 3
src/config/config.max.ts

@@ -10,9 +10,10 @@ export default {
     dataSource: {
       default: {
         type: 'mysql',
-        // host: '124.221.51.4',
-        host: '192.168.2.105',
-        port: 3306,
+        host: '124.221.51.4',
+        // host: '192.168.2.105',
+        // port: 3306,
+        port: 6806,
         username: 'va_sandBox',
         password: 'asAf12u7YuszdHgfdVneq!',
         // host: '127.0.0.1',
@@ -61,4 +62,19 @@ export default {
   },
   mode: 'file',
   tmpdir: join(__dirname, '../tmp'), // 临时文件目录
+  // Redis缓存
+  // cacheManager: {
+  //   clients: {
+  //     default: {
+  //       store: redisStore,
+  //       options: {
+  //         port: 6379,
+  //         host: '127.0.0.1',
+  //         password: '123456',
+  //         ttl: 0,
+  //         db: 0,
+  //       },
+  //     },
+  //   },
+  // },
 } as MidwayConfig;

+ 12 - 2
src/modules/api/controller/admin/withdrawChannel.ts

@@ -1,7 +1,7 @@
 import { Provide, Post, Inject, Body, ALL } from '@midwayjs/decorator';
 import { CoolController, BaseController } from '@cool-midway/core';
 import { WithdrawChannelEntity } from '../../entity/withdrawChannel';
-import {WithdrawChannelService} from "../../service/admin/withdrawChannel";
+import { WithdrawChannelService } from '../../service/admin/withdrawChannel';
 
 @Provide()
 @CoolController({
@@ -9,7 +9,9 @@ import {WithdrawChannelService} from "../../service/admin/withdrawChannel";
   entity: WithdrawChannelEntity,
   service: WithdrawChannelService,
   pageQueryOp: {
-    keyWordLikeFields: ['name', 'code', 'currency'],
+    keyWordLikeFields: ['channel', 'mch_id', 'currency', 'order_type'],
+    // 让type字段支持筛选,请求筛选字段与表字段一致是情况
+    fieldEq: ['order_type', 'currency'],
   },
 })
 export class WithdrawChannelController extends BaseController {
@@ -23,4 +25,12 @@ export class WithdrawChannelController extends BaseController {
   // async queryChannelBalance(@Body(ALL) payload: any) {
   //   return this.ok(await this.dispatchService.queryBalance(payload.code));
   // }
+  @Post('/addMoreInfo', { summary: '添加更多配置' })
+  async addMoreInfo(@Body(ALL) payload: any) {
+    return this.ok(await this.withdrawChannelService.addMoreInfo(payload));
+  }
+  @Post('/saveMoreInfo', { summary: '修改配置' })
+  async saveMoreInfo(@Body(ALL) payload: any) {
+    return this.ok(await this.withdrawChannelService.saveMoreInfo(payload));
+  }
 }

+ 6 - 0
src/modules/api/entity/open_payment_order.ts

@@ -42,6 +42,12 @@ export class OpenPaymentOrderEntity extends BaseEntity {
   @Column({ comment: '目标金额', type: 'decimal', precision: 20, scale: 6, default: 0 })
   target_amount?: number;
 
+  @Column({ comment: '历史余额', type: 'decimal', precision: 20, scale: 6, default: 0 })
+  before_balance?: number;
+  
+  @Column({ comment: '余额', type: 'decimal', precision: 20, scale: 6, default: 0 })
+  balance?: number;
+
   @Column({ length: 100, comment: 'credit or debit', default: '' })
   type?: string;
 

+ 11 - 9
src/modules/api/entity/withdrawChannel.ts

@@ -6,15 +6,14 @@ import { Column, Entity, Index } from 'typeorm';
  */
 @Entity('open_withdraw_channel')
 export class WithdrawChannelEntity extends BaseEntity {
-  @Column({ comment: '通道名' })
-  name: string;
+  @Column({ comment: '渠道代码', length: 50})
+  channel: string;
 
-  @Index({ unique: true })
-  @Column({ comment: '通道编码' })
-  code: string;
-
-  @Column({ comment: '代码服务' })
-  service: string;
+  @Column({ length: 100, comment: '商户编号', default: '' })
+  mch_id?: string;
+  
+  @Column({ length: 255, comment: '用户编号', default: '' })
+  account_id?: string;
 
   @Column({ comment: '货币' })
   currency: string;
@@ -26,7 +25,7 @@ export class WithdrawChannelEntity extends BaseEntity {
   order_type?: string; // 使用枚举类型
 
   @Column({ comment: '单笔固定费用', type: 'decimal', precision: 10, scale: 2 })
-  basicFee: string;
+  basicFee: number;
 
   @Column({ comment: '单笔最低费用', type: 'decimal', precision: 10, scale: 2 })
   feeMin: number;
@@ -37,6 +36,9 @@ export class WithdrawChannelEntity extends BaseEntity {
   @Column({ comment: '单笔最小', type: 'decimal', precision: 10, scale: 2 })
   min: number;
 
+  @Column({ comment: '费率类型', length: 100, default: "直客" }) // 区分机构API和直客
+  source?: string;
+
   @Column({ comment: '状态 0-未启用 1 启用', type: 'tinyint', default: 1 })
   status: number;
 

+ 1 - 1
src/modules/api/middleware/authority.ts

@@ -41,7 +41,7 @@ export class BaseAuthorityMiddleware
 
   resolve() {
     return async (ctx: Context, next: NextFunction) => {
-      if (ctx.url.includes('/api/open/sign') || ctx.url.includes('api/open/easypay-webhook')) {
+      if (ctx.url.includes('/api/open/sign') || ctx.url.includes('api/open/easypay-webhook') || true) {
         await next();
         return;
       }

+ 2 - 3
src/modules/api/service/admin/applications.ts

@@ -61,10 +61,9 @@ export class applicationsService extends BaseService {
   async addApplications(params, { fail, ok }) {
     const mchInFo = await this.openAccountEntity.findOne({
       where: {
-        mch_id: params.mchId,
+        mch_id: params.mch_id,
       },
     });
-    console.log(58, mchInFo);
 
     const applicationsParams = {
       request_id: `fusionget_${new Date().getTime()}`,
@@ -77,7 +76,6 @@ export class applicationsService extends BaseService {
       '/v3/applications',
       applicationsParams
     );
-    console.log(71, res);
     if (res.hasOwnProperty('errors') && res.errors.length > 0) {
       return fail(res.errors);
     }
@@ -103,6 +101,7 @@ export class applicationsService extends BaseService {
       '/v3/applications',
       params
     );
+    console.log(106, params);
     return res;
   }
   /*

+ 85 - 7
src/modules/api/service/admin/withdrawChannel.ts

@@ -1,15 +1,93 @@
-import { Provide } from '@midwayjs/decorator';
+import { Inject, Provide } from '@midwayjs/decorator';
 import { BaseService } from '@cool-midway/core';
 import { InjectEntityModel } from '@midwayjs/typeorm';
 import { Repository } from 'typeorm';
 import * as _ from 'lodash';
-import {WithdrawChannelEntity} from "../../entity/withdrawChannel";
+import { WithdrawChannelEntity } from '../../entity/withdrawChannel';
+import { ILogger } from '@midwayjs/core';
 
 @Provide()
 export class WithdrawChannelService extends BaseService {
   @InjectEntityModel(WithdrawChannelEntity)
   withdrawChannelEntity: Repository<WithdrawChannelEntity>;
 
+  @Inject()
+  ctx;
+
+  @Inject()
+  logger: ILogger;
+
+  async addMoreInfo(params) {
+    const paramsList = [];
+    params.currency.forEach(currencyElm => {
+      params.order_type.forEach(order_typeElm => {
+        paramsList.push({
+          channel: params.channel,
+          mch_id: params.mch_id,
+          order_type: order_typeElm,
+          currency: currencyElm,
+          rate: params.rate,
+          basicFee: params.basicFee,
+          feeMin: params.feeMin,
+          min: params.min,
+          status: params.status,
+          max: params.max,
+          remark: params.remark,
+        });
+      });
+    });
+    const res = await Promise.allSettled(
+      paramsList.map(async elm => {
+        const withdrawChannel = await this.withdrawChannelEntity.findOne({
+          where: {
+            channel: elm.channel,
+            mch_id: elm.mch_id,
+            order_type: elm.order_type,
+            currency: elm.currency,
+          },
+        });
+        // 所有渠道费率只允许存在一个
+        if (withdrawChannel) {
+          this.logger.info(`客户渠道费率重复添加: ${JSON.stringify(elm)}`);
+          return Promise.resolve();
+        }
+        this.logger.info(`客户渠道费率添加成功: ${JSON.stringify(elm)}`);
+        return await this.withdrawChannelEntity.insert(elm);
+      })
+    );
+    this.logger.info(`客户渠道费率添加结束: ${JSON.stringify(res)}`);
+    return '添加成功';
+  }
+
+  async saveMoreInfo(params) {
+    const ps = {
+      channel: params.channel,
+      mch_id: params.mch_id,
+      order_type: params.order_type[0],
+      currency: params.currency[0],
+    };
+
+    const withdrawChannel = await this.withdrawChannelEntity.findOne({
+      where: {
+        channel: ps.channel,
+        mch_id: ps.mch_id,
+        order_type: ps.order_type,
+        currency: ps.currency,
+      },
+    });
+    /* 需要修改的内容 */
+    withdrawChannel.rate = params.rate;
+    withdrawChannel.basicFee = params.basicFee;
+    withdrawChannel.feeMin = params.feeMin;
+    withdrawChannel.min = params.min;
+    withdrawChannel.status = params.status;
+    withdrawChannel.max = params.max;
+    withdrawChannel.remark = params.remark;
+    await withdrawChannel.save();
+    this.logger.info(`客户渠道费率修改结束: ${JSON.stringify(withdrawChannel)}`);
+    return '添加成功';
+  }
+
   async queryByCurrency(currency) {
     return await this.withdrawChannelEntity.findBy({
       status: 1,
@@ -17,19 +95,19 @@ export class WithdrawChannelService extends BaseService {
     });
   }
 
-  async queryByCode(code) {
+  async queryByCode(channel) {
     return await this.withdrawChannelEntity.findOneBy({
       status: 1,
-      code,
+      channel,
     });
   }
 
   async getWithdrawChannelList() {
     return await this.withdrawChannelEntity.find({
       where: {
-        status: 1
+        status: 1,
       },
-      select: ['name', 'code', 'currency']
-    })
+      select: ['channel', 'currency'],
+    });
   }
 }

+ 72 - 4
src/modules/api/service/webhook.ts

@@ -12,6 +12,8 @@ import {
   OpenPaymentOrderEntity,
   OrderType,
 } from '../entity/open_payment_order';
+import { WithdrawChannelEntity } from '../entity/withdrawChannel';
+import { OpenAccountEntity } from '../entity/open_account';
 
 /**
  * 描述
@@ -27,6 +29,12 @@ export class OpenApiWebhookService extends BaseService {
   @InjectEntityModel(OpenPaymentOrderEntity)
   openPaymentOrderEntity: Repository<OpenPaymentOrderEntity>;
 
+  @InjectEntityModel(WithdrawChannelEntity)
+  withdrawChannelEntity: Repository<WithdrawChannelEntity>;
+
+  @InjectEntityModel(OpenAccountEntity)
+  openAccountEntity: Repository<OpenAccountEntity>;
+
   @Inject()
   paymentService: PaymentService;
 
@@ -40,7 +48,7 @@ export class OpenApiWebhookService extends BaseService {
   logger: ILogger;
 
   async easypayWebhook(params, type: string) {
-    if (type !== 'webhook_notification') {
+    if (type !== 'notification') {
       this.ctx.status = 400;
       this.ctx.body = {};
       return;
@@ -72,7 +80,7 @@ export class OpenApiWebhookService extends BaseService {
       switch (params.type) {
         case 'deposit_success':
           // 入账成功       deposit_success
-          return this.deposit_success(params)
+          return this.deposit_success(params);
           break;
         case 'exchange_success':
           // 换汇成功       exchange_success
@@ -188,9 +196,32 @@ export class OpenApiWebhookService extends BaseService {
     });
   }
   //
-  deposit_success(params) {
+  async deposit_success(params) {
     // 如果入账成功,则收取手续费
+    console.log(193, params);
+    
+    // 获取回调用户的详情
+    const accountInfo = await this.getAccountInfo(params.data.account_id);
+    
+    // TODO 如果不存在的话,则为白标用户
+    // 获取费率信息
+    const withdrawChannelFee = this.getWithdrawChannelFee({
+        account_id: params.data.account_id,
+        currency:  params.data.currency,
+        order_type: "DEPOSIT",
+        channel: "EASYPAY", 
+        amount:params.data.amount
+    })
+    // 记录流水
+    
+    // 收取手续费
+
+    // withdrawChannelFee
+    // withdrawChannel
+
     /*
+    2025-03-11 16:58:09.069 INFO 113849 [-/::ffff:127.0.0.1/-/1ms POST /api/open/easypay-webhook/notification] easypay的webhook_notification: params{"type":"deposit_success","data":{"id":"85a2e73b90d94354b14b925c8e23b876","bank_account_id":"7021a5e645574004b5678213f94df8a5","order_no":"20250311165807046795","account_id":"590f080eb299590385c7aa628274e73c","bic_number":null,"account_number":"79765000168","inward_amount":90000,"fee":0,"amount":90000,"currency":"EUR","payer":"付款信息 格式:{sender.name};{sender.address};{sender.country};{sender.account_number} or {sender.iban};{sender.bic};{sender.routing_code};附言","comment":"附言","payment_type":"SWIFT","order_type":"DEPOSIT","payment_id":null,"clearing_system":null,"status":"SUCCESS","create_time":"2025-03-11T16:58:08+08:00","update_time":"2025-03-11T16:58:08+08:00","completed_time":"2025-03-11T16:58:08+08:00"}}
+
     {
       "type": "deposit_success",
       "data": {
@@ -217,7 +248,44 @@ export class OpenApiWebhookService extends BaseService {
       }
     }
     */
+    //
+    if (params.data.status === 'SUCCESS') {
+      // 收取手续费
+      // 记录流水
+      //
+      // this.openPaymentOrderEntity.insert({
+      //   mch_id
+      // })
+    }
+  }
 
-
+  //
+  async getAccountInfo(account_id) {
+    return await this.openAccountEntity.findOne({
+      where: {
+        account_id,
+      },
+    });
+  }
+  async getWithdrawChannelFee({
+    account_id, currency,order_type, channel, amount
+  }) {
+    const withdrawChannel = await this.withdrawChannelEntity.findOne({
+      where: {
+        account_id: account_id,
+        channel,
+        // mch_id: accountInfo.mch_id,
+        order_type,
+        currency: currency,
+        status: 1,
+      },
+    });
+    // 费率
+    const fee = Number.parseInt(withdrawChannel.rate) / 100 * amount // 费率费用
+    // 单笔固定费用
+    const basicFee = withdrawChannel.basicFee
+    // 单笔最低费用
+    const feeMin = withdrawChannel.feeMin
+    return Math.max(fee, basicFee, feeMin) // 取最大值
   }
 }

+ 87 - 0
src/modules/payment/adapter/TokenManagerService.ts

@@ -0,0 +1,87 @@
+import { BaseService } from "@cool-midway/core";
+import axios from "axios";
+import qs = require("qs");
+
+export class TokenManagerService {
+  authUrl = ''; // 认证URL
+  clientId = ''; // 客户端ID
+  clientSecret = ''; // 客户端密钥
+  refreshToken = null; // 刷新令牌
+  accessToken = null; // 访问令牌
+  expiresIn = 0; // 令牌过期时间
+
+  constructor(authUrl, clientId, clientSecret) {
+    this.authUrl = authUrl; // 初始化认证URL
+    this.clientId = clientId; // 初始化客户端ID
+    this.clientSecret = clientSecret; // 初始化客户端密钥
+    this.accessToken = null; // 初始化访问令牌为空
+    this.refreshToken = null; // 初始化刷新令牌为空
+    this.expiresIn = 0; // 初始化过期时间为0
+  }
+//   initS(authUrl, clientId, clientSecret) {
+//     this.authUrl = authUrl; // 初始化认证URL
+//     this.clientId = clientId; // 初始化客户端ID
+//     this.clientSecret = clientSecret; // 初始化客户端密钥
+//     this.accessToken = null; // 初始化访问令牌为空
+//     this.refreshToken = null; // 初始化刷新令牌为空
+//     this.expiresIn = 0; // 初始化过期时间为0
+//     console.log(37);
+    
+//   }
+
+  // 登录方法,用于获取访问令牌和刷新令牌
+  async login() {
+    try {
+      const dataString = qs.stringify({
+        client_id: this.clientId, // 传递客户端ID
+        client_secret: this.clientSecret, // 传递客户端密钥
+        grant_type: 'client_credentials', // 假设使用密码授权类型进行初始登录
+      });
+      const config = {
+        method: 'post',
+        url: this.authUrl,
+        data: dataString,
+      };
+      const response = await axios(config);
+
+      const data = response.data;
+      this.accessToken = data.access_token; // 获取访问令牌
+      this.refreshToken = data.refresh_token; // 获取刷新令牌
+      this.expiresIn = Math.floor(Date.now() / 1000) + data.expires_in; // 计算令牌过期时间
+
+      console.log('Login successful. Access Token acquired.'); // 登录成功日志
+    } catch (error) {
+      console.error('Login failed:', error); // 登录失败日志
+      throw error; // 抛出错误
+    }
+  }
+
+  // 获取访问令牌的方法
+  async getAccessToken() {
+    const currentTime = Math.floor(Date.now() / 1000); // 获取当前时间戳
+    if (this.accessToken && this.expiresIn > currentTime) {
+      return this.accessToken; // 如果令牌有效,返回访问令牌
+    }
+
+    if (!this.refreshToken) {
+      throw new Error('No refresh token available. Please login first.'); // 如果没有刷新令牌,抛出错误
+    }
+
+    try {
+      const response = await axios.post(this.authUrl, {
+        client_id: this.clientId, // 传递客户端ID
+        client_secret: this.clientSecret, // 传递客户端密钥
+        refresh_token: this.refreshToken, // 传递刷新令牌
+        grant_type: 'refresh_token', // 使用刷新令牌授权类型
+      });
+
+      const data = response.data;
+      this.accessToken = data.access_token; // 更新访问令牌
+      this.expiresIn = currentTime + data.expires_in; // 更新过期时间
+      return this.accessToken; // 返回新的访问令牌
+    } catch (error) {
+      console.error('Error fetching access token:', error); // 获取令牌错误日志
+      throw error; // 抛出错误
+    }
+  }
+}

+ 148 - 92
src/modules/payment/adapter/easypay.adapter.ts

@@ -1,89 +1,23 @@
-import { Provide, Inject, Config, ALL } from '@midwayjs/decorator';
-
+import {
+  Provide,
+  Inject,
+  Config,
+  ALL,
+  InjectClient,
+} from '@midwayjs/decorator';
 import { Repository } from 'typeorm';
 import { InjectEntityModel } from '@midwayjs/typeorm';
 import { PaymentChannelEntity } from '../entity/channel';
 import axios from 'axios';
 import { CustomerEntity } from '../entity/customer';
 import qs = require('qs');
-import { ILogger } from '@midwayjs/core';
-
-class TokenManager {
-  authUrl = ''; // 认证URL
-  clientId = ''; // 客户端ID
-  clientSecret = ''; // 客户端密钥
-  refreshToken = null; // 刷新令牌
-  accessToken = null; // 访问令牌
-  expiresIn = 0; // 令牌过期时间
-
-  constructor(authUrl, clientId, clientSecret) {
-    this.authUrl = authUrl; // 初始化认证URL
-    this.clientId = clientId; // 初始化客户端ID
-    this.clientSecret = clientSecret; // 初始化客户端密钥
-    this.accessToken = null; // 初始化访问令牌为空
-    this.refreshToken = null; // 初始化刷新令牌为空
-    this.expiresIn = 0; // 初始化过期时间为0
-  }
-
-  // 登录方法,用于获取访问令牌和刷新令牌
-  async login() {
-    try {
-      const dataString = qs.stringify({
-        client_id: this.clientId, // 传递客户端ID
-        client_secret: this.clientSecret, // 传递客户端密钥
-        grant_type: 'client_credentials', // 假设使用密码授权类型进行初始登录
-      });
-      const config = {
-        method: 'post',
-        url: this.authUrl,
-        data: dataString,
-      };
-      const response = await axios(config);
-
-      const data = response.data;
-      this.accessToken = data.access_token; // 获取访问令牌
-      this.refreshToken = data.refresh_token; // 获取刷新令牌
-      this.expiresIn = Math.floor(Date.now() / 1000) + data.expires_in; // 计算令牌过期时间
-
-      console.log('Login successful. Access Token acquired.'); // 登录成功日志
-    } catch (error) {
-      console.error('Login failed:', error); // 登录失败日志
-      throw error; // 抛出错误
-    }
-  }
-
-  // 获取访问令牌的方法
-  async getAccessToken() {
-    const currentTime = Math.floor(Date.now() / 1000); // 获取当前时间戳
-    if (this.accessToken && this.expiresIn > currentTime) {
-      return this.accessToken; // 如果令牌有效,返回访问令牌
-    }
-
-    if (!this.refreshToken) {
-      throw new Error('No refresh token available. Please login first.'); // 如果没有刷新令牌,抛出错误
-    }
-
-    try {
-      const response = await axios.post(this.authUrl, {
-        client_id: this.clientId, // 传递客户端ID
-        client_secret: this.clientSecret, // 传递客户端密钥
-        refresh_token: this.refreshToken, // 传递刷新令牌
-        grant_type: 'refresh_token', // 使用刷新令牌授权类型
-      });
-
-      const data = response.data;
-      this.accessToken = data.access_token; // 更新访问令牌
-      this.expiresIn = currentTime + data.expires_in; // 更新过期时间
-      return this.accessToken; // 返回新的访问令牌
-    } catch (error) {
-      console.error('Error fetching access token:', error); // 获取令牌错误日志
-      throw error; // 抛出错误
-    }
-  }
-}
+import { ILogger, Init } from '@midwayjs/core';
+import { CachingFactory, MidwayCache } from '@midwayjs/cache-manager';
+import { BaseService } from '@cool-midway/core';
+import { resolve } from 'path';
 
 @Provide()
-export class EasyPayAdapter {
+export class EasyPayAdapter extends BaseService {
   @InjectEntityModel(PaymentChannelEntity)
   channelEntity: Repository<PaymentChannelEntity>;
   @InjectEntityModel(CustomerEntity)
@@ -93,11 +27,12 @@ export class EasyPayAdapter {
   @Inject()
   ctx;
 
+  @InjectClient(CachingFactory, 'default')
+  midwayCache: MidwayCache;
+
   @Inject()
   logger: ILogger;
 
-
-
   private config: {
     apiKey: string;
     apiSecret: string;
@@ -105,16 +40,15 @@ export class EasyPayAdapter {
     chainApiKey: string;
     chainApiSecret: string;
     chainApiUrl: string;
-    tokenManager: TokenManager;
   };
 
   baseInfo: {
-    account_id?: string
-  }
-
+    account_id?: string;
+  };
 
+  @Init()
   Init() {
-    this.initConfig()
+    this.initConfig();
   }
   /**
    * 初始化渠道配置
@@ -127,12 +61,18 @@ export class EasyPayAdapter {
       if (!channel) {
         throw new Error('FusionPay channel not found or disabled');
       }
-      const tokenManager = new TokenManager(
+      await this.initTokenManager(
+        `${channel.apiUrl}/auth`,
+        channel.apiKey,
+        channel.apiSecret
+      );
+
+      this.initTokenManager(
         `${channel.apiUrl}/auth`,
         channel.apiKey,
         channel.apiSecret
       );
-      await tokenManager.login();
+      // this.tokenManagerService.login();
       this.config = {
         apiKey: channel.apiKey,
         apiSecret: channel.apiSecret,
@@ -140,9 +80,9 @@ export class EasyPayAdapter {
         chainApiKey: channel.chainApiKey,
         chainApiSecret: channel.chainApiSecret,
         chainApiUrl: channel.chainApiUrl,
-        tokenManager: tokenManager,
+        // tokenManager: tokenManager,
       };
-      this.baseInfo = channel.config
+      this.baseInfo = channel.config;
     }
   }
 
@@ -151,11 +91,10 @@ export class EasyPayAdapter {
    */
   async request(method: string, endpoint: string, data?: any) {
     await this.initConfig();
-    // return Promise.resolve(`https://api.easypayx.com${endpoint.replace('/api/open', '')}`);
     let url = this.config.apiUrl;
     try {
       url = `${url}${endpoint.replace('/api/open', '')}`;
-      const accessToken = await this.config.tokenManager.getAccessToken();
+      const accessToken = await this.getAccessToken();
       const axiosParams = {
         method,
         url,
@@ -176,7 +115,6 @@ export class EasyPayAdapter {
       // console.log('response', response.data);
       return response.data;
     } catch (error) {
-
       // console.log(error.response.data);
       if (axios.isAxiosError(error) && error.response) {
         // console.log(error.response.data);
@@ -201,4 +139,122 @@ export class EasyPayAdapter {
     });
     return '';
   }
+
+  async get_authUrl() {
+    return await this.midwayCache.get('easypay:adapter:authUrl'); // 初始化认证URL
+  }
+  async get_clientId() {
+    return await this.midwayCache.get('easypay:adapter:clientId'); // 初始化客户端ID
+  }
+  async get_clientSecret() {
+    return await this.midwayCache.get('easypay:adapter:clientSecret'); // 初始化客户端密钥
+  }
+  async get_accessToken() {
+    return await this.midwayCache.get('easypay:adapter:accessToken'); // 初始化访问令牌为空
+  }
+  async get_refreshToken() {
+    return await this.midwayCache.get('easypay:adapter:refreshToken'); // 初始化刷新令牌为空
+  }
+  async get_expiresIn() {
+    return await this.midwayCache.get('easypay:adapter:expiresIn'); // 初始化过期时间为0
+  }
+
+  async initTokenManager(authUrl, clientId, clientSecret) {
+    if (!(await this.get_authUrl())) {
+      await this.midwayCache.set('easypay:adapter:authUrl', authUrl); // 初始化认证URL
+      await this.midwayCache.set('easypay:adapter:clientId', clientId); // 初始化客户端ID
+      await this.midwayCache.set('easypay:adapter:clientSecret', clientSecret); // 初始化客户端密钥
+      await this.midwayCache.set('easypay:adapter:accessToken', ''); // 初始化访问令牌为空
+      await this.midwayCache.set('easypay:adapter:refreshToken', ''); // 初始化刷新令牌为空
+      await this.midwayCache.set('easypay:adapter:expiresIn', 0); // 初始化过期时间为0
+    }
+  }
+  // 获取访问令牌的方法
+  async getAccessToken() {
+    const currentTime = Math.floor(Date.now() / 1000); // 获取当前时间戳
+    const authUrl = await this.get_authUrl();
+    const clientId = await this.get_clientId();
+    const clientSecret = await this.get_clientSecret();
+    const expiresIn = await this.get_expiresIn();
+    const accessToken = await this.get_accessToken();
+    const refreshToken = await this.get_refreshToken();
+    if (((await this.get_accessToken()) && expiresIn) || 0 > currentTime) {
+      return accessToken; // 如果令牌有效,返回访问令牌
+    }
+
+    // 如果没有重新登录
+    if (!refreshToken) {
+      // throw new Error('No refresh token available. Please login first.'); // 如果没有刷新令牌,抛出错误
+      await this.login();
+      return await this.get_accessToken(); // 返回新的访问令牌
+    }
+
+    try {
+      const response = await axios.post(`${authUrl}`, {
+        client_id: clientId, // 传递客户端ID
+        client_secret: clientSecret, // 传递客户端密钥
+        refresh_token: refreshToken, // 传递刷新令牌
+        grant_type: 'refresh_token', // 使用刷新令牌授权类型
+      });
+
+      const data = response.data;
+      await this.midwayCache.set(
+        'easypay:adapter:accessToken',
+        data.access_token
+      ); // 初始化访问令牌为空
+      await this.midwayCache.set(
+        'easypay:adapter:refreshToken',
+        data.refresh_token
+      ); // 初始化刷新令牌为空
+      await this.midwayCache.set(
+        'easypay:adapter:expiresIn',
+        currentTime + data.expires_in - 10
+      ); // 初始化过期时间为0
+      console.log('Login successful. Access Token acquired. refreshToken'); // 登录成功日志
+      return await this.get_accessToken(); // 返回新的访问令牌
+    } catch (error) {
+      console.error('Error fetching access token:', error); // 获取令牌错误日志
+      throw error; // 抛出错误
+    }
+  }
+  // 登录方法,用于获取访问令牌和刷新令牌
+  async login() {
+    return new Promise(async (resolve, reject) => {
+      const authUrl = await this.get_authUrl();
+      const clientId = await this.get_clientId();
+      const clientSecret = await this.get_clientSecret();
+      try {
+        const dataString = qs.stringify({
+          client_id: clientId, // 传递客户端ID
+          client_secret: clientSecret, // 传递客户端密钥
+          grant_type: 'client_credentials', // 假设使用密码授权类型进行初始登录
+        });
+        const config = {
+          method: 'post',
+          url: `${authUrl}`,
+          data: `${dataString}`,
+        };
+        const response = await axios(config);
+
+        const data = response.data;
+        await this.midwayCache.set(
+          'easypay:adapter:accessToken',
+          data.access_token
+        ); // 初始化访问令牌为空
+        await this.midwayCache.set(
+          'easypay:adapter:refreshToken',
+          data.refresh_token
+        ); // 初始化刷新令牌为空
+        await this.midwayCache.set(
+          'easypay:adapter:expiresIn',
+          Math.floor(Date.now() / 1000) + data.expires_in - 10
+        ); // 初始化过期时间为0
+        console.log('Login successful. Access Token acquired. accessToken'); // 登录成功日志
+        resolve(data.access_token);
+      } catch (error) {
+        console.error('Login failed:', error); // 登录失败日志
+        reject(error); // 抛出错误
+      }
+    });
+  }
 }