Flow
- Masnet delivers the
com.masnet.price_request.requested.v1event to the channel destination, or leaves it in the events log if the channel has no webhook. - The system answers the webhook with a 2xx and processes the request asynchronously.
- If
truncatedincludeslines, it reads every line withGET …/price-requests/{id}/lines. - It quotes and sends a single answer with
POST …/price-requests/{id}/responsebeforerespond_by. - Masnet applies every line in one transaction and returns the result per line. The request becomes
appliedeven if some lines have problems.
Requirements
- A production integration of the company designated as the price request channel. Only one integration per company can be the channel. Designating and withdrawing it require a second factor and are audited. An integration of the
testenvironment cannot be the channel, but it does receive the test request. - The designation grants the
price_requestsdomain: the API client usesread:price_requeststo read andwrite:price_requeststo answer.read:price_requestsincludes the current products and prices of the bid lines. - The channel destination is subscribed to the
com.masnet.price_request.requested.v1type. Without a destination, the system reads the event from the events log withread:events. That event is routed and only the channel integration lists it. - The client authenticates as in the rest of the data API, with base
https://daas.masnet.com/api/v1/integrations. - The integration must be active: as a draft or paused it receives no requests even if it is the channel, and its token answers 403
access_denied. The steps in Masnet are in Configure in Masnet.
The event is signed like any Masnet webhook. Verify the signature before parsing the body: Node.js, Python, Java or C#.
Configure in Masnet
These steps are done in the Masnet application, at https://app.masnet.com/workspace/company?section=integrations (Company › Integrations), with the session of a person of the company. Integration administration only accepts a human session: no API key or integration token replaces it. An agent that controls the browser can do every step except those marked Person: there it must ask the person to complete the dialog and wait until it closes. No data domain needs to be authorized other than Events in query mode: the designation of the channel grants the Price requests domain.
| Step | Permission of the person | Second factor |
|---|---|---|
| Create the integration, activate it, test a destination and send the test request | workspace.integrations.manage | No |
| Create an API client | workspace.integrations.credentials | Yes (Person) |
| Authorize Events (query mode) | workspace.integrations.authorize and workspace.access.manage | Yes (Person) |
| Use as channel and change the window | workspace.integrations.authorize, workspace.access.manage and workspace.offers.pricing | Yes (Person) |
| Create a destination (webhook) | workspace.integrations.manage and workspace.integrations.credentials | Yes (Person) |
| Stop being the channel and complete the withdrawal | workspace.integrations.authorize and workspace.access.manage | Yes (Person) |
1. Create the integration
- Select New integration. In Basics enter the Name (unique in the company), choose the System and, in Environment, Production. Select Create and continue: the integration is a draft, and a draft receives no requests.
- Use the Test environment only to validate the system before using real data: a test integration cannot be the channel, but it receives the test request. A company allows up to 20 integrations.
- Select Continue later: the wizard closes without losing what was done and the next steps are done from the integration tabs.
2. API access
- In the API access tab select New client. In Client type choose OAuth with secret: it obtains short-lived tokens with
client_credentials, like the reference code. - In Scopes check
read:price_requests(Price requests) andwrite:price_requests(Price request responses). They are offered before the designation, with the note "Designating the price request channel grants the permission.". - Only in query mode, also check
read:events(Event log). That scope requires the Events domain: in Authorized data check Events and select Authorize data (Person: second factor). Events is the permission of the events API and has no event types of its own. It is not authorized for webhook delivery. - Select Create client (Person: second factor). Copy the Client identifier (
mkc_) and the Client secret (mks_, shown only once) toMASNET_CLIENT_IDandMASNET_CLIENT_SECRET. An integration allows up to 5 clients. - The system requests the token with
POST https://daas.masnet.com/api/v1/integrations/oauth/token,Authorization: Basicandgrant_type=client_credentials. It lasts 15 minutes. It answers 403access_deniedwhile the integration is not active (step 5).
3. Use as channel
- In Overview, Price requests card, the Tenders row shows No channel and "Offer · no company integration receives these requests today". The integration can still be a draft: the designation does not require it to be active.
- Without destinations, the Would receive the request at row says "No webhook: the system reads it from the event log". That is how it should be: the webhook, if you use one, is created in step 4.
- Select Use as channel (Person: second factor). Masnet grants the integration the Price requests domain for reading and writing.
- Result: the row shows Company channel and "Offer · since {date} by {name}, with second factor", Receives the request at says "No webhook: the system reads it from the event log", and Responds with says "API access · 1 API client · Price requests: read and write".
| Text in the card | Why it cannot be used as channel | What to do |
|---|---|---|
| "A test integration cannot be the channel." | The integration belongs to the Test environment. | Create a Production integration. |
| "A revoked integration cannot be the channel." | The integration is revoked. | Create another integration. |
| "To respond, the integration needs an API client with write:price_requests." | There is no active client with that scope. | Do step 2. |
| Another integration and "{name} is currently the company channel for {flow}. To use {system}, it must stop being the channel first." | Each flow allows a single channel per company. | Stop being the channel in the other integration. |
4. Webhook (only when receiving by webhook)
- In the Webhooks tab select New destination. Destination address (https): the public URL of the receiver, with
https, port 443 or 8443 and a public DNS name. - Format: Standard JSON. Authentication: Signature only is enough for the reference code, which verifies the Masnet signature. If your network requires another credential, choose it here and check it in the receiver.
- Event types: in the Price requests group check the request of the flow (
com.masnet.price_request.requested.v1). The group appears after step 3: before it, the domain is not granted and Masnet rejects the type with 400domain_not_granted. - Select Create destination (Person: second factor). The Destination created dialog shows the Signing secret (
whsec_) only once: copy it with Copy, store it asMASNET_SIGNING_SECRETin the receiver secret store and select I have saved it. If it is lost, use Rotate signing secret. - Select Test destination and Send test. The result shows the response code and the timings: the receiver must answer 2xx with the signature verified. After a successful test Activate destination appears and the destination becomes Active.
- Result: the destination is titled Price requests and, in Overview, Receives the request at says "Webhook · Price requests · Standard Webhooks signature". Masnet delivers the request to that destination while it is Active.
- Each flow allows a single destination per integration: a second destination subscribed to the same request is rejected with 409
PRICE_REQUEST_CHANNEL_TAKEN. To change the webhook, delete the current destination or, if it has other event types, remove the request from it, then subscribe the new one.
5. Activate the integration
- By webhook, once the destination is Active and its test succeeded, Setup (in Overview) enables Activate in the Activate the integration step. In query mode, without a destination, the Successful test step stays pending and that button is not enabled: use Actions › Activate, which is available in both modes.
- Activation requires at least one authorized domain and an active destination or an API client. Otherwise Masnet answers 422
activation_requirements. The Price requests domain of step 3 and the client of step 2 meet it. - From then on requests are created: a draft or paused integration receives no requests even if it is the channel, and its token answers 403.
6. Response window
- With a designated flow, Response window appears. Select Change, choose 1, 5, 15 or 30 minutes, or 1, 2, 4, 8, 12 or 24 hours, and select Save window (Person: second factor). The default is 30 minutes.
- The window belongs to the integration and applies to both flows. In Tenders,
respond_byalso ends no later than 15 minutes before the tender closing. When it ends, the request becomesexpired.
7. Send the test request
- In the Tenders row, Last test request offers Send test request when the flow is already the channel and the integration has a destination: the test is sent by webhook, so it is not offered in query mode. In a test integration it is offered whenever there is a destination.
- The Test price request dialog shows the destination and the content. Select Send test: the row changes to "Sent; waiting for the response from {system}". The system answers with its token, which requires the integration to be active (step 5).
- When the system answers, the row says "Valid response on the {n} lines" or "{n} lines with problems in the response", with the time and the person. The card checks every 5 seconds for 3 minutes.
- An answer rejected with 400 is not recorded: the row keeps waiting. Check the system log, where the reference code writes
codeandissues, fix it and send another test.
8. Stop being the channel
- Stop being the channel opens "Stop using {system} as the Tenders channel", which states how many open requests are cancelled and whether the Price requests domain is revoked. Confirm with Stop being the channel (Person: second factor). From then on no requests of the flow are created.
- If the cancellation did not finish, the card shows "{system} is no longer the channel, but its open requests are not cancelled yet and the domain is still granted." Select Complete the withdrawal a few seconds later.
- If the integration is no longer the channel of any flow, Masnet revokes the Price requests domain and removes the subscription to the requests from its destinations. A webhook that only had the request is left without event types: it is not deleted and raises no error, it receives no deliveries and its title becomes the host of its address. To use it again, use the integration as channel again choosing it in Webhook that receives the request (with a single destination, it is that one), which subscribes it again. Otherwise, delete it.
- If the integration is still the channel of the other flow, the domain stays and the webhook keeps the subscription, but Masnet does not deliver requests of a flow without a channel.
The event
data.object is a price-request.v1 object: the tender, the bid, the deadline and up to 200 lines. Each line carries its line_key, the buyer description and quantity, and the product and price the bid has today.
{
"specversion": "1.0",
"id": "evt_01JD3K8W5F2Q9X7M4N6P8R0T2V",
"type": "com.masnet.price_request.requested.v1",
"subject": "price_request/0b7d5c2e-6f1a-4c4e-9a37-1f8f3c2d9e10",
"dataschema": "https://masnet.com/developers/schemas/price_request/v1.json",
"data": {
"object": {
"contract_version": "price-request.v1",
"id": "0b7d5c2e-6f1a-4c4e-9a37-1f8f3c2d9e10",
"status": "requested",
"requested_at": "2026-11-17T14:02:11Z",
"respond_by": "2026-11-17T14:32:11Z",
"requested_by": {
"id": "5d1e9a3c-2b7f-4c6d-8e0a-1f2b3c4d5e6f"
},
"tender": {
"code": "1075963-358-LP26",
"purchase_channel": "LP",
"title": "Adquisición de medicamentos oncológicos",
"status": "published",
"buyer": {
"code": "7248",
"name": "Hospital Regional",
"rut": "61.608.000-0"
}
},
"bid": {
"id": "9f8e7d6c-5b4a-4321-8fed-cba987654321",
"name": "Oferta principal",
"kind": "principal",
"currency": "CLP"
},
"lines_total": 3,
"lines": [
{
"line_key": "a3f1c0de5b7e4f2a9c1d8e6b4a2f0c19",
"item_number": 1,
"tender_item_id": "8812345",
"buyer": {
"description": "Afatinib 40 mg comprimido",
"quantity": "120",
"unit": "Unidad"
},
"offer": {
"status": "offered",
"product": {
"catalog_item_id": "90211",
"internal_code": "AF-40",
"name": "Afatinib 40 mg x 30"
},
"unit_price": {
"value": "15400.00",
"currency": "CLP"
},
"price_requested": true
}
},
{
"line_key": "b9c2d4e6f8a0b2c4d6e8f0a2b4c6d8e0",
"item_number": 2,
"tender_item_id": "8812346",
"buyer": {
"description": "Ondansetrón 8 mg comprimido",
"quantity": "600",
"unit": "Unidad"
},
"offer": {
"status": "not_started",
"product": null,
"unit_price": null,
"price_requested": true
}
},
{
"line_key": "c004e1f2a3b4c5d6e7f8091a2b3c4d5e",
"item_number": 3,
"tender_item_id": "8812347",
"buyer": {
"description": "Filgrastim 300 mcg jeringa prellenada",
"quantity": "40",
"unit": "Unidad"
},
"offer": {
"status": "offered",
"product": {
"catalog_item_id": "90377",
"internal_code": "FG-300",
"name": "Filgrastim 300 mcg"
},
"unit_price": null,
"price_requested": true
}
}
],
"truncated": [],
"links": {
"self": "https://daas.masnet.com/api/v1/integrations/data/price-requests/0b7d5c2e-6f1a-4c4e-9a37-1f8f3c2d9e10",
"lines": "https://daas.masnet.com/api/v1/integrations/data/price-requests/0b7d5c2e-6f1a-4c4e-9a37-1f8f3c2d9e10/lines",
"response": "https://daas.masnet.com/api/v1/integrations/data/price-requests/0b7d5c2e-6f1a-4c4e-9a37-1f8f3c2d9e10/response"
}
},
"previous": null,
"changed_fields": [],
"actor": {
"type": "user"
},
"evidence": "masnet_record"
}
}line_keyidentifies the bid line and is the key the answer must return.offer.price_requestedtells whether the line asks for a price. A line without a product travels as context: the system may propose a product and a price.respond_byis the answer deadline. Delivery retries of the event also end at that time, not after the 72 hours of other events.webhook-idis kept across retries. Discard repeats with a 2xx. The same request is never emitted again.
Read every line
If the request has more than 200 lines, truncated includes lines and the event carries only the first ones. Read the full list in pages of up to 500 lines, ordered by item_number. next_cursor is opaque and is null on the last page.
GET /api/v1/integrations/data/price-requests/0b7d5c2e-6f1a-4c4e-9a37-1f8f3c2d9e10/lines?limit=500 HTTP/1.1
Host: daas.masnet.com
Authorization: Bearer <token con read:price_requests>
HTTP/1.1 200 OK
{ "lines": [ … ], "next_cursor": "500:a3f1c0de5b7e4f2a9c1d8e6b4a2f0c19" }GET …/price-requests/{id} returns the same object with its current status and, once applied, the summary and the results per line. A request of another integration or another company answers 404.
Answer
POST /api/v1/integrations/data/price-requests/0b7d5c2e-6f1a-4c4e-9a37-1f8f3c2d9e10/response HTTP/1.1
Host: daas.masnet.com
Authorization: Bearer <token con write:price_requests>
Content-Type: application/json
Idempotency-Key: COT-2026-00123-1
{
"contract_version": "price-response.v1",
"erp_reference": "COT-2026-00123",
"currency": "CLP",
"lines": [
{
"line_key": "a3f1c0de5b7e4f2a9c1d8e6b4a2f0c19",
"result": "priced",
"product": {
"internal_code": "AF-40"
},
"unit_price": "15100.00"
},
{
"line_key": "b9c2d4e6f8a0b2c4d6e8f0a2b4c6d8e0",
"result": "priced",
"product": {
"internal_code": "ON-08"
},
"unit_price": "820.00",
"note": "Precio con stock en Santiago"
},
{
"line_key": "c004e1f2a3b4c5d6e7f8091a2b3c4d5e",
"result": "unavailable",
"note": "Sin stock"
}
]
}resultispriced(withproductandunit_price) orunavailable(with an optionalnote). A system that cannot quote answers every lineunavailable. There is no other way to reject.productcarries exactly one of the keyscatalog_item_id,internal_codeorexternal_id.external_idis valid only if the channel integration has a catalog source. Every key must match a single active product of the company catalog.unit_priceis a positive decimal as text, with up to 14 integer digits and 4 decimals. Nothing is rounded.currencymust be the bid currency.noteis plain text of up to 500 characters. The answer admits up to 2000 lines, eachline_keyonce, and a body of 4 MiB at most.Idempotency-Keyis required: 1 to 255 visible ASCII characters. Use the same key when retrying the same answer.- The quantity is the buyer quantity and the answer does not change it. It does not reactivate a line marked "Do not bid" either.
Result per line
An accepted answer returns 200 with the summary and the result of each line:
{
"price_request_id": "0b7d5c2e-6f1a-4c4e-9a37-1f8f3c2d9e10",
"status": "applied",
"replayed": false,
"summary": {
"total": 3,
"by_result": {
"price_set": 1,
"product_added": 1,
"no_price": 1
}
},
"lines": [
{
"line_key": "a3f1c0de5b7e4f2a9c1d8e6b4a2f0c19",
"line_number": 1,
"result": "price_set"
},
{
"line_key": "b9c2d4e6f8a0b2c4d6e8f0a2b4c6d8e0",
"line_number": 2,
"result": "product_added"
},
{
"line_key": "c004e1f2a3b4c5d6e7f8091a2b3c4d5e",
"line_number": 3,
"result": "no_price"
}
],
"rejected_lines": []
}result | When | What changes in the bid |
|---|---|---|
price_set | Same product, new price | The price, marked as coming from the ERP |
product_added | Line without a product, and the system brings product and price | Product and price |
product_replaced | A product other than the one the line had | Product and price |
unchanged | Same product and same price | Nothing |
no_price | result: unavailable | Nothing. The bid shows the note |
not_returned | A requested line the answer does not include | Nothing |
invalid | A price that does not match the format, or a currency other than the bid currency | Nothing |
product_unknown | A key without an active product, or external_id without a catalog source | Nothing |
product_ambiguous | The key matches more than one active product | Nothing |
line_fixed | The field is fixed by an approval | Nothing |
line_changed | The line changed after the request was sent | Nothing. The bid shows the proposal |
line_not_offered | The line is marked "Do not bid" | Nothing. The bid shows the proposal |
rejected_unknown_line | The line_key is not part of the request | Nothing |
Deadline, retries and errors
| Response | When | What to do |
|---|---|---|
200 with replayed: true | A repeat of the same content already applied (header Idempotent-Replayed: true) | Nothing: it is the stored result, not applied again |
503 with Retry-After | The transaction did not finish and nothing was applied | Retry with the same Idempotency-Key and the same body |
| PRICE_RESPONSE_INVALID (400) | The body does not match price-response.v1. issues tells where | Fix the body |
| idempotency_key_required (400) | Idempotency-Key is missing or malformed | Send the header |
| insufficient_scope (403) | The token lacks write:price_requests (or read:price_requests when reading): the channel is not designated yet or the client does not have the scope | Use the integration as channel or add the scope to the client and request another token |
| not_found (404) | The request does not exist, belongs to another integration or is a framework agreement test | Verify the identifier and the credential |
| PRICE_REQUEST_NOT_AWAITING (409) | The request was cancelled or its delivery failed | Do not retry |
| PRICE_REQUEST_EXPIRED (409) | respond_by has passed | Do not retry. The person can request again |
| PRICE_RESPONSE_CONFLICT (409) | Another answer with different content was already applied | Do not retry: the first accepted answer wins |
| payload_too_large (413) | The body exceeds 4 MiB | Answer only the lines that are quoted |
| unsupported_media_type (415) | The body is not application/json | Send UTF-8 JSON |
{
"type": "https://masnet.com/developers/errors/PRICE_REQUEST_EXPIRED",
"title": "Plazo vencido",
"status": 409,
"detail": "Venció el plazo de respuesta de la solicitud (respond_by).",
"code": "PRICE_REQUEST_EXPIRED",
"correlation_id": "7c9e6679-7425-40de-944b-e07fc1f90ae7"
}Error responses use RFC 9457, like the rest of the API. The full catalog is in Errors. While the request is open, the requested lines stay locked in the bid. They are released when the request expires, is cancelled or is answered.
Test request
The destination test sends a request with fixed content and a test_… id of 32 hexadecimal digits. It does not come from a bid and locks no lines. The system reads it and answers it through the same routes.
- The answer returns 200 with
status: validatedandtest: true: the result of every line under the rules above, with the product keys looked up in the company catalog in read-only mode. Nothing is applied. - It can be answered for 30 minutes, plus 5 minutes of grace. After that it answers
PRICE_REQUEST_EXPIRED. - Masnet accepts it for production and test integrations, whether or not they are the channel, as long as they are active and have a destination. The Price requests card offers Send test request when the flow is already the channel and, in a test integration, always.
Reference code
Complete and minimal code, without dependencies: Node.js 18 or later and Python 3.10 or later. A test of this site runs it against a Masnet test double that only accepts the routes, headers and fields of the contract. The shared client serves both flows. The flow file reads all the lines, builds the answer and sends it. Signature verification is the function of Node.js (node-manual.mjs) or Python (python_manual.py), in the same folder.
| Part | What it does |
|---|---|
| Receiver | Verifies the signature over the received bytes, answers 204 at once, drops a repeated webhook-id and processes afterwards. An invalid signature gets 401, which Masnet treats as a final rejection. |
| Query mode | With MASNET_MODE=poll it reads GET https://daas.masnet.com/api/v1/integrations/data/events every 30 seconds with type, since and limit=200, walks every page with cursor and drops the id values already seen. |
| Token | Requests the token with client_credentials and renews it one minute before it expires, or once after a 401. |
| Reading | If truncated includes the lines, it reads them by pages with the maximum limit and next_cursor. |
| Answer | A single POST with Idempotency-Key {id}:1 and the same body on every retry. It waits out Retry-After on 429 and 503 until respond_by, does not retry a 409 and logs code and issues of a 400. |
| Quote | The quote function is an example with fixed prices: replace it with the ERP lookup. |
// Masnet price requests, shared client (contract 1.6.0). Node.js 18 or later, no dependencies.
// OAuth token, data API calls that wait out 429 and 503, the webhook receiver and the events log reader.
// `verify` is the function of the guide "Verify the Masnet signature in Node.js" (node-manual.mjs).
import { createServer } from 'node:http'
import { setTimeout as sleep } from 'node:timers/promises'
import { verify } from './node-manual.mjs'
export const API_BASE = 'https://daas.masnet.com/api/v1/integrations'
/** Retry-After in seconds or as an HTTP date, in milliseconds. Without the header, 5 seconds. */
function retryAfterMs(value) {
if (value && /^\d+$/.test(value)) return Number(value) * 1000
const at = value ? Date.parse(value) : NaN
return Number.isFinite(at) ? Math.max(0, at - Date.now()) : 5000
}
/** `id` and `secret` are the client identifier (mkc_) and the client secret (mks_) shown once in API access. */
export function createClient({ id, secret, apiBase = API_BASE }) {
let token = null
/** Access token of the API client (client_credentials), renewed one minute before it expires. */
async function accessToken() {
if (token && token.expiresAt - 60_000 > Date.now()) return token.value
const res = await fetch(`${apiBase}/oauth/token`, {
method: 'POST',
headers: {
authorization: `Basic ${Buffer.from(`${id}:${secret}`).toString('base64')}`,
'content-type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({ grant_type: 'client_credentials' }),
})
const body = await res.json().catch(() => null)
// 400 invalid_scope: no scope of the client has authorized data yet (before the channel is designated, for example).
// 403 access_denied: the integration is not active.
if (!res.ok) throw new Error(`token: ${res.status} ${body?.error}`)
token = { value: body.access_token, expiresAt: Date.now() + body.expires_in * 1000 }
return token.value
}
/** One data API call. Waits out 429 and 503 (Retry-After) until `deadline` and renews the token once after a 401. */
async function call(method, url, { body, idempotencyKey, deadline = Date.now() + 10 * 60_000 } = {}) {
const payload = body === undefined ? undefined : JSON.stringify(body)
let renewed = false
for (;;) {
const headers = { authorization: `Bearer ${await accessToken()}` }
if (payload !== undefined) headers['content-type'] = 'application/json'
if (idempotencyKey) headers['idempotency-key'] = idempotencyKey
const res = await fetch(url, { method, headers, body: payload })
const json = await res.json().catch(() => null)
if (res.status === 401 && !renewed) {
token = null
renewed = true
continue
}
if (res.status === 429 || res.status === 503) {
const wait = retryAfterMs(res.headers.get('retry-after'))
if (Date.now() + wait < deadline) {
await sleep(wait)
continue
}
}
return { status: res.status, body: json }
}
}
/** Query mode: the events of `type` admitted since `since`, every page, leaving out the ids already in `seen`. */
async function newEvents(type, since, seen) {
const events = []
let cursor = null
do {
const query = new URLSearchParams({ type, since: since.toISOString(), limit: '200' })
if (cursor) query.set('cursor', cursor)
const page = await call('GET', `${apiBase}/data/events?${query}`)
if (page.status !== 200) throw new Error(`events: ${page.status} ${page.body?.code}`)
for (const event of page.body.data) {
if (seen.has(event.id)) continue
seen.add(event.id)
events.push(event)
}
cursor = page.body.next_cursor
} while (cursor)
return events
}
return { accessToken, call, newEvents }
}
/**
* Webhook receiver. It verifies the signature over the raw bytes, answers 204 at once and hands each new event to `onEvent`
* after answering. `webhook-id` is the same on every retry, so a repeated one is acknowledged and dropped.
* A wrong signature gets 401, which Masnet takes as a final rejection. Serve it behind HTTPS on port 443 or 8443.
*/
export function createReceiver({ signingSecret, onEvent, seen = new Set() }) {
return createServer((req, res) => {
const chunks = []
req.on('data', (chunk) => chunks.push(chunk))
req.on('end', () => {
const rawBody = Buffer.concat(chunks)
if (req.method !== 'POST' || !verify({ secret: signingSecret, headers: req.headers, rawBody })) {
res.writeHead(401).end()
return
}
res.writeHead(204).end()
const id = req.headers['webhook-id']
if (seen.has(id)) return
seen.add(id)
setImmediate(() => {
Promise.resolve()
.then(() => onEvent(JSON.parse(rawBody.toString('utf8'))))
.catch((error) => console.error('price request not answered:', error.message))
})
})
})
}
/**
* Runs the channel with the environment variables MASNET_CLIENT_ID, MASNET_CLIENT_SECRET and, for webhooks, MASNET_SIGNING_SECRET
* and PORT. With MASNET_MODE=poll it reads the events log every 30 seconds instead (channel without webhook, scope read:events).
* Keep `seen` in a database in production, so a restart does not answer twice.
*/
export async function run({ type, handle }) {
const client = createClient({ id: process.env.MASNET_CLIENT_ID, secret: process.env.MASNET_CLIENT_SECRET })
const onEvent = (event) => handle(client, event)
if (process.env.MASNET_MODE !== 'poll') {
createReceiver({ signingSecret: process.env.MASNET_SIGNING_SECRET, onEvent }).listen(Number(process.env.PORT ?? 8080))
return
}
const seen = new Set()
let since = new Date(Date.now() - 24 * 3600_000)
for (;;) {
const started = Date.now()
try {
for (const event of await client.newEvents(type, since, seen)) await onEvent(event).catch((error) => console.error(error.message))
since = new Date(started - 120_000)
} catch (error) {
console.error(error.message)
}
await sleep(30_000)
}
}// Tender price requests (contract 1.3.0): read every line, quote with the ERP and answer once before respond_by.
// Webhook: MASNET_CLIENT_ID=mkc_... MASNET_CLIENT_SECRET=mks_... MASNET_SIGNING_SECRET=whsec_... PORT=8080 node price-requests.mjs
// Query mode (channel without webhook): MASNET_MODE=poll with the client identifier and secret only.
import { fileURLToPath } from 'node:url'
import { run } from './price-requests-client.mjs'
export const REQUESTED = 'com.masnet.price_request.requested.v1'
const TEST = 'com.masnet.integration.test.v1'
const OPEN = ['requested', 'delivered']
const LINES_PAGE_MAX = 500
/** Line results that applied nothing because of the answer itself. */
const PROBLEMS = ['invalid', 'product_unknown', 'product_ambiguous', 'not_returned', 'rejected_unknown_line']
/** The request inside a webhook or an events log entry. The test request arrives as integration.test with the same object. */
export function requestOf(event) {
if (event?.type !== REQUESTED && event?.type !== TEST) return null
const object = event.data?.object
return object?.contract_version === 'price-request.v1' ? object : null
}
/** Every line. The event carries up to 200 and `truncated` says when the rest must be read from `links.lines`. */
export async function allLines(client, request) {
if (!request.truncated.includes('lines')) return request.lines
const lines = []
let cursor = null
do {
const url = new URL(request.links.lines)
url.searchParams.set('limit', String(LINES_PAGE_MAX))
if (cursor) url.searchParams.set('cursor', cursor)
const page = await client.call('GET', url.href, { deadline: Date.parse(request.respond_by) })
if (page.status !== 200) throw new Error(`lines: ${page.status} ${page.body?.code}`)
lines.push(...page.body.lines)
cursor = page.body.next_cursor
} while (cursor)
return lines
}
/** price-response.v1 in the currency of the bid. A line that asks for a price and has no quote is answered unavailable. */
export function buildResponse(request, lines, quote) {
const out = []
for (const line of lines) {
const offer = quote(line, request)
if (offer) out.push({ line_key: line.line_key, result: 'priced', product: { internal_code: offer.internal_code }, unit_price: offer.unit_price })
else if (line.offer.price_requested) out.push({ line_key: line.line_key, result: 'unavailable' })
}
return { contract_version: 'price-response.v1', currency: request.bid.currency, lines: out }
}
/** Answers one request. Returns the 200 body (applied, or validated for a test), or null when it no longer takes an answer. */
export async function answer(client, request, quote) {
const deadline = Date.parse(request.respond_by)
if (!OPEN.includes(request.status) || deadline <= Date.now()) return null
const body = buildResponse(request, await allLines(client, request), quote)
// The same key and the same body on every retry: a repeat returns the stored result with replayed: true.
const result = await client.call('POST', request.links.response, { body, idempotencyKey: `${request.id}:1`, deadline })
if (result.status === 200) {
const problems = result.body.lines.filter((line) => PROBLEMS.includes(line.result))
if (problems.length > 0) console.warn('lines with problems:', problems)
return result.body
}
if (result.status === 400) throw new Error(`answer rejected: ${result.body?.code} ${JSON.stringify(result.body?.issues ?? [])}`)
if (result.status === 409) {
// PRICE_REQUEST_EXPIRED, PRICE_REQUEST_NOT_AWAITING or PRICE_RESPONSE_CONFLICT: do not retry.
console.warn(`not answered: ${result.body?.code}`)
return null
}
throw new Error(`answer: ${result.status} ${result.body?.code}`)
}
// Example quote: replace the map with the ERP lookup. Prices are decimal text, never rounded by Masnet.
const ERP_PRICES = new Map([['AF-40', '15100.00'], ['FG-300', '98000.00']])
export function quote(line) {
const code = line.offer.product?.internal_code
const price = code ? ERP_PRICES.get(code) : undefined
return price ? { internal_code: code, unit_price: price } : null
}
export async function handle(client, event) {
const request = requestOf(event)
if (request) console.log(request.id, await answer(client, request, quote))
}
if (process.argv[1] === fileURLToPath(import.meta.url)) await run({ type: REQUESTED, handle })"""Masnet price requests, shared client (contract 1.6.0). Python 3.10 or later, standard library only.
OAuth token, data API calls that wait out 429 and 503, the webhook receiver and the events log reader.
`verify` is the function of the guide "Verify the Masnet signature in Python" (python_manual.py).
"""
import base64
import json
import os
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timedelta, timezone
from email.utils import parsedate_to_datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from python_manual import verify
API_BASE = "https://daas.masnet.com/api/v1/integrations"
def _retry_after(value):
"""Retry-After in seconds or as an HTTP date. Without the header, 5 seconds."""
if value and value.isdigit():
return int(value)
try:
return max(0.0, parsedate_to_datetime(value).timestamp() - time.time())
except (TypeError, ValueError):
return 5.0
def _send(method, url, headers, data=None):
request = urllib.request.Request(url, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(request, timeout=30) as response:
status, response_headers, raw = response.status, response.headers, response.read()
except urllib.error.HTTPError as error:
status, response_headers, raw = error.code, error.headers, error.read()
try:
return status, response_headers, json.loads(raw) if raw else None
except ValueError:
return status, response_headers, None
class Client:
"""`client_id` and `secret` are the client identifier (mkc_) and the client secret (mks_) shown once in API access."""
def __init__(self, client_id, secret, api_base=API_BASE):
self.api_base = api_base
self._basic = base64.b64encode(f"{client_id}:{secret}".encode()).decode()
self._token = None
self._expires_at = 0.0
self._lock = threading.Lock()
def access_token(self):
"""Access token of the API client (client_credentials), renewed one minute before it expires."""
with self._lock:
if self._token and self._expires_at - 60 > time.time():
return self._token
headers = {"Authorization": f"Basic {self._basic}", "Content-Type": "application/x-www-form-urlencoded"}
form = urllib.parse.urlencode({"grant_type": "client_credentials"}).encode()
status, _, body = _send("POST", f"{self.api_base}/oauth/token", headers, form)
# 400 invalid_scope: no scope of the client has authorized data yet (before the channel is designated, for example).
# 403 access_denied: the integration is not active.
if status != 200:
raise RuntimeError(f"token: {status} {(body or {}).get('error')}")
self._token, self._expires_at = body["access_token"], time.time() + body["expires_in"]
return self._token
def call(self, method, url, body=None, idempotency_key=None, deadline=None):
"""One data API call. Waits out 429 and 503 (Retry-After) until `deadline` and renews the token once after a 401."""
deadline = deadline or time.time() + 600
data = None if body is None else json.dumps(body).encode()
renewed = False
while True:
headers = {"Authorization": f"Bearer {self.access_token()}"}
if data is not None:
headers["Content-Type"] = "application/json"
if idempotency_key:
headers["Idempotency-Key"] = idempotency_key
status, response_headers, payload = _send(method, url, headers, data)
if status == 401 and not renewed:
self._token, renewed = None, True
continue
if status in (429, 503):
wait = _retry_after(response_headers.get("Retry-After"))
if time.time() + wait < deadline:
time.sleep(wait)
continue
return status, payload
def new_events(self, event_type, since, seen):
"""Query mode: the events of `event_type` admitted since `since`, every page, leaving out the ids already in `seen`."""
events, cursor = [], None
while True:
query = {"type": event_type, "since": since.isoformat().replace("+00:00", "Z"), "limit": "200"}
if cursor:
query["cursor"] = cursor
status, page = self.call("GET", f"{self.api_base}/data/events?{urllib.parse.urlencode(query)}")
if status != 200:
raise RuntimeError(f"events: {status} {(page or {}).get('code')}")
for event in page["data"]:
if event["id"] not in seen:
seen.add(event["id"])
events.append(event)
cursor = page["next_cursor"]
if not cursor:
return events
def _safely(on_event, event):
try:
on_event(event)
except Exception as error: # noqa: BLE001
print("price request not answered:", error)
def receiver(port, signing_secret, on_event, seen=None):
"""Webhook receiver. It verifies the signature over the raw bytes, answers 204 at once and hands each new event to
`on_event` in a thread. `webhook-id` is the same on every retry, so a repeated one is acknowledged and dropped. A wrong
signature gets 401, which Masnet takes as a final rejection. Serve it behind HTTPS on port 443 or 8443."""
seen = set() if seen is None else seen
lock = threading.Lock()
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
raw = self.rfile.read(int(self.headers.get("Content-Length") or 0))
if not verify(signing_secret, self.headers, raw):
self.send_response(401)
self.end_headers()
return
self.send_response(204)
self.end_headers()
with lock:
event_id = self.headers.get("webhook-id")
if event_id in seen:
return
seen.add(event_id)
threading.Thread(target=_safely, args=(on_event, json.loads(raw)), daemon=True).start()
def log_message(self, *args):
pass
return ThreadingHTTPServer(("", port), Handler)
def run(event_type, handle):
"""Runs the channel with MASNET_CLIENT_ID, MASNET_CLIENT_SECRET and, for webhooks, MASNET_SIGNING_SECRET and PORT. With
MASNET_MODE=poll it reads the events log every 30 seconds instead (channel without webhook, scope read:events). Keep `seen`
in a database in production, so a restart does not answer twice."""
client = Client(os.environ["MASNET_CLIENT_ID"], os.environ["MASNET_CLIENT_SECRET"])
if os.environ.get("MASNET_MODE") != "poll":
receiver(int(os.environ.get("PORT", "8080")), os.environ["MASNET_SIGNING_SECRET"], lambda event: handle(client, event)).serve_forever()
return
seen, since = set(), datetime.now(timezone.utc) - timedelta(days=1)
while True:
started = datetime.now(timezone.utc)
try:
for event in client.new_events(event_type, since, seen):
_safely(lambda item: handle(client, item), event)
since = started - timedelta(minutes=2)
except Exception as error: # noqa: BLE001
print(error)
time.sleep(30)"""Tender price requests (contract 1.3.0): read every line, quote with the ERP and answer once before respond_by.
Webhook: MASNET_CLIENT_ID=mkc_... MASNET_CLIENT_SECRET=mks_... MASNET_SIGNING_SECRET=whsec_... PORT=8080 python3 price_requests.py
Query mode (channel without webhook): MASNET_MODE=poll with the client identifier and secret only.
"""
import time
import urllib.parse
from datetime import datetime
from price_requests_client import run
REQUESTED = "com.masnet.price_request.requested.v1"
TEST = "com.masnet.integration.test.v1"
OPEN = ("requested", "delivered")
LINES_PAGE_MAX = 500
# Line results that applied nothing because of the answer itself.
PROBLEMS = ("invalid", "product_unknown", "product_ambiguous", "not_returned", "rejected_unknown_line")
def _deadline(request):
return datetime.fromisoformat(request["respond_by"].replace("Z", "+00:00")).timestamp()
def request_of(event):
"""The request inside a webhook or an events log entry. The test request arrives as integration.test with the same object."""
if not isinstance(event, dict) or event.get("type") not in (REQUESTED, TEST):
return None
obj = (event.get("data") or {}).get("object") or {}
return obj if obj.get("contract_version") == "price-request.v1" else None
def all_lines(client, request):
"""Every line. The event carries up to 200 and `truncated` says when the rest must be read from `links.lines`."""
if "lines" not in request["truncated"]:
return request["lines"]
lines, cursor = [], None
while True:
query = {"limit": str(LINES_PAGE_MAX)}
if cursor:
query["cursor"] = cursor
status, page = client.call("GET", f"{request['links']['lines']}?{urllib.parse.urlencode(query)}", deadline=_deadline(request))
if status != 200:
raise RuntimeError(f"lines: {status} {(page or {}).get('code')}")
lines.extend(page["lines"])
cursor = page["next_cursor"]
if not cursor:
return lines
def build_response(request, lines, quote):
"""price-response.v1 in the currency of the bid. A line that asks for a price and has no quote is answered unavailable."""
out = []
for line in lines:
offer = quote(line, request)
if offer:
out.append({"line_key": line["line_key"], "result": "priced", "product": {"internal_code": offer["internal_code"]}, "unit_price": offer["unit_price"]})
elif line["offer"]["price_requested"]:
out.append({"line_key": line["line_key"], "result": "unavailable"})
return {"contract_version": "price-response.v1", "currency": request["bid"]["currency"], "lines": out}
def answer(client, request, quote):
"""Answers one request. Returns the 200 body (applied, or validated for a test), or None when it no longer takes an answer."""
deadline = _deadline(request)
if request["status"] not in OPEN or deadline <= time.time():
return None
body = build_response(request, all_lines(client, request), quote)
# The same key and the same body on every retry: a repeat returns the stored result with replayed: true.
status, result = client.call("POST", request["links"]["response"], body=body, idempotency_key=f"{request['id']}:1", deadline=deadline)
if status == 200:
problems = [line for line in result["lines"] if line["result"] in PROBLEMS]
if problems:
print("lines with problems:", problems)
return result
if status == 400:
raise RuntimeError(f"answer rejected: {(result or {}).get('code')} {(result or {}).get('issues', [])}")
if status == 409:
# PRICE_REQUEST_EXPIRED, PRICE_REQUEST_NOT_AWAITING or PRICE_RESPONSE_CONFLICT: do not retry.
print("not answered:", (result or {}).get("code"))
return None
raise RuntimeError(f"answer: {status} {(result or {}).get('code')}")
# Example quote: replace the map with the ERP lookup. Prices are decimal text, never rounded by Masnet.
ERP_PRICES = {"AF-40": "15100.00", "FG-300": "98000.00"}
def quote(line, request):
code = ((line["offer"].get("product") or {}).get("internal_code"))
price = ERP_PRICES.get(code) if code else None
return {"internal_code": code, "unit_price": price} if price else None
def handle(client, event):
request = request_of(event)
if request:
print(request["id"], answer(client, request, quote))
if __name__ == "__main__":
run(REQUESTED, handle)- Webhook:
MASNET_CLIENT_ID,MASNET_CLIENT_SECRET,MASNET_SIGNING_SECRETandPORT, thennode price-requests.mjsorpython3 price_requests.py. Publish the port behind HTTPS on 443 or 8443, with the URL of step 4. - Query mode:
MASNET_MODE=pollwith the client identifier and secret. It opens no port. - In production keep the processed
webhook-idvalues and eventidvalues in a database: in memory, a restart forgets them. The sameIdempotency-Keyprevents a second different answer, but not the repeated work.
Schemas
- price-request.v1: the request object, in the event and in the read.
- price-response.v1: the answer body and the applied result (
$defs/applied). - The event
dataschemais price_request, which describesdata. Both schemas are byte for byte copies of the ones Masnet validates.