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.
Your browser
never sees the key
Your server
X-Api-Key: dgw_…
DGateway
Iotec · Relworx · Stripe
The browser talks to your server. Only your server holds the key and calls DGateway.
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.
Add your keys
Put the API URL and key in .env.local. They are read on the server only.
# .env.local
DGATEWAY_API_URL=https://dgatewayapi.desispay.com
DGATEWAY_API_KEY=dgw_test_xxxxxxxxxxxxxxxxxxxx
DGATEWAY_WEBHOOK_SECRET=your_webhook_secretNever prefix these with NEXT_PUBLIC_
Create the API client
A small server-side wrapper keeps the header and base URL in one place.
// 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}`);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);
}| Field | Type | Notes |
|---|---|---|
| amount | number | Required. Whole units of the currency. |
| currency | string | UGX, KES, TZS, RWF, USD, EUR or GBP. |
| phone_number | string | 256XXXXXXXXX (12 digits) or 0XXXXXXXXX. A leading + is stripped. |
| provider | string | iotec, relworx or stripe. Defaults to iotec; passing it is recommended. |
| callback_url | string | Optional. Public HTTPS URL for the final webhook. |
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
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);
}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
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.
| Number | Result |
|---|---|
| 011177777x | success |
| 011177799x | failed |
| 011177778x | pending |
| 011177779x | SentToVendor |
Errors
Every error uses the same envelope. Failed transactions also carry a failure_reason.
| Code | HTTP | Meaning |
|---|---|---|
| VALIDATION_ERROR | 400 | Missing or invalid fields |
| INVALID_PHONE | 400 | Phone number is not in a supported format |
| INVALID_CURRENCY | 400 | Currency is not supported |
| AUTHENTICATION_ERROR | 401 | Missing or invalid API key |
| PROVIDER_LINE_DOWN | 503 | The provider line (e.g. MTN) is down; retry or switch provider |
| INSUFFICIENT_BALANCE | 400 | Withdrawal is larger than your balance |
| RATE_LIMIT | 429 | Too many requests; back off |
Next steps
Card payments
Mount Stripe Elements with the returned client secret.
ReadWithdrawals
Pay out your balance to mobile money or a bank.
ReadSubscriptions
Plans, cycles and the subscription lifecycle.
ReadCountry guides
Kenya, Rwanda, Tanzania and Uganda specifics.
ReadWas this page helpful?