Flutterwave Checkout (Standard): hosted payment page, webhooks, verify and refunds

Create a Flutterwave-hosted payment link from your server, verify webhooks (verif-hash on v3, HMAC-SHA256 flutterwave-signature on v4), confirm by transaction id and issue refunds.

Provider
Flutterwave
Level
Beginner
Stacks
Node.js (Express), Python (FastAPI), PHP, React
Code maturity
Sandbox-ready
Last verified
25 Nov 2026

Introduction

Flutterwave is a pan-African payment company. Its simplest integration is Checkout (long known as Flutterwave Standard): your server asks Flutterwave for a hosted payment link, you redirect the customer there, and Flutterwave redirects back and sends a webhook when the payment completes. Your server then verifies the transaction by id before giving value.

This guide uses the v3 API (https://api.flutterwave.com/v3), which is where hosted Checkout is documented as of November 2026.

Warning: Flutterwave also publishes a v4 API (OAuth 2.0 tokens, new base URLs, HMAC-signed webhooks). On 2026-11-25 the v4 docs covered direct charges and orchestration but showed no hosted-checkout endpoint, so this guide documents v3 Checkout and points out the v4 differences. Check the docs before starting a new project — this may change.

What Checkout does

  • Your server calls POST https://api.flutterwave.com/v3/payments with tx_ref, amount, currency, redirect_url and customer.email.
  • The response (message: "Hosted Link") contains data.link, a page on checkout.flutterwave.com. Redirect the customer to it.
  • After payment (or cancel), Flutterwave redirects to redirect_url with status, tx_ref and transaction_id query parameters, and sends a charge.completed webhook if webhooks are enabled.
  • Your server calls GET /v3/transactions/{id}/verify and checks status, amount, currency and tx_ref.

If a payment attempt fails, the page stays open so the customer can retry; after a cancel Flutterwave redirects with tx_ref and status=failed — always verify instead of trusting the query string.

Countries and currencies

Flutterwave supports many African currencies and some international ones; availability of each method depends on the country and your account. If you omit currency, the docs say NGN is assumed.

The authoritative list is the Coverage page, which shows payment methods and networks per country. This guide does not repeat it because it changes and per-merchant enablement differs.

Payment methods

Checkout can show cards, bank transfer, USSD, mobile money (for example M-Pesa, Ghana, Uganda, Rwanda, Zambia, Tanzania and francophone mobile money), bank account charge, NIBSS QR, OPay, 1Voucher and others, depending on country and settings.

Limit what is shown with payment_options (comma-separated). The docs warn this works only if Disable preferred payment methods is turned off in your dashboard's business preferences.

When to use Flutterwave Checkout

  • You sell to customers in several African countries and want one integration for cards and local methods.
  • You want Flutterwave to host the payment form (less PCI scope, less UI work).
  • You need features like split payments (subaccounts) or payment plans later.

When not to use it

  • You need a fully custom in-page card form — that is Direct Charge, with encryption and more compliance work.
  • You are starting a new v4-only integration and want everything on OAuth 2.0 — check whether v4 offers hosted checkout for your account first.
  • You only serve one country with one dominant method (for example M-Pesa in Kenya) and need that provider's native features — a direct integration may fit better.

Real-world scenarios

  • Pan-African e-commerce: one checkout for NGN, GHS, KES and USD customers.
  • Course platform: create a link per enrolment; the webhook unlocks the course after verification.
  • Donations: let donors pay by card or mobile money with customizations.title set to the campaign.
  • Invoices: email the hosted link; limit its life with configurations.session_duration.

Registration and onboarding

  • Create a Flutterwave account and open the dashboard. Use the Test mode toggle to see test API keys.
  • Under Settings → Webhooks add your webhook URL and a secret hash, tick the events you need, and enable webhook retries.
  • Complete KYC/business verification to be approved for live transactions and settlements.
  • Add your settlement bank account or choose wallet settlement.

Warning: Approval requirements and settlement schedules vary by country and are only partly published. Check the dashboard and Flutterwave support pages for your country.

Test mode

v3 test and live use the same host, https://api.flutterwave.com/v3; test keys (prefixed FLWSECK_TEST- / FLWPUBK_TEST-) put requests in test mode. Test-mode receipt emails go to your business email, not to customers.

Published test cards (test mode only):

  • Mastercard PIN: 5531 8866 5214 2950, exp 09/32, CVV 564, PIN 3310, OTP 12345.
  • Visa 3DS: 4187 4274 1556 4246, exp 09/32, CVV 828, PIN 3310, OTP 12345.
  • Insufficient funds (fails): 5258 5859 2266 6506, exp 09/31, CVV 883, PIN 3310, OTP 12345.
  • Do not honour (fails): 5143 0105 2233 9965, exp 08/32, CVV 276, PIN 3310, OTP 12345.

Any OTP passes in test mode except the special values 5548 (wrong OTP) and 6648 (insufficient funds), which only work when OTP is entered inside the payment modal. Test bank accounts: Access Bank (044) 0690000031–0690000041, OTP 12345.

v4 uses separate hosts: sandbox https://developersandbox-api.flutterwave.com, production https://f4bexperience.flutterwave.com.

Tip: The testing page says to open checkout from localhost: rather than 127.0.0.1: during local development, otherwise checkout may fail to render.

Credentials you need

v3 (this guide):

  • Secret key — server only; sent as Authorization: Bearer <secret key>.
  • Public key — only for client-side Inline checkout.
  • Secret hash — a random value YOU choose in the webhook settings; Flutterwave echoes it in the verif-hash header.
  • Encryption key — only for Direct Charge (not needed here).

v4: a client_id and client_secret exchanged at https://idp.flutterwave.com/realms/flutterwave/protocol/openid-connect/token (form-encoded, grant_type=client_credentials) for a bearer token that lives 10 minutes (expires_in: 600); refresh about a minute early.

Security: The secret key moves money and issues refunds. Keep it in server-side environment variables only — never in React, mobile apps or Git.

Environment configuration

Commit a .env.example; keep the real .env out of version control.

.env.example · Node.js (Express)

# Flutterwave v3 — Dashboard (Test mode) > Settings > API keys
FLW_SECRET_KEY=FLWSECK_TEST-replace-me
FLW_PUBLIC_KEY=FLWPUBK_TEST-replace-me
# The random "secret hash" you set in Settings > Webhooks (sent back as verif-hash).
# On v4 the same value is the HMAC-SHA256 key for the flutterwave-signature header.
FLW_SECRET_HASH=replace-with-long-random-string
# Where Flutterwave sends the customer after paying (must reach your server)
FLW_REDIRECT_URL=http://localhost:3000/payments/flutterwave/return
PORT=3000

Authentication and a small API helper

v3 requests use Authorization: Bearer <secret key> — no token exchange. Responses have status (success or error), message and data. The helper below is reused by the Node examples.

flw.mjs — v3 helper + webhook checks (Node 18+) · Node.js (Express)

import crypto from "node:crypto";

const BASE = "https://api.flutterwave.com/v3";

export async function flw(method, path, body) {
  const res = await fetch(BASE + path, {
    method,
    headers: { Authorization: "Bearer " + process.env.FLW_SECRET_KEY, "Content-Type": "application/json" },
    body: body ? JSON.stringify(body) : undefined,
  });
  const json = await res.json().catch(() => ({}));
  if (!res.ok || json.status !== "success") {
    throw new Error("Flutterwave " + path + " failed: " + (json.message || res.status));
  }
  return json.data;
}

function safeEqual(a, b) {
  if (typeof a !== "string" || typeof b !== "string") return false;
  const x = Buffer.from(a);
  const y = Buffer.from(b);
  return x.length === y.length && crypto.timingSafeEqual(x, y);
}

// v3: verif-hash header must equal the secret hash you configured.
export function validVerifHash(header, secretHash) {
  return Boolean(secretHash) && safeEqual(header, secretHash);
}

// v4: flutterwave-signature = base64(HMAC-SHA256(rawBody, secretHash)).
export function validV4Signature(rawBody, header, secretHash) {
  if (!secretHash) return false;
  const expected = crypto.createHmac("sha256", secretHash).update(rawBody).digest("base64");
  return safeEqual(header, expected);
}

Backend: create the link, handle the redirect and webhook, settle once

Responsibilities:

  • Create the payment with a unique tx_ref and the amount from YOUR order. Flutterwave amounts are in major units (7500 NGN = ₦7,500), unlike Paystack.
  • Webhook: check verif-hash (v3) or flutterwave-signature (v4), return 200 quickly, then verify by data.id.
  • Redirect handler: read transaction_id and verify — never trust status=successful in the URL.
  • Settle once: only a pending order may become paid; check status === "successful", tx_ref, currency and amount.

The webhook route uses a raw body so the same handler also works for v4's HMAC signature.

server.mjs — Express (npm i express dotenv) · Node.js (Express)

import "dotenv/config";
import express from "express";
import crypto from "node:crypto";
import { flw, validVerifHash, validV4Signature } from "./flw.mjs";

const app = express();
const orders = new Map(); // demo store: use a DB with unique(tx_ref)

async function settle(transactionId) {
  const tx = await flw("GET", "/transactions/" + encodeURIComponent(transactionId) + "/verify");
  const order = orders.get(tx.tx_ref);
  if (!order || order.status !== "pending") return order; // unknown or done: idempotent
  if (tx.status === "successful" && tx.currency === order.currency && Number(tx.amount) >= order.amount) {
    order.status = "paid"; // SQL: UPDATE ... WHERE tx_ref=? AND status='pending'
    order.flwId = tx.id;
  } else if (tx.status === "failed") {
    order.status = "failed";
  }
  return order;
}

app.post("/webhooks/flutterwave", express.raw({ type: "application/json", limit: "1mb" }), (req, res) => {
  const secret = process.env.FLW_SECRET_HASH;
  const ok = req.get("flutterwave-signature")
    ? validV4Signature(req.body, req.get("flutterwave-signature"), secret)
    : validVerifHash(req.get("verif-hash"), secret);
  if (!ok) return res.sendStatus(401);
  res.sendStatus(200); // acknowledge within the 60 s timeout, then work
  const event = JSON.parse(req.body.toString("utf8"));
  if (event.event === "charge.completed" && event.data && event.data.id) {
    settle(event.data.id).catch((e) => console.error("settle failed", e.message));
  }
});

app.use(express.json({ limit: "50kb" }));

app.post("/api/checkout", async (req, res) => {
  const email = String(req.body.email || "").trim();
  if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) return res.status(400).json({ error: "Valid email required" });
  const order = { txRef: "ord_" + crypto.randomUUID(), amount: 7500, currency: "NGN", status: "pending" };
  orders.set(order.txRef, order);
  try {
    const data = await flw("POST", "/payments", {
      tx_ref: order.txRef,
      amount: String(order.amount),       // major units, from your catalogue
      currency: order.currency,
      redirect_url: process.env.FLW_REDIRECT_URL,
      customer: { email },
      customizations: { title: "My Shop" },
      configurations: { session_duration: 30, max_retry_attempt: 5 },
    });
    res.json({ link: data.link, txRef: order.txRef });
  } catch (e) {
    console.error(e.message);
    res.status(502).json({ error: "Could not start payment" });
  }
});

// Flutterwave redirects here with ?status=&tx_ref=&transaction_id=
app.get("/payments/flutterwave/return", async (req, res) => {
  const id = String(req.query.transaction_id || "");
  const order = id ? await settle(id).catch(() => null) : orders.get(String(req.query.tx_ref || ""));
  const txRef = encodeURIComponent(String(req.query.tx_ref || ""));
  res.redirect("/orders/" + txRef + "?status=" + (order ? order.status : "unknown"));
});

app.get("/api/orders/:txRef", (req, res) => {
  const o = orders.get(req.params.txRef);
  if (!o) return res.sendStatus(404);
  res.json({ txRef: o.txRef, status: o.status });
});

app.listen(process.env.PORT || 3000);

main.py — FastAPI (pip install fastapi uvicorn httpx) · Python (FastAPI)

import base64, hashlib, hmac, json, os, uuid
import httpx
from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.responses import RedirectResponse

API = "https://api.flutterwave.com/v3"
HEADERS = {"Authorization": "Bearer " + os.environ["FLW_SECRET_KEY"]}
SECRET_HASH = os.environ.get("FLW_SECRET_HASH", "")
app = FastAPI()
orders: dict = {}  # demo store: use a DB with unique(tx_ref) and conditional updates

async def settle(transaction_id: str):
    async with httpx.AsyncClient(timeout=30) as c:
        r = await c.get(f"{API}/transactions/{transaction_id}/verify", headers=HEADERS)
    tx = r.json().get("data") or {}
    order = orders.get(tx.get("tx_ref"))
    if not order or order["status"] != "pending":
        return order  # idempotent
    if tx.get("status") == "successful" and tx.get("currency") == order["currency"] \
            and float(tx.get("amount", 0)) >= order["amount"]:
        order.update(status="paid", flw_id=tx.get("id"))
    elif tx.get("status") == "failed":
        order["status"] = "failed"
    return order

@app.post("/api/checkout")
async def checkout(payload: dict):
    email = str(payload.get("email", "")).strip()[:254]
    if "@" not in email:
        raise HTTPException(400, "Valid email required")
    tx_ref = "ord_" + uuid.uuid4().hex
    orders[tx_ref] = {"tx_ref": tx_ref, "amount": 7500, "currency": "NGN", "status": "pending"}
    body = {"tx_ref": tx_ref, "amount": "7500", "currency": "NGN",
            "redirect_url": os.environ["FLW_REDIRECT_URL"], "customer": {"email": email}}
    async with httpx.AsyncClient(timeout=30) as c:
        r = await c.post(f"{API}/payments", json=body, headers=HEADERS)
    data = r.json()
    if r.status_code != 200 or data.get("status") != "success":
        raise HTTPException(502, "Could not start payment")
    return {"link": data["data"]["link"], "txRef": tx_ref}

@app.get("/payments/flutterwave/return")
async def back(transaction_id: str = "", tx_ref: str = ""):
    order = await settle(transaction_id) if transaction_id.isdigit() else orders.get(tx_ref)
    return RedirectResponse(f"/orders/{tx_ref}?status={(order or {}).get('status', 'unknown')}")

@app.post("/webhooks/flutterwave")
async def webhook(request: Request):
    raw = await request.body()
    v4_sig = request.headers.get("flutterwave-signature")
    if v4_sig:
        expected = base64.b64encode(hmac.new(SECRET_HASH.encode(), raw, hashlib.sha256).digest()).decode()
        ok = bool(SECRET_HASH) and hmac.compare_digest(v4_sig, expected)
    else:
        ok = bool(SECRET_HASH) and hmac.compare_digest(request.headers.get("verif-hash", ""), SECRET_HASH)
    if not ok:
        return Response(status_code=401)
    event = json.loads(raw)
    if event.get("event") == "charge.completed" and str(event.get("data", {}).get("id", "")).isdigit():
        await settle(str(event["data"]["id"]))  # use a background task/queue in production
    return Response(status_code=200)

Tip: The docs suggest accepting amount >= expected and refunding any excess. Many shops prefer exact equality and a manual review for mismatches — pick one rule and apply it everywhere.

Frontend: send the customer to the hosted page

The simplest secure front end asks your backend for a link and redirects. After payment, Flutterwave sends the customer to your backend's return URL, which verifies and then shows an order page.

Flutterwave also offers Inline (https://checkout.flutterwave.com/v3.js, FlutterwaveCheckout({...})) and the flutterwave-react-v3 package referenced in the docs. Inline runs in the browser with your public key, so the amount is visible to the client — if you use it, send a server-computed payload_hash (see Checksum) so tampering is rejected, and still verify on the server.

FlutterwavePayButton.jsx — redirect to hosted Checkout · React

import { useState } from "react";

export default function FlutterwavePayButton({ email }) {
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");

  async function pay() {
    setBusy(true);
    setError("");
    try {
      const res = await fetch("/api/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }), // the server decides the amount
      });
      const data = await res.json();
      if (!res.ok || !data.link) throw new Error(data.error || "Could not start payment");
      window.location.assign(data.link); // Flutterwave-hosted page
    } catch (e) {
      setError(e.message);
      setBusy(false);
    }
  }

  return (
    <div>
      <button type="button" onClick={pay} disabled={busy}>
        {busy ? "Redirecting..." : "Pay with Flutterwave"}
      </button>
      {error && <p role="alert">{error}</p>}
    </div>
  );
}

// On /orders/:txRef, read the status from YOUR API (GET /api/orders/:txRef),
// not from the ?status= query parameter, before showing "Payment successful".

Creating the payment link (raw request)

POST https://api.flutterwave.com/v3/payments. Fields from the Checkout docs:

  • tx_ref (unique per transaction), amount, currency (default NGN), redirect_url, customer (email required; name, phonenumber optional).
  • Optional: customizations (title, logo, description), meta, payment_options, payment_plan, subaccounts, payload_hash, and configurations with session_duration (minutes, max 1440) and max_retry_attempt.

Disable an unused link with POST /v3/payments/link/disable and body { "link": "..." }.

create_payment.php — plain PHP with cURL · PHP

<?php
// Run behind your own auth/CSRF checks. Requires ext-curl and ext-json.
$secret = getenv('FLW_SECRET_KEY');
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if (!$email) { http_response_code(400); exit('Valid email required'); }

$txRef = 'ord_' . bin2hex(random_bytes(12));
$amount = 7500;               // from your catalogue, major units (NGN)
// Save the order first: INSERT INTO orders (tx_ref, amount, currency, status) VALUES (?, ?, 'NGN', 'pending')

$payload = [
    'tx_ref' => $txRef,
    'amount' => (string) $amount,
    'currency' => 'NGN',
    'redirect_url' => getenv('FLW_REDIRECT_URL'),
    'customer' => ['email' => $email],
    'customizations' => ['title' => 'My Shop'],
];

$ch = curl_init('https://api.flutterwave.com/v3/payments');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $secret, 'Content-Type: application/json'],
    CURLOPT_POSTFIELDS => json_encode($payload),
]);
$response = json_decode((string) curl_exec($ch), true);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($code !== 200 || ($response['status'] ?? '') !== 'success') {
    http_response_code(502);
    exit('Could not start payment');
}
header('Location: ' . $response['data']['link'], true, 303);

Create a link with curl (test key) · Node.js (Express)

curl -s -X POST https://api.flutterwave.com/v3/payments \
  -H "Authorization: Bearer $FLW_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "tx_ref": "ord_test_0001", "amount": "7500", "currency": "NGN",
        "redirect_url": "http://localhost:3000/payments/flutterwave/return",
        "customer": { "email": "[email protected]" } }'
# => {"status":"success","message":"Hosted Link","data":{"link":"https://checkout.flutterwave.com/v3/hosted/pay/..."}}

Confirming the payment

Call GET https://api.flutterwave.com/v3/transactions/{id}/verify with the numeric transaction id (transaction_id from the redirect, data.id from the webhook). The docs list what to check before giving value:

  • data.tx_ref matches the reference you generated;
  • data.status is successful;
  • data.currency is the expected currency;
  • data.amount is at least the expected amount (refund any excess, or apply your own exact-match rule).

If you only have your reference, GET /v3/transactions/verify_by_reference?tx_ref=... looks the transaction up by tx_ref.

Warning: The redirect's status=successful query parameter can be typed by anyone. Treat it as a hint to verify, never as proof.

Webhooks

v3: set a secret hash in Settings → Webhooks; Flutterwave sends it in the verif-hash header. Compare it in constant time with your stored value and discard the request if it is missing or different. This proves the sender knows your secret, but it is not a signature over the body — so always re-verify via the API.

v4: Flutterwave computes HMAC-SHA256 over the raw body with your secret hash and sends it (base64) as flutterwave-signature. Recompute over the raw bytes and compare.

Delivery rules (v3 webhooks page): respond with 200 (any other code, including 3xx, is a failure); requests time out after 60 seconds; with retries enabled Flutterwave retries 3 times, 30 minutes apart. Flutterwave's IPs are dynamic, so the docs advise against strict IP allow-listing. Exclude the route from CSRF protection.

v3 payment webhooks use event: "charge.completed" with data.status successful or failed — a failed attempt also produces charge.completed, so always look at the verified status.

webhook.php — verif-hash + verify + idempotent update (PDO) · PHP

<?php
$secretHash = (string) getenv('FLW_SECRET_HASH');
$given = $_SERVER['HTTP_VERIF_HASH'] ?? '';
if ($secretHash === '' || !hash_equals($secretHash, $given)) {
    http_response_code(401);
    exit;
}

$event = json_decode(file_get_contents('php://input'), true);
http_response_code(200); // acknowledge; heavy work belongs in a queue

if (($event['event'] ?? '') !== 'charge.completed' || !ctype_digit((string) ($event['data']['id'] ?? ''))) {
    exit;
}

$ch = curl_init('https://api.flutterwave.com/v3/transactions/' . $event['data']['id'] . '/verify');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('FLW_SECRET_KEY')],
]);
$tx = json_decode((string) curl_exec($ch), true)['data'] ?? [];
curl_close($ch);

$pdo = new PDO(getenv('DB_DSN'), getenv('DB_USER'), getenv('DB_PASS'), [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
if (($tx['status'] ?? '') === 'successful') {
    // Conditional update = idempotent: only a pending order with matching amount/currency changes.
    $stmt = $pdo->prepare(
        "UPDATE orders SET status = 'paid', flw_id = :id
         WHERE tx_ref = :ref AND status = 'pending' AND currency = :cur AND amount <= :amt"
    );
    $stmt->execute([':id' => $tx['id'], ':ref' => $tx['tx_ref'], ':cur' => $tx['currency'], ':amt' => $tx['amount']]);
} elseif (($tx['status'] ?? '') === 'failed') {
    $pdo->prepare("UPDATE orders SET status = 'failed' WHERE tx_ref = :ref AND status = 'pending'")
        ->execute([':ref' => $tx['tx_ref'] ?? '']);
}

Security: Pick a long random secret hash (for example 32+ random bytes, hex-encoded) and rotate it if it ever appears in logs. With v3 it is effectively a shared password in a header.

Status checks and reconciliation

Flutterwave's own best practice: don't rely only on webhooks. Run a background job (for example hourly) that verifies every pending order — by transaction_id if you saved one, otherwise by tx_ref with verify_by_reference — until it is successful or failed. Respect the rate limits.

If a webhook was missed, POST /v3/transactions/{id}/resend-hook asks Flutterwave to resend it.

reconcile.mjs — verify pending orders by tx_ref · Node.js (Express)

import { flw } from "./flw.mjs";

// pending: [{ txRef, amount, currency }] older than ~10 minutes, loaded from your DB.
export async function reconcile(pending, markPaid, markFailed) {
  for (const order of pending) {
    try {
      const tx = await flw("GET", "/transactions/verify_by_reference?tx_ref=" + encodeURIComponent(order.txRef));
      if (tx.status === "successful" && tx.currency === order.currency && Number(tx.amount) >= order.amount) {
        await markPaid(order.txRef, tx.id); // UPDATE ... WHERE tx_ref=? AND status='pending'
      } else if (tx.status === "failed") {
        await markFailed(order.txRef);
      }
    } catch (err) {
      // Not found yet usually means the customer never completed checkout.
      console.warn("verify_by_reference", order.txRef, err.message);
    }
    await new Promise((r) => setTimeout(r, 250));
  }
}

Refunds

POST https://api.flutterwave.com/v3/transactions/{id}/refund where {id} is the transaction id (data.id). Optional body: amount (set it for a partial refund), comments, and callbackurl for refund result callbacks. The API reference says refunds usually take 3–15 working days to complete.

List or fetch refunds with GET /v3/refunds and GET /v3/refunds/{id}. On v4, refunds live at /refunds on the v4 hosts.

Partial refund with curl · Node.js (Express)

# 288200108 = the Flutterwave transaction id (data.id), not your tx_ref
curl -s -X POST https://api.flutterwave.com/v3/transactions/288200108/refund \
  -H "Authorization: Bearer $FLW_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "amount": 2500, "comments": "Item out of stock" }'

Tip: Store the refund id from the response and your own refund record before calling the API again, so a retried admin click cannot create a second refund.

Errors

Error responses have status: "error", a human-readable message and usually data: null (for example Invalid Link with HTTP 400 when disabling a bad link). Requests without valid authorization get 401. The errors page lists codes per product.

On verify, inspect data.status and data.processor_response (for example Approved by Financial Institution or a decline reason) and keep them for support.

Going to production

  • Get approved for live mode, switch to live keys on the server and set the live webhook URL, secret hash and retries.
  • Use your real domain for redirect_url; make the webhook a public HTTPS endpoint that answers within 60 seconds.
  • Database: unique tx_ref, conditional updates, a background queue for webhook processing, and an hourly reconciliation job.
  • Plan your v4 migration path: OAuth tokens (10-minute lifetime), new hosts and flutterwave-signature HMAC webhooks.

Warning: The v4 Environments page's sample config assigns the sandbox URL when isProd is true (the hosts are swapped). Use developersandbox-api.flutterwave.com for test and f4bexperience.flutterwave.com for production, as the page's prose says.

Security checklist

  • Secret key and secret hash only in server-side environment variables.
  • Amount and currency come from your database; the client sends only an email/cart id.
  • Webhook authenticated (verif-hash or v4 HMAC, constant-time compare), then re-verified via the API before any state change.
  • Idempotent settlement: only pending → paid; unique tx_ref; duplicates are no-ops.
  • Optional payload_hash checksum when using client-side Inline checkout.
  • Use session_duration and max_retry_attempt to limit abuse of open checkouts.

Security: Never mark an order paid from the redirect query string or a browser callback. Only your server's verify call decides.

Testing

  • Use test keys and expose your server with an HTTPS tunnel; set it as the test webhook URL (or inspect payloads with webhook.site first).
  • Pay with the PIN Mastercard (5531 8866 5214 2950) and with the insufficient-funds card; check both outcomes.
  • Replay the same webhook twice and confirm the second is a no-op; send one with a wrong verif-hash and expect 401.
  • Hit the return URL with status=successful and a made-up transaction_id; your server must not mark anything paid.

Replay a v3 webhook locally · Node.js (Express)

curl -s -X POST http://localhost:3000/webhooks/flutterwave \
  -H "Content-Type: application/json" \
  -H "verif-hash: $FLW_SECRET_HASH" \
  -d '{"event":"charge.completed","data":{"id":REPLACE_WITH_TEST_TRANSACTION_ID,"tx_ref":"ord_REPLACE"}}' \
  -w "%{http_code}\n"
# Expect 200; the handler re-verifies with Flutterwave before changing the order.

Common mistakes

  • Trusting status=successful in the redirect URL instead of calling verify.
  • Verifying by tx_ref in the /transactions/{id}/verify path — that endpoint needs the numeric Flutterwave id; use verify_by_reference for tx_ref.
  • Sending amounts in kobo/cents — v3 Checkout takes major units.
  • Reusing tx_ref across attempts; it must be unique per transaction.
  • Treating every charge.completed as a success — failed attempts use the same event name.
  • Strict IP allow-listing of webhooks; Flutterwave's IPs change.
  • CSRF middleware (Django, Rails, Laravel web routes) rejecting the webhook.
  • Using payment_options while "Disable preferred payment methods" is on — the filter is ignored.

Troubleshooting

  • 401 on API calls: wrong key, test/live mix-up, or a malformed header (Bearer + space + key, no colon).
  • Webhook never arrives: URL not saved for the current mode, server returns a redirect, or it takes longer than 60 seconds. Enable retries and check the dashboard's webhook logs.
  • verif-hash mismatch: the secret hash in the dashboard differs from FLW_SECRET_HASH (watch for trailing spaces) or you are on v4 and should check flutterwave-signature.
  • v4 signature mismatch: you hashed parsed JSON instead of the raw bytes, or compared hex instead of base64.
  • Checkout page fails to load locally: open your app on localhost:<port>, not 127.0.0.1.
  • Amount mismatch on verify: currency conversion or fees changed amount vs charged_amount; compare in the same currency and decide your rule.

Further reading

Official documentation

Checked 2026-11-25 (v3 pages last updated 13 September 2026; v4 pages 19 October 2026).

Official documentation

Sources

More payment guides