Mohamed Ali Mejbar
FR Fès Book a call
Contents
  1. 01 Work
  2. 02 Method
  3. 03 Prices
  4. 04 About
Book a call ali@mejbar.com It's in Fès.
← The notebook Payments · Convex · Next.js October 2026 · 17 min

NETOPIA Payments API v2 hosted checkout

Hosted checkout, signed notifications, and safe payment-state handling with NETOPIA's v2 JSON API.

Written by .

NETOPIA was the part of Congrès Médicis I least wanted to learn twice. We had to connect ticket stock, payment attempts and participant access while working through documentation that did not always describe the same flow. This is the guide I wanted before writing that checkout.

The working pattern here is hosted checkout: my backend creates the attempt, NETOPIA collects payment on its own page, and authenticated server responses or signed notifications determine the payment state. The customer’s browser return never establishes success.

NETOPIA calls v2.x its latest and recommended API. It uses JSON endpoints and API-token authentication. The older v1.x API is a different integration: it uses the classic XML/encrypted request model and confirm/return terminology. Do not combine its XML response or <crc> acknowledgement with the v2 JSON flow. The API overview says v1.x is being phased out.

What we learned building this for Congrès Médicis

The fetch call was not the hard part. Knowing what its result allowed us to do was. A narrative example, an OpenAPI schema and an SDK can all be first-party and still leave you with different acknowledgement shapes or assumptions. I do not want the next merchant to have to work that out just to sell a ticket.

  • Treat the contract as separate, testable pieces. I kept the v2 JSON start flow, notification JWT, status operation, and legacy v1 XML vocabulary separate. A schema listing an operation does not prove that the merchant account has it enabled, so I exercise each operation in sandbox before making it part of an automated workflow.
  • Hosted checkout and 3DS are different transports. For Congrès Médicis, the normal path is the hosted paymentURL: I save the attempt and send the browser to the exact URL returned by NETOPIA. An Authentication3D response is not another URL to GET; it is a POST continuation carrying the complete unchanged formData, with its authentication token kept server-side. Treating those as the same handoff loses protocol fields.
  • The signed thing is the original body, not equivalent JSON. I preserve the received body before parsing and bind the JWT’s SHA-512 subject to that original payload. Re-stringifying parsed JSON can change whitespace, key order, escaping, or newlines, so the verifier checks RS512, issuer/audience, and the raw-body hash before the notification can touch an order.
  • Payment is asynchronous state, not a browser result. A redirect means “we are checking,” not “paid.” A notification can race the start response, and delivery can repeat. The checklist I take from this is to pre-create the attempt, check the orderID/ntpID/amount/currency binding in the durable transaction, make fulfilment idempotent, and reconcile unknown or late outcomes. Those checks belong together; a valid signature alone is not an order-state policy.

That is why the examples below are deliberately strict. They show the seams I had to make explicit, rather than hiding them behind a helper that only works for the happy path.

1. Choose one environment and keep its credentials together

The v2 start endpoints documented by NETOPIA are:

Environment Start endpoint
Sandbox https://secure.sandbox.netopia-payments.com/payment/card/start
Production https://secure.mobilpay.ro/pay/payment/card/start

The provider’s OpenAPI specification uses those same environment bases for /operation/status, /operation/credit, and /operation/expire. It supplies request/response schemas, but still labels these operations “will be available at a future date.” Their presence in the schema is not proof that your merchant account can use them: exercise each enabled operation in sandbox before building an automated workflow around it.

The credentials have different jobs:

Value Sent where Job
API key Authorization header on server-to-server API calls Authenticates the request. The specification defines a raw API key, not a Bearer token.
POS signature order.posSignature; also the expected notification audience Identifies the merchant POS/order namespace. It is not the API key.
NETOPIA RSA public verification key/certificate Local webhook verifier only Verifies the signature on the verification-token JWT. Obtain it through NETOPIA’s trusted configuration channel, never from the incoming request.

Keep sandbox and production endpoint, API key, POS signature, and verification key as a complete set. Use server-only environment variables; for example, NETOPIA_API_KEY, NETOPIA_POS, NETOPIA_PUBLIC_KEY, and an explicit environment selector. Normalize escaped newlines when a deployment stores a PEM as a single-line variable.

Do not read a key from a browser bundle, hard-code it, or silently fall back to the other environment. A deployment should fail at startup when the selected environment has no complete credential set.

2. Start a hosted payment

The v2 start request is JSON with config, payment, and order. The official start-payment reference documents these fields and requires a merchant orderID, amount, currency, POS signature, billing information, and callback URLs.

Create and persist the merchant orderID before making the request. Bind it to an immutable order total, currency, and customer. In a system with multiple payment attempts, retain each attempt’s merchant reference and provider transaction ID instead of overwriting the previous attempt.

order.ntpID is empty/null for a new payment; NETOPIA generates payment.ntpID. Save both identifiers. A start timeout is an unknown outcome, not a decline: a request may have reached NETOPIA even though its response never reached you. Do not blindly issue another start request and assume the provider will deduplicate it.

This server-side Node 20+ example accepts an already-persisted order and returns the transaction metadata needed to save the result. It does not charge a browser-supplied amount or return only a URL:

type Billing = {
  email: string;
  phone: string;
  firstName: string;
  lastName: string;
  city: string;
  country: number; // ISO 3166-1 numeric code, not a calling code
  state: string;
  postalCode: string;
  details: string;
};

type StartOptions = {
  apiKey: string;
  posSignature: string;
  sandbox: boolean;
  notifyUrl: string;
  redirectUrl: string;
  order: {
    orderID: string;
    amount: number;
    currency: string;
    description: string;
    billing: Billing;
    products: { code: string; name: string; category: string; price: number }[];
  };
};

type StartedPayment = {
  orderID: string;
  ntpID: string;
  status: number | null;
  amount: number | null;
  currency: string | null;
  hostedUrl: string | null;
  customerAction: {
    type?: string;
    url?: string;
    authenticationToken?: string;
    formData?: Record<string, string>;
  } | null;
};

export async function startHostedPayment({
  apiKey,
  posSignature,
  sandbox,
  notifyUrl,
  redirectUrl,
  order,
}: StartOptions): Promise<StartedPayment> {
  const endpoint = sandbox
    ? "https://secure.sandbox.netopia-payments.com/payment/card/start"
    : "https://secure.mobilpay.ro/pay/payment/card/start";

  const response = await fetch(endpoint, {
    method: "POST",
    headers: {
      Accept: "application/json",
      Authorization: apiKey,
      "Content-Type": "application/json",
    },
    signal: AbortSignal.timeout(30_000),
    body: JSON.stringify({
      config: { language: "en", notifyUrl, redirectUrl },
      order: {
        ntpID: null,
        posSignature,
        dateTime: new Date().toISOString(),
        orderID: order.orderID,
        description: order.description,
        amount: order.amount,
        currency: order.currency,
        billing: order.billing,
        products: order.products,
      },
      payment: {
        options: { installments: 1, bonus: 0 },
        instrument: { type: "card" },
      },
    }),
  });

  if (!response.ok) throw new Error(`NETOPIA HTTP ${response.status}`);

  const result = (await response.json()) as {
    error?: { code?: string };
    payment?: {
      ntpID?: string;
      status?: number;
      amount?: number;
      currency?: string;
      paymentURL?: string;
    };
    customerAction?: StartedPayment["customerAction"];
  };
  const payment = result.payment;
  if (!payment?.ntpID) {
    throw new Error(
      `NETOPIA response has no payment.ntpID (code ${result.error?.code ?? "absent"})`
    );
  }

  return {
    orderID: order.orderID,
    ntpID: payment.ntpID,
    status: payment.status ?? null,
    amount: payment.amount ?? null,
    currency: payment.currency ?? null,
    hostedUrl: payment.paymentURL ?? null,
    customerAction: result.customerAction ?? null,
  };
}

After the call, await a database transaction that binds the returned ntpID and provider state to that attempt before returning a redirect to the browser. Keep missing fields as unknown; do not replace a missing amount with the requested amount and then pretend it was verified. Do not persist customerAction.formData: the provider says it must be forwarded unchanged, not stored. Keep any authentication token server-side for the documented continuation.

Choose the next step from the actual response:

Response Next step
payment.paymentURL Save the attempt, then redirect to this exact hosted URL. Do not construct one.
customerAction.type = Authentication3D, status 15 This is a 3DS continuation, not the same thing as a hosted URL. The Action schema says to POST the complete, unchanged formData to customerAction.url, retain authenticationToken server-side, and complete the documented /payment/card/verify-auth flow. A plain GET redirect drops required fields.
Status 3 or 5, no URL Reconcile the immediate server-side result using the same order/transaction/amount/currency checks as a notification; do not invent a browser redirect as proof of payment.
No URL, no supported continuation, no verified success Retain the attempt for diagnosis/reconciliation. Do not fulfil or start another charge automatically.

The v2 response examples demonstrate both a non-3DS result and an authentication action. This guide implements the hosted handoff; a direct-card/3DS adapter is a separate integration and must implement the complete provider protocol, not just navigate to its action URL.

3. Notify and redirect are different channels

Set both URLs, and give them different responsibilities:

  • config.notifyUrl is the server-to-server notification/IPN destination. It must be publicly reachable by NETOPIA, accept POST, retain the raw body, authenticate the notification, and update the order.
  • config.redirectUrl is the customer’s browser return destination. It is for showing “we are checking your payment” and polling the merchant backend. It is not proof of payment.

Use a stable browser return route containing an encoded merchant reference, then have it query your backend for the durable payment state. Treat any query string, route parameter, or success message from the browser as untrusted input.

A customer can close the hosted page, lose connectivity, or return before the notification arrives. For a direct-card flow, redirectUrl can also be the 3DS authentication-return destination described by the API; do not confuse that browser transport with a signed payment result. Only a verified notification or an authenticated server-side provider response may confirm payment.

4. Verify the notification over the original bytes

Read the body once, before JSON middleware changes it, and obtain the verification-token header. Hashing JSON.stringify(JSON.parse(body)) is wrong: whitespace, key order, escaping, and newlines are part of the signed payload.

The first-party Go SDK implementation shows the wire contract: an RSA-signed JWT, issuer NETOPIA Payments, POS audience, and a sub containing the Base64-encoded SHA-512 digest of the raw body. Pin the expected signing algorithm rather than accepting whatever the token header requests.

This self-contained Node verifier requires RS512, verifies the signature and body binding, and validates optional JWT time claims. Its five-minute clock tolerance and rejection of a future iat are explicit application policy, not a provider-mandated retry window. An old iat alone does not reject a delayed delivery; durable idempotency handles replays.

Supply the original body as a Buffer, a trusted PEM public key/certificate, and the configured POS signature:

import {
  createHash,
  createPublicKey,
  createVerify,
  timingSafeEqual,
} from "node:crypto";

function decodeBase64Url(value: string): Buffer {
  const base64 = value.replace(/-/g, "+").replace(/_/g, "/");
  return Buffer.from(
    base64 + "=".repeat((4 - (base64.length % 4)) % 4),
    "base64"
  );
}

function readJsonPart<T>(part: string): T {
  return JSON.parse(decodeBase64Url(part).toString("utf8")) as T;
}

type Claims = {
  exp?: number;
  nbf?: number;
  aud?: string | string[];
  iss?: string;
  sub?: string;
  iat?: number;
};

export function verifyNetopiaNotification(
  rawBody: Buffer,
  verificationToken: string,
  publicKeyPem: string,
  expectedPos: string,
  nowSeconds = Math.floor(Date.now() / 1000)
): Record<string, unknown> {
  const parts = verificationToken.trim().split(".");
  if (parts.length !== 3) throw new Error("invalid verification-token format");

  const [encodedHeader, encodedPayload, encodedSignature] = parts;
  if (!encodedHeader || !encodedPayload || !encodedSignature) {
    throw new Error("invalid verification-token format");
  }
  const header = readJsonPart<{ alg?: string }>(encodedHeader);
  const claims = readJsonPart<Claims>(encodedPayload);
  if (header.alg !== "RS512") throw new Error("unsupported JWT algorithm");

  const verifier = createVerify("RSA-SHA512");
  verifier.update(`${encodedHeader}.${encodedPayload}`, "ascii");
  verifier.end();
  if (
    !verifier.verify(
      createPublicKey(publicKeyPem),
      decodeBase64Url(encodedSignature)
    )
  ) {
    throw new Error("invalid verification-token signature");
  }

  const audiences =
    typeof claims.aud === "string"
      ? [claims.aud]
      : Array.isArray(claims.aud)
        ? claims.aud
        : [];
  if (!audiences.includes(expectedPos))
    throw new Error("notification audience mismatch");
  if (claims.iss !== "NETOPIA Payments")
    throw new Error("notification issuer mismatch");

  const claimedHash = claims.sub
    ? decodeBase64Url(claims.sub)
    : Buffer.alloc(0);
  const actualHash = createHash("sha512").update(rawBody).digest();
  if (
    claimedHash.length !== actualHash.length ||
    !timingSafeEqual(claimedHash, actualHash)
  ) {
    throw new Error("notification body hash mismatch");
  }

  const clockToleranceSeconds = 300;
  for (const claim of ["iat", "nbf", "exp"] as const) {
    const value = claims[claim];
    if (
      value !== undefined &&
      (typeof value !== "number" || !Number.isFinite(value))
    ) {
      throw new Error(`invalid JWT ${claim}`);
    }
  }
  if (
    claims.iat !== undefined &&
    claims.iat > nowSeconds + clockToleranceSeconds
  ) {
    throw new Error("notification issued in the future");
  }
  if (
    claims.nbf !== undefined &&
    claims.nbf > nowSeconds + clockToleranceSeconds
  ) {
    throw new Error("notification is not active yet");
  }
  if (
    claims.exp !== undefined &&
    claims.exp <= nowSeconds - clockToleranceSeconds
  ) {
    throw new Error("notification has expired");
  }

  const parsed = JSON.parse(rawBody.toString("utf8")) as Record<
    string,
    unknown
  >;
  return parsed;
}

In a Fetch/Convex HTTP route, Buffer.from(await request.arrayBuffer()) preserves the bytes; pass the token from request.headers.get("verification-token") and reject a missing header. Express needs a raw-body middleware on this route, not the normal JSON parser. Run this verifier in a Node-compatible server runtime, not in the browser.

After verification, validate the JSON notification’s order.orderID, payment.ntpID, status, amount, and currency against the stored attempt before writing state. Invalid authentication should produce a non-success response; a storage failure must not be acknowledged as completed work.

Acknowledgement: do not mix API generations

The working v2 integration behind this guide acknowledges a durably accepted notification with:

HTTP/1.1 200 OK
Content-Type: application/json

{"errorCode":0}

The public contracts are not perfectly aligned here: the OpenAPI sandbox callback models a {code, message} response, whereas the Go SDK’s verification result uses errorCode/errorMessage. Confirm the response body expected by your provisioned callback contract rather than assuming those shapes are interchangeable. The legacy XML <crc> acknowledgement belongs to v1.x, not this JSON integration. Whatever body is agreed, send success only after durable acceptance, including an already-processed duplicate.

5. Persist safe state, not just a webhook log

A notification is a delivery attempt, not a new order. The durable update should be one transaction (or an equivalent outbox/transaction boundary):

  1. Resolve order.orderID to an existing payment attempt and its merchant order.
  2. Verify payment.ntpID is bound to that attempt and is not reused by another order.
  3. Compare provider amount and currency with the immutable total. Never fulfil a mismatch; hold it for reconciliation.
  4. Check the provider status against an explicit transition policy.
  5. Record the verified event/provider identifiers and an access-restricted audit record.
  6. Update payment state and enqueue fulfilment only on the first allowed transition into paid/confirmed.
  7. Commit, then acknowledge. If the transaction fails, return failure so delivery can be retried.

The notification can arrive before the start response has been saved. Pre-create the attempt so its merchant reference already resolves. If its provider ID is still unbound, bind the first verified ntpID atomically after the order/amount/currency checks, enforcing uniqueness across attempts. If the event cannot be matched unambiguously, hold it for reconciliation rather than guessing an order or dropping a real payment.

Store money internally as integer minor units or an exact decimal type, with a currency-aware conversion at the API boundary. Do not compare arbitrary floating-point calculations with ===. The start response schema says its amount mirrors the request; the notification schema contains confusing “1234 = 12.34” wording. Capture a real signed sandbox notification and status response for a known total, establish their units, and test that conversion explicitly. Do not silently divide every provider field by 100.

No idempotency-key request header is defined in the current OpenAPI security/request schemas. Keep application-level idempotency and an outbox for receipts/access/inventory: a retried webhook or status poll must not send a second receipt or grant access twice. Do not deduplicate every event solely by ntpID + status; two distinct partial-credit operations can have the same status and need separate records.

6. Map provider status without corrupting order state

The Payment schema explicitly defines 3 as paid, 5 as confirmed, 12 as rejected, and 15 as 3-D Secure authentication required. The first-party Go status constants give the additional names below. These are provider codes, not application-invented labels:

Code Provider name Application treatment
1 / 2 NEW / OPENED Created/opened, not proof of payment.
3 / 5 PAID / CONFIRMED Confirm only after authentication and order/transaction/amount/currency binding.
4 CANCELED Cancelled attempt; do not turn a later pending update into a new order.
6 / 18 PENDING / PENDING_ANY Keep pending; do not fulfil.
8 CREDIT Reconcile the credit amount; do not assume every credit is a full refund.
11 / 12 ERROR / DECLINED Failure; a deliberate new attempt may be allowed by your order policy.
13 FRAUD Hold for review; do not fulfil automatically.
14 / 15 PENDING_AUTH / 3D_AUTH Authentication/authorization still pending.
17 REVERSED Reconcile a reversed payment separately from an ordinary decline.
23 EXPIRED Expired attempt; do not fulfil.

Do not copy the SDK’s statusMessage business logic verbatim: it groups STATUS_NEW with paid/confirmed in its delivery message. A new payment is not evidence that money was received.

Keep three distinct fields: raw provider status, payment-attempt state, and order/fulfilment state. A duplicate success is a no-op, a stale pending event cannot downgrade a paid attempt, and a later credit/reversal must not be discarded merely because payment previously succeeded. An unknown numeric code is held for reconciliation, never defaulted to success.

A late verified payment after local expiry/cancellation is still money received. Record it, then decide whether the order can be fulfilled safely or needs a refund; do not silently lose the event or reopen released inventory. Paid/confirmed is also not a guarantee of bank settlement.

Finally, error.code is not a payment state. Provider examples use both 00 and 0 in approved contexts; the authenticated status and order binding decide whether fulfilment is allowed.

7. Status checks, expiry, refunds, and late notifications

A delayed notification is not proof of failure. If status retrieval is enabled for your account, use the same API-key header and environment as start. The OpenAPI request schema permits ntpID, orderID, and posID; this integration uses both stored transaction/order identifiers:

POST /operation/status HTTP/1.1
Authorization: <API key>
Content-Type: application/json

{"ntpID":"1309088","orderID":"ORDER-123"}

Poll only attempts that can still change, cap the frequency, and back off after transport failures. Reconcile the authenticated result through the same transaction used for notifications; a poll is not a second fulfilment path.

Before expiring a stale attempt:

  1. Query current provider status.
  2. If paid/confirmed, validate and record the payment; do not call expire.
  3. If already cancelled, expired, credited, or reversed, reconcile that result instead.
  4. Only if the result is a known state eligible for expiry under your enabled API contract, call /operation/expire.
  5. Release the reservation only after the expiry result and the local state agree. An unavailable endpoint, timeout, or unknown status is not confirmation of expiry.

The status check and expiry request are not one atomic provider operation: payment can complete between them. Handle an expiry refusal or a late success through reconciliation, not by pretending the timer won.

A refund is a separate operation. The /operation/credit schema uses ntpID and amount (plus optional split destinations), not the status request’s body. Record a durable credit operation, its requested amount, operator, response, and outcome. For a timed-out credit request, reconcile before retrying: issuing it again may create a second refund. The schema’s future-availability warning applies here too.

8. Troubleshooting by symptom

Start call returns 401/403 or an unexpected 404

Check the selected endpoint character-for-character, the API key environment, and whether the key belongs to sandbox or production. The OpenAPI specifies a raw key in Authorization, without Bearer. Log endpoint, HTTP status, and a redacted provider error, never the key.

Start call is HTTP 200 but there is no hosted URL

Inspect error.code, error.message, payment.ntpID, payment.status, and customerAction in a restricted diagnostic record. A missing paymentURL is not a reason to invent a checkout URL or mark the order paid. Status 15 may require a POST-based 3DS action; status 3/5 still requires the immutable order binding.

Customer sees success but the order remains pending

The browser redirect is not authoritative. Check whether NETOPIA reached notifyUrl, whether the body was preserved byte-for-byte, and whether the order ID in order.orderID resolves to the same environment/database. Query status server-to-server using ntpID and merchant order ID, then reconcile.

Webhook returns 401

Look for a missing verification-token, wrong environment public key, wrong POS audience, non-RS512 token, signature failure, body-hash mismatch, or a body that was parsed and reserialized before verification. Capture raw body length, token presence, environment, and a reason code, never token contents. Fix the adapter/key pairing; do not disable verification as a permanent workaround.

Webhook returns 200 but no state changes

Check that order.orderID is present and resolves, that the notification amount/currency matches the stored order, and that the transition is allowed. A duplicate or out-of-order notification should be an audit event and no-op, not a second fulfilment.

The provider status and local status disagree

Use operation/status with both ntpID and orderID, compare the raw response with the last verified notification, and inspect environment labels. Do not “repair” a mismatch by trusting whichever side is newer by wall-clock time; reconcile provider state, amount, currency, and the local transition history.

Sandbox appears silent

Verify that the sandbox POS/API key/public key are paired, that the sandbox callback URL is reachable from outside the local network, and that the deployment is actually using sandbox mode. Exercise the callback independently with a signed fixture; do not accept an unsigned debug request as a payment test.

9. Go-live checklist

  • Confirm the account is using v2 JSON, not the legacy XML API.
  • Confirm sandbox and production endpoint, API key, POS signature, and verification key as a complete set.
  • Send a start request with a unique merchant orderID; persist ntpID and the exact amount/currency before redirecting.
  • Verify the hosted URL is returned from the provider response; never construct one.
  • Confirm notifyUrl reaches the backend with the raw body intact and redirectUrl reaches only the browser UI.
  • Test a successful payment, a declined payment, a 3DS/authorization continuation, a duplicate notification, an out-of-order notification, a missing notification, and a late notification after an expiry attempt.
  • Verify RS512, RSA signature, issuer/audience, raw-body SHA-512 subject, and strict production enforcement.
  • Verify that mismatched order ID, ntpID, amount, or currency is quarantined and cannot fulfil.
  • Verify the endpoint returns the agreed JSON acknowledgement only after durable processing; never use the v1 XML <crc> response in v2.
  • Exercise status, expire, and refund/credit paths in sandbox and retain redacted request/response audit records.
  • Confirm production callback URLs are HTTPS and that logs never contain API keys, public-token contents, or card data.

References and known documentation gaps

The implementation pattern comes from Congrès Médicis’s Next.js/Convex checkout; the code above exposes the storage boundary instead of depending on its private helpers. The public sources disagree on callback acknowledgement shapes and notification amount wording, and operation endpoints retain future-availability warnings. Resolve those specific contracts with a signed sandbox exchange and NETOPIA’s merchant configuration before production; do not bridge the gaps by accepting unsigned notifications or trusting the browser.

§ 05 · Contact

Your turn.

A launch, a rebuild, or a product to keep improving? Tell me the scope, budget and timing. I'll reply within two working days, from Fès.

Book a 30-minute call

ali@mejbar.com. The calendar only offers the times I'm really free.