@ngn-net/payment-provider-sdk 1.0.11 → 1.0.13

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.
@@ -1,4 +1,3 @@
1
- import { FiatCurrency, PayCurrency, PaymentIntentStatus } from "../entity/crypto.entity";
2
1
  export declare const RABBIT_URI: () => string[];
3
2
  export declare const rabbitUri: string[];
4
3
  export interface RabbitAddress {
@@ -32,8 +31,66 @@ export declare const PaymentRabbitApi: {
32
31
  crypto_intent: {
33
32
  key: string;
34
33
  };
34
+ stripe_ship: {
35
+ key: string;
36
+ };
37
+ stripe_refund: {
38
+ key: string;
39
+ };
40
+ stripe_cancel: {
41
+ key: string;
42
+ };
43
+ payment_methods: {
44
+ key: string;
45
+ };
46
+ payment_methods_update: {
47
+ key: string;
48
+ };
49
+ intent_status: {
50
+ key: string;
51
+ };
52
+ available_methods: {
53
+ key: string;
54
+ };
35
55
  };
36
56
  };
57
+ export declare function paymentEventRoutingKey(serviceName: string): string;
58
+ export interface RpcClientContext {
59
+ serviceName: string;
60
+ signature: string;
61
+ correlationId?: string;
62
+ }
63
+ export interface RpcEnvelope<T = unknown> extends RpcClientContext {
64
+ data: T;
65
+ callbackRoutingKey?: string;
66
+ }
67
+ export interface GetIntentByOrderId {
68
+ orderId: string;
69
+ }
70
+ export interface UpdatePaymentMethodDto {
71
+ name: string;
72
+ enabled: boolean;
73
+ }
74
+ export interface OrderActionResponse {
75
+ orderId: string;
76
+ status: string;
77
+ }
78
+ export interface IntentStatusResult {
79
+ orderId: string;
80
+ status: string;
81
+ }
82
+ export interface MethodStatus {
83
+ enabled: boolean;
84
+ healthy: boolean;
85
+ status: boolean;
86
+ }
87
+ export interface AvailableMethodsResponse {
88
+ stripe: MethodStatus;
89
+ nowPayment: MethodStatus & {
90
+ currency: string[];
91
+ };
92
+ active: string[];
93
+ }
37
94
  export interface CreateStripeCheckoutResponse {
38
95
  id: string;
39
96
  checkoutId: string;
@@ -58,22 +115,10 @@ export interface StripePaymentCompleteEvent {
58
115
  export interface CreateCryptoIntentResponse {
59
116
  id: string;
60
117
  paymentId: string;
61
- amountInFiat: number;
62
- fiatCurrency: FiatCurrency;
63
- payCurrency: PayCurrency;
118
+ amount: number;
64
119
  payAdress: string;
65
120
  payAmount: number;
66
- status: PaymentIntentStatus;
67
- orderId: string;
68
121
  }
69
- interface EventDataMap {
70
- stripe_succeeded: StripePaymentCompleteEvent;
71
- }
72
- export type StripeEvent<T extends keyof EventDataMap = keyof EventDataMap> = {
73
- id: string;
74
- type: T;
75
- data: EventDataMap[T];
76
- };
77
122
  export interface EventResponse<T> {
78
123
  correlationId: string;
79
124
  code: number;
@@ -86,15 +131,23 @@ export interface NPCompleteEvent {
86
131
  payAddress: string;
87
132
  orderId: string;
88
133
  amount: number;
89
- amountReceived: number;
134
+ amountRecieved: number;
90
135
  }
91
- interface EventDataMap {
136
+ export interface EventDataMap {
92
137
  stripe_succeeded: StripePaymentCompleteEvent;
93
138
  nowPayment_succeeded: NPCompleteEvent;
94
139
  }
95
140
  export type PaymentEvent<T extends keyof EventDataMap = keyof EventDataMap> = {
96
141
  id: string;
97
142
  type: T;
143
+ serviceName?: string;
144
+ correlationId?: string;
145
+ signature?: string;
98
146
  data: EventDataMap[T];
99
147
  };
100
- export {};
148
+ export interface PaymentResolveResponse<T = unknown> {
149
+ code: number;
150
+ message: string;
151
+ correlationId?: string;
152
+ data?: T;
153
+ }
@@ -1,12 +1,21 @@
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("@");
8
+ if (!hosts) {
9
+ // No credentials part in the URI (e.g. amqp://host:5672 or plain
10
+ // comma-separated hosts) — use the URI(s) as-is instead of crashing.
11
+ return rabbitUri
12
+ .split(",")
13
+ .map((entry) => entry.trim())
14
+ .filter(Boolean);
15
+ }
7
16
  const hostList = hosts.split(",");
8
- return hostList.map((host, index) => {
9
- return `${creadential}@${host}`;
17
+ return hostList.map((host) => {
18
+ return `${creadential}@${host.trim()}`;
10
19
  });
11
20
  };
12
21
  exports.RABBIT_URI = RABBIT_URI;
@@ -30,5 +39,32 @@ exports.PaymentRabbitApi = {
30
39
  crypto_intent: {
31
40
  key: "cryptoIntent",
32
41
  },
42
+ stripe_ship: {
43
+ key: "stripeShip",
44
+ },
45
+ stripe_refund: {
46
+ key: "stripeRefund",
47
+ },
48
+ stripe_cancel: {
49
+ key: "stripeCancel",
50
+ },
51
+ payment_methods: {
52
+ key: "paymentMethods",
53
+ },
54
+ payment_methods_update: {
55
+ key: "paymentMethodsUpdate",
56
+ },
57
+ intent_status: {
58
+ key: "intentStatus",
59
+ },
60
+ available_methods: {
61
+ key: "availableMethods",
62
+ },
33
63
  },
34
64
  };
65
+ /// Events for a given service are published on a dedicated routing key so
66
+ /// that a service only receives events that belong to it (bindings must
67
+ /// be per-service; wildcard bindings across services are NOT supported).
68
+ function paymentEventRoutingKey(serviceName) {
69
+ return `paymentEvents.${serviceName || "default"}`;
70
+ }
@@ -3,4 +3,7 @@ export declare class CreateCryptoPaymentDto {
3
3
  orderId: string;
4
4
  amount: number;
5
5
  currency: PayCurrency;
6
+ description?: string;
7
+ includeFee?: 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, "includeFee", 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,11 +1,27 @@
1
1
  import { CreateStripeCheckoutDto, CreateStripePaymentIntentDto } from "./dto/stripe.dto";
2
2
  import { AmqpConnection } from "@golevelup/nestjs-rabbitmq";
3
- import { CreateCryptoIntentResponse, CreateStripeCheckoutResponse, CreateStripePaymentIntentResponse } from "./dto/common.interface";
3
+ import { AvailableMethodsResponse, CreateCryptoIntentResponse, CreateStripeCheckoutResponse, CreateStripePaymentIntentResponse, GetIntentByOrderId, IntentStatusResult, OrderActionResponse, UpdatePaymentMethodDto } from "./dto/common.interface";
4
4
  import { CreateCryptoPaymentDto } from "./dto/crypto.dto";
5
+ export interface PaymentProviderOptions {
6
+ serviceName: string;
7
+ secret: string;
8
+ }
5
9
  export declare class PaymentProvider {
6
10
  private readonly rabbit;
7
- constructor(rabbit: AmqpConnection);
11
+ private readonly logger;
12
+ private readonly serviceName;
13
+ private readonly secret;
14
+ constructor(rabbit: AmqpConnection, options?: PaymentProviderOptions);
15
+ private envelope;
16
+ private request;
8
17
  createStripeCheckout(payload: CreateStripeCheckoutDto): Promise<CreateStripeCheckoutResponse>;
9
18
  createStripePaymentIntent(payload: CreateStripePaymentIntentDto): Promise<CreateStripePaymentIntentResponse>;
10
19
  createCryptoPayment(payload: CreateCryptoPaymentDto): Promise<CreateCryptoIntentResponse>;
20
+ getIntentStatus(payload: GetIntentByOrderId): Promise<IntentStatusResult | null>;
21
+ markShipped(payload: GetIntentByOrderId): Promise<OrderActionResponse>;
22
+ refundStripeIntent(payload: GetIntentByOrderId): Promise<OrderActionResponse>;
23
+ cancelStripeIntent(payload: GetIntentByOrderId): Promise<OrderActionResponse>;
24
+ getAvailableMethods(): Promise<AvailableMethodsResponse>;
25
+ setPaymentMethodEnabled(payload: UpdatePaymentMethodDto): Promise<AvailableMethodsResponse>;
26
+ availableMethods<T = unknown>(): Promise<T>;
11
27
  }
@@ -8,43 +8,93 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
8
8
  var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
10
  };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ var PaymentProvider_1;
11
15
  Object.defineProperty(exports, "__esModule", { value: true });
12
16
  exports.PaymentProvider = void 0;
13
17
  const common_1 = require("@nestjs/common");
14
18
  const nestjs_rabbitmq_1 = require("@golevelup/nestjs-rabbitmq");
15
19
  const common_interface_1 = require("./dto/common.interface");
16
- let PaymentProvider = class PaymentProvider {
17
- constructor(rabbit) {
20
+ const payment_signature_1 = require("./payment.signature");
21
+ const crypto_1 = require("crypto");
22
+ let PaymentProvider = PaymentProvider_1 = class PaymentProvider {
23
+ constructor(rabbit, options) {
18
24
  this.rabbit = rabbit;
25
+ this.logger = new common_1.Logger(PaymentProvider_1.name);
26
+ this.serviceName = options?.serviceName?.trim() ?? "";
27
+ this.secret = options?.secret?.trim() ?? "";
19
28
  }
20
- async createStripeCheckout(payload) {
21
- const res = await this.rabbit.request({
22
- exchange: common_interface_1.PaymentRabbitApi.exchange,
23
- routingKey: common_interface_1.PaymentRabbitApi.routingkeys.stripe_checkout.key,
24
- payload,
25
- });
26
- if (res.code !== 200) {
27
- console.error("Raw RPC response:", JSON.stringify(res));
28
- throw new Error(res.message);
29
+ /// Wrap a payload in the signed RPC envelope the gateway requires
30
+ /// (`clientRegistry.verify` rejects anything else). Every call gets a
31
+ /// fresh correlationId for end-to-end tracing.
32
+ envelope(data) {
33
+ if (!this.serviceName) {
34
+ throw new Error('PaymentProvider is not configured: "serviceName" is missing — ' +
35
+ "pass it via PaymentModule.forRoot({ serviceName, secret })");
29
36
  }
30
- return res.data;
37
+ if (!this.secret) {
38
+ throw new Error(`PaymentProvider is not configured: "secret" is missing for service ` +
39
+ `"${this.serviceName}" — it must match the gateway's PAYMENT_CLIENTS entry`);
40
+ }
41
+ const correlationId = (0, crypto_1.randomUUID)();
42
+ return {
43
+ serviceName: this.serviceName,
44
+ correlationId,
45
+ signature: (0, payment_signature_1.signPayload)(this.secret, data, correlationId),
46
+ data,
47
+ };
31
48
  }
32
- async createStripePaymentIntent(payload) {
49
+ async request(routingKey, data) {
33
50
  const res = await this.rabbit.request({
34
51
  exchange: common_interface_1.PaymentRabbitApi.exchange,
35
- routingKey: common_interface_1.PaymentRabbitApi.routingkeys.stripe_intent.key,
36
- payload,
52
+ routingKey,
53
+ payload: this.envelope(data),
37
54
  });
38
55
  if (res.code !== 200) {
56
+ this.logger.error(`payment RPC ${routingKey} failed: ${res.message}`);
39
57
  throw new Error(res.message);
40
58
  }
41
59
  return res.data;
42
60
  }
61
+ async createStripeCheckout(payload) {
62
+ return this.request(common_interface_1.PaymentRabbitApi.routingkeys.stripe_checkout.key, payload);
63
+ }
64
+ async createStripePaymentIntent(payload) {
65
+ return this.request(common_interface_1.PaymentRabbitApi.routingkeys.stripe_intent.key, payload);
66
+ }
43
67
  async createCryptoPayment(payload) {
68
+ return this.request(common_interface_1.PaymentRabbitApi.routingkeys.crypto_intent.key, payload);
69
+ }
70
+ /// Query a payment intent's status by orderId. Resolves `null` when the
71
+ /// gateway has no intent for that order (code 200 with null data).
72
+ async getIntentStatus(payload) {
73
+ return this.request(common_interface_1.PaymentRabbitApi.routingkeys.intent_status.key, payload);
74
+ }
75
+ /// Mark a Stripe intent shipped (post-fulfillment settlement).
76
+ async markShipped(payload) {
77
+ return this.request(common_interface_1.PaymentRabbitApi.routingkeys.stripe_ship.key, payload);
78
+ }
79
+ /// Refund a Stripe intent (full or partial — decided gateway-side).
80
+ async refundStripeIntent(payload) {
81
+ return this.request(common_interface_1.PaymentRabbitApi.routingkeys.stripe_refund.key, payload);
82
+ }
83
+ /// Cancel a Stripe intent before it is paid.
84
+ async cancelStripeIntent(payload) {
85
+ return this.request(common_interface_1.PaymentRabbitApi.routingkeys.stripe_cancel.key, payload);
86
+ }
87
+ async getAvailableMethods() {
88
+ return this.request(common_interface_1.PaymentRabbitApi.routingkeys.payment_methods.key, {});
89
+ }
90
+ async setPaymentMethodEnabled(payload) {
91
+ return this.request(common_interface_1.PaymentRabbitApi.routingkeys.payment_methods_update.key, payload);
92
+ }
93
+ async availableMethods() {
44
94
  const res = await this.rabbit.request({
45
95
  exchange: common_interface_1.PaymentRabbitApi.exchange,
46
- routingKey: common_interface_1.PaymentRabbitApi.routingkeys.crypto_intent.key,
47
- payload,
96
+ routingKey: common_interface_1.PaymentRabbitApi.routingkeys.available_methods.key,
97
+ payload: {},
48
98
  });
49
99
  if (res.code !== 200) {
50
100
  throw new Error(res.message);
@@ -53,7 +103,9 @@ let PaymentProvider = class PaymentProvider {
53
103
  }
54
104
  };
55
105
  exports.PaymentProvider = PaymentProvider;
56
- exports.PaymentProvider = PaymentProvider = __decorate([
106
+ exports.PaymentProvider = PaymentProvider = PaymentProvider_1 = __decorate([
57
107
  (0, common_1.Injectable)(),
58
- __metadata("design:paramtypes", [nestjs_rabbitmq_1.AmqpConnection])
108
+ __param(1, (0, common_1.Optional)()),
109
+ __param(1, (0, common_1.Inject)("PAYMENT_PROVIDER_OPTIONS")),
110
+ __metadata("design:paramtypes", [nestjs_rabbitmq_1.AmqpConnection, Object])
59
111
  ], PaymentProvider);
@@ -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,90 @@
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
+ /// `PAYMENT_CLIENT_NAME` is canonical (see the gateway's RPC-INTEGRATION
25
+ /// guide); `PAYMENT_SERVICE_NAME` is accepted as a fallback.
26
+ const WEBHOOK_ROUTING_KEY = () => `paymentEvents.${process.env.PAYMENT_CLIENT_NAME?.trim() || process.env.PAYMENT_SERVICE_NAME?.trim() || "default"}`;
27
+ exports.WEBHOOK_ROUTING_KEY = WEBHOOK_ROUTING_KEY;
28
+ let PaymentWebhookService = PaymentWebhookService_1 = class PaymentWebhookService {
29
+ constructor(options, rabbit) {
30
+ this.rabbit = rabbit;
31
+ this.logger = new common_1.Logger(PaymentWebhookService_1.name);
32
+ this.handlers = new Map();
33
+ this.serviceName = options.serviceName;
34
+ this.secret = options.secret;
35
+ }
36
+ /// Register a handler for an event type. Chainable.
37
+ on(type, handler) {
38
+ const set = this.handlers.get(type) ?? new Set();
39
+ set.add(handler);
40
+ this.handlers.set(type, set);
41
+ return this;
42
+ }
43
+ /// RabbitMQ subscription. The queue is bound to this service's own
44
+ /// routing key (`paymentEvents.<serviceName>`) so it only receives
45
+ /// events addressed to it.
46
+ async handleEvent(event) {
47
+ if (!event?.type || !event?.data)
48
+ return;
49
+ const verified = event.signature
50
+ ? (0, payment_signature_1.verifyPayloadSignature)(this.secret, event.data, event.signature, event.correlationId)
51
+ : false;
52
+ const handlers = this.handlers.get(event.type);
53
+ if (!handlers?.size) {
54
+ this.logger.debug(`no handler registered for ${String(event.type)}`);
55
+ return;
56
+ }
57
+ for (const fn of handlers) {
58
+ try {
59
+ await fn(event.data, {
60
+ event: event,
61
+ verified,
62
+ correlationId: event.correlationId,
63
+ });
64
+ }
65
+ catch (err) {
66
+ this.logger.error(`handler error for ${String(event.type)}: ${err instanceof Error ? err.message : String(err)}`);
67
+ }
68
+ }
69
+ }
70
+ };
71
+ exports.PaymentWebhookService = PaymentWebhookService;
72
+ __decorate([
73
+ (0, nestjs_rabbitmq_1.RabbitSubscribe)({
74
+ exchange: common_interface_1.PaymentRabbitApi.exchange,
75
+ routingKey: (0, exports.WEBHOOK_ROUTING_KEY)(),
76
+ queueOptions: {
77
+ durable: true,
78
+ autoDelete: false,
79
+ },
80
+ allowNonJsonMessages: true,
81
+ }),
82
+ __metadata("design:type", Function),
83
+ __metadata("design:paramtypes", [Object]),
84
+ __metadata("design:returntype", Promise)
85
+ ], PaymentWebhookService.prototype, "handleEvent", null);
86
+ exports.PaymentWebhookService = PaymentWebhookService = PaymentWebhookService_1 = __decorate([
87
+ (0, common_1.Injectable)(),
88
+ __param(0, (0, common_1.Inject)("PAYMENT_WEBHOOK_OPTIONS")),
89
+ __metadata("design:paramtypes", [Object, nestjs_rabbitmq_1.AmqpConnection])
90
+ ], PaymentWebhookService);
package/package.json CHANGED
@@ -1,12 +1,14 @@
1
1
  {
2
2
  "name": "@ngn-net/payment-provider-sdk",
3
- "version": "1.0.11",
3
+ "version": "1.0.13",
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
  }