Pepguy commited on
Commit
d658b4f
·
verified ·
1 Parent(s): 175f3d8

Update app.js

Browse files
Files changed (1) hide show
  1. app.js +352 -346
app.js CHANGED
@@ -1,5 +1,5 @@
1
  // paystack-webhook.js
2
- // Node >= 14, install dependencies:
3
  // npm install express firebase-admin axios
4
 
5
  const express = require('express');
@@ -9,455 +9,420 @@ const axios = require('axios');
9
 
10
  const app = express();
11
 
12
- // -------------------------------------------------
13
- // Environment variables (set these in your env/secrets)
14
- // -------------------------------------------------
15
- // - FIREBASE_CREDENTIALS: stringified JSON service account
16
- // - PAYSTACK_DEMO_SECRET
17
- // - PAYSTACK_LIVE_SECRET
18
- // - PORT (optional)
19
- // -------------------------------------------------
20
-
21
  const {
22
  FIREBASE_CREDENTIALS,
23
  PAYSTACK_DEMO_SECRET,
24
  PAYSTACK_LIVE_SECRET,
25
- PORT,
26
  } = process.env;
27
-
28
- // choose which secret to use (dev/demo by default)
29
  const PAYSTACK_SECRET = PAYSTACK_DEMO_SECRET || PAYSTACK_LIVE_SECRET;
30
 
31
- if (!PAYSTACK_SECRET) {
32
- console.warn('WARNING: PAYSTACK_SECRET is not set. Outgoing Paystack calls and webhook verification will fail.');
33
- }
34
 
35
- // Initialize Firebase Admin using credentials read from env
36
  let db = null;
37
  try {
38
  if (FIREBASE_CREDENTIALS) {
39
- const serviceAccount = JSON.parse(FIREBASE_CREDENTIALS);
40
- admin.initializeApp({
41
- credential: admin.credential.cert(serviceAccount),
42
- });
43
  db = admin.firestore();
44
  console.log('Firebase admin initialized from FIREBASE_CREDENTIALS env var.');
45
  } else {
46
- // If admin was already initialized in the environment (e.g. GCP), this will succeed
47
  if (!admin.apps.length) {
48
- console.warn('FIREBASE_CREDENTIALS not provided. Firebase admin not initialized. Some operations will error if they require Firestore.');
49
  } else {
50
  db = admin.firestore();
51
  }
52
  }
53
- } catch (err) {
54
- console.error('Failed to initialize Firebase admin:', err);
55
- // keep running — code paths that need db will guard and log appropriately
 
 
 
 
 
56
  }
57
 
58
- // -------------------------------------------------
59
- // Utility: verify x-paystack-signature
60
- // -------------------------------------------------
61
  function verifyPaystackSignature(rawBodyBuffer, signatureHeader) {
62
- if (!PAYSTACK_SECRET) return false;
63
- if (!rawBodyBuffer) return false;
64
  try {
65
  const hmac = crypto.createHmac('sha512', PAYSTACK_SECRET);
66
  hmac.update(rawBodyBuffer);
67
  const expected = hmac.digest('hex');
68
- // signatureHeader may be undefined - handle gracefully
69
- if (!signatureHeader) return false;
70
  return crypto.timingSafeEqual(Buffer.from(expected, 'utf8'), Buffer.from(String(signatureHeader), 'utf8'));
71
  } catch (e) {
72
- console.error('Error while verifying signature:', e);
73
  return false;
74
  }
75
  }
76
 
77
- // Helper: safe JSON parse
78
- function safeParseJSON(raw) {
 
79
  try {
80
- return JSON.parse(raw);
81
- } catch (err) {
82
- return null;
 
 
 
 
 
 
 
83
  }
 
84
  }
85
 
86
- // ------------------------------
87
- // Expiry helper: getExpiryFromPlan
88
- // ------------------------------
89
- const EXTRA_FREE_MS = 2 * 60 * 60 * 1000; // 2 hours in ms
90
-
91
- const WEEKLY_PLAN_IDS = new Set([
92
- 3311892,
93
- 3305738,
94
- 'PLN_ngz4l76whecrpkv',
95
- 'PLN_f7a3oagrpt47d5f',
96
- ]);
97
-
98
- const MONTHLY_PLAN_IDS = new Set([
99
- 3305739,
100
- 'PLN_584ck56g65xhkum',
101
- ]);
102
-
103
  function getExpiryFromPlan(planInput) {
104
- let interval = null;
105
- let planId = null;
106
- let planCode = null;
107
-
108
- if (!planInput) {
109
- interval = null;
110
- } else if (typeof planInput === 'object') {
111
  planId = planInput.id ?? planInput.plan_id ?? null;
112
  planCode = planInput.plan_code ?? planInput.planCode ?? null;
113
- interval = (planInput.interval || planInput.billing_interval || null);
114
- } else if (typeof planInput === 'number') {
115
- planId = planInput;
116
- } else if (typeof planInput === 'string') {
117
- planCode = planInput;
118
- const asNum = Number(planInput);
119
- if (!Number.isNaN(asNum)) planId = asNum;
120
- }
121
 
122
  if (interval) {
123
  interval = String(interval).toLowerCase();
124
  if (interval.includes('week')) {
125
- const expires = Date.now() + 7 * 24 * 60 * 60 * 1000 + EXTRA_FREE_MS;
126
  return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
127
  }
128
  if (interval.includes('month')) {
129
- const expires = Date.now() + 30 * 24 * 60 * 60 * 1000 + EXTRA_FREE_MS;
130
  return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
131
  }
132
  if (interval.includes('hour')) {
133
- // treat hour interval as a week by default (matching original logic)
134
- const expires = Date.now() + 7 * 24 * 60 * 60 * 1000 + EXTRA_FREE_MS;
135
  return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
136
  }
137
  }
138
 
139
  if (planId && WEEKLY_PLAN_IDS.has(planId)) {
140
- const expires = Date.now() + 7 * 24 * 60 * 60 * 1000 + EXTRA_FREE_MS;
141
  return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
142
  }
143
  if (planCode && WEEKLY_PLAN_IDS.has(planCode)) {
144
- const expires = Date.now() + 7 * 24 * 60 * 60 * 1000 + EXTRA_FREE_MS;
145
  return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
146
  }
147
  if (planId && MONTHLY_PLAN_IDS.has(planId)) {
148
- const expires = Date.now() + 30 * 24 * 60 * 60 * 1000 + EXTRA_FREE_MS;
149
  return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
150
  }
151
  if (planCode && MONTHLY_PLAN_IDS.has(planCode)) {
152
- const expires = Date.now() + 30 * 24 * 60 * 60 * 1000 + EXTRA_FREE_MS;
153
  return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
154
  }
155
 
156
- const expires = Date.now() + 30 * 24 * 60 * 60 * 1000 + EXTRA_FREE_MS;
157
  return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
158
  }
159
 
160
- // ------------------------------
161
- // Helper: get userId from stored slug mapping
162
- // - try doc id == slug
163
- // - fallback: query where pageId == slug
164
- // ------------------------------
165
  async function getUserIdFromSlug(dbInstance, slugOrPageId) {
166
- if (!slugOrPageId || !dbInstance) return null;
167
  try {
168
- // try doc id first (we store mapping under doc id === slug)
169
- const doc = await dbInstance.collection('paystack-page-mappings').doc(String(slugOrPageId)).get();
170
- if (doc.exists) {
171
- const data = doc.data();
172
- if (data?.userId) return data.userId;
 
 
 
 
173
  }
174
-
175
- // fallback: maybe caller passed pageId; search by pageId field
176
  const q = await dbInstance.collection('paystack-page-mappings').where('pageId', '==', String(slugOrPageId)).limit(1).get();
177
  if (!q.empty) {
178
  const d = q.docs[0].data();
 
179
  if (d?.userId) return d.userId;
180
  }
181
-
182
  return null;
183
  } catch (e) {
184
- console.error('Failed to read page mapping for slug/pageId:', slugOrPageId, e);
185
  return null;
186
  }
187
  }
188
 
189
- // ------------------------------
190
- // Robust extractor for userId (tries metadata, custom_fields, customer metadata, slug mapping, email fallback)
191
- // ------------------------------
192
- async function extractUserIdFromPayload(data = {}, dbInstance) {
193
- // 1) direct metadata on data
194
- const metadata = data.metadata || {};
195
- if (metadata.userId || metadata.user_id) return { userId: metadata.userId || metadata.user_id, source: 'metadata' };
196
-
197
- // 2) customer.metadata
198
- const custMeta = data.customer?.metadata || {};
199
- if (custMeta.userId || custMeta.user_id) return { userId: custMeta.userId || custMeta.user_id, source: 'customer.metadata' };
200
-
201
- // 3) top-level custom_fields (array)
202
- if (Array.isArray(data.custom_fields)) {
203
- for (const f of data.custom_fields) {
204
- const name = (f.variable_name || f.display_name || '').toString().toLowerCase();
205
- if ((name.includes('user') || name.includes('user_id') || name.includes('userid')) && f.value) {
206
- return { userId: f.value, source: 'custom_fields' };
207
- }
208
- }
209
- }
210
 
211
- // 4) metadata.custom_fields
212
- if (metadata.custom_fields) {
213
- if (Array.isArray(metadata.custom_fields)) {
214
- for (const f of metadata.custom_fields) {
215
- const name = (f.variable_name || f.display_name || '').toString().toLowerCase();
216
- if (name.includes('user') && f.value) return { userId: f.value, source: 'metadata.custom_fields' };
217
- }
218
- } else if (typeof metadata.custom_fields === 'object') {
219
- for (const k of Object.keys(metadata.custom_fields)) {
220
- if (k.toLowerCase().includes('user')) return { userId: metadata.custom_fields[k], source: 'metadata.custom_fields_object' };
221
  }
 
 
222
  }
223
- }
224
 
225
- // 5) slug / page id mapping fallback - many Paystack page webhooks include data.page.slug or data.page.id
226
- const slugCandidate = data.slug || data.page?.slug || data.page?.id || metadata?.slug || metadata?.page_slug || null;
227
- if (slugCandidate && dbInstance) {
228
- const mappedUserId = await getUserIdFromSlug(dbInstance, slugCandidate);
229
- if (mappedUserId) return { userId: mappedUserId, source: 'slug_mapping' };
230
- }
 
 
 
 
 
231
 
232
- // 6) email fallback (return email so caller can search)
233
- if (data.customer?.email) return { userId: data.customer.email, source: 'email' };
 
 
 
 
 
 
 
 
 
234
 
235
- // nothing found
236
- return { userId: null, source: null };
 
 
 
237
  }
238
 
239
- // ------------------------------
240
- // Helper: find user doc reference in Firestore (tries doc id and queries by fields)
241
- // ------------------------------
242
  async function findUserDocRef(dbInstance, { metadataUserId, email, paystackCustomerId } = {}) {
243
  if (!dbInstance) return null;
244
  const usersRef = dbInstance.collection('users');
245
 
246
  if (metadataUserId) {
247
- // if metadataUserId looks like an email, skip docId check and search by email
248
  if (!String(metadataUserId).includes('@')) {
249
  try {
250
  const docRef = usersRef.doc(String(metadataUserId));
251
- const snap = await docRef.get();
252
- if (snap.exists) return docRef;
253
- } catch (e) {
254
- // continue to queries
255
- }
256
  }
257
 
258
- // try equality queries on commonly used id fields
259
- const idFields = ['userId', 'uid', 'id'];
260
- for (const field of idFields) {
261
  try {
262
- const qSnap = await usersRef.where(field, '==', metadataUserId).limit(1).get();
263
- if (!qSnap.empty) return qSnap.docs[0].ref;
264
- } catch (e) {
265
- // ignore and proceed
266
- }
267
  }
268
  }
269
 
270
- // If paystack_customer_id was provided, try that too
271
  if (paystackCustomerId) {
272
  try {
273
- const qSnap = await usersRef.where('paystack_customer_id', '==', String(paystackCustomerId)).limit(1).get();
274
- if (!qSnap.empty) return qSnap.docs[0].ref;
275
- } catch (e) {
276
- // ignore
277
- }
278
  }
279
 
280
  if (email) {
281
  try {
282
- const qSnap = await usersRef.where('email', '==', email).limit(1).get();
283
- if (!qSnap.empty) return qSnap.docs[0].ref;
284
- } catch (e) {
285
- // ignore
286
- }
287
  }
288
 
289
- // Not found
290
  return null;
291
  }
292
 
293
- // ------------------------------
294
- // Cleanup that should run after a successful charge for the user
295
- // - Deletes page mapping doc if slug provided and mapping matches user
296
- // - Removes any "pending-payments" documents for the user (optional)
297
- // - Writes a paymentCleanup log
298
- // Customize this per your app's needs.
299
- // ------------------------------
300
  async function cleanUpAfterSuccessfulCharge(dbInstance, userDocRef, { slug, pageId, reference, email } = {}) {
301
  if (!dbInstance || !userDocRef) return;
302
  try {
303
- // 1) delete mapping doc if exists and mapping.userId === user's id
304
- if (slug) {
305
  try {
306
- const mapRef = dbInstance.collection('paystack-page-mappings').doc(String(slug));
307
- const mapSnap = await mapRef.get();
308
- if (mapSnap.exists) {
309
- const map = mapSnap.data();
310
- // if mapping.userId equals user doc id or equals user's email or similar, delete.
311
- const userIdCandidate = userDocRef.id;
312
- if (String(map.userId) === String(userIdCandidate) || (email && String(map.userId) === String(email))) {
313
- await mapRef.delete();
314
- console.log('Deleted paystack-page-mappings doc for slug:', slug);
315
- } else {
316
- console.log('Skipping deletion of mapping for slug (owner mismatch):', slug);
317
- }
318
  }
319
  } catch (e) {
320
- console.error('Error deleting paystack-page-mappings doc for slug:', slug, e);
321
  }
322
- }
 
 
323
 
324
- // 2) optional: remove pending-payments documents (if your app stores them)
325
  try {
326
  const pendingRef = dbInstance.collection('pending-payments');
327
- const q = await pendingRef.where('userId', '==', userDocRef.id).limit(50).get();
328
  if (!q.empty) {
329
  const batch = dbInstance.batch();
330
- q.docs.forEach(doc => batch.delete(doc.ref));
331
  await batch.commit();
332
  console.log('Deleted pending-payments for user:', userDocRef.id);
333
  }
334
  } catch (e) {
335
- // not critical
336
- console.error('Failed to delete pending-payments (non-fatal):', e);
337
  }
338
 
339
- // 3) log the cleanup
340
  try {
341
  await dbInstance.collection('paystack-cleanups').add({
342
  userRef: userDocRef.path,
343
  slug: slug || null,
344
- pageId: pageId ? String(pageId) : null,
345
  reference: reference || null,
346
  email: email || null,
347
  cleanedAt: admin.firestore.FieldValue.serverTimestamp(),
348
  });
349
  } catch (e) {
350
- console.error('Failed to log cleanup:', e);
351
  }
352
  } catch (e) {
353
- console.error('Unexpected error during cleanup:', e);
354
  }
355
  }
356
 
357
- // ------------------------
358
- // Webhook endpoint (only this route uses express.raw so other routes can use express.json)
359
- // ------------------------
360
  app.post('/webhook/paystack', express.raw({ type: 'application/json', limit: '1mb' }), async (req, res) => {
361
- const raw = req.body; // Buffer
362
  const signature = req.get('x-paystack-signature') || req.get('X-Paystack-Signature');
363
 
364
- // Verify signature
365
  if (!signature || !verifyPaystackSignature(raw, signature)) {
366
- console.warn('Paystack webhook signature verification failed. Signature header:', signature);
367
  return res.status(400).json({ ok: false, message: 'Invalid signature' });
368
  }
369
 
370
- // Parse payload
371
  const bodyStr = raw.toString('utf8');
372
  const payload = safeParseJSON(bodyStr);
373
-
374
- if (!payload) {
375
- console.warn('Could not parse webhook JSON payload.');
376
- return res.status(400).json({ ok: false, message: 'Invalid JSON' });
377
- }
378
 
379
  const event = (payload.event || payload.type || '').toString();
380
  const isRefund = /refund/i.test(event);
381
  const isChargeSuccess = /charge\.success/i.test(event);
382
- const isInvoiceOrSubscription = /invoice\.(payment_succeeded|paid)|subscription\./i.test(event);
383
  const isPayment = isChargeSuccess;
384
 
385
- if (!db) {
386
- console.error('Firestore (admin) not initialized; webhook will not persist data.');
 
 
 
 
 
 
 
387
  }
388
 
389
- if (isRefund || isPayment || /subscription\.create/i.test(event) || /subscription\.update/i.test(event)) {
390
  console.log('--- PAYSTACK WEBHOOK (INTERESTING EVENT) ---');
391
  console.log('event:', event);
392
- // persist webhook for auditing (best-effort)
393
- console.log(payload);
394
-
395
- try {
396
- if (db) {
397
- await db.collection('paystack-webhooks').add({
398
- event,
399
- payload,
400
- receivedAt: admin.firestore.FieldValue.serverTimestamp(),
401
- });
 
 
 
 
 
 
 
 
402
  }
403
- } catch (err) {
404
- console.error('Failed to persist webhook audit:', err);
405
  }
406
 
407
- const data = payload.data || {};
 
408
 
409
- // Try to extract userId robustly (metadata/custom_fields/slug/email)
410
  let metadataUserId = null;
411
  let customerEmail = null;
412
  let extractorSource = null;
413
- let maybeSlug = null;
414
- let maybePageId = null;
415
  try {
416
- const extracted = await extractUserIdFromPayload(data, db);
417
- metadataUserId = extracted.userId || null;
418
- extractorSource = extracted.source || null;
419
- // If extractor returned an email, set as customerEmail
420
- if (metadataUserId && String(metadataUserId).includes('@')) {
421
- customerEmail = String(metadataUserId);
422
- metadataUserId = null;
 
 
 
 
 
 
 
 
 
 
 
 
 
423
  }
424
  } catch (e) {
425
- console.error('Error extracting userId from payload:', e);
426
  }
427
 
428
- // Also set explicit customer email if present
429
  if (!customerEmail && data.customer?.email) customerEmail = data.customer.email;
430
-
431
- // Save possible slug/pageId for cleanup/connection
432
- maybeSlug = data.slug || data.page?.slug || data.metadata?.slug || null;
433
- maybePageId = data.page?.id || data.page_id || data.metadata?.page_id || null;
434
-
435
- // Also try to get paystack customer id from payload (helps linking)
436
  const paystackCustomerId = data.customer?.id ?? data.customer?.customer_code ?? null;
437
 
438
- // Find user doc reference
439
  let userDocRef = null;
440
  try {
441
- userDocRef = await findUserDocRef(db, { metadataUserId, email: customerEmail, paystackCustomerId });
442
- // If still null and metadataUserId is present but looks like slug, try slug mapping as last resort
443
- if (!userDocRef && metadataUserId && db) {
444
- const mapped = await getUserIdFromSlug(db, metadataUserId);
445
- if (mapped) {
446
- userDocRef = await findUserDocRef(db, { metadataUserId: mapped, email: customerEmail, paystackCustomerId });
447
- }
 
 
448
  }
449
- } catch (err) {
450
- console.error('Error finding user doc:', err);
451
  userDocRef = null;
452
  }
453
 
454
- // Handler: subscription.create - store subscription id and paystack_customer_id
455
  if (/subscription\.create/i.test(event) || event === 'subscription.create') {
456
  const subscriptionCode = data.subscription_code || data.subscription?.subscription_code || (data.id ? String(data.id) : null);
457
  const status = data.status || 'active';
458
  const planObj = data.plan || data.subscription?.plan || null;
459
  const expiry = getExpiryFromPlan(planObj);
460
- const paystackCustomerId = data.customer?.id ?? (data.customer?.customer_code ? data.customer.customer_code : null);
461
 
462
  if (userDocRef && subscriptionCode) {
463
  try {
@@ -473,24 +438,21 @@ app.post('/webhook/paystack', express.raw({ type: 'application/json', limit: '1m
473
  },
474
  updatedAt: admin.firestore.FieldValue.serverTimestamp(),
475
  };
476
-
477
- // attach paystack_customer_id if present
478
- if (paystackCustomerId) {
479
- updateObj.paystack_customer_id = String(paystackCustomerId);
480
- }
481
-
482
  await userDocRef.update(updateObj);
483
- console.log(`User doc updated with subscription ${subscriptionCode} and expiry ${expiry.expiresAtIso} (source: ${extractorSource})`);
484
- } catch (err) {
485
- console.error('Failed to update user subscription info:', err);
486
  }
487
  } else {
488
  console.warn('subscription.create received but user not found or subscriptionCode missing — skipping user update.');
489
  }
490
  }
491
 
492
- // Handler: charge.success - add entitlement on successful subscription charge
493
  if (isPayment) {
 
 
494
  const recurringMarker = Boolean((data.metadata && (data.metadata.custom_filters?.recurring || data.metadata.recurring)) || false);
495
  const hasSubscription = !!(data.subscription || data.subscriptions || data.plan);
496
  const isLikelySubscriptionPayment = recurringMarker || hasSubscription;
@@ -507,149 +469,193 @@ app.post('/webhook/paystack', express.raw({ type: 'application/json', limit: '1m
507
  plan: planObj ? { id: planObj.id, code: planObj.plan_code } : null,
508
  expiresAtMs: expiry.expiresAtMs,
509
  expiresAtIso: expiry.expiresAtIso,
510
- createdAt: admin.firestore.FieldValue.serverTimestamp(),
511
  };
512
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
513
  if (userDocRef && isLikelySubscriptionPayment) {
514
  try {
 
515
  await userDocRef.update({
516
  entitlements: admin.firestore.FieldValue.arrayUnion(entitlement),
517
- updatedAt: admin.firestore.FieldValue.serverTimestamp(),
518
  lastPaymentAt: admin.firestore.FieldValue.serverTimestamp(),
519
- // Save paystack_customer_id if present and not already present
520
  ...(paystackCustomerId ? { paystack_customer_id: String(paystackCustomerId) } : {}),
521
  });
522
- console.log('Added entitlement to user:', entitlement.id || entitlement.reference, 'expiry:', expiry.expiresAtIso);
523
-
524
- // Run cleanup now that the charge is successful for this user
 
525
  try {
526
- await cleanUpAfterSuccessfulCharge(db, userDocRef, {
527
- slug: maybeSlug,
528
- pageId: maybePageId,
529
- reference: entitlement.reference || entitlement.id,
530
- email: customerEmail,
531
- });
532
- } catch (cleanupErr) {
533
- console.error('Cleanup after successful charge failed:', cleanupErr);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
534
  }
 
535
 
536
- } catch (err) {
537
- console.error('Failed to add entitlement to user:', err);
 
 
 
538
  }
539
  } else if (userDocRef && !isLikelySubscriptionPayment) {
540
- console.log('charge.success received but not marked recurring/subscription - skipping entitlement add by default.');
541
  } else {
542
  console.warn('charge.success: user not found, skipping entitlement update.');
 
 
 
 
 
 
 
 
 
 
 
543
  }
544
  }
545
 
546
- // Handler: refunds - remove entitlement(s) associated with refunded transaction
547
  if (isRefund) {
548
  const refund = data;
549
  const refundedReference = refund.reference || refund.transaction?.reference || refund.transaction?.id || null;
550
-
551
  if (userDocRef && refundedReference) {
552
  try {
553
  const snap = await userDocRef.get();
554
  if (snap.exists) {
555
  const userData = snap.data();
556
- const currentEntitlements = Array.isArray(userData.entitlements) ? userData.entitlements : [];
557
- const filtered = currentEntitlements.filter(e => {
558
- const ref = e.reference || e.id || '';
559
- return ref !== refundedReference && ref !== String(refundedReference);
560
- });
561
-
562
- await userDocRef.update({
563
- entitlements: filtered,
564
- updatedAt: admin.firestore.FieldValue.serverTimestamp(),
565
  });
566
- console.log('Removed entitlements matching refunded reference:', refundedReference);
 
567
  } else {
568
- console.warn('Refund handling: user doc disappeared between lookup and removal.');
569
  }
570
- } catch (err) {
571
- console.error('Failed to remove entitlement on refund:', err);
572
  }
573
  } else {
574
- console.warn('Refund received but user or refundedReference not found — skipping entitlement removal.');
575
  }
576
  }
577
  } else {
578
- console.log(`Received Paystack webhook for event "${event}" — ignored (not refund/payment/subscription.create).`);
579
  }
580
 
581
  return res.status(200).json({ ok: true });
582
  });
583
 
584
- // ------------------------
585
- // Create Payment Page (link) for a plan
586
- // ------------------------
587
  app.post('/create-payment-link', express.json(), async (req, res) => {
588
  const { planId, userId, name, amount, redirect_url, collect_phone = false, fixed_amount = false } = req.body || {};
 
 
 
589
 
590
- if (!planId) return res.status(400).json({ ok: false, message: 'planId is required' });
591
- if (!userId) return res.status(400).json({ ok: false, message: 'userId is required' });
592
- if (!name) return res.status(400).json({ ok: false, message: 'name is required (page title)' });
593
-
594
- // Build the body per Paystack's Payment Pages API.
595
- const payload = {
596
- name,
597
- type: 'subscription',
598
- plan: planId,
599
- metadata: {
600
- userId: String(userId),
601
- },
602
- collect_phone,
603
- fixed_amount,
604
- };
605
-
606
- if (amount) payload.amount = amount; // amount is optional (in kobo/cents)
607
  if (redirect_url) payload.redirect_url = redirect_url;
608
 
609
  try {
610
  const response = await axios.post('https://api.paystack.co/page', payload, {
611
- headers: {
612
- Authorization: `Bearer ${PAYSTACK_SECRET}`,
613
- 'Content-Type': 'application/json',
614
- },
615
  timeout: 10_000,
616
  });
617
 
618
  const pageData = response.data && response.data.data ? response.data.data : response.data;
619
 
620
- // Persist slug -> userId mapping so webhooks can recover missing metadata later
621
  try {
622
- const slug = pageData.slug || pageData.data?.slug || null;
623
- const pageId = pageData.id || pageData.data?.id || null;
624
- if (slug && db) {
625
- await db.collection('paystack-page-mappings').doc(String(slug)).set({
626
- userId: String(userId),
627
- pageId: pageId ? String(pageId) : null,
628
- createdAt: admin.firestore.FieldValue.serverTimestamp(),
629
- }, { merge: true });
630
- console.log('Saved page slug mapping for', slug);
631
- } else if (pageId && db) {
632
- // also ensure a record exists by pageId lookup (useful if slug missing in some responses)
633
- await db.collection('paystack-page-mappings').doc(String(pageId)).set({
634
- userId: String(userId),
635
- pageId: String(pageId),
636
- createdAt: admin.firestore.FieldValue.serverTimestamp(),
637
- }, { merge: true });
 
 
 
 
 
 
 
 
 
638
  }
639
  } catch (e) {
640
- console.error('Failed to persist page slug mapping:', e);
641
  }
642
 
643
  return res.status(201).json({ ok: true, page: pageData });
644
  } catch (err) {
645
- console.error('Error creating Paystack payment page:', err?.response?.data || err.message || err);
646
  const errorDetail = err?.response?.data || { message: err.message };
647
  return res.status(500).json({ ok: false, error: errorDetail });
648
  }
649
  });
650
 
651
- // Simple health check
652
- app.get('/health', (req, res) => res.json({ ok: true }));
653
 
654
  app.listen(PORT, () => {
655
  console.log(`Paystack webhook server listening on port ${PORT}`);
 
1
  // paystack-webhook.js
2
+ // Node >= 14
3
  // npm install express firebase-admin axios
4
 
5
  const express = require('express');
 
9
 
10
  const app = express();
11
 
 
 
 
 
 
 
 
 
 
12
  const {
13
  FIREBASE_CREDENTIALS,
14
  PAYSTACK_DEMO_SECRET,
15
  PAYSTACK_LIVE_SECRET,
16
+ PORT = 7860,
17
  } = process.env;
 
 
18
  const PAYSTACK_SECRET = PAYSTACK_DEMO_SECRET || PAYSTACK_LIVE_SECRET;
19
 
20
+ if (!PAYSTACK_SECRET) console.warn('WARNING: PAYSTACK secret not set.');
 
 
21
 
 
22
  let db = null;
23
  try {
24
  if (FIREBASE_CREDENTIALS) {
25
+ const svc = JSON.parse(FIREBASE_CREDENTIALS);
26
+ admin.initializeApp({ credential: admin.credential.cert(svc) });
 
 
27
  db = admin.firestore();
28
  console.log('Firebase admin initialized from FIREBASE_CREDENTIALS env var.');
29
  } else {
 
30
  if (!admin.apps.length) {
31
+ console.warn('FIREBASE_CREDENTIALS not provided and admin not initialized.');
32
  } else {
33
  db = admin.firestore();
34
  }
35
  }
36
+ } catch (e) {
37
+ console.error('Failed to init Firebase admin:', e);
38
+ }
39
+
40
+ /* -------------------- Helpers -------------------- */
41
+
42
+ function safeParseJSON(raw) {
43
+ try { return JSON.parse(raw); } catch (e) { return null; }
44
  }
45
 
 
 
 
46
  function verifyPaystackSignature(rawBodyBuffer, signatureHeader) {
47
+ if (!PAYSTACK_SECRET || !rawBodyBuffer || !signatureHeader) return false;
 
48
  try {
49
  const hmac = crypto.createHmac('sha512', PAYSTACK_SECRET);
50
  hmac.update(rawBodyBuffer);
51
  const expected = hmac.digest('hex');
 
 
52
  return crypto.timingSafeEqual(Buffer.from(expected, 'utf8'), Buffer.from(String(signatureHeader), 'utf8'));
53
  } catch (e) {
54
+ console.error('Signature verification error:', e);
55
  return false;
56
  }
57
  }
58
 
59
+ function extractSlugFromReferrer(refUrl) {
60
+ if (!refUrl || typeof refUrl !== 'string') return null;
61
+ // common patterns: https://paystack.shop/pay/<slug>, https://example.com/pay/<slug>?...
62
  try {
63
+ // quick regex: look for /pay/<slug> or /p/<slug>
64
+ const m = refUrl.match(/\/(?:pay|p)\/([^\/\?\#]+)/i);
65
+ if (m && m[1]) return m[1];
66
+ // fallback: last path segment
67
+ const parts = new URL(refUrl).pathname.split('/').filter(Boolean);
68
+ if (parts.length) return parts[parts.length - 1];
69
+ } catch (e) {
70
+ // invalid URL string; try fallback heuristic
71
+ const fallback = (refUrl.split('/').pop() || '').split('?')[0].split('#')[0];
72
+ return fallback || null;
73
  }
74
+ return null;
75
  }
76
 
77
+ /* expiry helper (same as before) */
78
+ const EXTRA_FREE_MS = 2 * 60 * 60 * 1000;
79
+ const WEEKLY_PLAN_IDS = new Set([3311892, 3305738, 'PLN_ngz4l76whecrpkv', 'PLN_f7a3oagrpt47d5f']);
80
+ const MONTHLY_PLAN_IDS = new Set([3305739, 'PLN_584ck56g65xhkum']);
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  function getExpiryFromPlan(planInput) {
82
+ let interval = null, planId = null, planCode = null;
83
+ if (!planInput) { interval = null; }
84
+ else if (typeof planInput === 'object') {
 
 
 
 
85
  planId = planInput.id ?? planInput.plan_id ?? null;
86
  planCode = planInput.plan_code ?? planInput.planCode ?? null;
87
+ interval = planInput.interval || planInput.billing_interval || null;
88
+ } else if (typeof planInput === 'number') planId = planInput;
89
+ else if (typeof planInput === 'string') { planCode = planInput; const asNum = Number(planInput); if (!Number.isNaN(asNum)) planId = asNum; }
 
 
 
 
 
90
 
91
  if (interval) {
92
  interval = String(interval).toLowerCase();
93
  if (interval.includes('week')) {
94
+ const expires = Date.now() + 7*24*60*60*1000 + EXTRA_FREE_MS;
95
  return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
96
  }
97
  if (interval.includes('month')) {
98
+ const expires = Date.now() + 30*24*60*60*1000 + EXTRA_FREE_MS;
99
  return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
100
  }
101
  if (interval.includes('hour')) {
102
+ const expires = Date.now() + 7*24*60*60*1000 + EXTRA_FREE_MS;
 
103
  return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
104
  }
105
  }
106
 
107
  if (planId && WEEKLY_PLAN_IDS.has(planId)) {
108
+ const expires = Date.now() + 7*24*60*60*1000 + EXTRA_FREE_MS;
109
  return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
110
  }
111
  if (planCode && WEEKLY_PLAN_IDS.has(planCode)) {
112
+ const expires = Date.now() + 7*24*60*60*1000 + EXTRA_FREE_MS;
113
  return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
114
  }
115
  if (planId && MONTHLY_PLAN_IDS.has(planId)) {
116
+ const expires = Date.now() + 30*24*60*60*1000 + EXTRA_FREE_MS;
117
  return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
118
  }
119
  if (planCode && MONTHLY_PLAN_IDS.has(planCode)) {
120
+ const expires = Date.now() + 30*24*60*60*1000 + EXTRA_FREE_MS;
121
  return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
122
  }
123
 
124
+ const expires = Date.now() + 30*24*60*60*1000 + EXTRA_FREE_MS;
125
  return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
126
  }
127
 
128
+ /* -------------------- Mapping resolution helpers -------------------- */
129
+
130
+ // get userId string from mapping doc (doc id == slug or where pageId==slug)
 
 
131
  async function getUserIdFromSlug(dbInstance, slugOrPageId) {
132
+ if (!dbInstance || !slugOrPageId) return null;
133
  try {
134
+ // doc id lookup
135
+ const docRef = dbInstance.collection('paystack-page-mappings').doc(String(slugOrPageId));
136
+ const snap = await docRef.get();
137
+ if (snap.exists) {
138
+ const d = snap.data();
139
+ if (d?.userId) {
140
+ console.log('Found mapping doc (by docId) for', slugOrPageId, ':', d);
141
+ return d.userId;
142
+ }
143
  }
144
+ // fallback query by pageId
 
145
  const q = await dbInstance.collection('paystack-page-mappings').where('pageId', '==', String(slugOrPageId)).limit(1).get();
146
  if (!q.empty) {
147
  const d = q.docs[0].data();
148
+ console.log('Found mapping doc (by pageId) for', slugOrPageId, ':', d);
149
  if (d?.userId) return d.userId;
150
  }
 
151
  return null;
152
  } catch (e) {
153
+ console.error('getUserIdFromSlug error:', e);
154
  return null;
155
  }
156
  }
157
 
158
+ // Attempt resolution: given mapping key (slug), return a users/<docRef> or null
159
+ async function resolveUserDocFromMapping(dbInstance, key) {
160
+ if (!dbInstance || !key) return null;
161
+ try {
162
+ // map to userId (string) first
163
+ const mappedUserId = await getUserIdFromSlug(dbInstance, key);
164
+ if (!mappedUserId) return null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
 
166
+ const usersRef = dbInstance.collection('users');
167
+
168
+ // try doc id first
169
+ try {
170
+ const directRef = usersRef.doc(String(mappedUserId));
171
+ const ds = await directRef.get();
172
+ if (ds.exists) {
173
+ console.log('Resolved user by direct doc id:', directRef.path);
174
+ return directRef;
 
175
  }
176
+ } catch (e) {
177
+ // continue to queries
178
  }
 
179
 
180
+ // if mappedUserId looks like email, try email query
181
+ const looksLikeEmail = String(mappedUserId).includes('@');
182
+ if (looksLikeEmail) {
183
+ try {
184
+ const q = await usersRef.where('email', '==', String(mappedUserId)).limit(1).get();
185
+ if (!q.empty) {
186
+ console.log('Resolved user by email query for', mappedUserId);
187
+ return q.docs[0].ref;
188
+ }
189
+ } catch (e) { /* ignore */ }
190
+ }
191
 
192
+ // fallback to common id fields
193
+ const idFields = ['userId','uid','id'];
194
+ for (const f of idFields) {
195
+ try {
196
+ const q = await usersRef.where(f,'==',mappedUserId).limit(1).get();
197
+ if (!q.empty) {
198
+ console.log('Resolved user by field', f, 'for', mappedUserId);
199
+ return q.docs[0].ref;
200
+ }
201
+ } catch (e) { /* ignore */ }
202
+ }
203
 
204
+ return null;
205
+ } catch (e) {
206
+ console.error('resolveUserDocFromMapping error:', e);
207
+ return null;
208
+ }
209
  }
210
 
211
+ /* -------------------- Fallback user resolution -------------------- */
212
+
 
213
  async function findUserDocRef(dbInstance, { metadataUserId, email, paystackCustomerId } = {}) {
214
  if (!dbInstance) return null;
215
  const usersRef = dbInstance.collection('users');
216
 
217
  if (metadataUserId) {
 
218
  if (!String(metadataUserId).includes('@')) {
219
  try {
220
  const docRef = usersRef.doc(String(metadataUserId));
221
+ const s = await docRef.get();
222
+ if (s.exists) return docRef;
223
+ } catch (e) {}
 
 
224
  }
225
 
226
+ const idFields = ['userId','uid','id'];
227
+ for (const f of idFields) {
 
228
  try {
229
+ const q = await usersRef.where(f,'==',metadataUserId).limit(1).get();
230
+ if (!q.empty) return q.docs[0].ref;
231
+ } catch (e) {}
 
 
232
  }
233
  }
234
 
 
235
  if (paystackCustomerId) {
236
  try {
237
+ const q = await usersRef.where('paystack_customer_id','==',String(paystackCustomerId)).limit(1).get();
238
+ if (!q.empty) return q.docs[0].ref;
239
+ } catch (e) {}
 
 
240
  }
241
 
242
  if (email) {
243
  try {
244
+ const q = await usersRef.where('email','==',String(email)).limit(1).get();
245
+ if (!q.empty) return q.docs[0].ref;
246
+ } catch (e) {}
 
 
247
  }
248
 
 
249
  return null;
250
  }
251
 
252
+ /* -------------------- Cleanup -------------------- */
253
+
 
 
 
 
 
254
  async function cleanUpAfterSuccessfulCharge(dbInstance, userDocRef, { slug, pageId, reference, email } = {}) {
255
  if (!dbInstance || !userDocRef) return;
256
  try {
257
+ const tryDelete = async (docId) => {
258
+ if (!docId) return;
259
  try {
260
+ const ref = dbInstance.collection('paystack-page-mappings').doc(String(docId));
261
+ const s = await ref.get();
262
+ if (!s.exists) return;
263
+ const map = s.data();
264
+ const owner = String(map.userId || '');
265
+ if (owner === String(userDocRef.id) || (email && owner === String(email))) {
266
+ await ref.delete();
267
+ console.log('Deleted mapping doc:', docId);
268
+ } else {
269
+ console.log('Mapping owner mismatch, not deleting:', docId, 'owner=', owner, 'user=', userDocRef.id);
 
 
270
  }
271
  } catch (e) {
272
+ console.error('Error deleting mapping doc', docId, e);
273
  }
274
+ };
275
+ await tryDelete(slug);
276
+ await tryDelete(pageId);
277
 
278
+ // optional: clear pending-payments
279
  try {
280
  const pendingRef = dbInstance.collection('pending-payments');
281
+ const q = await pendingRef.where('userId','==',userDocRef.id).limit(100).get();
282
  if (!q.empty) {
283
  const batch = dbInstance.batch();
284
+ q.docs.forEach(d => batch.delete(d.ref));
285
  await batch.commit();
286
  console.log('Deleted pending-payments for user:', userDocRef.id);
287
  }
288
  } catch (e) {
289
+ console.error('Failed deleting pending-payments (non-fatal):', e);
 
290
  }
291
 
292
+ // log cleanup
293
  try {
294
  await dbInstance.collection('paystack-cleanups').add({
295
  userRef: userDocRef.path,
296
  slug: slug || null,
297
+ pageId: pageId || null,
298
  reference: reference || null,
299
  email: email || null,
300
  cleanedAt: admin.firestore.FieldValue.serverTimestamp(),
301
  });
302
  } catch (e) {
303
+ console.error('Failed logging cleanup:', e);
304
  }
305
  } catch (e) {
306
+ console.error('Unexpected cleanup error:', e);
307
  }
308
  }
309
 
310
+ /* -------------------- Webhook route -------------------- */
311
+
 
312
  app.post('/webhook/paystack', express.raw({ type: 'application/json', limit: '1mb' }), async (req, res) => {
313
+ const raw = req.body;
314
  const signature = req.get('x-paystack-signature') || req.get('X-Paystack-Signature');
315
 
 
316
  if (!signature || !verifyPaystackSignature(raw, signature)) {
317
+ console.warn('Paystack webhook signature verify failed. header:', signature);
318
  return res.status(400).json({ ok: false, message: 'Invalid signature' });
319
  }
320
 
 
321
  const bodyStr = raw.toString('utf8');
322
  const payload = safeParseJSON(bodyStr);
323
+ if (!payload) return res.status(400).json({ ok: false, message: 'Invalid JSON' });
 
 
 
 
324
 
325
  const event = (payload.event || payload.type || '').toString();
326
  const isRefund = /refund/i.test(event);
327
  const isChargeSuccess = /charge\.success/i.test(event);
 
328
  const isPayment = isChargeSuccess;
329
 
330
+ if (!db) console.error('Firestore admin not initialized — cannot persist webhook data.');
331
+
332
+ // audit write
333
+ try {
334
+ if (db) {
335
+ await db.collection('paystack-webhooks').add({ event, payload, receivedAt: admin.firestore.FieldValue.serverTimestamp() });
336
+ }
337
+ } catch (e) {
338
+ console.error('Failed to persist webhook audit:', e);
339
  }
340
 
341
+ if (/subscription\.create/i.test(event) || isRefund || isPayment || /subscription\.update/i.test(event)) {
342
  console.log('--- PAYSTACK WEBHOOK (INTERESTING EVENT) ---');
343
  console.log('event:', event);
344
+ // payload.data is the object of interest
345
+ const data = payload.data || {};
346
+
347
+ // Extract slug candidate:
348
+ // prefer: data.page.id / data.page.slug / data.slug
349
+ // else: look into data.metadata.referrer URL and extract /pay/<slug>
350
+ let maybePageId = data.page?.id || data.page_id || null;
351
+ let maybeSlug = data.page?.slug || data.slug || null;
352
+
353
+ // Look for metadata.referrer (primary for your case)
354
+ const referrer = data.metadata?.referrer || (data.metadata && data.metadata.referrer) || null;
355
+ if (!maybeSlug && referrer) {
356
+ const extracted = extractSlugFromReferrer(String(referrer));
357
+ if (extracted) {
358
+ maybeSlug = extracted;
359
+ console.log('Extracted slug from metadata.referrer:', maybeSlug, ' (referrer=', referrer, ')');
360
+ } else {
361
+ console.log('Could not extract slug from referrer:', referrer);
362
  }
 
 
363
  }
364
 
365
+ // Also log the metadata object for debugging
366
+ console.log('payload.data.metadata (raw):', data.metadata);
367
 
368
+ // Try to extract userId from other places (metadata.custom_fields, customer.metadata, email)
369
  let metadataUserId = null;
370
  let customerEmail = null;
371
  let extractorSource = null;
 
 
372
  try {
373
+ // quick extraction: metadata.userId etc
374
+ const metadata = data.metadata || {};
375
+ if (metadata.userId || metadata.user_id) {
376
+ metadataUserId = metadata.userId || metadata.user_id;
377
+ extractorSource = 'metadata';
378
+ } else if (data.customer?.metadata) {
379
+ const cm = data.customer.metadata;
380
+ if (cm.userId || cm.user_id) {
381
+ metadataUserId = cm.userId || cm.user_id;
382
+ extractorSource = 'customer.metadata';
383
+ }
384
+ } else if (Array.isArray(data.custom_fields)) {
385
+ for (const f of data.custom_fields) {
386
+ const n = (f.variable_name || f.display_name || '').toString().toLowerCase();
387
+ if ((n.includes('user') || n.includes('user_id') || n.includes('userid')) && f.value) {
388
+ metadataUserId = f.value;
389
+ extractorSource = 'custom_fields';
390
+ break;
391
+ }
392
+ }
393
  }
394
  } catch (e) {
395
+ console.error('Error during quick metadata extraction:', e);
396
  }
397
 
 
398
  if (!customerEmail && data.customer?.email) customerEmail = data.customer.email;
 
 
 
 
 
 
399
  const paystackCustomerId = data.customer?.id ?? data.customer?.customer_code ?? null;
400
 
401
+ // Resolve user: mapping-first using maybeSlug (important)
402
  let userDocRef = null;
403
  try {
404
+ const mappingKey = maybeSlug || maybePageId || metadataUserId || null;
405
+ if (mappingKey && db) {
406
+ userDocRef = await resolveUserDocFromMapping(db, mappingKey);
407
+ if (userDocRef) console.log('resolveUserDocFromMapping found user:', userDocRef.path, 'using key:', mappingKey);
408
+ else console.log('resolveUserDocFromMapping found nothing for key:', mappingKey);
409
+ }
410
+ if (!userDocRef) {
411
+ userDocRef = await findUserDocRef(db, { metadataUserId, email: customerEmail, paystackCustomerId });
412
+ if (userDocRef) console.log('findUserDocRef found user:', userDocRef.path);
413
  }
414
+ } catch (e) {
415
+ console.error('Error resolving userDocRef (mapping-first):', e);
416
  userDocRef = null;
417
  }
418
 
419
+ // subscription.create handler
420
  if (/subscription\.create/i.test(event) || event === 'subscription.create') {
421
  const subscriptionCode = data.subscription_code || data.subscription?.subscription_code || (data.id ? String(data.id) : null);
422
  const status = data.status || 'active';
423
  const planObj = data.plan || data.subscription?.plan || null;
424
  const expiry = getExpiryFromPlan(planObj);
425
+ const paystackCustomerIdLocal = data.customer?.id ?? data.customer?.customer_code ?? null;
426
 
427
  if (userDocRef && subscriptionCode) {
428
  try {
 
438
  },
439
  updatedAt: admin.firestore.FieldValue.serverTimestamp(),
440
  };
441
+ if (paystackCustomerIdLocal) updateObj.paystack_customer_id = String(paystackCustomerIdLocal);
 
 
 
 
 
442
  await userDocRef.update(updateObj);
443
+ console.log('subscription.create: updated user with subscription:', subscriptionCode);
444
+ } catch (e) {
445
+ console.error('subscription.create: failed to update user:', e);
446
  }
447
  } else {
448
  console.warn('subscription.create received but user not found or subscriptionCode missing — skipping user update.');
449
  }
450
  }
451
 
452
+ // charge.success handler - entitlement add
453
  if (isPayment) {
454
+ console.log('charge.success identifiers:', { metadataUserId, customerEmail, maybeSlug, maybePageId, paystackCustomerId, extractorSource });
455
+
456
  const recurringMarker = Boolean((data.metadata && (data.metadata.custom_filters?.recurring || data.metadata.recurring)) || false);
457
  const hasSubscription = !!(data.subscription || data.subscriptions || data.plan);
458
  const isLikelySubscriptionPayment = recurringMarker || hasSubscription;
 
469
  plan: planObj ? { id: planObj.id, code: planObj.plan_code } : null,
470
  expiresAtMs: expiry.expiresAtMs,
471
  expiresAtIso: expiry.expiresAtIso,
472
+ createdAt: admin.firestore.Timestamp.now(),
473
  };
474
 
475
+ // debug record
476
+ try {
477
+ if (db) {
478
+ await db.collection('paystack-debug').add({
479
+ kind: 'charge-success',
480
+ mappingKey: maybeSlug || maybePageId || null,
481
+ identifiers: { metadataUserId, customerEmail, maybeSlug, maybePageId, paystackCustomerId, extractorSource },
482
+ entitlement,
483
+ raw: data,
484
+ createdAt: admin.firestore.FieldValue.serverTimestamp(),
485
+ });
486
+ }
487
+ } catch (e) {
488
+ console.error('Failed writing paystack-debug:', e);
489
+ }
490
+
491
  if (userDocRef && isLikelySubscriptionPayment) {
492
  try {
493
+ console.log('Adding entitlement to', userDocRef.path);
494
  await userDocRef.update({
495
  entitlements: admin.firestore.FieldValue.arrayUnion(entitlement),
 
496
  lastPaymentAt: admin.firestore.FieldValue.serverTimestamp(),
497
+ updatedAt: admin.firestore.FieldValue.serverTimestamp(),
498
  ...(paystackCustomerId ? { paystack_customer_id: String(paystackCustomerId) } : {}),
499
  });
500
+ console.log('Entitlement added (arrayUnion) to', userDocRef.path);
501
+ } catch (err) {
502
+ console.error('arrayUnion failed, falling back:', err);
503
+ // fallback: read-modify-write
504
  try {
505
+ const snap = await userDocRef.get();
506
+ const userData = snap.exists ? snap.data() : {};
507
+ const current = Array.isArray(userData.entitlements) ? userData.entitlements : [];
508
+ const exists = current.some(e => (e.reference || e.id) === (entitlement.reference || entitlement.id));
509
+ if (!exists) {
510
+ current.push(entitlement);
511
+ await userDocRef.update({
512
+ entitlements: current,
513
+ lastPaymentAt: admin.firestore.FieldValue.serverTimestamp(),
514
+ updatedAt: admin.firestore.FieldValue.serverTimestamp(),
515
+ ...(paystackCustomerId ? { paystack_customer_id: String(paystackCustomerId) } : {}),
516
+ });
517
+ console.log('Entitlement appended via fallback.');
518
+ } else {
519
+ console.log('Entitlement already present, skipping append.');
520
+ }
521
+ } catch (err2) {
522
+ console.error('Fallback persistence failed:', err2);
523
+ try {
524
+ if (db) {
525
+ await db.collection('paystack-debug-failures').add({
526
+ kind: 'entitlement-persist-failure',
527
+ userRef: userDocRef.path,
528
+ error: String(err2 && err2.message ? err2.message : err2),
529
+ entitlement,
530
+ raw: data,
531
+ createdAt: admin.firestore.FieldValue.serverTimestamp(),
532
+ });
533
+ }
534
+ } catch (e) {
535
+ console.error('Failed writing failure debug doc:', e);
536
+ }
537
  }
538
+ }
539
 
540
+ // cleanup (best effort)
541
+ try {
542
+ await cleanUpAfterSuccessfulCharge(db, userDocRef, { slug: maybeSlug, pageId: maybePageId, reference: entitlement.reference || entitlement.id, email: customerEmail });
543
+ } catch (e) {
544
+ console.error('Cleanup failed:', e);
545
  }
546
  } else if (userDocRef && !isLikelySubscriptionPayment) {
547
+ console.log('charge.success received but not flagged subscription/recurring - skipping entitlement add.');
548
  } else {
549
  console.warn('charge.success: user not found, skipping entitlement update.');
550
+ try {
551
+ if (db) {
552
+ await db.collection('paystack-unmatched').add({
553
+ kind: 'charge.success.unmatched',
554
+ mappingKey: maybeSlug || maybePageId || null,
555
+ identifiers: { metadataUserId, customerEmail, maybeSlug, maybePageId, paystackCustomerId, extractorSource },
556
+ raw: data,
557
+ createdAt: admin.firestore.FieldValue.serverTimestamp(),
558
+ });
559
+ }
560
+ } catch (e) { console.error('Failed creating unmatched debug doc:', e); }
561
  }
562
  }
563
 
564
+ // refunds
565
  if (isRefund) {
566
  const refund = data;
567
  const refundedReference = refund.reference || refund.transaction?.reference || refund.transaction?.id || null;
 
568
  if (userDocRef && refundedReference) {
569
  try {
570
  const snap = await userDocRef.get();
571
  if (snap.exists) {
572
  const userData = snap.data();
573
+ const current = Array.isArray(userData.entitlements) ? userData.entitlements : [];
574
+ const filtered = current.filter(e => {
575
+ const r = e.reference || e.id || '';
576
+ return r !== refundedReference && r !== String(refundedReference);
 
 
 
 
 
577
  });
578
+ await userDocRef.update({ entitlements: filtered, updatedAt: admin.firestore.FieldValue.serverTimestamp() });
579
+ console.log('Removed entitlements matching refund:', refundedReference);
580
  } else {
581
+ console.warn('Refund handling: user doc vanished.');
582
  }
583
+ } catch (e) {
584
+ console.error('Refund entitlement removal failed:', e);
585
  }
586
  } else {
587
+ console.warn('Refund: user or refundedReference missing; skipping.');
588
  }
589
  }
590
  } else {
591
+ console.log('Ignoring event:', event);
592
  }
593
 
594
  return res.status(200).json({ ok: true });
595
  });
596
 
597
+ /* -------------------- Create payment link endpoint -------------------- */
598
+
 
599
  app.post('/create-payment-link', express.json(), async (req, res) => {
600
  const { planId, userId, name, amount, redirect_url, collect_phone = false, fixed_amount = false } = req.body || {};
601
+ if (!planId) return res.status(400).json({ ok: false, message: 'planId required' });
602
+ if (!userId) return res.status(400).json({ ok: false, message: 'userId required' });
603
+ if (!name) return res.status(400).json({ ok: false, message: 'name required' });
604
 
605
+ const payload = { name, type: 'subscription', plan: planId, metadata: { userId: String(userId) }, collect_phone, fixed_amount };
606
+ if (amount) payload.amount = amount;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
607
  if (redirect_url) payload.redirect_url = redirect_url;
608
 
609
  try {
610
  const response = await axios.post('https://api.paystack.co/page', payload, {
611
+ headers: { Authorization: `Bearer ${PAYSTACK_SECRET}`, 'Content-Type': 'application/json' },
 
 
 
612
  timeout: 10_000,
613
  });
614
 
615
  const pageData = response.data && response.data.data ? response.data.data : response.data;
616
 
617
+ // persist mapping docs: docId = slug and docId = pageId if available
618
  try {
619
+ if (db) {
620
+ const slug = pageData.slug || pageData.data?.slug || null;
621
+ const pageId = pageData.id || pageData.data?.id || null;
622
+
623
+ if (slug) {
624
+ await db.collection('paystack-page-mappings').doc(String(slug)).set({
625
+ userId: String(userId),
626
+ userIdType: String(userId).includes('@') ? 'email' : 'uid',
627
+ pageId: pageId ? String(pageId) : null,
628
+ slug: String(slug),
629
+ createdAt: admin.firestore.FieldValue.serverTimestamp(),
630
+ }, { merge: true });
631
+ console.log('Saved page slug mapping for', slug);
632
+ }
633
+
634
+ if (pageId) {
635
+ await db.collection('paystack-page-mappings').doc(String(pageId)).set({
636
+ userId: String(userId),
637
+ userIdType: String(userId).includes('@') ? 'email' : 'uid',
638
+ pageId: String(pageId),
639
+ slug: slug || null,
640
+ createdAt: admin.firestore.FieldValue.serverTimestamp(),
641
+ }, { merge: true });
642
+ console.log('Saved pageId mapping for', pageId);
643
+ }
644
  }
645
  } catch (e) {
646
+ console.error('Failed to persist mapping docs:', e);
647
  }
648
 
649
  return res.status(201).json({ ok: true, page: pageData });
650
  } catch (err) {
651
+ console.error('Error creating Paystack page:', err?.response?.data || err.message || err);
652
  const errorDetail = err?.response?.data || { message: err.message };
653
  return res.status(500).json({ ok: false, error: errorDetail });
654
  }
655
  });
656
 
657
+ /* health */
658
+ app.get('/health', (_req, res) => res.json({ ok: true }));
659
 
660
  app.listen(PORT, () => {
661
  console.log(`Paystack webhook server listening on port ${PORT}`);