McTaba Labs logo
Software EngineeringThe WhiteboardProjectsEventsMasterclassesWebinarsLearn
Book Call

500+ developers already in the community

Get answers, find accountability partners, and stay ahead

Join Discord →
McTaba Labs logo

Educating 1 million students in tech by 2030.

Programs

  • HighSchool Graduates Launchpad
  • AI & Business Automation
  • Corporate Training
  • McTaba Story & Mission
  • Full-Stack Curriculum
  • Course Pricing & Plans
  • Frequently Asked Questions

Resources

  • Join Discord Community
  • Tech Events in Nairobi
  • Masterclasses
  • Free Resources
  • Learn
  • Campus
  • Africa Tech Talent Report
  • Partner With Us
  • Start a Project
  • Our Work

Contact Us

  • 124 Manyani East Road, Lavington, Nairobi
  • +254727795603
  • Book a Discovery Call

Office Hours:

Mon-Fri: 9am - 2pm EAT

Sat: 10am - 12pm EAT

© 2027 McTaba Labs - A product of Edtech Industries. All rights reserved.

Privacy PolicyTerms of ServiceRefund Policy
  1. Learn
  2. Paystack for African Developers
  3. Accept Payments with Paystack in Firebase Cloud Functions
Bonaventure OgetoBy Bonaventure Ogeto|Updated July 22, 2026

Accept Payments with Paystack in Firebase Cloud Functions

Create a Firebase Cloud Function using onRequest (v2). Store your Paystack secret key with firebase functions:secrets:set PAYSTACK_SECRET_KEY. In the function, access it with process.env.PAYSTACK_SECRET_KEY, call the Paystack initialize endpoint using native fetch (Node 18+), and return the authorization URL to your frontend.

In this article

  1. 1. Setup: Secret and Project
  2. 2. Initialize Transaction Function
  3. 3. Deploy and Call from Frontend
  4. 4. Learn More

Setup: Secret and Project

# Initialize Cloud Functions if not already done
firebase init functions
# Choose TypeScript, Node 18

# Store Paystack secret key as a Firebase secret
firebase functions:secrets:set PAYSTACK_SECRET_KEY

# Install dependencies
cd functions
npm install cors
npm install --save-dev @types/cors

Initialize Transaction Function

// functions/src/index.ts
import { onRequest } from "firebase-functions/v2/https";
import { defineSecret } from "firebase-functions/params";
import * as cors from "cors";

const paystackSecretKey = defineSecret("PAYSTACK_SECRET_KEY");
const corsHandler = cors({ origin: true });

export const initializePayment = onRequest(
  { secrets: [paystackSecretKey] },
  async (req, res) => {
    corsHandler(req, res, async () => {
      if (req.method !== "POST") {
        res.status(405).send("Method not allowed");
        return;
      }

      const secretKey = paystackSecretKey.value();
      const { email, amount } = req.body;

      if (!email || !amount) {
        res.status(400).json({ error: "email and amount are required" });
        return;
      }

      const reference = "fcn_" + Date.now() + "_" + Math.random().toString(36).slice(2, 8);

      try {
        const paystackRes = await fetch(
          "https://api.paystack.co/transaction/initialize",
          {
            method: "POST",
            headers: {
              Authorization: "Bearer " + secretKey,
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              email,
              amount: Math.round(Number(amount) * 100),
              reference,
            }),
          }
        );

        const data = await paystackRes.json();

        if (!data.status) {
          res.status(400).json({ error: data.message });
          return;
        }

        res.json({
          authorization_url: data.data.authorization_url,
          access_code: data.data.access_code,
          reference: data.data.reference,
        });
      } catch (error) {
        res.status(500).json({ error: "Failed to initialize payment" });
      }
    });
  }
);

Get weekly developer tips

Join 25,000+ developers. Practical guides, job tips, and new content — straight to your inbox.

No spam. Unsubscribe anytime.

Deploy and Call from Frontend

# Deploy the function
firebase deploy --only functions:initializePayment

# Get the function URL from the console or CLI output:
# https://<region>-<project-id>.cloudfunctions.net/initializePayment
// Frontend call
async function initializePayment(email: string, amount: number) {
  var response = await fetch(
    "https://<region>-<project-id>.cloudfunctions.net/initializePayment",
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email, amount }),
    }
  )

  var data = await response.json()
  // data.authorization_url — redirect or open in WebView
  window.location.href = data.authorization_url
}

Learn More

This guide is part of the Paystack integration guides by language and framework series.

Next: Verify Paystack Payments in Firebase Cloud Functions

Sign up for the McTaba newsletter

Key Takeaways

  • ✓Use Firebase Cloud Functions v2 (onRequest) for Paystack backend. Node 18+ includes native fetch.
  • ✓Store the secret key with: firebase functions:secrets:set PAYSTACK_SECRET_KEY
  • ✓Declare the secret in your function: { secrets: ["PAYSTACK_SECRET_KEY"] }. Access with process.env.PAYSTACK_SECRET_KEY.
  • ✓Handle CORS in the function using the cors npm package or manual header setting.
  • ✓Deploy with: firebase deploy --only functions:initializePayment
  • ✓Call the function URL from your frontend. Get it from the Firebase console or CLI output.

Frequently Asked Questions

Should I use Firebase Cloud Functions v1 or v2 for Paystack?
Use v2 (firebase-functions/v2/https). It has native secret management with defineSecret, runs on Node 18 with native fetch, and has better cold start performance. V1 is legacy. The code pattern is slightly different — v2 uses onRequest() as a named export, not functions.https.onRequest().
How do I store the Paystack secret key in Firebase?
Use Firebase Secrets: run firebase functions:secrets:set PAYSTACK_SECRET_KEY in your terminal and paste the key when prompted. In your function, declare it with defineSecret("PAYSTACK_SECRET_KEY") and pass it to the secrets array in onRequest options. Access the value with paystackSecretKey.value() inside the function.
Do I need to install node-fetch in Firebase Cloud Functions?
Not if you use Node 18 or above (the default for v2 functions). Node 18 includes native fetch. If your functions are still on Node 16, install node-fetch@2 (CommonJS compatible) with npm install node-fetch@2.
How do I handle CORS for Paystack Cloud Functions called from a browser?
Install the cors npm package and wrap your handler with corsHandler(req, res, async () => { ... }). For simple cases, you can also set headers manually: res.set("Access-Control-Allow-Origin", "*") before returning the response. Handle OPTIONS preflight by returning 204 with the CORS headers.

Learn Paystack Integration

KES 2,999

The definitive guide to building payment systems with Paystack — from your first transaction to production-grade payment infrastructure across Africa. 9 modules, 47 lessons. Free preview available.

Start Paystack Course

Not ready? Create Free Account

Keep reading

Paystack Integration Guides by Language and Framework

A complete directory of Paystack integration guides organized by programming language and framework. Each guide covers accepting payments, verifying transactions, handling webhooks, and building subscriptions in your specific stack.

Read more

Verify Paystack Payments in Firebase Cloud Functions

Verify Paystack payments server-side using Firebase Cloud Functions. This guide covers reading the transaction reference, calling the Paystack verify endpoint, validating the amount against Firestore, and updating the order status.

Read more

Handle Paystack Webhooks in Firebase Cloud Functions

Handle Paystack webhook events in Firebase Cloud Functions. This guide covers HMAC SHA512 signature verification using Node.js crypto, reading the raw request body, returning 200 before processing, and updating Firestore with payment results.

Read more

Build Paystack Subscriptions in Firebase Cloud Functions

Add recurring billing to a Firebase project using Paystack subscriptions and Cloud Functions. This guide covers subscription checkout with a plan code, webhook handling for subscription.create and invoice.payment_failed, and checking subscription status from Firestore.

Read more

Why You Must Never Call the Paystack API From Your Frontend

Putting your Paystack secret key in frontend JavaScript is the most dangerous mistake in payment integration. This guide shows exactly what goes wrong, why CORS will also fight you, and the correct pattern: frontend talks to your server, your server talks to Paystack.

Read more

Paystack Transaction References: Design Patterns That Prevent Chaos

Your transaction reference is the single string that ties a Paystack payment to your internal records. A sloppy reference scheme leads to duplicate charges, mystery transactions, and 2 AM debugging sessions. This guide covers UUID, sequential, and composite patterns with code for each.

Read more

Explore related topics

M-Pesa & African Stack

M-Pesa Daraja API tutorials, USSD development, and WhatsApp Business API guides. The African Stack that global bootcamps do not teach.

Learn to Code in Kenya

Everything a Kenyan needs to know before writing their first line of code. Career paths, real costs, hardware requirements, and honest answers about what it takes.

Learning to Code

Roadmaps, language guides, and practical advice for learning to code and launching a programming career.

Breaking Into Tech

Practical, no-nonsense guides for anyone looking to start or change their career in tech. From choosing your first language to acing interviews.

The African Stack: Skills for This Market

The skills that make Kenyan developers hard to replace: M-Pesa, USSD, WhatsApp, fintech, and building for the African market.

Bonaventure Ogeto

Bonaventure Ogeto

Founder, McTaba Labs

Bonaventure is the founder of McTaba Labs, a coding bootcamp in Nairobi, Kenya. He has spent years building products for the African market and mentoring the next generation of developers across the continent.