FAA.ZONE™ Documentation

PayPal Subscriptions Integration Manual

Minutes of Meeting: PayPal Subscriptions Integration

Date: June 11, 2025

Project: FAA™ Seedwave Admin Portal

Topic: Integration of PayPal Subscription Payments

This document provides a comprehensive guide for the setup, deployment, and management of PayPal subscription payments within the FAA™ Seedwave Admin Portal and associated product pages. It serves as an installation manual for staff, detailing code, configuration, and critical steps for live activation.

Key Architectural Decisions

Important Note on Currency:

All PayPal plans created via this integration are assumed to be in **ZAR**. Ensure your PayPal Business Account is set up to receive ZAR payments. If you intend to use another currency (e.g., USD), you **must** update the currency parameter in the PayPal SDK script (`currency=ZAR`) and the currencyCode in your backend's create-plan endpoint (`currencyCode: 'ZAR'`).

Prerequisites for Staff

Before proceeding with any steps, ensure the following are installed and accessible:

Installation & Setup Guide

Follow these detailed steps to set up and deploy the PayPal subscription integration.

I. Project Setup & Dependencies

  1. **Clone the Repository (if new staff):**
    git clone [YOUR_GITHUB_REPOSITORY_URL]
    cd seedwave
  2. **Navigate to Project Root:** Ensure your terminal is in the seedwave directory (where package.json resides).
    samantha@Samanthas-iMac my_payfast_app % cd ..
    samantha@Samanthas-iMac seedwave % pwd
    # Expected output: /Users/samantha/seedwave (or similar path to your project root)
  3. **Install Node.js Dependencies:**
    samantha@Samanthas-iMac seedwave % npm install node-fetch
    Note: node-fetch is for Node.js versions older than 18. If using Node.js 18+ (where fetch is built-in), this step is optional but harmless.

II. PayPal Live API Credentials & Vercel Environment Variables

Action: Obtain your **LIVE PayPal Client ID** and **LIVE PayPal Client Secret** from the PayPal Developer Dashboard.

  1. **Go to:** https://developer.paypal.com/ and log in to your Live PayPal Business Account.
  2. **Navigate to:** "My Apps & Credentials" → "Live".
  3. **Locate:** Your REST API app (e.g., "MyApp_Zoho" or the one you designated for live transactions).
  4. **Copy:** The **full, untruncated Client ID** and **Secret**.

Action: Set these as Environment Variables in Vercel. These variables will be securely accessed by your backend functions.

  1. **Go to:** Your Vercel project dashboard.
  2. **Navigate to:** "Settings" → "Environment Variables".
  3. **Add New Variables:**
    • Name: PAYPAL_LIVE_CLIENT_ID
    • Value: [PASTE_YOUR_FULL_LIVE_PAYPAL_CLIENT_ID_HERE]
    • Environments: Select `Production`, `Preview`, `Development`.
    • Name: PAYPAL_LIVE_CLIENT_SECRET
    • Value: [PASTE_YOUR_FULL_LIVE_PAYPAL_CLIENT_SECRET_HERE]
    • Environments: Select `Production`, `Preview`, `Development`.

III. Backend API Code Setup (`api/paypal/index.js`)

This serverless function handles all secure communication with PayPal's API.

  1. **File Path:** seedwave/api/paypal/index.js
  2. **Content Confirmation:** Ensure this file contains the following structure and settings:
    // api/paypal/index.js
    
    const fetch = require('node-fetch'); // Remove if Node.js >= 18
    
    async function generateAccessToken() {
        const clientId = process.env.PAYPAL_LIVE_CLIENT_ID;
        const clientSecret = process.env.PAYPAL_LIVE_CLIENT_SECRET;
        const auth = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
        const tokenUrl = 'https://api-m.paypal.com/v1/oauth2/token'; // LIVE endpoint
        // ... (rest of function logic) ...
    }
    
    module.exports = async (req, res) => {
        const PAYPAL_API_BASE_URL = 'https://api-m.paypal.com'; // LIVE API Base URL
        const { action } = req.query;
    
        if (req.method === 'POST') {
            try {
                const accessToken = await generateAccessToken();
                switch (action) {
                    case 'create-product': {
                        // ... (logic for creating product) ...
                        // currencyCode for create-plan: Ensure this is 'ZAR'
                    }
                    case 'create-plan': {
                        // ... (logic for creating plan) ...
                        // Ensure currencyCode in planBody is 'ZAR'
                    }
                    case 'create-subscription': {
                        // ... (logic for creating subscription) ...
                    }
                    case 'webhook': {
                        // ... (logic for handling webhooks) ...
                        // CRITICAL: Implement robust Webhook Signature Verification for LIVE!
                    }
                    // ... (default/error handling) ...
                }
            } catch (error) { /* ... */ }
        } else { /* ... */ }
    };
    

IV. Frontend HTML & JavaScript Integration

These files manage the user interface and interact with your backend API.

A. `public/admin-portal.html` (Admin Plan Deployment UI)

This file allows you to programmatically create (or log the IDs of manually created) PayPal Products and Plans in your LIVE PayPal account.

  1. **File Path:** seedwave/public/admin-portal.html
  2. **PayPal SDK Script Tag:** Located just before the </body> tag.
    <!-- PayPal JavaScript SDK - REQUIRED FOR SUBSCRIPTIONS -->
    <!-- NOW USING LIVE PAYPAL CLIENT ID -->
    <script src="https://www.paypal.com/sdk/js?client-id=BAAThS_oBJJ22PM5R1nVJ...¤cy=ZAR&vault=true&intent=subscription"></script>
    <!-- IMPORTANT: Replace 'BAAThS_oBJJ22PM5R1nVJ...' with the FULL, untruncated LIVE Client ID for 'MyApp_Zoho' or your primary live app. -->
    <!-- The 'currency' parameter MUST match the currency of your LIVE PayPal Plans (which we've set to ZAR). -->
    
  3. **JavaScript Block:** Within the main <script> tag, ensure the following constants and functions are present:
    
    // IMPORTANT: Replace this placeholder with your actual LIVE PayPal Product ID.
    // This is the ID you copied after creating your product in the LIVE PayPal Developer Dashboard.
    const YOUR_PAYPAL_PRODUCT_ID = 'PROD-YOUR_LIVE_PRODUCT_ID_HERE'; // <--- !!! REPLACE THIS WITH YOUR ACTUAL LIVE PRODUCT ID !!! --->
    
    async function deploySectorPlanToPayPal(sectorKey) {
        // ... (function logic as provided in previous response) ...
        // Note: currencyCode for create-plan call is 'ZAR'
    }
    
    async function initiateSubscription(tierName, rawAmount, sectorKey) {
        // ... (function logic as provided in previous response) ...
        // IMPORTANT: Plan IDs here must be your LIVE Plan IDs.
        // Example: planId = 'P-YOUR_AGRICULTURE_MONTHLY_LIVE_PLAN_ID';
    }
    

B. `public/products.html` (User Subscription UI)

This is the main user-facing page where customers select and subscribe to SAAS plans.

  1. **File Path:** seedwave/public/products.html
  2. **PayPal SDK Script Tag:** Located just before the </body> tag.
    <!-- PayPal JavaScript SDK - REQUIRED FOR SUBSCRIPTIONS -->
    <!-- NOW USING LIVE PAYPAL CLIENT ID -->
    <script src="https://www.paypal.com/sdk/js?client-id=BAAThS_oBJJ22PM5R1nVJ...¤cy=ZAR&vault=true&intent=subscription"></script>
    <!-- IMPORTANT: Replace 'BAAThS_oBJJ22PM5R1nVJ...' with the FULL, untruncated LIVE Client ID for 'MyApp_Zoho' or your primary live app. -->
    <!-- The 'currency' parameter MUST match the currency of your LIVE PayPal Plans (e.g., 'ZAR'). -->
    
  3. **Product Card Buttons:** Ensure each "Subscribe Now" button has the correct onclick and data- attributes.
    
    <button class="buy-now-button featured-button w-full bg-indigo-600 text-white font-semibold py-3 px-6 rounded-xl shadow-lg transition duration-300 ease-in-out transform hover:scale-105"
            data-product-name="Starter Package"
            data-amount="199.00"
            data-billing-cycle="MONTHLY"
            data-plan-key="Starter Package_MONTHLY"
            onclick="initiatePayPalSubscription(event)">
        Subscribe Now (Monthly)
    </button>
    
  4. **JavaScript Block:**
    
    // IMPORTANT: Replace this placeholder with your actual LIVE PayPal Product ID.
    const YOUR_PAYPAL_PRODUCT_ID = 'PROD-YOUR_LIVE_PRODUCT_ID_HERE'; // <--- !!! REPLACE THIS WITH YOUR LIVE PRODUCT ID !!! --->
    
    // IMPORTANT: You MUST replace these placeholders with the actual LIVE PayPal Plan IDs
    // obtained after manually creating them in the LIVE PayPal Developer Dashboard.
    const PAYPAL_PLAN_IDS = {
        "Starter Package_MONTHLY": "P-YOUR_STARTER_MONTHLY_LIVE_PLAN_ID",    // <--- !!! REPLACE WITH ACTUAL LIVE ID !!! --->
        "Starter Package_ANNUAL": "P-YOUR_STARTER_ANNUAL_LIVE_PLAN_ID",      // <--- !!! REPLACE WITH ACTUAL LIVE ID !!! --->
        // ... (add all other LIVE plan mappings here) ...
    };
    
    // Current logged-in user ID. Replace 'CURRENT_LOGGED_IN_USER_ID' with dynamic user ID from your auth system.
    const CURRENT_USER_ID = 'CURRENT_LOGGED_IN_USER_ID'; // <--- !!! REPLACE THIS !!! --->
    
    // ... (Currency Converter Logic as previously provided) ...
    
    // PayPal Subscription Initiation function
    async function initiatePayPalSubscription(event) {
        // ... (function logic as previously provided) ...
        // Note: This call will now use LIVE backend credentials.
    }
    
    document.querySelectorAll('.buy-now-button').forEach(button => {
        button.addEventListener('click', initiatePayPalSubscription);
    });
    

C. Redirect Pages

These static pages provide feedback to the user after completing or cancelling a PayPal flow.

V. PayPal Live Webhook Configuration (CRITICAL)

This is absolutely essential for receiving real-time updates from PayPal about subscription status, payment completions, failures, and cancellations. Without this, your internal systems (e.g., user access, Zoho Books) will not be reliably updated.

  1. **Log into:** https://developer.paypal.com/ with your **Live PayPal Business Account**.
  2. **Navigate to:** "My Apps & Credentials" → "Live" → Your REST API App.
  3. **Scroll down to "WEBHOOKS"** and click "Add Webhook".
  4. **Webhook URL:** Enter your deployed live API endpoint:
    https://seedwave.faa.zone/api/paypal?action=webhook
  5. **Event Types:** Select the following events (at a minimum). These cover the full subscription lifecycle:
    • `BILLING.SUBSCRIPTION.ACTIVATED`
    • `BILLING.SUBSCRIPTION.CANCELLED`
    • `BILLING.SUBSCRIPTION.PAYMENT.COMPLETED`
    • `BILLING.SUBSCRIPTION.PAYMENT.FAILED`
    • `BILLING.SUBSCRIPTION.SUSPENDED`
    • `BILLING.SUBSCRIPTION.UPDATED`
    • `PAYMENT.CAPTURE.COMPLETED` (for initial setup fee if any)
    • `CUSTOMER.DISPUTE.CREATED` (for chargebacks/disputes)
  6. Click **"Save"**. Note down the Webhook ID for your records (useful for debugging).

Final Placeholder Replacements (CRITICAL FOR LIVE!)

Before deploying, you **MUST** ensure all placeholder values below are replaced with your **ACTUAL LIVE PayPal IDs**. Failure to do so will result in failed transactions.

Deployment to Vercel

Once all code changes are committed and placeholders replaced:

  1. **Commit & Push Changes to GitHub:**
    samantha@Samanthas-iMac seedwave % git add .
    samantha@Samanthas-iMac seedwave % git commit -m "feat: Integrated live PayPal Subscriptions and finalized setup"
    samantha@Samanthas-iMac seedwave % git push origin main # Or your main branch name
  2. **Deploy to Production via Vercel CLI (or through your connected Git repository):**
    samantha@Samanthas-iMac seedwave % vercel --prod
    This will deploy your application to your live domain (e.g., https://seedwave.faa.zone).

Post-Deployment Testing (LIVE Environment)

Perform thorough testing of the entire subscription flow in your LIVE environment. Use **real PayPal accounts and real money** for these tests.

  1. **Admin Test (from deployed admin-portal.html):**
    • Confirm the "Deploy Plan" button **does not** create duplicate plans if clicked again (PayPal API handles idempotency, but verify the output).
    • Confirm the displayed Plan IDs match your manually created LIVE plans.
  2. **User Subscription Test (from deployed products.html):**
    • Access your deployed products.html (e.g., https://seedwave.faa.zone/products.html).
    • Test the currency converter.
    • Click "Subscribe Now" for a product.
    • Complete the PayPal payment flow.
    • Verify successful redirection to subscription-success.html.
  3. **Backend & Webhook Monitoring:**
    • Check your Vercel dashboard logs for messages from the /api/paypal?action=webhook endpoint. You should see `BILLING.SUBSCRIPTION.ACTIVATED` and `BILLING.SUBSCRIPTION.PAYMENT.COMPLETED` events for successful subscriptions.
    • Confirm your internal systems (e.g., Zoho Books/CRM, user access management) are updated based on webhook data.
    • Verify the new subscription appears in your **LIVE PayPal Business Account** under "Subscriptions".