StampMitraDevelopers
Livee-Stamp Paper APIStep 8 of 8

e-Stamp order status and certificate download: from placed to a stored PDF

Retrieve the generated e-Stamp certificate/document once an order completes.

GET/v1/orders/:id/documentsScope documents.readAPI fee ₹5 per call
curl -X GET "https://api-b2b.stampmitra.in/v1/orders/:id/documents" \
  -H "Authorization: Bearer $STAMPMITRA_API_KEY"

Everything in the e-Stamp flow exists to produce one file: the certificate. The last step is where you find out whether it exists yet, fetch it before the link dies, put it somewhere durable and tell the customer. It is also the step where impatience, a short-lived URL and a sandbox whose certificate is only a sample file combine to create most of the late-night bugs. This page covers how to read an order and its stamps, what each status means, how the certificate route behaves, how to download and store the file safely, how to combine polling with webhooks, how to cancel or replace a stamp, and how to test the path, including what the sandbox simulates and what it cannot tell you. It is step eight, the last, of the eight-step e-Stamp flow.

A framing that helps: your product moves through three questions in this order. Is the order still being reviewed? Is a stamp being produced? Is the certificate available yet? Each has its own route and its own statuses, and treating them as one question is the most common reason a product tells a customer something untrue.

The routes at a glance

All routes use the base URL https://api-b2b.stampmitra.in, authenticate with Authorization: Bearer <key> or x-api-key, and sit behind the estamp.enabled entitlement.

RouteAnswersScopeMetered by StampMitra
GET /v1/estamp/ordersWhich orders do I have, and in what statusestamp.orders.readNo
GET /v1/estamp/orders/:idWhere is this orderestamp.orders.readNo
GET /v1/estamp/stamps/:stampIdWhat state is this stamp inestamp.stamps.readNo
GET /v1/estamp/stamps/:stampId/certificateIs the certificate available, and where is itestamp.stamps.readNo
POST /v1/estamp/stamps/:stampId/cancelCancel a stampestamp.stamps.cancelNo
POST /v1/estamp/stamps/:stampId/replaceReplace a defective stampestamp.stamps.replaceNo

The reference page for this step also documents the generic document routes GET /v1/orders/:id/documents and GET /v1/orders/:id/documents/:documentId/download under documents.read. Those belong to the generic order resource, and a section below explains how they relate. For e-Stamp orders created through the e-Stamp routes, the stamp and certificate routes above are the path.

GET/v1/orders/:id/documents

List documents for an order

Request parameters

Request parameters
FieldTypeDescription
AuthorizationrequiredheaderBearer <api-key> (e.g. sk_test_... in sandbox, sk_live_... in production). The x-api-key header is also accepted.

GET/v1/orders/:id/documents/:documentId/download

Get a document download URL

Request parameters

Request parameters
FieldTypeDescription
AuthorizationrequiredheaderBearer <api-key> (e.g. sk_test_... in sandbox, sk_live_... in production). The x-api-key header is also accepted.

Response fields

Response fields
FieldType
downloadUrlstring
expiresAtstring

Reading an order

The order is the container, and its status describes review, not production. A read returns the order record you saw at creation, updated.

cURL
export STAMPMITRA_API_KEY="sk_test_xxxxxxxxxxxx"
export BASE="https://api-b2b.stampmitra.in"

curl -s "$BASE/v1/estamp/orders/estord_9c1f2a3b" -H "Authorization: Bearer $STAMPMITRA_API_KEY"
JSON
{
  "id": "estord_9c1f2a3b",
  "orderId": "6a0e2b9a-5f1d-4c63-9c2e-0d4e7b1f3a55",
  "reference": "lease-2026-0412",
  "state": "MH",
  "status": "READY_TO_PLACE",
  "isTest": false,
  "stampCount": 1,
  "stamps": [{ "id": "eststamp_4f21ab", "clientReference": "line-001" }],
  "errors": [],
  "warnings": [],
  "createdAt": "2026-10-29T09:12:03.000Z",
  "updatedAt": "2026-10-29T10:40:11.000Z"
}

The order statuses are PENDING_REVIEW, READY_TO_PLACE, WARNINGS, NEEDS_INFORMATION, VALIDATION_FAILED and CANCELLED, covered on the order page. They are the platform's own pre-placement vocabulary. The thing to take from this page's point of view is that an order status never says "stamped". Once an order has been placed, the interesting information moves to its stamps, which you reach through the ids in stamps[].

Reading a stamp

GET /v1/estamp/stamps/:stampId returns one stamp with the issuing side's own fields.

cURL
curl -s "$BASE/v1/estamp/stamps/eststamp_4f21ab" -H "Authorization: Bearer $STAMPMITRA_API_KEY"
JSON
{
  "id": "eststamp_4f21ab",
  "clientReference": "line-001",
  "bulkOrderId": "estord_9c1f2a3b",
  "status": "GENERATING",
  "verified": false,
  "state": "MH",
  "category": "e_stamp",
  "amount": 1000,
  "uin": null,
  "costCentre": "CC-100",
  "businessUnit": "BU-Retail",
  "purpose": "Leave and licence agreement"
}
FieldWhat it tells you
idThe stamp id
clientReferenceYour own line reference, echoed
bulkOrderIdThe order this stamp belongs to
statusThe issuing side's lifecycle status
verifiedWhether the stamp has completed verification
state, categoryState and e_stamp or traditional_stamp
amountThe stamp's denomination
uinThe unique identification number, present once generated
costCentre, businessUnit, purposeYour tags and the stated purpose, where supplied

The read merges the platform's own record of the stamp with a live read from the issuing side for fields such as verified and amount, so a slow upstream can make this call slower than a pure database read. Do not poll it in a tight loop.

What each stamp status means

StatusMeaningWhat to do
PLACEDThe order was placed with the issuing sideWait; a stamp is being assigned
ASSIGNEDA stamp has been assigned to the lineWait
GENERATINGThe certificate is being generatedPoll the certificate route at a relaxed pace
VERIFYINGGenerated, now being verifiedPoll the certificate route
VERIFIEDVerified. The certificate followsFetch the certificate when available turns true
CANCELLEDCancelled at the issuing sideStop polling; handle as cancelled

A stamp that is VERIFIED and a certificate that is available are separate facts. The certificate is delivered to the platform after verification, and the certificate route reports whether that has happened. Treat VERIFIED as "very soon" and available: true as the only evidence that a file exists to fetch.

Map unknown status strings to a "needs attention" state instead of throwing, and keep the raw value. The vocabulary belongs to the issuing side, and it can grow.

The certificate route

GET /v1/estamp/stamps/:stampId/certificate is a deliberate passthrough with an explicit discriminator. It always returns HTTP 200 for a stamp that exists, with one of two shapes.

JSON
{ "available": false, "status": "not_yet_available" }
JSON
{
  "available": true,
  "status": "available",
  "downloadUrl": "https://api-b2b.stampmitra.in/v1/estamp/certificates/eststamp_4f21ab/download?token=...",
  "expiresAt": "2026-10-29T10:05:00.000Z",
  "certificateNumber": "IN-MH-2026-0917-001234"
}
FieldMeaning
availableWhether the certificate has been delivered and can be downloaded
statusnot_yet_available or available
downloadUrlA time-limited, presigned URL hosted by StampMitra. Present only when available
expiresAtWhen the URL stops working, an ISO 8601 timestamp. Present only when available
certificateNumberThe certificate number, once issued. It can be null even when the certificate is available

Four rules follow from this design.

  1. not_yet_available is not an error. It is HTTP 200, because the stamp exists and the file does not yet. Poll, with backoff.
  2. The route never falls back to a live call to the issuing side. It reports what the platform has ingested. If the file has not arrived, it says so.
  3. The URL is StampMitra's, never a third party's. The platform rewrites the issuing side's own link before it reaches you, and the link you receive lives five minutes.
  4. certificateNumber can be null. Do not make it a required field in your database.

Downloading safely

The five-minute lifetime is the single most important operational fact on this page. A downloadUrl is a ticket to fetch the file right now, not a stable address. Fetch the URL immediately after you receive it, stream the file to your own storage, verify what you stored, and only then mark the stamp as delivered.

JavaScript
// Node 18+; server side only
import { createHash } from "node:crypto";
import { writeFile } from "node:fs/promises";

const BASE = "https://api-b2b.stampmitra.in";
const headers = { Authorization: `Bearer ${process.env.STAMPMITRA_API_KEY}` };

export async function fetchCertificate(stampId, saveTo) {
  const res = await fetch(`${BASE}/v1/estamp/stamps/${stampId}/certificate`, { headers });
  const body = await res.json();
  if (res.status === 404) return { state: "unknown-stamp" };
  if (!res.ok) throw Object.assign(new Error(body.error?.message), { status: res.status, requestId: body.error?.requestId });
  if (!body.available) return { state: "pending" };

  // The link lives five minutes: use it now, in the same function
  const file = await fetch(body.downloadUrl);
  if (!file.ok) return { state: "download-failed", status: file.status };   // fetch a fresh link next time
  const bytes = Buffer.from(await file.arrayBuffer());
  if (bytes.subarray(0, 4).toString() !== "%PDF") return { state: "not-a-pdf" };

  await writeFile(saveTo, bytes);
  const sha256 = createHash("sha256").update(bytes).digest("hex");
  return { state: "stored", certificateNumber: body.certificateNumber ?? null, sha256, size: bytes.length };
}
Python
import hashlib, os, requests

BASE = "https://api-b2b.stampmitra.in"
H = {"Authorization": f"Bearer {os.environ['STAMPMITRA_API_KEY']}"}

def fetch_certificate(stamp_id: str, save_to: str) -> dict:
    r = requests.get(f"{BASE}/v1/estamp/stamps/{stamp_id}/certificate", headers=H, timeout=20)
    body = r.json()
    if r.status_code == 404:
        return {"state": "unknown-stamp"}
    if not r.ok:
        err = body["error"]
        raise RuntimeError(f"{r.status_code} {err['code']} req={err['requestId']}")
    if not body["available"]:
        return {"state": "pending"}

    f = requests.get(body["downloadUrl"], timeout=60)          # the link lives five minutes
    if not f.ok:
        return {"state": "download-failed", "status": f.status_code}
    if not f.content.startswith(b"%PDF"):
        return {"state": "not-a-pdf"}
    with open(save_to, "wb") as out:
        out.write(f.content)
    return {"state": "stored", "certificate_number": body.get("certificateNumber"),
            "sha256": hashlib.sha256(f.content).hexdigest(), "size": len(f.content)}

If the download fails, do not retry the old URL. Request the certificate route again and use the fresh link, since each call to the route returns a new presigned URL. Never put the downloadUrl in an email, a notification or a log, because it is a bearer ticket for a customer document. And never ship your API key to a browser to let the user download directly: stream the file through your own server, or serve it from your own storage with your own access control.

A polling schedule that respects everyone

Polling is the fallback that always works, so make it cheap and polite. A fixed interval is wasteful early and slow late. A graduated schedule fits the shape of the wait.

Time since the order was placedPoll the stamp or certificate every
First 10 minutes60 seconds
10 minutes to 2 hours5 minutes
2 to 24 hours30 minutes
After 24 hours2 hours, and raise an internal alert

Add jitter so that a thousand stamps do not all poll on the same second, honour 429 responses by doubling the wait, and poll stamps individually rather than in a tight loop over the whole list. Stop polling a stamp on CANCELLED or once the certificate is stored. Your expected waiting time should come from your own measurements, since the catalogue's processingTimeHours is only an expectation.

JavaScript
// Decide when to look at a stamp next, in milliseconds
export function nextPollDelayMs(placedAt, now = Date.now()) {
  const ageMin = (now - new Date(placedAt).getTime()) / 60_000;
  const base = ageMin < 10 ? 60_000 : ageMin < 120 ? 5 * 60_000 : ageMin < 1440 ? 30 * 60_000 : 2 * 3600_000;
  return Math.round(base * (0.8 + Math.random() * 0.4));   // +/- 20 percent jitter
}

Keeping polling cheap

Polling costs nothing on StampMitra's side, since these reads are not metered, but it is not free. It consumes rate limit, it loads your own workers and, for stamp reads, it can touch the issuing side. A few habits keep it cheap. Poll the certificate route in preference to the stamp route once a stamp is VERIFYING or later, because the certificate route answers your real question directly. Keep one scheduler that owns the next-poll time for every stamp, instead of a timer per stamp. Store the next poll time in the database so that a restart does not make every stamp poll at once. And measure: the number of polls per stored certificate is a good health number, and a figure much above the length of your schedule means something is polling too eagerly.

Webhooks as hints

The webhooks reference lists the order lifecycle events: order.created, order.payment_confirmed, order.fulfilment_started, order.fulfilment_completed, order.failed, order.cancelled, order.refund_completed and order.document_ready. The last one is the one this step cares about: a generated document, such as an e-stamp certificate, is ready to download. A delivery is a signed POST with a JSON body.

JSON
{
  "coreOrderId": "core_order_9f3a1c2b8e4d4a5f",
  "coreEventType": "FULFILMENT_COMPLETED",
  "occurredAt": "2026-09-25T09:05:00.000Z",
  "orderId": "ord_4f5a6b7c8d9e0f1a",
  "externalOrderId": "ord_ext_123",
  "status": "FULFILMENT_COMPLETED"
}
HeaderValue
X-Webhook-SignatureHex HMAC-SHA256 of the timestamp, a dot and the raw body, keyed with your endpoint secret
X-Webhook-SignaturesDuring a secret rotation, every currently valid signature as v1=<hex> entries
X-Webhook-TimestampUnix seconds when the attempt was signed. Part of the signed string
X-Webhook-Event-IdA stable event id. Use it to de-duplicate retries

Failed deliveries retry with exponential backoff, at roughly one minute, five minutes, thirty minutes, two hours and twelve hours, and are dead-lettered after six attempts. Verify against the raw bytes, reject timestamps far from your clock (the official SDKs default to 300 seconds), compare in constant time, de-duplicate on the event id and answer with a 2xx quickly, doing real work off the request path. Register endpoints on the Webhooks page of the dashboard; the webhooks page has verification code in seven languages.

One caveat matters here. The events are keyed to the platform's generic order lifecycle, and the example payload shows its field names. For an order created through the e-Stamp routes, do not assume that every event in the list fires, or that the payload carries a stamp id. Confirm coverage for your account with developer support before you depend on any event, and design so that you do not have to.

Webhooks and polling, together

The sturdy design treats an event as a nudge and the certificate route as the truth.

  1. On an event, verify the signature, de-duplicate on the event id, and enqueue a job to look at the order's stamps. Respond 2xx immediately.
  2. In the job, read each stamp and its certificate route, and act only on what they return.
  3. On a schedule, poll every stamp that is not yet stored, using the graduated schedule above, as a backstop for events that never came or came out of order.
  4. Make everything idempotent. Fetching a certificate you already stored should be a cheap no-op.

With this design a lost event costs you a few minutes of latency, a duplicated event costs nothing, and an event that arrives before the certificate does is simply a poll that finds not_yet_available.

Storing certificates

A certificate is a legal document that may matter for years, and the five-minute link means your copy is the only durable one you control.

PracticeWhy
Store the PDF in durable, access-controlled object storage, not on an application server's diskDisks are lost, and certificates are not replaceable by you
Name the object from your own ids, such as agreement/{id}/stamp/{stampId}.pdfPredictable, searchable, not dependent on the platform's links
Record stampId, certificateNumber, uin, sha256, size, fetchedAt and the order ids in a tableThe metadata is what you search, not the file
Keep the file immutable and versionedA re-fetch should never overwrite the original silently
Encrypt at rest and restrict who and which services can read itThe document names the parties
Back it up and test the restoreA certificate you cannot restore is a certificate you do not have
Apply a retention rule that matches your own obligationsKeeping forever is a decision, not a default

StampMitra's data retention and deletion schedule describes what the platform keeps on its side. Do not treat that as your archive: your records are yours to keep and protect.

Metadata worth recording with every file

The PDF is the document, and the metadata is how you find it, prove it and explain it. Record at least the following next to each stored certificate, in a table you can query.

ColumnSourceWhy it matters
stamp_id, platform_order_id, core_order_idThe create responseJoin keys to the platform's records
agreement_id, client_referenceYour ownWhich document this certificate belongs to
certificate_number, uinThe certificate route and the stampWhat the customer or an authority may quote
state, category, amountThe stampWhat was bought, for audits and reports
status_at_fetch, verifiedThe stampThe state of the stamp when you stored the file
sha256, size_bytes, storage_keyYour storage stepIntegrity and location
fetched_at, fetched_by_job, request_idYour workerWho fetched it, when, and the request that returned the link

Add a row to an audit table each time the file is read by a person or a service, and each time it is shared. When a customer asks months later for "the stamp for my lease", a single query by agreement id should return the file, its number and its history.

Checking a certificate

A stamp carries identifiers you can record and check. The uin is the unique identification number of the stamp, and the certificateNumber is the number on the certificate. The verified flag on the stamp says that verification completed on the issuing side. A practical routine is to store all three, to show the certificate number to the customer next to the download, and to treat the file as the primary document. If you or your customer need independent assurance, an e-stamp certificate can generally be checked with the issuing authority's own verification facility for the state, using the certificate number, and the right place and procedure are the state's to define, so confirm them with the authority or your counsel.

Do a basic sanity check on every download: the file starts with %PDF, it is of a plausible size, and the certificate number you stored matches the one in the response. If a file fails any check, keep it aside, alert a person and fetch again. Do not hand a customer a file you have not looked at.

Cancelling and replacing a stamp

Stamp-level actions exist for the cases an order-level cancel cannot reach.

ActionRouteWhen it worksWhen it does not
Cancel a stampPOST /v1/estamp/stamps/:stampId/cancelWhile the stamp is in a cancellable state at the issuing sideVERIFIED or already cancelled returns 409 INVALID_STATE
Replace a stampPOST /v1/estamp/stamps/:stampId/replaceAfter a generation or printing defect, where the stamp is replaceableA stamp not in a replaceable state returns 409 INVALID_STATE

Use replace for a defect in the stamp, not for a wrong detail. A wrong party name or amount is a new order. A replace returns the replacement stamp, which has its own id, so record the link between the old and the new stamp and start polling the new one. A cancel does not guarantee an immediate refund, and the ledger is where you will see any credit, as the payment page explains.

The generic document routes

The reference also lists GET /v1/orders/:id/documents, which lists the documents of a generic order, and GET /v1/orders/:id/documents/:documentId/download, which returns a short-lived signed URL. They need the documents.read scope and return a downloadUrl and an expiresAt.

JSON
{
  "downloadUrl": "https://files.stampmitra.in/signed/doc_00789.pdf?token=abc123",
  "expiresAt": "2026-10-29T09:56:07.000Z"
}

These belong to the generic order resource, the platform-wide one that works for any entitled service code. An e-Stamp order created through POST /v1/estamp/orders is read and fulfilled through the stamp and certificate routes above. If you also use the generic resource for another service, the same rules apply to its download URLs: they are short-lived, they are bearer tickets, and you should fetch and store immediately. If a download is not yet supported for an order, the platform answers with a clear "not available yet" message instead of a broken link.

Delivering the certificate to your customer

A stored file is not yet a delivered one. How you hand the certificate over is a product decision with a few firm edges.

  • Serve it from your own storage, behind your own login. The customer clicks a link in your app, your server checks who they are and streams the file. Never forward the platform's downloadUrl.
  • Notify with a link, not an attachment, by default. An email that says "your stamp is ready" and points to your authenticated page keeps the document out of inboxes. If a customer needs the file by email, attach it deliberately and say who it was sent to.
  • Give every party access that they should have. A tenant and a landlord are both parties to the instrument. Decide who may see the certificate, and record each download with who, when and from where.
  • Show the certificate number beside the download, so that the customer has something to quote if they are ever asked for it.
  • Be careful with printouts. Whether a printed copy of an e-stamp certificate is acceptable, and for what, depends on the state and the purpose, so do not tell a customer a printout is enough. Point them to the state's rule or to their adviser.
  • Mind the order of events. A stamp is meant to be purchased on or before the date the document is executed. Tell customers to sign after the certificate is ready, and show the certificate date in your signing flow.
  • Keep your own links short-lived too. If you issue time-limited links to your own storage, set an expiry that matches your risk, and make "send me a new link" one click.

A good delivery screen is dull: the document, its number, a download button, who else can see it, and one line about what to do next.

Binding the certificate to the signed agreement

The certificate and the agreement are two files that belong together, and your system should make that link explicit.

  1. Store them under one agreement id, with the stamp id, the certificate number and the uin on the same record.
  2. Keep the hash of each file so that a later copy can be checked against what you stored.
  3. Check the parties. Before the agreement goes to signing, compare the names on the certificate with the names in the agreement. A mismatch is far cheaper to fix before signature than after.
  4. Check the amount and the state. The denomination and the state on the stamp should match what the agreement was priced and drafted for.
  5. Record the sequence. Keep timestamps for stamp purchased, certificate stored, agreement signed and, where relevant, registered, so that the order of events is demonstrable.
  6. Decide what a mismatch triggers. A defect in the stamp is a replace. A wrong name or amount is a new order and, if the first stamp is unused, a cancellation. Put that decision in a runbook with a named owner.

If your product also handles signing, the e-sign policy describes how that service is treated. Registration, where a document needs it, is a separate step with its own rules, and your records should leave room for it.

What goes wrong, and what to do

SituationSignalWhat to do
The certificate is not there yetavailable: false, HTTP 200Keep polling on the schedule
The download link expiredThe download fails with an errorCall the certificate route again for a fresh link
The stamp was cancelledStatus CANCELLEDStop polling, tell the customer, check the ledger
A stamp stays in one status for far too longNo change past your alert thresholdAlert internally, then contact developer support with the stamp id
The file is not a PDF or looks wrongFails your sanity checkKeep it aside, fetch again, escalate if it repeats
An event arrives but the certificate is not availablePoll shows not_yet_availableTreat the event as early; the schedule will catch it
The same event arrives twiceSame X-Webhook-Event-IdIgnore the repeat
Your endpoint was down for hoursGaps in eventsThe polling backstop covers it; check dead-lettered deliveries with support

A stamp that never seems to arrive

Sometimes the wait is simply long. A short runbook turns an anxious customer into a routine escalation.

  1. Read the order and the stamp. Note both statuses and updatedAt.
  2. Compare the elapsed time with your own measured tail for that state, not with a catalogue estimate.
  3. If the order is still in a pre-placement status, the delay is in review. Check for NEEDS_INFORMATION, which means the platform is waiting for you.
  4. If the stamp is in PLACED, ASSIGNED, GENERATING or VERIFYING well past your tail, collect the stamp id, the order ids, the timestamps and a recent requestId.
  5. Contact developer support with that bundle, and tell the customer what you know and what you have done.

Give the customer a truthful sentence and a next update time. Silence is what turns a delay into a complaint.

Errors and how to react

All errors use { "error": { "code", "message", "requestId" } }.

StatusCodeWhenWhat to do
400BAD_REQUESTThe organisation is not entitled to e-StampCheck entitlement and production access
401UNAUTHORIZEDMissing or invalid keyFix the key
403FORBIDDENValid key without estamp.orders.read or estamp.stamps.readAdd the scope
404NOT_FOUNDNo such order or stamp for your organisationCheck the id and which key you used
409CONFLICTCancel or replace is not possible in the stamp's current stateRead the status and stop
429TOO_MANY_REQUESTSRate limit exceededBack off and add jitter
502INTERNAL_ERRORUpstream unreachableRetry with backoff; keep polling on schedule

A 404 on a stamp deserves a second look at which id you used. The stamp ids come from stamps[].id on the order, and an order id in a stamp path is a classic mix-up.

Sandbox and production

A sandbox key can take an order all the way to a certificate. The order advances by itself (see the order page), its stamps follow it, and the certificate route answers with a real, downloadable file. That file is a sample, and the difference matters, so this chapter is explicit about both what you can exercise and what you still cannot. Every e-Stamp sandbox request counts toward the sandbox limits (10 requests a minute and 200 a day per organisation, and 50 a day per IP address, resetting at midnight IST), so polling an order, a stamp or a certificate spends the same allowance as creating one. Poll at a sensible interval.

Stamps and the certificate in sandbox

A sandbox stamp has its own status that follows the order's clock.

Order statusStamp statusCertificate route
CREATED, PAYMENT_PENDINGPLACED{ "available": false, "status": "not_yet_available" }
PROCESSING, first thirdASSIGNEDnot yet available
PROCESSING, second thirdGENERATINGnot yet available
PROCESSING, last thirdVERIFYINGnot yet available
ISSUEDVERIFIED, with verified: true and a uinavailable: true with a downloadUrl, expiresAt and certificateNumber
PAYMENT_FAILED, ISSUANCE_FAILED, CANCELLED, EXPIREDCANCELLEDnot yet available, and it stays so

When the certificate is available, downloadUrl is a short-lived link that works for five minutes and needs no API key header, exactly the situation your download code must handle in production. It serves one small PDF, the same bytes for every stamp, watermarked SANDBOX SAMPLE, NOT A VALID STAMP. Nothing is stored per order. The certificateNumber starts with SBX-, and the uin on the stamp starts with IN-SBX, so neither can be mistaken for a real one. After the five minutes the link answers 404, which gives you a real expired-link case to test. The link itself needs no API key, so it does not use that allowance. It has its own small cap of 60 requests an hour per IP address, and the 61st answers 429 with the code SANDBOX_DOWNLOAD_LIMIT and a Retry-After header. Asking the certificate route for the link does count toward the sandbox limits.

Use that file to prove the whole path: fetch inside the window, check the %PDF bytes, store the file, attach it to your customer's record and send the notification. Do not keep the sample as if it were a certificate, and do not let it reach a customer.

Cancel and replace in sandbox

The rules are the production ones. A stamp can be cancelled until its certificate is delivered, so a VERIFIED stamp answers 409 and a second cancel of a cancelled stamp answers 409. A stamp cannot be replaced while it is only PLACED or after it is CANCELLED. A replacement returns a new stamp with a new id, the old stamp becomes CANCELLED, and the new stamp runs its own short timeline of about fifteen seconds from ASSIGNED to VERIFIED. The order lists the new stamp, not the old one. Cancelling the order cancels all its stamps and credits the sandbox wallets back.

Webhook events in sandbox

If the organisation has a webhook endpoint registered for the sandbox environment, each change sends the documented event to it, signed exactly like a production delivery. A production endpoint never receives a sandbox event.

WhenEvents sent
The order is createdorder.created
It enters PROCESSINGorder.payment_confirmed, then order.fulfilment_started
It becomes ISSUEDorder.fulfilment_completed, then order.document_ready
Payment fails, issuance fails or it expiresorder.failed, then order.refund_completed
It is cancelledorder.cancelled, then order.refund_completed

PAYMENT_PENDING has no event of its own. The payload carries orderId, reference, status and sandbox: true, the document_ready event adds the stampIds, and a failure adds the failure object. The event id stays the same on every retry, so de-duplicate on it. Events are queued within about ten seconds of the change, so keep polling as the backstop, as the earlier chapters advise.

What the sandbox still cannot tell you

Cover the rest with a small production rehearsal. The sandbox cannot show you the real review wait, because it has no reviewer. It cannot show you a real certificate, with its real bytes and layout, or how long a real delivery takes. It cannot tell you whether a given state will issue, since state availability is a production fact. Before launch, create one low-value production order, watch it all the way to a stored and checked certificate, and keep the fixture it produces. Production needs an approved production access request and funded wallets. The sandbox versus production guide covers the switch.

What to measure

A few numbers tell you whether this step is healthy.

  • Time from placement to certificate stored, as a median and a slow tail, by state. This is your honest delivery expectation.
  • Stamps older than your alert threshold without a stored certificate. The count should be zero on a good day.
  • Download failures, by cause: expired link, bad file, network. A rise in expired links means your fetch is not immediate.
  • Poll volume per stamp. A stamp polled hundreds of times means the schedule is too tight.
  • Events received, duplicated and out of order, if you use webhooks, so you know how much to trust them.
  • Dead-lettered webhook deliveries, which point to endpoint downtime.

Alert on the first two and look at the rest weekly.

Worked example: three stamps, one slow

A broker app placed an order with three lines: a leave and licence agreement, an indemnity bond and an affidavit. The order was placed at nine in the morning, and the app holds three stamp ids with their clientReference values.

At 9:05 the first poll reads each stamp. All three are PLACED. At 9:40 the lease and the affidavit are VERIFYING and the bond is still ASSIGNED. At 10:15 the app receives an order.document_ready event. It verifies the signature, records the event id, and enqueues a job. The job reads all three certificate routes. Two return available: true, and the job downloads each immediately, checks the %PDF header, stores the files with their hashes and certificate numbers, and marks those stamps delivered. The third returns not_yet_available, so the job leaves it on the schedule.

At 10:30 the broker's customer asks where the indemnity bond is. The app shows the lease and the affidavit as ready for download from the app's own storage, and the bond as "in progress, usually within a few hours". At 1:10 in the afternoon the bond's certificate becomes available. The scheduled poll finds it, downloads it within the same call and stores it. The customer is notified once, with all three documents.

Throughout, the app never relied on an event for the truth, never kept a download URL beyond the function that used it, and never told the customer a stamp was ready before a stored, checked file existed.

Testing

TestWhat it proves
available: false is handled as pending, not as an errorYou do not alarm customers early
available: true triggers an immediate fetch and storeThe five-minute link is respected
An expired link leads to a fresh certificate call, not a retry of the old URLYou recover correctly
A file that does not start with %PDF is quarantinedYou never deliver garbage
A null certificateNumber does not break storageThe field is optional
A duplicated event does not cause a second fetchDe-duplication works
A lost event is covered by the polling scheduleThe backstop works
CANCELLED stops polling and notifiesTerminal states are handled
Unknown status strings land in "needs attention"A new status cannot crash the poller
Stored files can be restored from backupThe archive is real

Common mistakes

  • Treating VERIFIED as "the file exists". Only available: true says so.
  • Keeping the downloadUrl. It lives five minutes and is a bearer ticket.
  • Retrying an expired URL. Ask the certificate route for a new one.
  • Treating not_yet_available as a failure. It is a normal HTTP 200 state.
  • Trusting an event over the route. Events are hints.
  • Putting the API key in a browser to download. Stream through your own server.
  • Storing only the link. Store the file.
  • Making certificateNumber required. It can be null.
  • Using replace for a wrong detail. Create a new order instead.
  • Treating the sandbox certificate as the real one. It is the same watermarked sample PDF for every stamp, and it is not a valid stamp.

Where this fits in the flow

Order status and document access is step eight, the last of eight. Before it come the catalogue, the schema, the state, instrument and article lookup, the duty and value calculation, the parties, the order and the payment. The overview guide shows all eight with a rental example, the order flow guide goes deeper on webhooks, and the e-Stamp API reference lists the routes in tabular form.

StampMitra is a private LegalTech platform operated by Bani Global Industries LLP. It is not a government body or a law firm, and nothing here is legal advice. Whether and where your document must be executed or registered is for you or your counsel.

Sources

Frequently asked questions

How do I download the e-stamp certificate through the API?

Call GET /v1/estamp/stamps/:stampId/certificate. When available is true it returns a downloadUrl, expiresAt and certificateNumber. Fetch the URL immediately, stream the PDF into your own storage, check it starts with %PDF and then mark the stamp delivered.

Why does the certificate route return 200 with available false?

The stamp exists but its certificate has not been delivered yet, so the route reports not_yet_available instead of an error. It never falls back to a live call upstream. Keep polling on a graduated schedule and do not alarm the customer.

How long is the certificate download link valid?

Five minutes. It is a presigned URL hosted by StampMitra, never a third-party link. If a download fails or the link expired, call the certificate route again for a fresh one, and never store or email the URL.

Does VERIFIED mean the certificate is ready?

Not by itself. VERIFIED means the stamp completed verification, and the certificate follows. Only available true on the certificate route proves that a file exists to fetch, so treat VERIFIED as very soon.

Can certificateNumber be null?

Yes, even when the certificate is available. Do not make it a required column. Store it when present, record the uin from the stamp as well, and show the certificate number to the customer only when you have it.

Should I use webhooks or polling for e-stamp certificates?

Both. Treat an order.document_ready event as a hint to look, verify its signature, de-duplicate on X-Webhook-Event-Id, then read the certificate route. Keep a graduated poll as a backstop, since events can be late, duplicated or missing for e-Stamp orders.

How often should I poll for a certificate?

Roughly every minute for the first ten minutes after placement, every five minutes up to two hours, every thirty minutes up to a day, then every two hours with an internal alert. Add jitter, back off on 429 and stop on CANCELLED or once stored.

Can I sandbox-test certificate download?

Yes. A sandbox order reaches ISSUED by itself in about thirty seconds, and the certificate route then returns a short-lived downloadUrl to one shared PDF watermarked SANDBOX SAMPLE, NOT A VALID STAMP. It is not a real certificate, so rehearse one low-value production order before launch.

How do I replace a defective e-stamp?

POST /v1/estamp/stamps/:stampId/replace requests a replacement for a defect such as a generation problem and returns the new stamp, which has its own id. A wrong party name or amount is not a defect: cancel and create a new order instead.

Can I cancel a stamp after it is verified?

No. A verified stamp cannot be cancelled and returns 409 INVALID_STATE. Cancellation works only while the stamp is in a cancellable state at the issuing side, and any credit appears in the wallet ledger rather than instantly.

Where should I store the certificate?

In durable, access-controlled object storage under your own naming, with the stamp id, certificate number, uin, hash and fetch time recorded in a table. Keep it immutable, encrypted and backed up, and serve it to customers from your own storage.

What are the generic order document routes?

GET /v1/orders/:id/documents and its download route belong to the platform-wide order resource and need documents.read. E-Stamp orders created through the e-Stamp routes use the stamp and certificate routes instead. Their download links are also short-lived and should be fetched immediately.

Build with AI

Integrate Order Status & Document Access with one prompt.

Pick your AI tool and copy a prompt written for this API. It already has the endpoints, fields and errors.

Claude prompt · Order Status & Document Access · 5,278 charactersOpen Claude ↗
I'm using Claude to build this.

Integrate the StampMitra API (Indian identity verification and e-Stamp Paper) into my app.

API facts (source of truth: https://developer.stampmitra.in/llms.txt)
- Base URL: https://api-b2b.stampmitra.in
- Auth: send "Authorization: Bearer <key>" (or "x-api-key: <key>") on every request
- Requests and responses are JSON. Send Content-Type: application/json on POST.
- Use a SANDBOX key (sk_test_...) while building. Read it from the environment variable STAMPMITRA_API_KEY.
- Never hard-code the key, never expose it to the browser, never log it.
- Call StampMitra only from server-side code. The UI calls my own backend route.

How to build it
- First inspect my project: language, framework, package manager, HTTP client, test runner and folder conventions. Follow them. If the project is empty, ask which stack I want before writing code.
- The official StampMitra SDKs (Node.js, Python, PHP, Java, Go, .NET, Ruby) are pre-release 0.1.0 and not yet published to npm, PyPI, Packagist, Maven Central, the Go module proxy, NuGet or RubyGems, so do not run an install command for them. Call the REST API over HTTPS with the HTTP client my project already uses. Do not install or invent a StampMitra package.
- Put every StampMitra call in ONE small client module. It adds the auth header, applies a 15 second timeout and turns error responses into a typed error with status, code, message and requestId.
- Add STAMPMITRA_API_KEY to .env.example with a placeholder (sk_test_xxx). Fail fast at startup with a clear message if it is missing. Never commit real keys.

Error handling (every error body is { error: { code, message, requestId } })
- 400 BAD_REQUEST: invalid input. Show a field-level message. Do not retry.
- 401 UNAUTHORIZED: key missing or invalid. This is my configuration problem, not the end user's. Show a generic "service unavailable" message, log the requestId, do not retry.
- 402 PAYMENT_REQUIRED: not enough wallet balance (production). Surface it to me as an operational alert, not to the end user.
- 403 FORBIDDEN: the key lacks the required scope or the service is not enabled. Say which scope the endpoint needs.
- 404 NOT_FOUND: wrong id or path. Do not retry.
- 429 TOO_MANY_REQUESTS (or, on a sandbox key, SANDBOX_RATE_LIMIT, SANDBOX_DAILY_LIMIT, SANDBOX_IP_LIMIT): rate limit, or the sandbox limits of 10 requests a minute and 200 a day per organisation. Retry at most 3 times with exponential backoff and jitter (honour Retry-After if present), then show a friendly "try again shortly" message.
- 5xx / 502 / network timeout: retry reads (GET) up to 2 times. For POST calls retry at most once, then show a friendly message.
- Log requestId and referenceId with every failure. Never log the API key, a full PAN, bank account number or whole response bodies.

TASK: Integrate the StampMitra "Order Status & Document Access" API
Retrieve the generated e-Stamp certificate/document once an order completes.

ENDPOINT: GET /v1/orders/:id/documents
- List documents for an order
- Required scope: documents.read

ENDPOINT: GET /v1/orders/:id/documents/:documentId/download
- Get a document download URL
- Required scope: documents.read
- Response fields: downloadUrl, expiresAt
- Example response: {"downloadUrl":"https://files.stampmitra.in/signed/doc_00789.pdf?token=abc123","expiresAt":"2026-10-15T09:56:07.000Z"}

Rules for this e-Stamp step
- This is one step of the e-Stamp order flow: services -> state/instrument/article -> schema -> duty -> order -> parties -> payment -> status -> documents.
- Build the form from the schema endpoint and do not invent e-Stamp fields.
- Send an Idempotency-Key header on order creation, store the order id, and make the flow resumable.
- Poll order status with backoff until a final status. Download documents through my backend, never from the browser with the key.
- If an endpoint returns 404 or is not enabled for my key, stop and ask me rather than guessing.

Test in Sandbox
- A successful call, a validation failure (expect 400), a missing or wrong key (expect 401) and the 429 / 5xx retry path.

How I want you to work:
1. Before writing code, list the files you will create or change and the plan in 5-8 bullets. Then implement without pausing for approval.
2. If the StampMitra MCP server (@stampmitra/mcp-server) is connected, use it to run real sandbox calls and check the response shape before coding against it.
3. Write tests for the API client module and the validation (mock the HTTP layer).
4. At the end, summarise what you changed, how to run it and what I must do manually (add the key, restart the server).

Acceptance checklist:
- Works end to end in Sandbox with the real response fields (no mocked data in the final path)
- No secrets in client code, logs, URLs or git
- Clear loading, empty and error states, including 400, 401, 402, 403, 429 and 5xx
- referenceId (and requestId on failures) is stored or logged for audit
- Inputs are validated on client and server, and sensitive values are masked in the UI
- Tests cover the API client, validation and at least one error path
- A short note on how to run it and how to switch from Sandbox to production later
- If anything is missing (like my key), ask me. Do not guess endpoints, fields or values.

Start with a sandbox key.

Free to try. Make your first test call today.