@ngn-net/payment-provider-sdk 1.0.10 → 1.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -32,11 +32,12 @@ export declare const PaymentRabbitApi: {
32
32
  crypto_intent: {
33
33
  key: string;
34
34
  };
35
- crypto_webhook: {
35
+ available_methods: {
36
36
  key: string;
37
37
  };
38
38
  };
39
39
  };
40
+ export declare function paymentEventRoutingKey(serviceName: string): string;
40
41
  export interface CreateStripeCheckoutResponse {
41
42
  id: string;
42
43
  checkoutId: string;
@@ -69,15 +70,8 @@ export interface CreateCryptoIntentResponse {
69
70
  status: PaymentIntentStatus;
70
71
  orderId: string;
71
72
  }
72
- interface EventDataMap {
73
- stripe_succeeded: StripePaymentCompleteEvent;
74
- }
75
- export type StripeEvent<T extends keyof EventDataMap = keyof EventDataMap> = {
76
- id: string;
77
- type: T;
78
- data: EventDataMap[T];
79
- };
80
- export interface RPCResponse<T> {
73
+ export interface EventResponse<T> {
74
+ correlationId: string;
81
75
  code: number;
82
76
  message: string;
83
77
  data: T;
@@ -90,13 +84,21 @@ export interface NPCompleteEvent {
90
84
  amount: number;
91
85
  amountReceived: number;
92
86
  }
93
- interface EventDataMap {
87
+ export interface EventDataMap {
94
88
  stripe_succeeded: StripePaymentCompleteEvent;
95
89
  nowPayment_succeeded: NPCompleteEvent;
96
90
  }
97
91
  export type PaymentEvent<T extends keyof EventDataMap = keyof EventDataMap> = {
98
92
  id: string;
99
93
  type: T;
94
+ serviceName?: string;
95
+ correlationId?: string;
96
+ signature?: string;
100
97
  data: EventDataMap[T];
101
98
  };
102
- export {};
99
+ export interface PaymentResolveResponse<T = unknown> {
100
+ code: number;
101
+ message: string;
102
+ correlationId?: string;
103
+ data?: T;
104
+ }
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PaymentRabbitApi = exports.rabbitUri = exports.RABBIT_URI = void 0;
4
+ exports.paymentEventRoutingKey = paymentEventRoutingKey;
4
5
  const RABBIT_URI = () => {
5
6
  const rabbitUri = process.env.RABBIT_URI || "amqp://user:pass@localhost:5672";
6
7
  const [creadential, hosts] = rabbitUri.split("@");
@@ -30,8 +31,14 @@ exports.PaymentRabbitApi = {
30
31
  crypto_intent: {
31
32
  key: "cryptoIntent",
32
33
  },
33
- crypto_webhook: {
34
- key: "cryptoWebhook",
34
+ available_methods: {
35
+ key: "availableMethods",
35
36
  },
36
37
  },
37
38
  };
39
+ /// Events for a given service are published on a dedicated routing key so
40
+ /// that a service only receives events that belong to it (bindings must
41
+ /// be per-service; wildcard bindings across services are NOT supported).
42
+ function paymentEventRoutingKey(serviceName) {
43
+ return `paymentEvents.${serviceName || "default"}`;
44
+ }
@@ -3,4 +3,7 @@ export declare class CreateCryptoPaymentDto {
3
3
  orderId: string;
4
4
  amount: number;
5
5
  currency: PayCurrency;
6
+ description?: string;
7
+ includeFe?: boolean;
8
+ isFixedRate?: boolean;
6
9
  }
@@ -35,3 +35,21 @@ __decorate([
35
35
  (0, class_validator_1.IsEnum)(crypto_entity_1.PayCurrency),
36
36
  __metadata("design:type", String)
37
37
  ], CreateCryptoPaymentDto.prototype, "currency", void 0);
38
+ __decorate([
39
+ (0, swagger_1.ApiPropertyOptional)({ example: "giftcard order" }),
40
+ (0, class_validator_1.IsOptional)(),
41
+ (0, class_validator_1.IsString)(),
42
+ __metadata("design:type", String)
43
+ ], CreateCryptoPaymentDto.prototype, "description", void 0);
44
+ __decorate([
45
+ (0, swagger_1.ApiPropertyOptional)({ default: true }),
46
+ (0, class_validator_1.IsOptional)(),
47
+ (0, class_validator_1.IsBoolean)(),
48
+ __metadata("design:type", Boolean)
49
+ ], CreateCryptoPaymentDto.prototype, "includeFe", void 0);
50
+ __decorate([
51
+ (0, swagger_1.ApiPropertyOptional)({ default: true }),
52
+ (0, class_validator_1.IsOptional)(),
53
+ (0, class_validator_1.IsBoolean)(),
54
+ __metadata("design:type", Boolean)
55
+ ], CreateCryptoPaymentDto.prototype, "isFixedRate", void 0);
@@ -2,6 +2,8 @@ export declare class CreateStripeCheckoutDto {
2
2
  amount: number;
3
3
  orderId: string;
4
4
  productName: string;
5
+ success_url: string;
6
+ cancel_url: string;
5
7
  }
6
8
  export declare class CreateStripePaymentIntentDto {
7
9
  amount: number;
@@ -34,6 +34,18 @@ __decorate([
34
34
  (0, class_validator_1.IsString)(),
35
35
  __metadata("design:type", String)
36
36
  ], CreateStripeCheckoutDto.prototype, "productName", void 0);
37
+ __decorate([
38
+ (0, swagger_1.ApiProperty)(),
39
+ (0, class_validator_1.IsNotEmpty)(),
40
+ (0, class_validator_1.IsString)(),
41
+ __metadata("design:type", String)
42
+ ], CreateStripeCheckoutDto.prototype, "success_url", void 0);
43
+ __decorate([
44
+ (0, swagger_1.ApiProperty)(),
45
+ (0, class_validator_1.IsNotEmpty)(),
46
+ (0, class_validator_1.IsString)(),
47
+ __metadata("design:type", String)
48
+ ], CreateStripeCheckoutDto.prototype, "cancel_url", void 0);
37
49
  class CreateStripePaymentIntentDto {
38
50
  }
39
51
  exports.CreateStripePaymentIntentDto = CreateStripePaymentIntentDto;
@@ -15,7 +15,8 @@ export declare enum PaymentIntentStatus {
15
15
  CONFIRMING = "CONFIRMING",
16
16
  CONFIRMED = "CONFIRMED",
17
17
  FAILED = "FAILED",
18
- EXPIRED = "EXPIRED"
18
+ EXPIRED = "EXPIRED",
19
+ REFUNDED = "REFUNDED"
19
20
  }
20
21
  export declare class CryptoIntent {
21
22
  amountInFiat: number;
@@ -22,6 +22,7 @@ var PaymentIntentStatus;
22
22
  PaymentIntentStatus["CONFIRMED"] = "CONFIRMED";
23
23
  PaymentIntentStatus["FAILED"] = "FAILED";
24
24
  PaymentIntentStatus["EXPIRED"] = "EXPIRED";
25
+ PaymentIntentStatus["REFUNDED"] = "REFUNDED";
25
26
  })(PaymentIntentStatus || (exports.PaymentIntentStatus = PaymentIntentStatus = {}));
26
27
  class CryptoIntent {
27
28
  }
package/dist/main.d.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  export * from "./payment.module";
2
2
  export * from "./payment.provider";
3
+ export * from "./payment.webhook";
4
+ export * from "./payment.signature";
3
5
  export * from "./dto/crypto.dto";
4
6
  export * from "./dto/stripe.dto";
5
7
  export * from "./dto/common.interface";
8
+ export * from "./dto/nowPayment.response";
6
9
  export * from "./entity/crypto.entity";
package/dist/main.js CHANGED
@@ -16,7 +16,10 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./payment.module"), exports);
18
18
  __exportStar(require("./payment.provider"), exports);
19
+ __exportStar(require("./payment.webhook"), exports);
20
+ __exportStar(require("./payment.signature"), exports);
19
21
  __exportStar(require("./dto/crypto.dto"), exports);
20
22
  __exportStar(require("./dto/stripe.dto"), exports);
21
23
  __exportStar(require("./dto/common.interface"), exports);
24
+ __exportStar(require("./dto/nowPayment.response"), exports);
22
25
  __exportStar(require("./entity/crypto.entity"), exports);
@@ -1,7 +1,11 @@
1
1
  import { DynamicModule } from "@nestjs/common";
2
2
  export interface PaymentModuleOptions {
3
3
  uri: string | string[];
4
+ serviceName: string;
5
+ secret: string;
4
6
  }
7
+ export declare const PAYMENT_PROVIDER_OPTIONS = "PAYMENT_PROVIDER_OPTIONS";
8
+ export declare const PAYMENT_WEBHOOK_OPTIONS = "PAYMENT_WEBHOOK_OPTIONS";
5
9
  export declare class PaymentModule {
6
10
  static forRoot(options: PaymentModuleOptions): DynamicModule;
7
11
  }
@@ -7,13 +7,30 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  };
8
8
  var PaymentModule_1;
9
9
  Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.PaymentModule = void 0;
10
+ exports.PaymentModule = exports.PAYMENT_WEBHOOK_OPTIONS = exports.PAYMENT_PROVIDER_OPTIONS = void 0;
11
11
  const common_1 = require("@nestjs/common");
12
12
  const nestjs_rabbitmq_1 = require("@golevelup/nestjs-rabbitmq");
13
13
  const payment_provider_1 = require("./payment.provider");
14
+ const payment_webhook_1 = require("./payment.webhook");
14
15
  const common_interface_1 = require("./dto/common.interface");
16
+ exports.PAYMENT_PROVIDER_OPTIONS = "PAYMENT_PROVIDER_OPTIONS";
17
+ exports.PAYMENT_WEBHOOK_OPTIONS = "PAYMENT_WEBHOOK_OPTIONS";
15
18
  let PaymentModule = PaymentModule_1 = class PaymentModule {
16
19
  static forRoot(options) {
20
+ const providerOptions = {
21
+ provide: exports.PAYMENT_PROVIDER_OPTIONS,
22
+ useValue: {
23
+ serviceName: options.serviceName,
24
+ secret: options.secret,
25
+ },
26
+ };
27
+ const webhookOptions = {
28
+ provide: exports.PAYMENT_WEBHOOK_OPTIONS,
29
+ useValue: {
30
+ serviceName: options.serviceName,
31
+ secret: options.secret,
32
+ },
33
+ };
17
34
  return {
18
35
  module: PaymentModule_1,
19
36
  imports: [
@@ -34,8 +51,13 @@ let PaymentModule = PaymentModule_1 = class PaymentModule {
34
51
  },
35
52
  }),
36
53
  ],
37
- providers: [payment_provider_1.PaymentProvider],
38
- exports: [payment_provider_1.PaymentProvider],
54
+ providers: [
55
+ providerOptions,
56
+ webhookOptions,
57
+ payment_provider_1.PaymentProvider,
58
+ payment_webhook_1.PaymentWebhookService,
59
+ ],
60
+ exports: [payment_provider_1.PaymentProvider, payment_webhook_1.PaymentWebhookService],
39
61
  };
40
62
  }
41
63
  };
@@ -1,14 +1,12 @@
1
1
  import { CreateStripeCheckoutDto, CreateStripePaymentIntentDto } from "./dto/stripe.dto";
2
2
  import { AmqpConnection } from "@golevelup/nestjs-rabbitmq";
3
- import { CreateCryptoIntentResponse, CreateStripeCheckoutResponse, CreateStripePaymentIntentResponse, PaymentEvent } from "./dto/common.interface";
3
+ import { CreateCryptoIntentResponse, CreateStripeCheckoutResponse, CreateStripePaymentIntentResponse } from "./dto/common.interface";
4
4
  import { CreateCryptoPaymentDto } from "./dto/crypto.dto";
5
- import { NowPaymentsPaymentCallback } from "./dto/nowPayment.response";
6
5
  export declare class PaymentProvider {
7
6
  private readonly rabbit;
8
7
  constructor(rabbit: AmqpConnection);
9
8
  createStripeCheckout(payload: CreateStripeCheckoutDto): Promise<CreateStripeCheckoutResponse>;
10
9
  createStripePaymentIntent(payload: CreateStripePaymentIntentDto): Promise<CreateStripePaymentIntentResponse>;
11
10
  createCryptoPayment(payload: CreateCryptoPaymentDto): Promise<CreateCryptoIntentResponse>;
12
- resolveCryptoPayment(payload: NowPaymentsPaymentCallback): Promise<CreateCryptoIntentResponse>;
13
- emitPaymentEvent(event: PaymentEvent): Promise<void>;
11
+ availableMethods<T = unknown>(): Promise<T>;
14
12
  }
@@ -51,20 +51,17 @@ let PaymentProvider = class PaymentProvider {
51
51
  }
52
52
  return res.data;
53
53
  }
54
- async resolveCryptoPayment(payload) {
54
+ async availableMethods() {
55
55
  const res = await this.rabbit.request({
56
56
  exchange: common_interface_1.PaymentRabbitApi.exchange,
57
- routingKey: common_interface_1.PaymentRabbitApi.routingkeys.crypto_webhook.key,
58
- payload,
57
+ routingKey: common_interface_1.PaymentRabbitApi.routingkeys.available_methods.key,
58
+ payload: {},
59
59
  });
60
60
  if (res.code !== 200) {
61
61
  throw new Error(res.message);
62
62
  }
63
63
  return res.data;
64
64
  }
65
- async emitPaymentEvent(event) {
66
- await this.rabbit.publish(common_interface_1.PaymentRabbitApi.exchange, common_interface_1.PaymentRabbitApi.routingkeys.events.key, event);
67
- }
68
65
  };
69
66
  exports.PaymentProvider = PaymentProvider;
70
67
  exports.PaymentProvider = PaymentProvider = __decorate([
@@ -0,0 +1,10 @@
1
+ /** Stable canonical JSON: object keys are sorted recursively so that two
2
+ * semantically-identical payloads produce the same signature. Mirrored
3
+ * byte-for-byte from the gateway's `client-signature.ts`. */
4
+ export declare function canonicalJson(value: unknown): string;
5
+ /** HMAC-SHA256 over the canonical payload (+ optional correlation id).
6
+ * Must match the gateway's `signPayload` exactly. */
7
+ export declare function signPayload(secret: string, data: unknown, correlationId?: string): string;
8
+ /** Verify an HMAC-SHA256 signature over `data` (+ correlation id).
9
+ * Timingsafe comparison — constant time, resistant to timing attacks. */
10
+ export declare function verifyPayloadSignature(secret: string, data: unknown, signature: string, correlationId?: string): boolean;
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.canonicalJson = canonicalJson;
4
+ exports.signPayload = signPayload;
5
+ exports.verifyPayloadSignature = verifyPayloadSignature;
6
+ const crypto_1 = require("crypto");
7
+ /** Stable canonical JSON: object keys are sorted recursively so that two
8
+ * semantically-identical payloads produce the same signature. Mirrored
9
+ * byte-for-byte from the gateway's `client-signature.ts`. */
10
+ function canonicalJson(value) {
11
+ if (Array.isArray(value)) {
12
+ return `[${value.map(canonicalJson).join(",")}]`;
13
+ }
14
+ if (value && typeof value === "object") {
15
+ const entries = Object.entries(value)
16
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
17
+ .map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`);
18
+ return `{${entries.join(",")}}`;
19
+ }
20
+ return JSON.stringify(value);
21
+ }
22
+ /** HMAC-SHA256 over the canonical payload (+ optional correlation id).
23
+ * Must match the gateway's `signPayload` exactly. */
24
+ function signPayload(secret, data, correlationId) {
25
+ const canonical = `payload=${canonicalJson(data)};correlationId=${correlationId ?? ""}`;
26
+ return (0, crypto_1.createHmac)("sha256", secret).update(canonical).digest("hex");
27
+ }
28
+ /** Verify an HMAC-SHA256 signature over `data` (+ correlation id).
29
+ * Timingsafe comparison — constant time, resistant to timing attacks. */
30
+ function verifyPayloadSignature(secret, data, signature, correlationId) {
31
+ if (!signature)
32
+ return false;
33
+ const expected = signPayload(secret, data, correlationId);
34
+ try {
35
+ return (0, crypto_1.timingSafeEqual)(Buffer.from(expected, "hex"), Buffer.from(signature, "hex"));
36
+ }
37
+ catch {
38
+ return false;
39
+ }
40
+ }
@@ -0,0 +1,22 @@
1
+ import { AmqpConnection } from "@golevelup/nestjs-rabbitmq";
2
+ import { EventDataMap, PaymentEvent } from "./dto/common.interface";
3
+ export interface WebhookOptions {
4
+ serviceName: string;
5
+ secret: string;
6
+ }
7
+ export type PaymentEventHandler<T extends keyof EventDataMap = keyof EventDataMap> = (data: EventDataMap[T], meta: {
8
+ event: PaymentEvent<T>;
9
+ verified: boolean;
10
+ correlationId?: string;
11
+ }) => Promise<void> | void;
12
+ export declare const WEBHOOK_ROUTING_KEY: () => string;
13
+ export declare class PaymentWebhookService {
14
+ private readonly rabbit;
15
+ private readonly logger;
16
+ private readonly serviceName;
17
+ private readonly secret;
18
+ private readonly handlers;
19
+ constructor(options: WebhookOptions, rabbit: AmqpConnection);
20
+ on<T extends keyof EventDataMap>(type: T, handler: PaymentEventHandler<T>): this;
21
+ handleEvent(event: PaymentEvent): Promise<void>;
22
+ }
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ var PaymentWebhookService_1;
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.PaymentWebhookService = exports.WEBHOOK_ROUTING_KEY = void 0;
17
+ const common_1 = require("@nestjs/common");
18
+ const nestjs_rabbitmq_1 = require("@golevelup/nestjs-rabbitmq");
19
+ const common_interface_1 = require("./dto/common.interface");
20
+ const payment_signature_1 = require("./payment.signature");
21
+ /// The binding key must be known at decorator-evaluation time (module
22
+ /// load) — `this.serviceName` is not available there. Derived from the
23
+ /// same env the gateway uses to route per-service events.
24
+ const WEBHOOK_ROUTING_KEY = () => `paymentEvents.${process.env.PAYMENT_CLIENT_NAME?.trim() || "default"}`;
25
+ exports.WEBHOOK_ROUTING_KEY = WEBHOOK_ROUTING_KEY;
26
+ let PaymentWebhookService = PaymentWebhookService_1 = class PaymentWebhookService {
27
+ constructor(options, rabbit) {
28
+ this.rabbit = rabbit;
29
+ this.logger = new common_1.Logger(PaymentWebhookService_1.name);
30
+ this.handlers = new Map();
31
+ this.serviceName = options.serviceName;
32
+ this.secret = options.secret;
33
+ }
34
+ /// Register a handler for an event type. Chainable.
35
+ on(type, handler) {
36
+ const set = this.handlers.get(type) ?? new Set();
37
+ set.add(handler);
38
+ this.handlers.set(type, set);
39
+ return this;
40
+ }
41
+ /// RabbitMQ subscription. The queue is bound to this service's own
42
+ /// routing key (`paymentEvents.<serviceName>`) so it only receives
43
+ /// events addressed to it.
44
+ async handleEvent(event) {
45
+ if (!event?.type || !event?.data)
46
+ return;
47
+ const verified = event.signature
48
+ ? (0, payment_signature_1.verifyPayloadSignature)(this.secret, event.data, event.signature, event.correlationId)
49
+ : false;
50
+ const handlers = this.handlers.get(event.type);
51
+ if (!handlers?.size) {
52
+ this.logger.debug(`no handler registered for ${String(event.type)}`);
53
+ return;
54
+ }
55
+ for (const fn of handlers) {
56
+ try {
57
+ await fn(event.data, {
58
+ event: event,
59
+ verified,
60
+ correlationId: event.correlationId,
61
+ });
62
+ }
63
+ catch (err) {
64
+ this.logger.error(`handler error for ${String(event.type)}: ${err instanceof Error ? err.message : String(err)}`);
65
+ }
66
+ }
67
+ }
68
+ };
69
+ exports.PaymentWebhookService = PaymentWebhookService;
70
+ __decorate([
71
+ (0, nestjs_rabbitmq_1.RabbitSubscribe)({
72
+ exchange: common_interface_1.PaymentRabbitApi.exchange,
73
+ routingKey: (0, exports.WEBHOOK_ROUTING_KEY)(),
74
+ queueOptions: {
75
+ durable: true,
76
+ autoDelete: false,
77
+ },
78
+ allowNonJsonMessages: true,
79
+ }),
80
+ __metadata("design:type", Function),
81
+ __metadata("design:paramtypes", [Object]),
82
+ __metadata("design:returntype", Promise)
83
+ ], PaymentWebhookService.prototype, "handleEvent", null);
84
+ exports.PaymentWebhookService = PaymentWebhookService = PaymentWebhookService_1 = __decorate([
85
+ (0, common_1.Injectable)(),
86
+ __param(0, (0, common_1.Inject)("PAYMENT_WEBHOOK_OPTIONS")),
87
+ __metadata("design:paramtypes", [Object, nestjs_rabbitmq_1.AmqpConnection])
88
+ ], PaymentWebhookService);
package/package.json CHANGED
@@ -1,12 +1,14 @@
1
1
  {
2
2
  "name": "@ngn-net/payment-provider-sdk",
3
- "version": "1.0.10",
3
+ "version": "1.0.12",
4
4
  "description": "Payment provider SDK",
5
5
  "main": "dist/main.js",
6
6
  "types": "dist/main.d.ts",
7
7
  "scripts": {
8
8
  "build": "tsc",
9
- "prepublishOnly": "npm run build"
9
+ "prepublishOnly": "npm run build",
10
+ "test": "jest",
11
+ "test:watch": "jest --watch"
10
12
  },
11
13
  "keywords": [],
12
14
  "author": "",
@@ -31,10 +33,13 @@
31
33
  "@nestjs/core": "^11.2.3",
32
34
  "@nestjs/swagger": "^11.4.7",
33
35
  "@types/amqplib": "^0.10.8",
36
+ "@types/jest": "^30.0.0",
34
37
  "@types/node": "^25.9.2",
35
38
  "amqplib": "^0.10.9",
39
+ "jest": "^30.5.1",
36
40
  "reflect-metadata": "^0.2.2",
37
41
  "rxjs": "^7.8.2",
42
+ "ts-jest": "^29.4.12",
38
43
  "typescript": "^6.0.3"
39
44
  }
40
45
  }