Tran Nhi Foods Co., Ltd · BuyerFeed

Tran Nhi Foods BuyerFeed: specification for Terr'Asia (Duval Foods)

Prepared 30 October 2026, in reply to the request of 29 October 2026 from Emilie Troeung, for your IT or EDI contact and your buying team. Revised 4 November 2026: sample shipment and test webhook (section 15), pages for people in a web browser (section 5), and Excel advice for CSV (section 10). Revised 5 November 2026: how the webhook secret is stored (section 4) and the security summary (section 12); nothing you send or receive changes.

You asked for batch/lot number, best-before date (BBD), your item reference, your PO number and quantity shipped, delivered when the shipping documents are issued. Pick one of four ways to receive it, or combine them: all carry the same data from the same release.

#ChannelHow it worksPick it when
1REST APIYour system calls us with a key and gets JSON (or CSV, XLSX, DESADV with ?format=)Your system can poll on a schedule or fetch on demand
2Signed webhookWe POST each release or correction to your HTTPS address as signed JSONYou want to be told straight after a release, with no polling
3CSV or XLSX by linkOne link per shipment and format, valid 30 days, no keyYour buying team works in Excel and has no IT project
4EDIFACT DESADV fileOne UN/EDIFACT D.96A despatch advice message per shipmentYou already run EDI. We need your EDI profile and GLNs first

1. What you get and when

2. The four channels

The table above says when to pick each. Channels 1 and 4 need an API key (DESADV files come from ?format=desadv), channel 2 needs a signing secret, channel 3 needs only the link. A correction reaches you when you poll (1 and 4), straight after the release (2), or when you open the link again, which always serves the latest version (3). The export desk creates channel 3 links on request, for one shipment. Opened in a web browser, a link shows the shipment on screen with an Excel and a CSV download; a program that calls the link gets the file itself. People should use the Excel file; the CSV is for programs (section 10).

3. Fields

Shipment header:

FieldTypeMeaning
payload_versionintegerVersion of this data layout
shipment_idtextTran Nhi's stable id. Never changes, even when corrected. Use it as your key. Letters, digits and . _ : ~ -, 1 to 200 characters, starting with a letter or digit
versionintegerRelease number: 1 first, then 2, 3 for corrections
client_idtextYour account name
our_reftextTran Nhi's reference (the PI number). Not guaranteed unique: the same PI number can exist on more than one order, so never use it as a key. Use shipment_id
issued_atdate or timestampYYYY-MM-DD, or a full ISO 8601 timestamp with Z or an offset. When the later of the Commercial Invoice and Packing List was issued (a date alone when no time is filed). A shipment whose documents were issued after it sailed (a rebuild of an earlier shipment) carries the Commercial Invoice's own date instead
etddate or blankEstimated sailing date as filed, YYYY-MM-DD
vesseltext or blankVessel name and voyage as filed
lineslist1 to 500 goods lines. Charge and fee lines are not sent

Each line:

FieldTypeMeaning
line_nointegerPosition among the goods lines, from 1
buyer_potext or blankYour PO number, per line. Blank, not guessed, where several POs were bundled and none is held per line
buyer_item_codetext or blankYour item reference: the code printed on your PO line (an alias, if your PO printed one). Where no printed code is on file, our catalogue code is sent
our_product_codetext or blankTran Nhi's catalogue code. Differs from yours only for an alias
descriptiontextProduct description as on our documents
cartonsnumber or blankCartons shipped: the invoice-adjusted figure, the quantity on the issued Commercial Invoice, which wins over the PO
bags_per_cartonnumber or blankRead from the packing string (500G X 20 BAGS gives 20)
bagsnumber or blankcartons times bags_per_carton
net_kgnumber or blankNet weight of the line in kg
unittextUnit of the cartons figure
lottext or blankBatch/lot number
lot_sourcederived, typed or blankderived: the lot is the shipment's PI number (one lot per shipment; the web page calls it the shipment number). typed: a person entered a lot for this line
bbddate or blankBest-before date, YYYY-MM-DD. Blank means not yet filed
bbd_sourcederived, typed or blankderived: filed production date plus the product's shelf life, minus one day. typed: a person entered the date for this line

lot and lot_source are both set or both blank, and so are bbd and bbd_source.

4. Authentication

5. Endpoints

Always use HTTPS. The production host is https://buyer-feed.vercel.app.

RequestReturns
GET /api/v1/shipmentsYour shipments, oldest first by the time we received them: {"data":[...],"next_since":"...","has_more":false}
GET /api/v1/shipments/{shipment_id}One shipment: the record itself, not wrapped
GET /d/{token}A link we gave you. In a web browser: a page with the shipment and the Excel and CSV downloads. From a program: the CSV or XLSX itself, or add ?download=xlsx or ?download=csv to choose. Valid 30 days unless we withdraw it sooner (see section 4), always the latest version
GET /api/v1/sampleThe sample shipment, so you can test your integration before a real one exists. JSON, or a file with ?format=csv, xlsx or desadv; the header X-Sample: true marks it. Needs your key. Never appears in GET /api/v1/shipments (section 15)
POST /api/v1/webhook-testSends one signed shipment.test event to your registered webhook address and tells you at once what your address answered (section 15). Needs your key
GET / and GET /docsAn overview and this specification, readable in a web browser. No key, and no shipment data
GET /api/health{"ok":true,"db":true}. No key, no data. db is false if our database is unreachable

Query parameters: since is an ISO 8601 timestamp with Z or an offset, or a date (read as midnight UTC), and returns shipments received strictly after it. In a URL a + must be written %2B (prefer Z). An empty since= means no since. limit is 1 to 200, default 50. format is json (default), csv, xlsx or desadv, in lower case; or send Accept: text/csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet or application/edifact. format wins over Accept. Accept is read simply: if the header names any of those three, the first of them in the order csv, xlsx, edifact wins (q-values are not read); anything else, text/html included, gives JSON.

Files from the list: the body is the file, and the headers X-Next-Since and X-Has-More carry the cursor. A file holds at most 5,000 goods lines, so you may get fewer than limit shipments. File names: <client_id>-<our_ref>.csv (or .xlsx, .edi) for one shipment, for example terrasia-<our_ref>.csv, and shipments-<yyyymmdd>.<ext> for several. The sample call names its files sample-<our_ref>.<ext>, so a sample never overwrites a real download. An empty page as a file is the header row only (CSV), a header-only sheet (XLSX), or an interchange with no message (DESADV, UNZ+0).

Caching: every successful answer carries an ETag. Send it back as If-None-Match and an unchanged answer is 304 with no body. This works for JSON and CSV. XLSX and DESADV files carry their creation time to the second, so their ETag changes from one second to the next: do not rely on it there. Answers say Cache-Control: no-store, so a standard HTTP cache will not revalidate for you: keep the ETag yourself. HEAD works like GET and counts against the limit; a trailing slash on an address is redirected (308) to the one without.

# Channel 1, REST: everything received since your cursor (key kept in an environment variable)
curl -sS -H "Authorization: Bearer $TNF_FEED_KEY" \
  "https://buyer-feed.vercel.app/api/v1/shipments?since=2026-10-01T00:00:00Z&limit=50"

# Channel 2, webhook: nothing to call. After downtime, catch up with the call above.

# Channel 3, CSV or XLSX: open the complete link the export desk sent you
curl -sS -o shipment.csv "<the link we sent you>"

# Channel 4, DESADV: fetch the EDIFACT file for one shipment (a shipment_id from your own list)
curl -sS -H "Authorization: Bearer $TNF_FEED_KEY" -o shipment.edi \
  "https://buyer-feed.vercel.app/api/v1/shipments/<shipment_id>?format=desadv"

# Before any real shipment: the sample, in any format (section 15)
curl -sS -H "Authorization: Bearer $TNF_FEED_KEY" -o sample.edi \
  "https://buyer-feed.vercel.app/api/v1/sample?format=desadv"

6. Rate limits

LimitValueOver the limit
API requests60 per minute per key, in one-minute windows. A 304 counts429 rate_limited
Failed sign-ins or wrong link tokens30 per minute per IP address429 instead of 401 or 404
One download link60 uses per minute429
Test webhook10 per minute per key, and each call also counts in the 60 API requests above429 rate_limited

Pages hold at most 200 shipments and files 5,000 lines: use next_since for the rest. Every API answer after sign-in carries RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset (seconds to the next window). A 429 also carries Retry-After.

7. Replay and idempotency

8. Webhooks

You give us an HTTPS address. Tran Nhi registers it and gives you a signing secret (whsec_ and a base64 string), shown once. We then POST shipment.released (version 1) or shipment.updated (a correction) straight after the release. The headers follow Standard Webhooks.

Headers: webhook-id (msg_ plus 26 hex characters, the same on every retry of one shipment and version), webhook-timestamp (Unix seconds, fresh on each attempt), webhook-signature (v1, plus a base64 HMAC-SHA256 signature), content-type: application/json, user-agent: TranNhiFoods-BuyerFeed/1.

The body is {"type":"shipment.released","timestamp":"<UTC time>","data":{<the shipment, as in section 3>}}. It is built when sent, so a retry carries the current figures.

Answer with any 2xx within 5 seconds. Anything else is retried: another status, a timeout, a connection error, or a redirect (redirects are never followed).

Retries wait, after the failed attempt before them: 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours, 12 hours, 1 day, then 2 days (8 retries).

The 8th retry comes about 3 days 21 hours after the first attempt. A job that runs every 5 minutes picks retries up, so each can be a few minutes later. After the 8th retry we stop and mark the delivery failed: catch up with channel 1. If a newer version is released while an older one waits for a retry, the older delivery is closed and the newer one carries the new figures.

Address rules: https only, at most 2,000 characters, no user name, password or # fragment, a valid certificate for its host name, and a host that resolves only to public addresses (private, loopback, link-local and reserved networks are refused). We check at registration and again before every send, and connect to the address we checked.

To verify a delivery: take the raw body bytes exactly as received (do not parse and re-serialise). Reject a timestamp more than 5 minutes (300 seconds) from your clock. The key is the base64-decoded part of the secret after whsec_. Compute HMAC-SHA256 over <webhook-id>.<webhook-timestamp>.<raw body>, base64-encode it and compare in constant time with the part after v1, (the header may hold several space-separated signatures; we send one). De-duplicate on webhook-id and answer 2xx quickly. Rotating the secret replaces it at once, and a retry made afterwards is signed with the new secret.

The receiver below applies these steps (Node 18 or later, no other packages). A longer version with a command-line mode for testing a saved delivery is available from the export desk.

// receiver.mjs: WEBHOOK_SECRET=whsec_... PORT=8080 node receiver.mjs
import http from 'node:http';
import { createHmac, timingSafeEqual } from 'node:crypto';

function verifyWebhook({ secret, headers, rawBody, toleranceSeconds = 300, now = Date.now() / 1000 }) {
  const id = headers['webhook-id'], timestamp = headers['webhook-timestamp'], signatures = headers['webhook-signature'];
  if (!secret?.startsWith('whsec_')) return { ok: false, reason: 'secret must start with whsec_' };
  if (!id || !timestamp || !signatures) return { ok: false, reason: 'missing webhook header' };
  if (!/^\d{1,12}$/.test(timestamp) || Math.abs(now - Number(timestamp)) > toleranceSeconds) return { ok: false, reason: 'bad or stale timestamp' };
  const key = Buffer.from(secret.slice('whsec_'.length), 'base64');
  const expected = createHmac('sha256', key).update(`${id}.${timestamp}.${rawBody}`, 'utf8').digest();
  for (const part of signatures.split(' ')) { // several signatures are allowed: one match is enough
    const [version, b64] = part.split(',');
    const given = Buffer.from(b64 || '', 'base64');
    if (version === 'v1' && given.length === expected.length && timingSafeEqual(given, expected)) {
      try { return { ok: true, id, event: JSON.parse(rawBody) }; } catch { return { ok: false, reason: 'body is not JSON' }; }
    }
  }
  return { ok: false, reason: 'no matching signature' };
}

const seen = new Set(), store = new Map(); // use a database in production
http.createServer((req, res) => {
  const chunks = [];
  req.on('data', (c) => chunks.push(c));
  req.on('end', () => {
    const rawBody = Buffer.concat(chunks).toString('utf8'); // the exact bytes received
    const r = verifyWebhook({ secret: process.env.WEBHOOK_SECRET, headers: req.headers, rawBody });
    if (req.method !== 'POST' || !r.ok) return res.writeHead(400).end(r.reason);
    if (r.event.type === 'shipment.test') { console.log('test event verified'); return res.writeHead(200).end('ok'); } // never store a test
    if (!seen.has(r.id)) { // de-duplicate retries on webhook-id
      seen.add(r.id);
      const d = r.event.data, held = store.get(d.shipment_id); // key on shipment_id, keep the highest version
      if (!held || d.version > held.version) store.set(d.shipment_id, d); // a blank in the new version replaces a value of the old one
      console.log(r.event.type, d.shipment_id, 'version', d.version);
    }
    res.writeHead(200).end('ok');
  });
}).listen(Number(process.env.PORT) || 8080);

9. Error codes

Every error has the body {"error":{"code":"<code>","message":"<text>"}}. Only invalid_payload adds details. A person who opens a download link in a web browser gets the same status as a readable page instead of this body. A 5xx without this body comes from the hosting platform, not the feed: retry later.

What you can meet:

HTTPcodeWhen
400bad_requestformat, limit or since is invalid. The message says which
401unauthorizedKey missing, malformed, unknown, revoked, or account suspended: one answer for all. Carries WWW-Authenticate: Bearer
404not_foundShipment id unknown, malformed or not yours (one answer for all three), or a download link unknown, altered or belonging to a suspended account
410link_expiredDownload link older than 30 days: ask for a new one
410link_revokedDownload link withdrawn: we revoked it, or your key was rotated after it was issued. Ask for a new one
422webhook_not_configuredPOST /api/v1/webhook-test and no webhook address is registered for your account. Give us the address (section 14)
429rate_limitedA limit in section 6 was passed: wait Retry-After seconds
404not_foundAlso: a path under /api that does not exist (the message says No such endpoint)
405method_not_allowedThe wrong method on a real address. The Allow header names the right one
500internal_errorSomething unexpected on our side. The body never shows internals. If it persists, tell us the time and the request

Used only between Tran Nhi's own systems (listed so nothing is hidden): bad_request (400, body not valid JSON or UTF-8), unauthorized (401, bad, expired or future-dated server signature or scheduler secret), not_found (404, admin request for an unknown shipment), version_conflict, stale_version, client_mismatch, replayed_request (all 409: same version with different content, a lower version than stored, shipment stored for another client, a signed admin request used twice), payload_too_large (413, body over 1 MB), invalid_payload (422, a release failed strict checks, details lists them), unknown_client (422), invalid_request (422, an admin request failed its checks), invalid_webhook_url (422, the webhook address broke the rules in section 8: we will tell you).

10. CSV columns and DESADV summary

CSV and XLSX have one row per goods line. The columns, in this fixed order, are the fields of section 3 except payload_version and client_id, with the header fields repeated on every row: shipment_id, version, our_ref, issued_at, etd, vessel, line_no, buyer_po, buyer_item_code, our_product_code, description, cartons, bags_per_carton, bags, net_kg, unit, lot, lot_source, bbd, bbd_source. A list download puts many shipments under one header.

DESADV is one UN/EDIFACT D.96A despatch advice per shipment (UNH+...+DESADV:D:96A:UN:EAN005), several in one interchange (the UNB and UNZ reference is the creation time to the second, yyyymmddhhmmss UTC, so two files made in the same second share it), ISO 8859-1 (UNOC), application/edifact. The full list of segments and the pages we read is available from the export desk. Confirmed means we read the code on the official UNECE or GS1 page.

SegmentCarriesStatus
BGM+351Number <our_ref>-<version>; function 9 original, 5 replace (a higher version)Codes confirmed; number format is ours
DTM+137, DTM+11Issue date; sailing date when filedConfirmed
LIN, PIA+5 ...:IN::92Line and your item reference; our code (PIA+1 ...:SA::91) only where it differsConfirmed
QTY+12Cartons. No unit is sentQualifier confirmed. The carton unit code is unconfirmed
CPS+1One packing level, every line under it. The file has one segment per line (LF after each ') and its times are UTCConfirmed for the segment
GIN+BXLot, at line levelValid D.96A. Placement for your profile is unconfirmed
DTM+361, RFF+ONBest-before date; your PO number, per lineConfirmed

A blank value drops its segment. A value is never invented. A DESADV names a shipment only as <our_ref>-<version> (BGM), and a PI number can repeat across orders (section 3): until your EDI profile says where a shipment_id reference should go, treat channels 1 and 2 as the source of truth for identity. Files for two shipments with the same PI number share a file name; rename them when you save.

Needs your EDI profile and GLNs. Neither GLN is on file, so the file leaves the sender and recipient (UNB) empty and has no party segments (NAD): structurally complete but not routable. Also unconfirmed: D.96A with EAN005 or D.01B with EAN008; where batch and best-before go (GIN under the line, PIA+1 ...:NB, or PCI then GIN); the unit on QTY. The vessel is not sent.

11. Retention

12. Security summary

How the feed answers the OWASP API Security Top 10 (2023). Every signed-in call to the buyer routes, API and download links alike, is also logged (section 11).

RiskWhat we do
API1 Broken object level authorizationEvery query carries your client id, and the database itself shows each request only the rows of the account it acts for. Another client's shipment and an unknown id give the same 404
API2 Broken authentication32-byte random keys, stored only as hashes, constant-time compare, revocable at once. Failures are limited per IP address, the address our hosting platform records for the connection: a forwarded-address header the caller sends cannot change it
API3 Broken object property level authorizationOutput fields are copied by name from a fixed list. Incoming data is strictly checked
API4 Unrestricted resource consumption60 requests a minute per key, pages of 200, files of 5,000 lines, bodies of 1 MB, 5-second webhook timeout
API5 Broken function level authorizationA buyer key only reads. Release, client and link functions accept only Tran Nhi's signed requests
API6 Unrestricted access to sensitive business flowsNothing a buyer calls can create, change or release a shipment
API7 Server-side request forgeryWebhook addresses must be HTTPS and public, are re-checked before each send, redirects are not followed
API8 Security misconfigurationSecurity headers on every answer, no cookies, no CORS, no internals in errors, minimal database rights. Row-level security on every table: each database transaction declares whose data it acts for, and one that declares nothing sees nothing. Request logs cannot be changed by the service. Webhook secrets are stored encrypted
API9 Improper inventory managementFour buyer-facing routes (section 5) under one versioned path, /api/v1
API10 Unsafe consumption of APIsInbound data comes only from Tran Nhi's own systems, signed over the exact bytes, valid for 5 minutes, then strictly validated

13. Sample files

A sample shipment in all four formats, and a webhook test vector, are available to your API key: GET /api/v1/sample returns the sample shipment (?format=csv, xlsx or desadv for the files), and POST /api/v1/webhook-test sends a signed test event to your registered address. See section 15.

14. What we need from you

  1. Your choice of channel (1 to 4, or several).
  2. A webhook address, for channel 2: an HTTPS URL that answers within 5 seconds, and a technical contact.
  3. Your GLN and EDI profile, for channel 4: both GLNs confirmed, your EDI guideline (D.96A with EAN005 or D.01B with EAN008), where batch and best-before go, and the unit on QTY.
  4. The item-code convention: please confirm that your item reference is the code printed in the product-code column of your PO lines, or tell us which column to use.
  5. Lot: please confirm that one lot per shipment (our PI number) is acceptable, or tell us if you need a lot for each product line.
  6. A named person to receive the API key and webhook secret.

Contact: Tran Nhi Foods export desk.

15. Try it before a real shipment exists

Both calls need your API key and touch no real shipment. Nothing you do here creates, changes or releases anything (section 12, API6).

  1. The sample shipment. GET /api/v1/sample answers with the four lines of section 13, shaped for your account (your client_id). Its shipment_id is sample_<our_ref>, the same in the sample files and in the test webhook: an id no real shipment has. Never store it as a shipment. ?format=csv, xlsx or desadv returns the file. Use it to build your parser. It never appears in GET /api/v1/shipments, so it cannot be mistaken for a real release.
  2. A test webhook. After we have registered your address and given you the signing secret, POST /api/v1/webhook-test (no body) sends one shipment.test event, signed exactly like a real one, with the same headers. Its data is the sample shipment. It answers with what your address replied: {"delivered":true,"http_status":200,"elapsed_ms":143,"webhook_id":"msg_...","event":"shipment.test"}. A reply that is not 2xx, a timeout or an unreachable address gives delivered: false and a short error. Real events are shipment.released and shipment.updated; ignore shipment.test in production. The call fails with 422 webhook_not_configured before an address is registered, and is limited to 10 a minute.
  3. Check your signature code offline. Download webhook-test-vector.json from https://buyer-feed.vercel.app/docs/samples/webhook-test-vector.json (the same path works at any address this service runs on; it is also linked at the bottom of /docs): a throwaway secret, the headers and the exact body of one event, and the signature our code produced. It holds no business data. Run your verifier on it with the clock pinned to the timestamp in the file (the 5-minute tolerance would reject it today); the expected result is ok.

Downloads

A throwaway test vector for your webhook signature check. It holds no business data. The sample shipment itself is served only to your API key (section 15).

webhook-test-vector.json