REDROOM
PHP 8.2.30
Path:
Logout
Edit File
Size: 7.96 KB
Close
/home/byroehnu/easepay.easetack.com/services/flutterwaveService.js
Text
Base64
// services/flutterwaveService.js - Flutterwave Integration Service const Flutterwave = require('flutterwave-node-v3'); const { prisma } = require('../config/prisma'); class FlutterwaveService { constructor() { this.flw = new Flutterwave( process.env.FLW_PUBLIC_KEY, process.env.FLW_SECRET_KEY ); } /** * Create a subscription plan in Flutterwave * @param {Object} planData - Plan details * @returns {Object} Created plan data */ async createPlan(planData) { try { const { name, amount, interval, currency = "NGN" } = planData; const payload = { amount: amount, name: name, interval: interval, // 'monthly', 'yearly' currency: currency, duration: 0 // 0 means infinite until cancelled }; console.log(`📦 Creating Flutterwave plan: ${name} - ${interval}`); const response = await this.flw.PaymentPlan.create(payload); if (response.status === 'success') { console.log(`✅ Plan created successfully: ${response.data.id}`); return response.data; } else { throw new Error(`Plan creation failed: ${response.message}`); } } catch (error) { console.error("❌ Flutterwave plan creation failed:", error); throw error; } } /** * Create a customer in Flutterwave * @param {Object} customerData - Customer details * @returns {Object} Created customer data */ async createCustomer(customerData) { try { const { email, phone, name } = customerData; const payload = { email: email, phonenumber: phone, name: name }; console.log(`👤 Creating Flutterwave customer: ${email}`); const response = await this.flw.Customer.create(payload); if (response.status === 'success') { console.log(`✅ Customer created successfully: ${response.data.id}`); return response.data; } else { throw new Error(`Customer creation failed: ${response.message}`); } } catch (error) { console.error("❌ Flutterwave customer creation failed:", error); throw error; } } /** * Generate payment link for subscription * @param {Object} subscriptionData - Subscription details * @returns {Object} Payment link data */ async generatePaymentLink(subscriptionData) { try { const { planId, customer, tx_ref, redirect_url, callback_url } = subscriptionData; const payload = { tx_ref: tx_ref, amount: customer.amount, currency: "NGN", payment_plan: planId, redirect_url: redirect_url, customer: { email: customer.email, phonenumber: customer.phone, name: customer.name }, customizations: { title: "EasePay Subscription", description: `Subscribe to ${customer.planName} plan`, logo: "https://your-logo-url.com/logo.png" }, callback_url: callback_url }; console.log(`💳 Generating payment link for: ${customer.email}`); const response = await this.flw.PaymentLink.create(payload); if (response.status === 'success') { console.log(`✅ Payment link generated: ${response.data.link}`); return response.data; } else { throw new Error(`Payment link generation failed: ${response.message}`); } } catch (error) { console.error("❌ Payment link generation failed:", error); throw error; } } /** * Cancel a subscription in Flutterwave * @param {string} subscriptionId - Flutterwave subscription ID * @returns {Object} Cancellation result */ async cancelSubscription(subscriptionId) { try { console.log(`❌ Cancelling Flutterwave subscription: ${subscriptionId}`); const response = await this.flw.Subscription.cancel({ id: subscriptionId }); if (response.status === 'success') { console.log(`✅ Subscription cancelled successfully`); return response.data; } else { throw new Error(`Subscription cancellation failed: ${response.message}`); } } catch (error) { console.error("❌ Subscription cancellation failed:", error); throw error; } } /** * Verify webhook signature * @param {string} signature - Webhook signature * @param {string} secretHash - Secret hash from environment * @returns {boolean} Verification result */ verifyWebhookSignature(signature, secretHash) { return signature && signature === secretHash; } /** * Initialize default plans in the system */ async initializePlans() { try { console.log('🏗️ Initializing subscription plans...'); const defaultPlans = [ { name: "Free", description: "Perfect for getting started", priceMonthly: 0, priceYearly: 0, maxInvoices: 5, maxTeamMembers: 1, maxReportExports: 2, hasAdvancedReports: false, hasAPIAccess: false, sortOrder: 1 }, { name: "Basic", description: "Ideal for small businesses", priceMonthly: 2000, priceYearly: 20000, maxInvoices: 50, maxTeamMembers: 3, maxReportExports: 10, hasAdvancedReports: true, hasAPIAccess: false, sortOrder: 2 }, { name: "Pro", description: "For growing businesses", priceMonthly: 5000, priceYearly: 50000, maxInvoices: 200, maxTeamMembers: 10, maxReportExports: 50, hasAdvancedReports: true, hasAPIAccess: true, hasPrioritySupport: true, sortOrder: 3 }, { name: "Enterprise", description: "For large organizations", priceMonthly: 10000, priceYearly: 100000, maxInvoices: -1, // Unlimited maxTeamMembers: -1, // Unlimited maxReportExports: -1, // Unlimited hasAdvancedReports: true, hasAPIAccess: true, hasPrioritySupport: true, sortOrder: 4 } ]; for (const planData of defaultPlans) { // Check if plan already exists const existingPlan = await prisma.plan.findUnique({ where: { name: planData.name } }); if (!existingPlan) { let flwPlanIdMonthly = null; let flwPlanIdYearly = null; // Create Flutterwave plans for paid plans if (planData.priceMonthly > 0) { const monthlyPlan = await this.createPlan({ name: `${planData.name} - Monthly`, amount: planData.priceMonthly, interval: "monthly" }); flwPlanIdMonthly = monthlyPlan.id; } if (planData.priceYearly > 0) { const yearlyPlan = await this.createPlan({ name: `${planData.name} - Yearly`, amount: planData.priceYearly, interval: "yearly" }); flwPlanIdYearly = yearlyPlan.id; } // Create plan in database await prisma.plan.create({ data: { ...planData, flwPlanIdMonthly, flwPlanIdYearly } }); console.log(`✅ Plan created: ${planData.name}`); } else { console.log(`⏭️ Plan already exists: ${planData.name}`); } } console.log('🎉 Plan initialization complete!'); } catch (error) { console.error('❌ Plan initialization failed:', error); throw error; } } } module.exports = new FlutterwaveService();
Save
Close
Exit & Reset
Text mode: syntax highlighting auto-detects file type.
Directory Contents
Dirs: 1 × Files: 4
Delete Selected
Select All
Select None
Sort:
Name
Size
Modified
Enable drag-to-move
Name
Size
Perms
Modified
Actions
services
DIR
-
drwxr-xr-x
2026-03-21 09:47:23
Edit
Download
Rename
Chmod
Change Date
Delete
OK
Cancel
recursive
OK
Cancel
recursive
OK
Cancel
.htaccess
127 B
lr--r--r--
2026-03-14 01:49:04
Edit
Download
Rename
Chmod
Change Date
Delete
OK
Cancel
recursive
OK
Cancel
recursive
OK
Cancel
flutterwaveService.js
7.96 KB
lrw-r--r--
2026-02-21 08:13:30
Edit
Download
Rename
Chmod
Change Date
Delete
OK
Cancel
recursive
OK
Cancel
recursive
OK
Cancel
notificationService.js
1.75 KB
lrw-r--r--
2026-02-23 08:53:43
Edit
Download
Rename
Chmod
Change Date
Delete
OK
Cancel
recursive
OK
Cancel
recursive
OK
Cancel
otpService.js
8.73 KB
lrw-r--r--
2026-03-02 02:04:36
Edit
Download
Rename
Chmod
Change Date
Delete
OK
Cancel
recursive
OK
Cancel
recursive
OK
Cancel
Zip Selected
If ZipArchive is unavailable, a
.tar
will be created (no compression).