Bläddra i källkod

Merge pull request #4 from maxVaJp/easypay

feat: 记录 easyPay 代理的信息
maxAdolphJp 5 månader sedan
förälder
incheckning
ce64a36fe5

+ 73 - 121
src/modules/api/controller/open.ts

@@ -1,7 +1,8 @@
 import {
   All,
   ALL,
-  Body, Del,
+  Body,
+  Del,
   Get,
   Inject,
   Param,
@@ -14,6 +15,8 @@ import { BaseController, CoolController } from '@cool-midway/core';
 import { Context } from 'vm';
 import { IndividualEntity } from '../../payment/entity/individual';
 import { EasyPayAdapter } from '../../payment/adapter/easypay.adapter';
+import { EasyOpenService } from '../service/open';
+import { OrderType } from '../entity/open_payment_order';
 
 /**
  * 客户管理
@@ -27,6 +30,18 @@ export class OpenApiController extends BaseController {
   @Inject()
   easyPayAdapter: EasyPayAdapter;
 
+  @Inject()
+  easyOpenService: EasyOpenService;
+
+  /**
+   * 生成sign
+   */
+  @Post('/sign', { summary: '创建sign' })
+  async createSign(@Body(ALL) userBody: any) {
+    const { params, timestamp, nonce, secret } = userBody;
+    return this.easyOpenService.createSign(params, timestamp, nonce, secret);
+  }
+
   /**
    * 创建账户
    */
@@ -34,7 +49,9 @@ export class OpenApiController extends BaseController {
   async createPayInOrder(@Body(ALL) params: any) {
     const method = this.ctx.method;
     const path = this.ctx.path;
-    return await this.easyPayAdapter.request(method, path, params);
+    const res = await this.easyPayAdapter.request(method, path, params);
+    this.easyOpenService.save_user(res, params);
+    return res;
   }
 
   /**
@@ -99,7 +116,9 @@ export class OpenApiController extends BaseController {
   async applications(@Body() params: any) {
     const method = this.ctx.method;
     const path = this.ctx.path;
-    return await this.easyPayAdapter.request(method, path, params);
+    const res = await this.easyPayAdapter.request(method, path, params);
+    this.easyOpenService.save_user_account(res, params);
+    return res;
   }
 
   /**
@@ -148,16 +167,11 @@ export class OpenApiController extends BaseController {
    */
   @Post('/v3/acquiring/payments', { summary: '创建支付订单' })
   async CreatedAcquiringPayments(@Body() params: any) {
-    // Access the request method and path
     const method = this.ctx.method;
     const path = this.ctx.path;
-
-    console.log('Request Method:', method);
-    console.log('Request Path:', path);
-    console.log('Request params:', params);
-    // console.log(typeof params)
-    // return `${method}, ${path}, ${params}`
-    return await this.easyPayAdapter.request(method, path, params);
+    const res = await this.easyPayAdapter.request(method, path, params);
+    this.easyOpenService.save_user_order(res, params, OrderType.ACQUIRING_PAYMENT);
+    return res;
   }
 
   /**
@@ -178,9 +192,9 @@ export class OpenApiController extends BaseController {
   }
 
   /**
-   * 查询支付单
+   * 取消支付单
    */
-  @Post('/v3/acquiring/payments/:id/cancel', { summary: '查询支付单' })
+  @Post('/v3/acquiring/payments/:id/cancel', { summary: '取消支付单' })
   async cancelAcquiringPayments(@Param('id') id: any) {
     // Access the request method and path
     const method = this.ctx.method;
@@ -210,8 +224,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
-
   /**
    * 退款
    */
@@ -226,7 +238,9 @@ export class OpenApiController extends BaseController {
     console.log('Request params:', params);
     // console.log(typeof params)
     // return `${method}, ${path}, ${params}`
-    return await this.easyPayAdapter.request(method, path, params);
+    const res = await this.easyPayAdapter.request(method, path, params);
+    this.easyOpenService.save_user_order(res, params, OrderType.ACQUIRING_REFUND);
+    return res;
   }
   /**
    * 查询退款
@@ -326,9 +340,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
-
-
   /**
    * 查询入账列表
    */
@@ -382,7 +393,7 @@ export class OpenApiController extends BaseController {
    * 查询汇率
    */
   @Get('/v1/exchange_rates', { summary: '入账凭证下载' })
-  async exchange_ratesInfo( @Query() params: any) {
+  async exchange_ratesInfo(@Query() params: any) {
     // Access the request method and path
     const method = this.ctx.method;
     const path = this.ctx.path;
@@ -398,27 +409,24 @@ export class OpenApiController extends BaseController {
    * 创建换汇订单
    */
   @Post('/v1/exchanges', { summary: '创建换汇订单' })
-  async createdExchanges( @Query() params: any) {
+  async createdExchanges(@Query() params: any) {
     // Access the request method and path
     const method = this.ctx.method;
     const path = this.ctx.path;
-
-    console.log('Request Method:', method);
-    console.log('Request Path:', path);
-
     // console.log(typeof params)
     // return `${method}, ${path}, ${params}`
-    return await this.easyPayAdapter.request(method, path, params);
+    const res = await this.easyPayAdapter.request(method, path, params);
+    console.log('Request Method:', method);
+    console.log('Request Path:', path);
+    this.easyOpenService.save_user_order(res, params, OrderType.CURRENCY_EXCHANGE);
+    return res;
   }
 
-
-
-
   /**
    * 查询换汇订单列表
    */
   @Get('/v1/exchanges', { summary: '查询换汇订单列表' })
-  async exchangesList( @Query() params: any) {
+  async exchangesList(@Query() params: any) {
     // Access the request method and path
     const method = this.ctx.method;
     const path = this.ctx.path;
@@ -431,13 +439,11 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
-
   /**
    * 查询换汇订单
    */
   @Get('/v1/exchanges/:id', { summary: '查询换汇订单' })
-  async exchangesInfo( @Param() id: any) {
+  async exchangesInfo(@Param() id: any) {
     // Access the request method and path
     const method = this.ctx.method;
     const path = this.ctx.path;
@@ -450,30 +456,27 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, {});
   }
 
-
   /**
    * 付款
    */
   @Post('/v1/payments', { summary: '付款' })
-  async createdPayments( @Body() params: any) {
+  async createdPayments(@Body() params: any) {
     // Access the request method and path
     const method = this.ctx.method;
     const path = this.ctx.path;
 
     console.log('Request Method:', method);
     console.log('Request Path:', path);
-
-    // console.log(typeof params)
-    // return `${method}, ${path}, ${params}`
-    return await this.easyPayAdapter.request(method, path, params);
+    const res = await this.easyPayAdapter.request(method, path, params);
+    this.easyOpenService.save_user_order(res, params, OrderType.PAYMENT);
+    return res;
   }
 
-
   /**
    * 查询付款列表
    */
   @Get('/v1/payments', { summary: '查询付款列表' })
-  async getPaymentsList( @Query() params: any) {
+  async getPaymentsList(@Query() params: any) {
     // Access the request method and path
     const method = this.ctx.method;
     const path = this.ctx.path;
@@ -486,12 +489,11 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
   /**
    * 查询付款
    */
   @Get('/v1/payments/:id', { summary: '查询付款' })
-  async paymentsInfo( @Param() id: any) {
+  async paymentsInfo(@Param() id: any) {
     // Access the request method and path
     const method = this.ctx.method;
     const path = this.ctx.path;
@@ -508,7 +510,7 @@ export class OpenApiController extends BaseController {
    * 补充材料
    */
   @Post('/v1/payments/:id/documents', { summary: '补充材料' })
-  async putPaymentsDocuments( @Param() id: any, @Body() params: any) {
+  async putPaymentsDocuments(@Param() id: any, @Body() params: any) {
     // Access the request method and path
     const method = this.ctx.method;
     const path = this.ctx.path;
@@ -521,14 +523,11 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
-
-
   /**
    * 付款凭证下载
    */
   @Get('/v1/payments/proof', { summary: '付款凭证下载' })
-  async paymentsProof( @Query() params: any) {
+  async paymentsProof(@Query() params: any) {
     // Access the request method and path
     const method = this.ctx.method;
     const path = this.ctx.path;
@@ -541,13 +540,11 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
-
   /**
    * 转账
    */
   @Post('/v1/transfers', { summary: '转账' })
-  async transfers( @Body() params: any) {
+  async transfers(@Body() params: any) {
     // Access the request method and path
     const method = this.ctx.method;
     const path = this.ctx.path;
@@ -557,16 +554,16 @@ export class OpenApiController extends BaseController {
 
     // console.log(typeof params)
     // return `${method}, ${path}, ${params}`
-    return await this.easyPayAdapter.request(method, path, params);
+    const res = await this.easyPayAdapter.request(method, path, params);
+    this.easyOpenService.save_user_order(res, params, OrderType.TRANSFER);
+    return res;
   }
 
-
-
   /**
    * 查询转账列表
    */
   @Get('/v1/transfers', { summary: '查询转账列表' })
-  async transfersList( @Query() params: any) {
+  async transfersList(@Query() params: any) {
     // Access the request method and path
     const method = this.ctx.method;
     const path = this.ctx.path;
@@ -579,13 +576,11 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
-
   /**
    * 查询转账
    */
   @Get('/v1/transfers/:id', { summary: '查询转账' })
-  async transfersInfo( @Param() id: any) {
+  async transfersInfo(@Param() id: any) {
     // Access the request method and path
     const method = this.ctx.method;
     const path = this.ctx.path;
@@ -598,13 +593,14 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, {});
   }
 
-
-
   /**
    * 查询账户流水
    */
   @Get('/v3/accounts/:account_id/transactions', { summary: '查询账户流水' })
-  async accountsTransactionsInfo( @Param() account_id: any, @Query() params: any) {
+  async accountsTransactionsInfo(
+    @Param() account_id: any,
+    @Query() params: any
+  ) {
     // Access the request method and path
     const method = this.ctx.method;
     const path = this.ctx.path;
@@ -617,12 +613,16 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
   /**
    * 根据 transaction ID 查询
    */
-  @Get('/v3/accounts/:account_id/transactions/:id', { summary: '根据 transaction ID 查询' })
-  async accountsTransactionsInfoByAccount_id( @Param() account_id: any,@Param() id: any) {
+  @Get('/v3/accounts/:account_id/transactions/:id', {
+    summary: '根据 transaction ID 查询',
+  })
+  async accountsTransactionsInfoByAccount_id(
+    @Param() account_id: any,
+    @Param() id: any
+  ) {
     // Access the request method and path
     const method = this.ctx.method;
     const path = this.ctx.path;
@@ -635,7 +635,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, {});
   }
 
-
   /**
    * 查询实名更新请求列表
    */
@@ -653,7 +652,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
   /**
    * 提交实名更新
    */
@@ -671,7 +669,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
   /**
    * 收款人信息校验
    */
@@ -689,7 +686,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
   /**
    * 通过实名
    */
@@ -707,11 +703,12 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, {});
   }
 
-
   /**
    * 通过实名更新
    */
-  @Post('/v3/simulate/legal_entity_requests/:id/confirm', { summary: '通过实名更新' })
+  @Post('/v3/simulate/legal_entity_requests/:id/confirm', {
+    summary: '通过实名更新',
+  })
   async simulateLegal_entity_requestsConfirm(@Param() id: any) {
     // Access the request method and path
     const method = this.ctx.method;
@@ -725,7 +722,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, {});
   }
 
-
   /**
    * 驳回实名
    */
@@ -743,7 +739,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, {});
   }
 
-
   /**
    * 创建实名更新
    */
@@ -777,11 +772,12 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
   /**
    * 拒绝更新请求
    */
-  @Post('/v3/simulate/legal_entity_requests/:id/reject', { summary: '拒绝更新请求' })
+  @Post('/v3/simulate/legal_entity_requests/:id/reject', {
+    summary: '拒绝更新请求',
+  })
   async simulateLegal_entity_requestsReject(@Param('id') id: any) {
     // Access the request method and path
     const method = this.ctx.method;
@@ -795,11 +791,12 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, {});
   }
 
-
   /**
    * 收款账户审核通过
    */
-  @Post('/v3/simulate/applications/:id/confirm', { summary: '收款账户审核通过' })
+  @Post('/v3/simulate/applications/:id/confirm', {
+    summary: '收款账户审核通过',
+  })
   async simulateApplicationsConfirm(@Param('id') id: any) {
     // Access the request method and path
     const method = this.ctx.method;
@@ -813,7 +810,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, {});
   }
 
-
   /**
    * 收款账户审核驳回
    */
@@ -831,7 +827,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, {});
   }
 
-
   /**
    * 通过付款
    */
@@ -849,7 +844,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, {});
   }
 
-
   /**
    * 拒绝付款
    */
@@ -1062,10 +1056,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
-
-
-
   /**
    * 收款账户申请成功
    */
@@ -1083,10 +1073,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
-
-
-
   /**
    * 收款账户申请失败
    */
@@ -1104,10 +1090,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
-
-
-
   /**
    * 收款账户信息变更
    */
@@ -1125,10 +1107,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
-
-
-
   /**
    * 收单支付成功通知
    */
@@ -1146,10 +1124,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
-
-
-
   /**
    * 收单退款成功通知
    */
@@ -1167,9 +1141,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
-
-
   /**
    * 收单退款失败通知
    */
@@ -1187,8 +1158,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
-
   /**
    * 入账成功
    */
@@ -1206,7 +1175,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
   /**
    * 换汇成功
    */
@@ -1224,7 +1192,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
   /**
    * 换汇失败
    */
@@ -1242,9 +1209,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
-
-
   /**
    * 收款账户已下发
    */
@@ -1262,9 +1226,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
-
-
   /**
    * 付款成功
    */
@@ -1282,9 +1243,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
-
-
   /**
    * 付款失败
    */
@@ -1302,9 +1260,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
-
-
   /**
    * 付款银行退回
    */
@@ -1322,8 +1277,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
-
   /**
    * 转账成功
    */
@@ -1341,7 +1294,6 @@ export class OpenApiController extends BaseController {
     return await this.easyPayAdapter.request(method, path, params);
   }
 
-
   /**
    * 转账失败
    */

+ 25 - 0
src/modules/api/entity/open_payment_account.ts

@@ -0,0 +1,25 @@
+import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
+import { BaseEntity } from '@cool-midway/core';
+
+/**
+ * 收款账户
+ */
+@Entity('open_payment_account')
+export class OpenPaymentAccountEntity extends BaseEntity {
+    /* 
+        申请收款账户
+        查询申请列表
+        查询收款账户列表
+    */
+    @Column({ length: 100, comment: '商户编号', default: '' })
+    mch_id: string;
+
+    @Column({ length: 100, comment: '用户编号', default: '' })
+    account_id?: string;
+    
+    @Column({ length: 100, comment: '收款账户', default: '' })
+    payment_account_id?: string;
+
+    @Column({ length: 100, comment: '客户来源', default: '' })
+    source?: string;
+}

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

@@ -0,0 +1,78 @@
+import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
+import { BaseEntity } from '@cool-midway/core';
+
+/**
+ * 订单管理
+ */
+@Entity('open_payment_order')
+export class OpenPaymentOrderEntity extends BaseEntity {
+  /*
+   * 申请收款账户
+   * 查询申请列表
+   * 查询收款账户列表
+   */
+
+  @Column({ length: 100, comment: '商户编号', default: '' })
+  mch_id: string;
+
+  @Column({ length: 100, comment: '用户编号', default: '' })
+  account_id?: string;
+
+  @Column({ length: 100, comment: '转出账户', default: '' })
+  from_account_id?: string;
+
+  @Column({ length: 100, comment: '转入账户', default: '' })
+  to_account_id?: string;
+
+  @Column({ length: 100, comment: '订单编号', default: '' })
+  request_id?: string;
+
+  @Column({ length: 100, comment: '数据编号', default: '' })
+  event_id?: string;
+
+  @Column({ length: 100, comment: '币种', default: '' })
+  currency?: string;
+
+  @Column({ comment: '金额', type: 'decimal', precision: 20, scale: 6 })
+  amount?: number;
+
+  @Column({ length: 100, comment: '目标币种', default: '' })
+  target_currency?: string;
+
+  @Column({ comment: '目标金额', type: 'decimal', precision: 20, scale: 6 })
+  target_amount?: number;
+
+  @Column({ length: 100, comment: 'credit or debit', default: '' })
+  type?: string;
+
+  @Column({ length: 100, comment: '订单类型', default: '' })
+  order_type?: OrderType; // 使用枚举类型
+
+  @Column({ length: 100, comment: '支付类型', default: '' })
+  payment_type?: string; // 使用枚举类型
+
+  @Column({ type: 'json', comment: '扩展信息' }) // 定义为 JSON 类型
+  additional_info?: any;
+
+  @Column({ length: 100, comment: '订单编号', default: '' })
+  order_id?: string;
+
+  @Column({ length: 100, comment: '订单状态', default: '' })
+  status?: string;
+
+  @Column({ length: 100, comment: '客户来源', default: '' })
+  source?: string;
+
+  @Column({ comment: '更新次数', default: 0 })
+  update_count: number;
+}
+
+// 定义枚举类型
+export enum OrderType {
+  CURRENCY_EXCHANGE = 'CURRENCY_EXCHANGE', // 换汇
+  ACQUIRING_PAYMENT = 'ACQUIRING_PAYMENT', // 收单支付订单
+  ACQUIRING_REFUND = 'ACQUIRING_REFUND', // 收单退款订单
+  PAYMENT = 'PAYMENT', // 付款
+  TRANSFER = 'TRANSFER', // 转账
+  DEPOSIT = 'DEPOSIT', // 入账
+}

+ 22 - 0
src/modules/api/entity/open_user.ts

@@ -0,0 +1,22 @@
+import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
+import { BaseEntity } from '@cool-midway/core';
+
+/**
+ * 开放订单主体
+ */
+@Entity('open_user')
+export class OpenUserEntity extends BaseEntity {
+    /* 
+        申请收款账户
+        查询申请列表
+        查询收款账户列表
+    */
+    @Column({ length: 100, comment: '商户编号', default: '' })
+    mch_id: string;
+
+    @Column({ length: 100, comment: '用户编号', default: '' })
+    account_id?: string;
+
+    @Column({ length: 100, comment: '客户来源', default: '' })
+    source?: string;
+}

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

@@ -41,10 +41,10 @@ export class BaseAuthorityMiddleware
 
   resolve() {
     return async (ctx: Context, next: NextFunction) => {
-      // if (ctx.url.includes('/api/open/')) {
-      //   await next();
-      //   return;
-      // }
+      if (ctx.url.includes('/api/open/sign')) {
+        await next();
+        return;
+      }
       // 签名校验
       let { header } = ctx;
       const {
@@ -54,13 +54,13 @@ export class BaseAuthorityMiddleware
         'fusionpay-sign': vaSign = '',
       } = header;
 
-      if(!vaKey || !vaTimestamp || !vaNonce || !vaSign) {
+      if (!vaKey || !vaTimestamp || !vaNonce || !vaSign) {
         ctx.status = 401;
         ctx.body = {
           code: ctx.status,
           message: '当前认证信息不存在,请确认之后重新发送',
         };
-        return
+        return;
       }
 
       const params =

+ 254 - 0
src/modules/api/service/open.ts

@@ -0,0 +1,254 @@
+import { BaseService, CoolTransaction } from '@cool-midway/core';
+import { ILogger, Inject, Provide } from '@midwayjs/core';
+import { InjectEntityModel } from '@midwayjs/typeorm';
+import { OpenUserEntity } from '../entity/open_user';
+import * as crypto from 'crypto';
+import { In, LessThan, QueryRunner, Repository } from 'typeorm';
+import {
+  OpenPaymentOrderEntity,
+  OrderType,
+} from '../entity/open_payment_order';
+import { OpenPaymentAccountEntity } from '../entity/open_payment_account';
+import { EasyPayAdapter } from '../../payment/adapter/easypay.adapter';
+
+/**
+ * 描述
+ */
+@Provide()
+export class EasyOpenService extends BaseService {
+  @InjectEntityModel(OpenUserEntity)
+  openUserEntity: Repository<OpenUserEntity>;
+
+  @InjectEntityModel(OpenPaymentOrderEntity)
+  openPaymentOrderEntity: Repository<OpenPaymentOrderEntity>;
+
+  @InjectEntityModel(OpenPaymentAccountEntity)
+  openPaymentAccountEntity: Repository<OpenPaymentAccountEntity>;
+
+  @Inject()
+  logger: ILogger;
+
+  @Inject()
+  easyPayAdapter: EasyPayAdapter;
+
+  @Inject()
+  ctx;
+
+  /* 
+    记录用户的数据来源
+    */
+  async save_user(userInfo, params) {
+    try {
+      const openUserObj = {
+        mch_id: this.ctx.admin.merchant.mchId,
+        account_id: userInfo.data.id,
+        source: 'EASYPAY',
+      };
+      await this.openUserEntity.insert(openUserObj);
+      this.logger.info(
+        `save_user 商户: ${this.ctx.admin.merchant.mchId}; userInfo${JSON.stringify(userInfo)} params${JSON.stringify(params)}`
+      );
+    } catch (error) {
+      this.logger.error('save_user:error: ', error);
+    }
+  }
+
+  /* 
+    记录用户的收款账户数据来源
+    */
+  async save_user_account(userInfo, params) {
+    try {
+      const openUserObj = {
+        mch_id: this.ctx.admin.merchant.mchId,
+        account_id: params.account_id,
+        payment_account_id: userInfo.data.id,
+        source: 'EASYPAY',
+      };
+      await this.openPaymentAccountEntity.insert(openUserObj);
+      this.logger.info(
+        `save_user_account 商户: ${this.ctx.admin.merchant.mchId}; userInfo${JSON.stringify(userInfo)} params${JSON.stringify(params)}`
+      );
+    } catch (error) {
+      this.logger.error('save_user_account:error: ', error);
+    }
+  }
+
+  /* 
+    记录用户的订单数据来源
+  */
+  async save_user_order(orderInfo, params, type: OrderType) {
+    try {
+      let openOrderObj: any = {
+        mch_id: this.ctx.admin.merchant.mchId,
+        account_id: params.account_id,
+        request_id: params.payment.request_id,
+        order_type: type,
+        additional_info: {
+          orderInfo,
+          params,
+          type,
+        },
+      };
+
+      // 收单支付订单
+      if (OrderType.ACQUIRING_PAYMENT === type) {
+        openOrderObj.amount = params.payment.amount;
+        openOrderObj.currency = params.payment.currency;
+      }
+
+      // 收单退款订单
+      if (OrderType.ACQUIRING_REFUND === type) {
+        openOrderObj.amount = params.refund.amount;
+        openOrderObj.currency = params.refund.currency;
+      }
+
+      // 换汇
+      if (OrderType.CURRENCY_EXCHANGE === type) {
+        openOrderObj.amount = params.sell_amount; // 卖出金额
+        openOrderObj.currency = params.sell_currency; // 卖出币种
+
+        openOrderObj.target_amount = params.buy_amount; // 买入金额
+        openOrderObj.target_currency = params.buy_currency; // 买入币种
+      }
+
+      // 付款
+      if (OrderType.PAYMENT === type) {
+        openOrderObj.amount = params.amount;
+        openOrderObj.currency = params.currency;
+      }
+
+      // 转账
+      if (OrderType.TRANSFER === type) {
+        openOrderObj.amount = params.amount;
+        openOrderObj.currency = params.currency;
+        openOrderObj.from_account_id = params.from_account_id;
+        openOrderObj.to_account_id = params.to_account_id;
+      }
+
+      // // 入账
+      // if (OrderType.DEPOSIT === type) {
+      //   openOrderObj.amount = params.payment.amount;
+      //   openOrderObj.currency = params.payment.currency;
+      // }
+
+      await this.openPaymentOrderEntity.insert(openOrderObj);
+
+      /* 更新相关订单信息 */
+
+      // 退款事件处理
+      if (OrderType.ACQUIRING_REFUND === type) {
+        const paymentOrder: any = {};
+        if (params.hasOwnProperty('payment_id')) {
+          paymentOrder.event_id = params.payment_id;
+        }
+        if (params.hasOwnProperty('payment_request_id')) {
+          paymentOrder.request_id = params.payment_request_id;
+        }
+        openOrderObj.currency = params.payment.currency;
+        await this.openPaymentOrderEntity.update(paymentOrder, {
+          status: 'REFUNDED',
+        });
+      }
+      this.logger.info(
+        `save_user_order 商户: ${this.ctx.admin.merchant.mchId}; userInfo${JSON.stringify(orderInfo)} params${JSON.stringify(params)}`
+      );
+    } catch (error) {
+      this.logger.error('save_user_order:error: ', error);
+    }
+  }
+
+  createSign(params, timestamp, nonce, secret) {
+    // 2. 生成签名
+    const sign = this.generateSignature(
+      `${timestamp}`,
+      `${nonce}`,
+      JSON.stringify(params),
+      `${secret}`
+    );
+    return sign;
+  }
+  /**
+   * 生成签名
+   * @see https://docs-merchant.sunpay.pro/guide
+   */
+  generateSignature(timestamp, nonce, body = '', secret = '') {
+    const payload = `${timestamp}${nonce}${body}`;
+    const signature = crypto
+      .createHmac('sha256', secret)
+      .update(payload)
+      .digest('hex')
+      .toUpperCase();
+    return signature;
+  }
+
+  /**
+   * 处理未完成的订单
+   */
+  @CoolTransaction({ isolation: 'SERIALIZABLE' })
+  async handleUnfinishedOrder(params, queryRunner?: QueryRunner) {
+    const orders = await this.openPaymentOrderEntity.find({
+      where: {
+        status: '',
+        // 1小时未完成的订单
+        createTime: LessThan(new Date(Date.now() - 1 * 60 * 60 * 1000)),
+      },
+    });
+    this.logger.info(`处理未完成的订单:${orders.length}`);
+    try {
+      for (const order of orders) {
+        const status = await this.thawed(order, queryRunner);
+        order.status = status;
+        await this.openPaymentOrderEntity.update(order.id, order);
+      }
+    } catch (err) {
+      this.logger.error(784, err);
+    }
+  }
+  /*
+   */
+  async thawed(order, queryRunner) {
+    // 收单支付订单
+    if (OrderType.ACQUIRING_PAYMENT === order.type) {
+      const res = await this.easyPayAdapter.request(
+        'GET',
+        `/v3/acgiinqru/payments/${order.event_id}`
+      );
+      return res.data.status;
+    }
+    // 收单退款订单
+    if (OrderType.ACQUIRING_REFUND === order.type) {
+      const res = await this.easyPayAdapter.request(
+        'GET',
+        `/v3/acquiring/refunds/${order.event_id}`
+      );
+      return res.data.status;
+    }
+
+    // 换汇
+    if (OrderType.CURRENCY_EXCHANGE === order.type) {
+      const res = await this.easyPayAdapter.request(
+        'GET',
+        `/v1/exchanges/${order.event_id}`
+      );
+      return res.data.status;
+    }
+
+    // 付款
+    if (OrderType.PAYMENT === order.type) {
+      const res = await this.easyPayAdapter.request(
+        'GET',
+        `/v1/payments/${order.event_id}`
+      );
+      return res.data.status;
+    }
+
+    // 转账
+    if (OrderType.TRANSFER === order.type) {
+      const res = await this.easyPayAdapter.request(
+        'GET',
+        `/v1/transfers/${order.event_id}`
+      );
+      return res.data.status;
+    }
+  }
+}

+ 32 - 20
src/modules/payment/adapter/easypay.adapter.ts

@@ -6,14 +6,15 @@ 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 // 令牌过期时间
+  authUrl = ''; // 认证URL
+  clientId = ''; // 客户端ID
+  clientSecret = ''; // 客户端密钥
+  refreshToken = null; // 刷新令牌
+  accessToken = null; // 访问令牌
+  expiresIn = 0; // 令牌过期时间
 
   constructor(authUrl, clientId, clientSecret) {
     this.authUrl = authUrl; // 初始化认证URL
@@ -30,12 +31,12 @@ class TokenManager {
       const dataString = qs.stringify({
         client_id: this.clientId, // 传递客户端ID
         client_secret: this.clientSecret, // 传递客户端密钥
-        grant_type: 'client_credentials' // 假设使用密码授权类型进行初始登录
+        grant_type: 'client_credentials', // 假设使用密码授权类型进行初始登录
       });
       const config = {
         method: 'post',
         url: this.authUrl,
-        data: dataString
+        data: dataString,
       };
       const response = await axios(config);
 
@@ -67,7 +68,7 @@ class TokenManager {
         client_id: this.clientId, // 传递客户端ID
         client_secret: this.clientSecret, // 传递客户端密钥
         refresh_token: this.refreshToken, // 传递刷新令牌
-        grant_type: 'refresh_token' // 使用刷新令牌授权类型
+        grant_type: 'refresh_token', // 使用刷新令牌授权类型
       });
 
       const data = response.data;
@@ -91,6 +92,10 @@ export class EasyPayAdapter {
   globalConfig;
   @Inject()
   ctx;
+
+  @Inject()
+  logger: ILogger;
+
   private config: {
     apiKey: string;
     apiSecret: string;
@@ -112,8 +117,12 @@ export class EasyPayAdapter {
       if (!channel) {
         throw new Error('FusionPay channel not found or disabled');
       }
-      const tokenManager = new TokenManager(`${channel.apiUrl}/auth`, channel.apiKey, channel.apiSecret)
-      await tokenManager.login()
+      const tokenManager = new TokenManager(
+        `${channel.apiUrl}/auth`,
+        channel.apiKey,
+        channel.apiSecret
+      );
+      await tokenManager.login();
       this.config = {
         apiKey: channel.apiKey,
         apiSecret: channel.apiSecret,
@@ -121,7 +130,7 @@ export class EasyPayAdapter {
         chainApiKey: channel.chainApiKey,
         chainApiSecret: channel.chainApiSecret,
         chainApiUrl: channel.chainApiUrl,
-        tokenManager: tokenManager
+        tokenManager: tokenManager,
       };
     }
   }
@@ -132,20 +141,22 @@ 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;
+    let url = this.config.apiUrl;
     try {
       url = `${url}${endpoint.replace('/api/open', '')}`;
       const accessToken = await this.config.tokenManager.getAccessToken();
-      const response = await axios({
+      const axiosParams = {
         method,
         url,
         data: method !== 'GET' ? data : undefined,
         params: method === 'GET' ? data : undefined,
         headers: {
           'Content-Type': 'application/json',
-          'Authorization': `Bearer ${accessToken}`,
+          Authorization: `Bearer ${accessToken}`,
         },
-      });
+      };
+      this.logger.info('向easyPay发送请求', axiosParams);
+      const response = await axios(axiosParams);
       // 检查响应
       // if (response.data.code !== 200) {
       //   console.log(response.data);
@@ -154,6 +165,7 @@ export class EasyPayAdapter {
       // console.log('response', response.data.data);
       return response.data.data;
     } catch (error) {
+      
       // console.log(error.response.data);
       if (axios.isAxiosError(error) && error.response) {
         // console.log(error.response.data);
@@ -161,6 +173,7 @@ export class EasyPayAdapter {
         this.ctx.status = error.response.status; // 服务器错误
         // this.ctx.body = error.response.data;
         // return this.res.status(500).json({});
+        this.logger.info('向easyPay发送请求失败了', error.response);
         return error.response.data;
         // throw this.ctx.body;
       }
@@ -173,9 +186,8 @@ export class EasyPayAdapter {
     const res = await axios.post(`${this.config.apiUrl}/auth`, {
       client_id: 'client_id',
       client_secret: this.config.apiSecret,
-      grant_type: 'client_credentials'
-    })
-    return ''
+      grant_type: 'client_credentials',
+    });
+    return '';
   }
-
 }

+ 5 - 0
src/modules/payment/job/order.ts

@@ -1,6 +1,7 @@
 import { Job, IJob } from '@midwayjs/cron';
 import { FORMAT, ILogger, Inject } from '@midwayjs/core';
 import { OrderService } from '../service/order';
+import { EasyOpenService } from '../../api/service/open';
 
 /**
  * 日志定时任务
@@ -12,6 +13,9 @@ import { OrderService } from '../service/order';
 export class OrderJob implements IJob {
   @Inject()
   orderService: OrderService;
+  
+  @Inject()
+  openOrderService: EasyOpenService;
 
   @Inject()
   logger: ILogger;
@@ -21,6 +25,7 @@ export class OrderJob implements IJob {
     this.logger.info('处理未完成的订单定时任务开始执行');
     const startTime = Date.now();
     await this.orderService.handleUnfinishedOrder({});
+    await this.openOrderService.handleUnfinishedOrder({});
     this.logger.info(
       `处理未完成的订单定时任务结束,耗时:${Date.now() - startTime}ms`
     );