@astratra/payments 0.1.0 → 1.0.0

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.
package/README.md CHANGED
@@ -6,6 +6,41 @@ Ce package n'importe **aucun SDK de paiement**. Tu lui passes ta fonction de
6
6
  vérification de signature ; il s'occupe de tout ce qui l'entoure, c'est-à-dire de
7
7
  tout ce qui casse en silence.
8
8
 
9
+ ## Le côté écran : quel plan, quelle page, quelle confirmation
10
+
11
+ Deux passerelles nomment les mêmes choses différemment et répondent
12
+ différemment. L'écran ne doit pas savoir laquelle est derrière.
13
+
14
+ ```js
15
+ const flow = createCheckoutFlow({
16
+ notPurchasable: ['trial'],
17
+ confirms: {
18
+ stripe: () => true,
19
+ cinetpay: (payload) => payload?.success === true
20
+ }
21
+ });
22
+
23
+ flow.planAction('pro', 'starter'); // 'choose' | 'current' | 'locked'
24
+ readCheckoutUrl(payload); // checkoutUrl ?? paymentUrl ?? url
25
+ ```
26
+
27
+ **Un plan peut être accordé plutôt que vendu.** L'essai est donné à la création
28
+ du compte ; proposer de l'acheter produit une erreur côté serveur et de
29
+ l'incompréhension côté personne.
30
+
31
+ **Un compte sans rien à facturer doit se l'entendre dire.** Le bouton de
32
+ paiement vérifiait « pas d'identifiant » puis sortait : aucune requête, aucun
33
+ message, rien. Un bouton qui ne fait rien passe pour une panne, alors que c'est
34
+ une situation parfaitement normale.
35
+
36
+ **« En attente » n'est pas « échoué ».** Quand la boucle de confirmation
37
+ abandonne, le paiement est peut-être passé : le webhook tranchera. Dire à
38
+ quelqu'un que son paiement a échoué pendant que son argent est en route est la
39
+ pire réponse possible.
40
+
41
+ **Une passerelle non déclarée n'est jamais confirmée** — le silence ne doit
42
+ jamais valoir un accès.
43
+
9
44
  ## Les quatre pièges
10
45
 
11
46
  Chacun tue des paiements pendant que le code a l'air correct.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/payments",
3
- "version": "0.1.0",
3
+ "version": "1.0.0",
4
4
  "description": "The payment webhook pipeline done once: raw-body signature checks, replay protection, and the answers that stop a provider retrying for days.",
5
5
  "engines": {
6
6
  "node": ">=20"
@@ -0,0 +1,130 @@
1
+ /**
2
+ * The client side of paying: which plan a button may buy, where to send the
3
+ * person, and how to decide the payment went through.
4
+ *
5
+ * None of this is gateway-specific — and that is the point. Two gateways name
6
+ * the same things differently, answer confirmation differently, and a screen
7
+ * should not know which one is behind it.
8
+ *
9
+ * Three rules were each written after a real complaint.
10
+ *
11
+ * A PLAN CAN BE GRANTED RATHER THAN SOLD. A trial is handed out when the
12
+ * account is created; offering to buy it produces an error from the server and
13
+ * bewilderment from the person. Such plans are declared unpurchasable.
14
+ *
15
+ * AN ACCOUNT WITH NOTHING TO BILL MUST BE TOLD. The pay button used to check
16
+ * "no account id" and return — no request, no message, nothing. A button that
17
+ * does nothing reads as a breakage; this is a normal situation and deserves a
18
+ * sentence.
19
+ *
20
+ * "PENDING" IS NOT "FAILED". When polling gives up, the payment may well have
21
+ * gone through: the webhook will settle it. Telling someone their payment
22
+ * failed while their money is on its way is the worst possible answer.
23
+ */
24
+
25
+ const DEFAULT_MAX_CONFIRMATION_ATTEMPTS = 24;
26
+ const DEFAULT_CONFIRMATION_INTERVAL_MS = 5000;
27
+ const CHECKOUT_URL_FIELDS = ['checkoutUrl', 'paymentUrl', 'url'];
28
+
29
+ /**
30
+ * The hosted payment page, whichever field the gateway used.
31
+ * @param {string[]} [fields] Extra names, for a gateway that invents its own.
32
+ */
33
+ function readCheckoutUrl(payload, fields = CHECKOUT_URL_FIELDS) {
34
+ if (!payload || typeof payload !== 'object') return null;
35
+ for (const field of fields) {
36
+ const value = payload[field];
37
+ if (typeof value === 'string' && value.length > 0) return value;
38
+ }
39
+ return null;
40
+ }
41
+
42
+ /**
43
+ * An id that arrives raw on one route and populated on another.
44
+ *
45
+ * Both must yield the same string, or a request goes out carrying
46
+ * "[object Object]" and fails somewhere far from the cause.
47
+ */
48
+ function readEntityId(value) {
49
+ if (typeof value === 'string') return value;
50
+ if (value && typeof value === 'object') {
51
+ const id = value._id ?? value.id;
52
+ if (typeof id === 'string') return id;
53
+ }
54
+ return '';
55
+ }
56
+
57
+ /** A gateway epoch, in seconds, as a date. Absent or nonsensical: no date. */
58
+ function readRenewalDate(seconds) {
59
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0) return null;
60
+ return new Date(seconds * 1000);
61
+ }
62
+
63
+ /**
64
+ * @param {object} [options]
65
+ * @param {string[]} [options.notPurchasable] Plans granted, never sold.
66
+ * @param {string} [options.defaultPlan] What "no plan" means. Default ''.
67
+ * @param {number} [options.maxAttempts]
68
+ * @param {number} [options.intervalMs]
69
+ * @param {Object<string,Function>} [options.confirms] gateway => (payload) => boolean.
70
+ */
71
+ function createCheckoutFlow(options = {}) {
72
+ const notPurchasable = new Set(options.notPurchasable || []);
73
+ const defaultPlan = options.defaultPlan || '';
74
+ const maxAttempts = options.maxAttempts || DEFAULT_MAX_CONFIRMATION_ATTEMPTS;
75
+ const intervalMs = options.intervalMs || DEFAULT_CONFIRMATION_INTERVAL_MS;
76
+ const confirms = options.confirms || {};
77
+
78
+ /** @returns {'current'|'locked'|'choose'} */
79
+ function planAction(planKey, currentPlanKey) {
80
+ if (planKey === (currentPlanKey || defaultPlan)) return 'current';
81
+ if (notPurchasable.has(planKey)) return 'locked';
82
+ return 'choose';
83
+ }
84
+
85
+ return {
86
+ maxAttempts,
87
+ intervalMs,
88
+
89
+ planAction,
90
+
91
+ isSelectable(planKey, currentPlanKey) {
92
+ return planAction(planKey, currentPlanKey) === 'choose';
93
+ },
94
+
95
+ /** Is there anything to bill at all? */
96
+ canPay(accountId) {
97
+ return typeof accountId === 'string' && accountId.length > 0;
98
+ },
99
+
100
+ /** @returns {'confirmed'|'retry'|'pending'} */
101
+ nextPoll({ confirmed, attempts } = {}) {
102
+ if (confirmed) return 'confirmed';
103
+ return Number(attempts) >= maxAttempts ? 'pending' : 'retry';
104
+ },
105
+
106
+ /**
107
+ * Did this gateway say the payment is done?
108
+ * An undeclared gateway is NEVER confirmed: silence must not grant access.
109
+ */
110
+ isConfirmed(gateway, payload) {
111
+ const read = confirms[gateway];
112
+ if (typeof read !== 'function') return false;
113
+ try {
114
+ return read(payload) === true;
115
+ } catch {
116
+ return false;
117
+ }
118
+ }
119
+ };
120
+ }
121
+
122
+ module.exports = {
123
+ CHECKOUT_URL_FIELDS,
124
+ DEFAULT_CONFIRMATION_INTERVAL_MS,
125
+ DEFAULT_MAX_CONFIRMATION_ATTEMPTS,
126
+ createCheckoutFlow,
127
+ readCheckoutUrl,
128
+ readEntityId,
129
+ readRenewalDate
130
+ };
package/src/index.d.ts CHANGED
@@ -86,3 +86,41 @@ export function createWebhookExemption(options: {
86
86
  suffix?: string;
87
87
  pattern?: RegExp;
88
88
  }): (input: RequestLike | string | null) => boolean;
89
+
90
+ /* ─────────────────── The client side of paying ─────────────────── */
91
+
92
+ export const CHECKOUT_URL_FIELDS: string[];
93
+ export const DEFAULT_MAX_CONFIRMATION_ATTEMPTS: number;
94
+ export const DEFAULT_CONFIRMATION_INTERVAL_MS: number;
95
+
96
+ /** The hosted payment page, whichever field the gateway used. */
97
+ export function readCheckoutUrl(payload: unknown, fields?: string[]): string | null;
98
+ /** Same id whether the field arrived raw or populated. */
99
+ export function readEntityId(value: unknown): string;
100
+ /** A gateway epoch in seconds, as a date. */
101
+ export function readRenewalDate(seconds: unknown): Date | null;
102
+
103
+ export type PlanAction = 'current' | 'locked' | 'choose';
104
+ export type PollDecision = 'confirmed' | 'retry' | 'pending';
105
+
106
+ export interface CheckoutFlow {
107
+ readonly maxAttempts: number;
108
+ readonly intervalMs: number;
109
+ planAction(planKey: string, currentPlanKey?: string | null): PlanAction;
110
+ isSelectable(planKey: string, currentPlanKey?: string | null): boolean;
111
+ /** False when there is nothing to bill — say so, never fail silently. */
112
+ canPay(accountId: string | null | undefined): boolean;
113
+ /** 'pending' is not 'failed': the webhook may still settle it. */
114
+ nextPoll(input?: { confirmed?: boolean; attempts?: number }): PollDecision;
115
+ /** An undeclared gateway is never confirmed. */
116
+ isConfirmed(gateway: string, payload: unknown): boolean;
117
+ }
118
+
119
+ export function createCheckoutFlow(options?: {
120
+ /** Plans granted rather than sold — a trial, typically. */
121
+ notPurchasable?: string[];
122
+ defaultPlan?: string;
123
+ maxAttempts?: number;
124
+ intervalMs?: number;
125
+ confirms?: Record<string, (payload: unknown) => boolean>;
126
+ }): CheckoutFlow;
package/src/index.js CHANGED
@@ -2,5 +2,6 @@ module.exports = {
2
2
  ...require('./outcomes'),
3
3
  ...require('./eventLog'),
4
4
  ...require('./webhook'),
5
- ...require('./exemption')
5
+ ...require('./exemption'),
6
+ ...require('./checkoutFlow')
6
7
  };