Docs / Getting started / Accept your first payment

Accept your first payment

Collect a mobile-money payment from a Next.js app in five steps, using a test key and a test number. The same request works for cards and the other providers.

Before you start

A DGateway app

Created in the dashboard, with a dgw_test_ key.

Node.js 18+

And Next.js 14+ with the App Router.

A public URL

Optional, for webhooks. Use a tunnel locally.

1

Add your keys

Put the API URL and key in .env.local. They are read on the server only.

.env.local
# .env.local
DGATEWAY_API_URL=https://dgatewayapi.desispay.com
DGATEWAY_API_KEY=dgw_test_xxxxxxxxxxxxxxxxxxxx
DGATEWAY_WEBHOOK_SECRET=your_webhook_secret

Never prefix these with NEXT_PUBLIC_

That would ship your secret key to every visitor's browser. Call DGateway from a server route instead.
2

Create the API client

A small server-side wrapper keeps the header and base URL in one place.

lib/dgateway.ts
// lib/dgateway.ts
const BASE = process.env.DGATEWAY_API_URL!;
const KEY = process.env.DGATEWAY_API_KEY!;

async function call(path: string, body?: unknown) {
  const res = await fetch(`${BASE}${path}`, {
    method: body ? "POST" : "GET",
    headers: { "X-Api-Key": KEY, "Content-Type": "application/json" },
    body: body ? JSON.stringify(body) : undefined,
  });
  return res.json();
}

export const collectPayment = (input: CollectInput) => call("/v1/payments/collect", input);
export const getTransaction = (reference: string) => call(`/v1/payments/transactions/${reference}`);
3

Start a collection

Create a server route that validates the amount and calls POST /v1/payments/collect. For mobile money, the customer gets a USSD prompt on their phone. For cards, the response also includes a Stripe client_secret.

// app/api/checkout/route.ts
import { NextRequest, NextResponse } from "next/server";
import { collectPayment } from "@/lib/dgateway";

export async function POST(req: NextRequest) {
  const { amount, phone } = await req.json();

  const result = await collectPayment({
    amount,
    currency: "UGX",
    phone_number: phone,
    provider: "iotec",
  });

  return NextResponse.json(result);
}
FieldTypeNotes
amountnumberRequired. Whole units of the currency.
currencystringUGX, KES, TZS, RWF, USD, EUR or GBP.
phone_numberstring256XXXXXXXXX (12 digits) or 0XXXXXXXXX. A leading + is stripped.
providerstringiotec, relworx or stripe. Defaults to iotec; passing it is recommended.
callback_urlstringOptional. Public HTTPS URL for the final webhook.
4

Track the payment status

Mobile-money payments complete when the customer approves the prompt. Poll the status by reference until it is completed or failed.

app/api/checkout/status/route.ts
// app/api/checkout/status/route.ts
import { NextRequest, NextResponse } from "next/server";
import { getTransaction } from "@/lib/dgateway";

export async function GET(req: NextRequest) {
  const reference = req.nextUrl.searchParams.get("reference")!;
  const result = await getTransaction(reference);
  return NextResponse.json(result);
}
5

Receive the webhook

If you passed callback_url, DGateway POSTs the final status there too — retried until your endpoint returns 200. Verify the X-DGateway-Signature header before trusting the payload: it's an HMAC-SHA256 of the raw body, hex-encoded, using your app's webhook secret.

app/api/webhooks/dgateway/route.ts
// app/api/webhooks/dgateway/route.ts
import crypto from "node:crypto";
import { NextRequest, NextResponse } from "next/server";

export async function POST(req: NextRequest) {
  const raw = await req.text();
  const signature = req.headers.get("x-dgateway-signature") ?? "";

  const expected = crypto
    .createHmac("sha256", process.env.DGATEWAY_WEBHOOK_SECRET!)
    .update(raw)
    .digest("hex");

  if (signature !== expected) {
    return NextResponse.json({ error: "invalid signature" }, { status: 401 });
  }

  const event = JSON.parse(raw);
  if (event.status === "completed") {
    // mark the order paid — look it up by event.reference
  }

  return new Response("ok"); // respond 200 fast; do slow work in a queue
}

Test numbers

Test numbers work only with dgw_test_ keys. Replace the last digit with any number from 0 to 9; the 12-digit form 256111777771 also works. Using one with a live key returns TEST_NUMBER_ON_LIVE_KEY.

NumberResult
011177777xsuccess
011177799xfailed
011177778xpending
011177779xSentToVendor

Errors

Every error uses the same envelope. Failed transactions also carry a failure_reason.

CodeHTTPMeaning
VALIDATION_ERROR400Missing or invalid fields
INVALID_PHONE400Phone number is not in a supported format
INVALID_CURRENCY400Currency is not supported
AUTHENTICATION_ERROR401Missing or invalid API key
PROVIDER_LINE_DOWN503The provider line (e.g. MTN) is down; retry or switch provider
INSUFFICIENT_BALANCE400Withdrawal is larger than your balance
RATE_LIMIT429Too many requests; back off

Next steps