Spaces:
Sleeping
Sleeping
Update app.js
Browse files
app.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
// paystack-webhook.js
|
| 2 |
-
// Node >= 14
|
| 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
|
| 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
|
| 49 |
} else {
|
| 50 |
db = admin.firestore();
|
| 51 |
}
|
| 52 |
}
|
| 53 |
-
} catch (
|
| 54 |
-
console.error('Failed to
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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('
|
| 73 |
return false;
|
| 74 |
}
|
| 75 |
}
|
| 76 |
|
| 77 |
-
|
| 78 |
-
|
|
|
|
| 79 |
try {
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
}
|
|
|
|
| 84 |
}
|
| 85 |
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
const
|
| 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 |
-
|
| 106 |
-
|
| 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 =
|
| 114 |
-
} else if (typeof planInput === 'number')
|
| 115 |
-
|
| 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
|
| 126 |
return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
|
| 127 |
}
|
| 128 |
if (interval.includes('month')) {
|
| 129 |
-
const expires = Date.now() + 30
|
| 130 |
return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
|
| 131 |
}
|
| 132 |
if (interval.includes('hour')) {
|
| 133 |
-
|
| 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
|
| 141 |
return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
|
| 142 |
}
|
| 143 |
if (planCode && WEEKLY_PLAN_IDS.has(planCode)) {
|
| 144 |
-
const expires = Date.now() + 7
|
| 145 |
return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
|
| 146 |
}
|
| 147 |
if (planId && MONTHLY_PLAN_IDS.has(planId)) {
|
| 148 |
-
const expires = Date.now() + 30
|
| 149 |
return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
|
| 150 |
}
|
| 151 |
if (planCode && MONTHLY_PLAN_IDS.has(planCode)) {
|
| 152 |
-
const expires = Date.now() + 30
|
| 153 |
return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
|
| 154 |
}
|
| 155 |
|
| 156 |
-
const expires = Date.now() + 30
|
| 157 |
return { expiresAtMs: expires, expiresAtIso: new Date(expires).toISOString() };
|
| 158 |
}
|
| 159 |
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
//
|
| 163 |
-
// - fallback: query where pageId == slug
|
| 164 |
-
// ------------------------------
|
| 165 |
async function getUserIdFromSlug(dbInstance, slugOrPageId) {
|
| 166 |
-
if (!
|
| 167 |
try {
|
| 168 |
-
//
|
| 169 |
-
const
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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('
|
| 185 |
return null;
|
| 186 |
}
|
| 187 |
}
|
| 188 |
|
| 189 |
-
//
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 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 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
if (k.toLowerCase().includes('user')) return { userId: metadata.custom_fields[k], source: 'metadata.custom_fields_object' };
|
| 221 |
}
|
|
|
|
|
|
|
| 222 |
}
|
| 223 |
-
}
|
| 224 |
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
|
| 232 |
-
|
| 233 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
|
| 235 |
-
|
| 236 |
-
|
|
|
|
|
|
|
|
|
|
| 237 |
}
|
| 238 |
|
| 239 |
-
|
| 240 |
-
|
| 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
|
| 252 |
-
if (
|
| 253 |
-
} catch (e) {
|
| 254 |
-
// continue to queries
|
| 255 |
-
}
|
| 256 |
}
|
| 257 |
|
| 258 |
-
|
| 259 |
-
const
|
| 260 |
-
for (const field of idFields) {
|
| 261 |
try {
|
| 262 |
-
const
|
| 263 |
-
if (!
|
| 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
|
| 274 |
-
if (!
|
| 275 |
-
} catch (e) {
|
| 276 |
-
// ignore
|
| 277 |
-
}
|
| 278 |
}
|
| 279 |
|
| 280 |
if (email) {
|
| 281 |
try {
|
| 282 |
-
const
|
| 283 |
-
if (!
|
| 284 |
-
} catch (e) {
|
| 285 |
-
// ignore
|
| 286 |
-
}
|
| 287 |
}
|
| 288 |
|
| 289 |
-
// Not found
|
| 290 |
return null;
|
| 291 |
}
|
| 292 |
|
| 293 |
-
|
| 294 |
-
|
| 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 |
-
|
| 304 |
-
|
| 305 |
try {
|
| 306 |
-
const
|
| 307 |
-
const
|
| 308 |
-
if (
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
console.log('Skipping deletion of mapping for slug (owner mismatch):', slug);
|
| 317 |
-
}
|
| 318 |
}
|
| 319 |
} catch (e) {
|
| 320 |
-
console.error('Error deleting
|
| 321 |
}
|
| 322 |
-
}
|
|
|
|
|
|
|
| 323 |
|
| 324 |
-
//
|
| 325 |
try {
|
| 326 |
const pendingRef = dbInstance.collection('pending-payments');
|
| 327 |
-
const q = await pendingRef.where('userId',
|
| 328 |
if (!q.empty) {
|
| 329 |
const batch = dbInstance.batch();
|
| 330 |
-
q.docs.forEach(
|
| 331 |
await batch.commit();
|
| 332 |
console.log('Deleted pending-payments for user:', userDocRef.id);
|
| 333 |
}
|
| 334 |
} catch (e) {
|
| 335 |
-
|
| 336 |
-
console.error('Failed to delete pending-payments (non-fatal):', e);
|
| 337 |
}
|
| 338 |
|
| 339 |
-
//
|
| 340 |
try {
|
| 341 |
await dbInstance.collection('paystack-cleanups').add({
|
| 342 |
userRef: userDocRef.path,
|
| 343 |
slug: slug || null,
|
| 344 |
-
pageId: pageId
|
| 345 |
reference: reference || null,
|
| 346 |
email: email || null,
|
| 347 |
cleanedAt: admin.firestore.FieldValue.serverTimestamp(),
|
| 348 |
});
|
| 349 |
} catch (e) {
|
| 350 |
-
console.error('Failed
|
| 351 |
}
|
| 352 |
} catch (e) {
|
| 353 |
-
console.error('Unexpected error
|
| 354 |
}
|
| 355 |
}
|
| 356 |
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
// ------------------------
|
| 360 |
app.post('/webhook/paystack', express.raw({ type: 'application/json', limit: '1mb' }), async (req, res) => {
|
| 361 |
-
const raw = req.body;
|
| 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
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 387 |
}
|
| 388 |
|
| 389 |
-
if (
|
| 390 |
console.log('--- PAYSTACK WEBHOOK (INTERESTING EVENT) ---');
|
| 391 |
console.log('event:', event);
|
| 392 |
-
//
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 402 |
}
|
| 403 |
-
} catch (err) {
|
| 404 |
-
console.error('Failed to persist webhook audit:', err);
|
| 405 |
}
|
| 406 |
|
| 407 |
-
|
|
|
|
| 408 |
|
| 409 |
-
// Try to extract userId
|
| 410 |
let metadataUserId = null;
|
| 411 |
let customerEmail = null;
|
| 412 |
let extractorSource = null;
|
| 413 |
-
let maybeSlug = null;
|
| 414 |
-
let maybePageId = null;
|
| 415 |
try {
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 423 |
}
|
| 424 |
} catch (e) {
|
| 425 |
-
console.error('Error
|
| 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 |
-
//
|
| 439 |
let userDocRef = null;
|
| 440 |
try {
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
|
|
|
|
|
|
| 448 |
}
|
| 449 |
-
} catch (
|
| 450 |
-
console.error('Error
|
| 451 |
userDocRef = null;
|
| 452 |
}
|
| 453 |
|
| 454 |
-
//
|
| 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
|
| 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(
|
| 484 |
-
} catch (
|
| 485 |
-
console.error('
|
| 486 |
}
|
| 487 |
} else {
|
| 488 |
console.warn('subscription.create received but user not found or subscriptionCode missing — skipping user update.');
|
| 489 |
}
|
| 490 |
}
|
| 491 |
|
| 492 |
-
//
|
| 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.
|
| 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 |
-
|
| 520 |
...(paystackCustomerId ? { paystack_customer_id: String(paystackCustomerId) } : {}),
|
| 521 |
});
|
| 522 |
-
console.log('
|
| 523 |
-
|
| 524 |
-
|
|
|
|
| 525 |
try {
|
| 526 |
-
await
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 534 |
}
|
|
|
|
| 535 |
|
| 536 |
-
|
| 537 |
-
|
|
|
|
|
|
|
|
|
|
| 538 |
}
|
| 539 |
} else if (userDocRef && !isLikelySubscriptionPayment) {
|
| 540 |
-
console.log('charge.success received but not
|
| 541 |
} else {
|
| 542 |
console.warn('charge.success: user not found, skipping entitlement update.');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 543 |
}
|
| 544 |
}
|
| 545 |
|
| 546 |
-
//
|
| 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
|
| 557 |
-
const filtered =
|
| 558 |
-
const
|
| 559 |
-
return
|
| 560 |
-
});
|
| 561 |
-
|
| 562 |
-
await userDocRef.update({
|
| 563 |
-
entitlements: filtered,
|
| 564 |
-
updatedAt: admin.firestore.FieldValue.serverTimestamp(),
|
| 565 |
});
|
| 566 |
-
|
|
|
|
| 567 |
} else {
|
| 568 |
-
console.warn('Refund handling: user doc
|
| 569 |
}
|
| 570 |
-
} catch (
|
| 571 |
-
console.error('
|
| 572 |
}
|
| 573 |
} else {
|
| 574 |
-
console.warn('Refund
|
| 575 |
}
|
| 576 |
}
|
| 577 |
} else {
|
| 578 |
-
console.log(
|
| 579 |
}
|
| 580 |
|
| 581 |
return res.status(200).json({ ok: true });
|
| 582 |
});
|
| 583 |
|
| 584 |
-
|
| 585 |
-
|
| 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 |
-
|
| 591 |
-
if (
|
| 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 |
-
//
|
| 621 |
try {
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 638 |
}
|
| 639 |
} catch (e) {
|
| 640 |
-
console.error('Failed to persist
|
| 641 |
}
|
| 642 |
|
| 643 |
return res.status(201).json({ ok: true, page: pageData });
|
| 644 |
} catch (err) {
|
| 645 |
-
console.error('Error creating Paystack
|
| 646 |
const errorDetail = err?.response?.data || { message: err.message };
|
| 647 |
return res.status(500).json({ ok: false, error: errorDetail });
|
| 648 |
}
|
| 649 |
});
|
| 650 |
|
| 651 |
-
|
| 652 |
-
app.get('/health', (
|
| 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}`);
|