PayGate is a REST API with thin official SDKs where they remove real work: Node/Bun on the server, the browser for checkout, and React Native/Expo on mobile. Everything else talks to the same API.
| Surface | Package | Holds the private key? |
|---|---|---|
| Node, Bun, serverless functions, Next.js route handlers | @paygate/server | Yes — server only |
| Browser checkout | @paygate/web | No — publishable key |
| React Native / Expo | @paygate/mobile + @paygate/mobile/relay | No — the relay runs on your server |
| Python, PHP, Dart, Go, Swift, Kotlin | REST | Your server, using the flow in Authentication |
#Next.js
Install the server SDK and keep it inside route handlers or server actions — never in a client component, and never behind NEXT_PUBLIC_.
bun add @paygate/server
Create the payment from a route handler:
import { NextResponse } from "next/server";
import Paygate from "@paygate/server";
const paygate = new Paygate(); // reads PAYGATE_URL, PAYGATE_CLIENT_ID, PAYGATE_PRIVATE_KEY
export async function POST(request: Request) {
const { orderId, amount } = await request.json();
const payment = await paygate.pay({
amount, // integer, minor units
currency: "KES",
reference: `order-${orderId}`,
return_url: `${process.env.APP_URL}/thanks`,
});
return NextResponse.json({ checkoutUrl: payment.checkout_url, id: payment.id });
}
Receive the webhook in its own route. The SDK verifies the signature over the raw body and answers non-2xx when your handler throws, so PayGate retries:
import Paygate from "@paygate/server";
const paygate = new Paygate();
const handle = paygate.webhook(async (event) => {
if (event.type === "payment.succeeded") {
await markOrderPaid(event.data.reference);
}
});
export const POST = (request: Request) => handle(request);
#React web
The browser gets a publishable key and can only list methods and open hosted checkout:
import { PaygateWeb } from "@paygate/web";
const pg = new PaygateWeb({ publishableKey: process.env.NEXT_PUBLIC_PAYGATE_KEY! });
// Ask your server for the payment it just created, then:
pg.go(payment.checkout_token); // full-page hosted checkout
// …or mount a button:
pg.mount("#pay", { token, label: "Pay KES 2,500" });
#React Native and Expo
The app never holds a tenant credential. Your backend mounts five relay routes; the app calls them.
One import mounts all five routes. createRelayHandler is callable as a fetch handler and also exports GET/POST for file-based routers. Both route exports always return a Response (a path outside basePath is a JSON 404), and take the optional context argument Next.js passes, so the destructured form passes Next's generated route-handler types:
import { createRelayHandler } from "@paygate/mobile/relay";
export const { GET, POST } = createRelayHandler({ paygate, authorize: requireSession });
The callable itself still returns null outside basePath, for mounting in front of an existing app (the Hono-style use below).
import { createRelayHandler } from "@paygate/mobile/relay";
const relay = createRelayHandler({ paygate, authorize: requireSession });
app.all("/paygate/*", (c) => relay(c.req.raw));
#Express and Node http
Express and Node's http module do not accept a Fetch handler directly. Convert their (req, res) pair to a Request and the relay's Response back; this adapter also handles the raw JSON body, which is why it must run before express.json():
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { createRelayHandler, type RelayHandler } from "@paygate/mobile/relay";
const relay = createRelayHandler({ paygate, authorize: requireSession });
function nodeHandler(relay: RelayHandler) {
return async (req: IncomingMessage, res: ServerResponse) => {
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(Buffer.from(chunk));
// Express removes the mount path from req.url; originalUrl keeps /paygate.
const originalUrl = (req as IncomingMessage & { originalUrl?: string }).originalUrl;
const url = new URL(originalUrl ?? req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
// Node's hop-by-hop headers are not valid on a Fetch Request, and the body
// has already been consumed into a buffer.
const skip = new Set([
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailer",
"transfer-encoding",
"upgrade",
]);
const headers: [string, string][] = [];
for (const [key, value] of Object.entries(req.headers)) {
if (value !== undefined && !skip.has(key)) {
headers.push([key, Array.isArray(value) ? value.join(", ") : value]);
}
}
const method = req.method ?? "GET";
const request = new Request(url, {
method,
headers,
body: method === "GET" || method === "HEAD" ? undefined : Buffer.concat(chunks),
});
const response = await relay(request);
if (!response) {
res.writeHead(404, { "content-type": "text/plain; charset=utf-8" }).end("Not found");
return;
}
res.writeHead(response.status, Object.fromEntries(response.headers));
res.end(Buffer.from(await response.arrayBuffer()));
};
}
// Plain node:http
createServer(nodeHandler(relay)).listen(3000);
// Express: same adapter, mounted before the body parser
// app.use("/paygate", nodeHandler(relay));
import { createPaygateMobile } from "@paygate/mobile";
const paygate = createPaygateMobile({ baseUrl: "https://api.yours.app/paygate", headers });
const { payment } = await paygate.pay({
reference: "order_8123",
amount: 1500,
phone: "254712345678",
});
// resolves only when the server says succeeded; otherwise throws PaygateMobileError
The relay exposes GET /methods, POST /payments, GET /payments/:id, POST /payments/:id/confirm and POST /payments/:id/cancel. No payouts, releases or withdrawals — deliberately.
#Python
No official SDK. Exchange a signed assertion for a token once, then send authorization: DPoP … and a fresh dpop proof per request, as described in Authentication. Keep the Ed25519 JWK in the environment, never in the repository.
pip install requests pyjwt cryptography
import os, requests
API = os.environ["PAYGATE_URL"]
def create_payment(amount: int, reference: str, token: str, proof: str) -> dict:
response = requests.post(
f"{API}/v1/payments",
headers={
"authorization": f"DPoP {token}",
"dpop": proof,
"idempotency-key": reference,
},
json={"amount": amount, "currency": "KES", "reference": reference},
timeout=15,
)
response.raise_for_status()
return response.json()
Django and Flask both give you the raw request body for webhook verification (request.body / request.get_data()); parse only after the HMAC matches.
#PHP
composer require guzzlehttp/guzzle firebase/php-jwt
<?php
$client = new \GuzzleHttp\Client(['base_uri' => getenv('PAYGATE_URL')]);
$response = $client->post('/v1/payments', [
'headers' => [
'authorization' => 'DPoP ' . $token,
'dpop' => $proof,
'idempotency-key' => $reference,
],
'json' => ['amount' => 250000, 'currency' => 'KES', 'reference' => $reference],
]);
$payment = json_decode($response->getBody(), true);
In Laravel, verify webhooks in a controller that receives the request before any middleware parses the JSON, and use $request->getContent() for the HMAC.
#Flutter and Dart
dependencies:
http: ^1.2.0
cryptography: ^2.7.0
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<Map<String, dynamic>> createPayment({
required String api,
required String token,
required String proof,
required int amount,
required String reference,
}) async {
final response = await http.post(
Uri.parse('$api/v1/payments'),
headers: {
'authorization': 'DPoP $token',
'dpop': proof,
'idempotency-key': reference,
'content-type': 'application/json',
},
body: jsonEncode({'amount': amount, 'currency': 'KES', 'reference': reference}),
);
if (response.statusCode != 201) {
throw Exception('PayGate ${response.statusCode}: ${response.body}');
}
return jsonDecode(response.body) as Map<String, dynamic>;
}
For mobile money, open checkout_url in a WebView, or POST /v1/payments/{id}/confirm from your backend — the Flutter app should never hold the Ed25519 key.
#Go, Swift, Kotlin
Same rule: the key stays on a server. Send the REST calls above with your language's HTTP client, and treat the API's status as the only source of truth — never a redirect the app observed.
#Choosing a surface
- Server renders the page (Next.js, Rails, Laravel, Django)? Create the payment on the server and redirect. No client SDK needed.
- Single-page app? Create the payment on the server, hand the browser the
checkout_token, and use@paygate/webto open it. - Mobile app? Mount the relay. It keeps the credential off the device and gives you one consistent error shape (
code,status,retryable,userMessage). - Writing a client in another language? Implement the token exchange and DPoP proof once, behind a small wrapper, and keep an
Idempotency-Keyper logical operation.
Whatever the surface: verify webhooks over the raw body, and show success only when the server reports succeeded.