Flow
- Masnet delivers the
com.masnet.framework_agreement_price_request.requested.v1event to the destination of the framework agreement channel. If the channel has no destination (query mode), the event stays in the events log and the system reads it from there. - The system answers the webhook with a 2xx and processes the request asynchronously.
- If
truncatedincludesrows, it reads every row withGET /data/framework-agreement-price-requests/{id}/rows. - It computes its prices and sends a single answer with
POST /data/framework-agreement-price-requests/{id}/responsebeforerespond_by. - Masnet validates the shape of the answer, stores it and responds
200withstatus: received. It creates no offers and changes neither the catalog nor the batch. - A person at the company reviews the answer in Masnet with the same observations as an uploaded spreadsheet and decides which offers to add to the batch in preparation. The batch is rehearsed and sent to the Mercado Público store from Masnet, at that person's decision.
Requirements
- A production integration of the company designated as the framework agreement channel. There is one per company, independent of the tender channel: it can be the same integration or another one. 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 same one as tender price requests: the API client usesread:price_requeststo read andwrite:price_requeststo answer. The grant is revoked when the integration is no longer the channel of either flow. - Each request is read and answered only by the clients of the integration it was sent to. For another integration, another company or an identifier that does not exist, the routes of this guide respond
404. - The channel destination is subscribed to the
com.masnet.framework_agreement_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 Framework Agreements row shows No channel and "Catalog and offers · 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 "Catalog and offers · 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.framework_agreement_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 Framework Agreements,
respond_byis the request time plus the window. When it ends, the request becomesexpired.
7. Send the test request
- In the Framework Agreements 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 Framework Agreement 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} rows" 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 Framework Agreements 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 framework-agreement-price-request.v1 object: the framework agreement, the currency, today's date in Chile, the deadline, the totals and up to 200 rows. subject is framework_agreement_price_request/{id}.
{
"specversion": "1.0",
"id": "evt_01JDQ4M7Z2H8K5N3P6R9T1V4X7",
"type": "com.masnet.framework_agreement_price_request.requested.v1",
"subject": "framework_agreement_price_request/9f2c1b4a-8c3d-4e7a-b012-71c9e4a1f021",
"dataschema": "https://masnet.com/developers/schemas/framework_agreement_price_request/v1.json",
"data": {
"object": {
"contract_version": "framework-agreement-price-request.v1",
"id": "9f2c1b4a-8c3d-4e7a-b012-71c9e4a1f021",
"status": "requested",
"requested_at": "2026-11-27T15:00:00Z",
"respond_by": "2026-11-27T15:30:00Z",
"requested_by": {
"id": "5d1e9a3c-2b7f-4c6d-8e0a-1f2b3c4d5e6f"
},
"convenio": {
"id": "5802377",
"code": "2239-16-LR24",
"name": "Convenio Marco Artículos de Escritorio",
"store": "escritorio3"
},
"currency": "CLP",
"today_cl": "2026-11-27",
"products_total": 2,
"rows_total": 3,
"rows": [
{
"sku": "1450921",
"name": "Resma papel carta 75 g, 500 hojas",
"region": "RM",
"region_name": "Metropolitana de Santiago",
"base_price": 4990,
"current_offer": null,
"min_start_date": "2026-11-28",
"days_range": {
"min": 1,
"max": 90
},
"read_at": "2026-11-27T13:12:00Z"
},
{
"sku": "1450921",
"name": "Resma papel carta 75 g, 500 hojas",
"region": "V",
"region_name": "Valparaíso",
"base_price": 5190,
"current_offer": {
"state": "scheduled",
"special_price": 4700,
"start_date": "2026-12-01",
"days": 15,
"end_date": "2026-12-15"
},
"min_start_date": "2026-11-28",
"days_range": {
"min": 1,
"max": 90
},
"read_at": "2026-11-27T13:12:00Z"
},
{
"sku": "1451230",
"name": "Archivador lomo ancho",
"region": null,
"region_name": null,
"base_price": 2490,
"current_offer": null,
"min_start_date": null,
"days_range": null,
"read_at": "2026-11-27T13:12:00Z"
}
],
"truncated": [],
"links": {
"self": "https://daas.masnet.com/api/v1/integrations/data/framework-agreement-price-requests/9f2c1b4a-8c3d-4e7a-b012-71c9e4a1f021",
"rows": "https://daas.masnet.com/api/v1/integrations/data/framework-agreement-price-requests/9f2c1b4a-8c3d-4e7a-b012-71c9e4a1f021/rows",
"response": "https://daas.masnet.com/api/v1/integrations/data/framework-agreement-price-requests/9f2c1b4a-8c3d-4e7a-b012-71c9e4a1f021/response"
}
},
"previous": null,
"changed_fields": [],
"actor": {
"type": "user"
},
"evidence": "masnet_record"
}
}| Row field | Content |
|---|---|
sku | Product code of the store: the "ID producto" column of the spreadsheet and the key of the answer. |
name | Product name in the store. |
region and region_name | Code and name of the region. null for a national product, which is not offered per region. |
base_price | Base price of the store in the region, or null if the store does not report it. |
current_offer | Active (active) or scheduled (scheduled) offer in the region, with its price, start, days and end, or null. |
min_start_date | Minimum start date the store accepts, or null if it does not report it. |
days_range | Range of days the store accepts, or null if it does not report it. The review then applies 1 to 365 days. |
read_at | Time when Masnet read the row in the store: it tells how recent the base price is. |
products_totalcounts the products of the request androws_totalits rows, one per product and region.convenio.code,convenio.nameandconvenio.storearenullif Masnet has not read them from the store yet.respond_byis the answer deadline. Delivery retries of the event also end at that time.webhook-idis kept across retries. Discard repeated ones with a 2xx. The same request is not emitted again.requested_bycarries only the opaque identifier of the person who asked, without name or email.
Read every row
The event carries up to 200 rows. If the request has more, or if the body does not fit in the maximum size of a webhook, truncated includes rows and rows may be incomplete or empty. Then read the full list by pages: 1,000 rows by default and at most 5,000 (limit), in product code and region order. next_cursor is opaque and is null on the last page.
GET /api/v1/integrations/data/framework-agreement-price-requests/9f2c1b4a-8c3d-4e7a-b012-71c9e4a1f021/rows?limit=2 HTTP/1.1
Host: daas.masnet.com
Authorization: Bearer <token con read:price_requests>
HTTP/1.1 200 OK
Content-Type: application/json
{
"rows": [
{
"sku": "1450921",
"name": "Resma papel carta 75 g, 500 hojas",
"region": "RM",
"region_name": "Metropolitana de Santiago",
"base_price": 4990,
"current_offer": null,
"min_start_date": "2026-11-28",
"days_range": {
"min": 1,
"max": 90
},
"read_at": "2026-11-27T13:12:00Z"
},
{
"sku": "1450921",
"name": "Resma papel carta 75 g, 500 hojas",
"region": "V",
"region_name": "Valparaíso",
"base_price": 5190,
"current_offer": {
"state": "scheduled",
"special_price": 4700,
"start_date": "2026-12-01",
"days": 15,
"end_date": "2026-12-15"
},
"min_start_date": "2026-11-28",
"days_range": {
"min": 1,
"max": 90
},
"read_at": "2026-11-27T13:12:00Z"
}
],
"next_cursor": "eyJza3UiOiIxNDUwOTIxIiwicmVnaW9uIjoiViJ9"
}GET /data/framework-agreement-price-requests/{id} returns the same object with its current status and, once answered, responded_at and rows_received. It also serves to reconcile a request whose event was not processed.
status | Meaning | Accepts an answer |
|---|---|---|
requested | Created. Delivery to the destination is in progress, or the channel has no destination. | Yes, until respond_by |
delivered | The channel destination answered the webhook with a 2xx. | Yes, until respond_by |
received | Masnet stored an answer. Repeating that same content returns its stored result. | No |
delivery_failed | Delivery failed permanently or expired without a 2xx. | No |
cancelled | A person cancelled it, or the company withdrew the framework agreement channel. | No |
expired | respond_by passed without an answer. | No |
In query mode, without a destination, the request goes from requested to received or expired, without delivered.
Answer
The answer is a framework-agreement-price-response.v1 object with the columns of the offer spreadsheet import, one row per product and region the system wants to offer:
| Field | Spreadsheet column | Shape rule |
|---|---|---|
sku | ID producto | Text of 1 to 12 digits. Required. |
price | Precio oferta | Positive integer in Chilean pesos, of up to 12 digits. Required. |
start_date | Fecha desde | Date YYYY-MM-DD. Required. |
days | Días | Integer from 1 to 365. Required. |
region | Región | Region code (I to XVI and RM), TODAS for every region of the product, or absent for a national product. |
POST /api/v1/integrations/data/framework-agreement-price-requests/9f2c1b4a-8c3d-4e7a-b012-71c9e4a1f021/response HTTP/1.1
Host: daas.masnet.com
Authorization: Bearer <token con write:price_requests>
Content-Type: application/json
Idempotency-Key: CM-5802377-2026-11-27-1
{
"contract_version": "framework-agreement-price-response.v1",
"rows": [
{
"sku": "1450921",
"region": "RM",
"price": 4390,
"start_date": "2026-11-28",
"days": 20
},
{
"sku": "1450921",
"region": "V",
"price": 4567,
"start_date": "2026-11-28",
"days": 15
},
{
"sku": "1450998",
"region": "TODAS",
"price": 12990,
"start_date": "2026-11-28",
"days": 15
},
{
"sku": "1451230",
"price": 2290,
"start_date": "2026-12-01",
"days": 30
}
]
}- A product the system does not want to offer is simply left out of
rows. There are no fields for notes, discounts or references: the schema accepts no additional fields. - The answer accepts up to 50,000 rows and a body of at most 4 MiB. The byte limit is usually reached first. The body goes as
Content-Type: application/json. Idempotency-Keyis required: 1 to 255 visible ASCII characters. Use the same key and the same body when retrying.- Masnet accepts a single answer per request: the first one wins. To correct prices later, a person at the company asks for the prices again and the system answers the new request.
The accepted answer returns 200 with the count of rows received:
{
"price_request_id": "9f2c1b4a-8c3d-4e7a-b012-71c9e4a1f021",
"status": "received",
"rows_received": 4,
"replayed": false
}What Masnet validates and what a person reviews
| Stage | What is checked |
|---|---|
On receipt (POST) | Only the shape: the strict schema, the types, the formats and the row and byte limits. An answer that meets them is stored. |
| In the review, in Masnet | The business rules, the same as for an uploaded spreadsheet: product outside the framework agreement, region the product does not have, price above the base price, date before the store minimum, days out of range, active or scheduled offers, repeated rows and high discounts. |
| In the batch | The person adds the offers they approve to the batch in preparation. A product already in the batch is replaced entirely by the one in the answer. The batch is rehearsed and sent to the store from Masnet. |
- A row with a product outside the framework agreement, a price above the base or a date out of range produces no HTTP error: it is accepted and appears with its observation in the review. If the review finds rows with errors, the person can ask whoever runs the system to correct them and request the prices again.
- To avoid observations in the review, use the data of the request:
min_start_dateas the minimum date,days_rangeas the range of days,base_priceas the price ceiling andcurrent_offerto avoid clashing with an active or scheduled offer.
Deadline, retries and errors
| Response | When | What to do |
|---|---|---|
200 with replayed: true | Repetition of the same content already stored (Idempotent-Replayed: true header), even after respond_by | Nothing: it is the stored result |
503 with Retry-After | Masnet did not finish storing and nothing was stored | Retry with the same Idempotency-Key and the same body |
| PRICE_RESPONSE_INVALID (400) | The body does not meet framework-agreement-price-response.v1. issues gives the path and rule of each problem, without values | Fix the body |
| idempotency_key_required (400) | Idempotency-Key is missing or does not meet its format | 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 tender 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 ask again |
| PRICE_RESPONSE_CONFLICT (409) | Another answer with different content was already stored | Do not retry: the first one accepted wins |
| payload_too_large (413) | The body exceeds 4 MiB | Answer only the rows that are offered or ask for a request with fewer products |
| unsupported_media_type (415) | The body is not application/json | Send UTF-8 JSON |
{
"type": "https://masnet.com/developers/errors/PRICE_RESPONSE_INVALID",
"title": "Respuesta no válida",
"status": 400,
"detail": "La respuesta no cumple framework-agreement-price-response.v1.",
"code": "PRICE_RESPONSE_INVALID",
"correlation_id": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"issues": [
{
"path": "/rows/2/days",
"keyword": "maximum"
}
]
}Error responses use RFC 9457, like the rest of the API. The full catalog is in Errors. Reads count against the client read quota and the answer also against the write quota (quotas).
Test request
The test of the framework agreement channel destination sends the com.masnet.integration.test.v1 test event with a fixed-content framework agreement request, with an id of test_ followed by 32 hexadecimal digits, test: true and the links of these same routes. It carries three rows: one product in two regions, one of them with a scheduled offer, and one national product. It does not come from a framework agreement of the company.
- The system reads and answers it through the same routes. The answer is validated against the same schema and returns 200 with
status: validated,test: trueandrows_received. Nothing is stored in Masnet or reaches a review. - It can be answered for 30 minutes, plus 5 of grace. After that it responds
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. A tender test read through these routes, or the other way around, responds
404.
{
"price_request_id": "test_4b1f0c2e9d8a47b6a3c5e1f20d9b8a76",
"status": "validated",
"rows_received": 3,
"replayed": false,
"test": true
}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 rows, 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 rows, 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)
}
}// Framework agreement price requests (contract 1.6.0): read every row, 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 framework-agreement-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.framework_agreement_price_request.requested.v1'
const TEST = 'com.masnet.integration.test.v1'
const OPEN = ['requested', 'delivered']
const ROWS_PAGE_MAX = 5000
/** 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 === 'framework-agreement-price-request.v1' ? object : null
}
/** Every row. The event carries up to 200 and `truncated` says when the rest must be read from `links.rows`. */
export async function allRows(client, request) {
if (!request.truncated.includes('rows')) return request.rows
const rows = []
let cursor = null
do {
const url = new URL(request.links.rows)
url.searchParams.set('limit', String(ROWS_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(`rows: ${page.status} ${page.body?.code}`)
rows.push(...page.body.rows)
cursor = page.body.next_cursor
} while (cursor)
return rows
}
/** framework-agreement-price-response.v1: one row per product and region to offer. A row without a quote is left out. */
export function buildResponse(request, rows, quote) {
const out = []
for (const row of rows) {
const offer = quote(row, request)
if (!offer) continue
out.push({ sku: row.sku, ...(row.region ? { region: row.region } : {}), price: offer.price, start_date: offer.start_date, days: offer.days })
}
return { contract_version: 'framework-agreement-price-response.v1', rows: out }
}
/** Answers one request. Returns the 200 body (received, 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 allRows(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) 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. It stays inside the rules of the Masnet review.
const ERP_PRICES = new Map([['1450921', 4390], ['1451230', 2290]])
export function quote(row, request) {
const price = ERP_PRICES.get(row.sku)
if (!price || (row.base_price !== null && price > row.base_price)) return null
const days = Math.min(Math.max(30, row.days_range?.min ?? 1), row.days_range?.max ?? 365)
return { price, start_date: row.min_start_date ?? request.today_cl, days }
}
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)"""Framework agreement price requests (contract 1.6.0): read every row, 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 framework_agreement_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.framework_agreement_price_request.requested.v1"
TEST = "com.masnet.integration.test.v1"
OPEN = ("requested", "delivered")
ROWS_PAGE_MAX = 5000
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") == "framework-agreement-price-request.v1" else None
def all_rows(client, request):
"""Every row. The event carries up to 200 and `truncated` says when the rest must be read from `links.rows`."""
if "rows" not in request["truncated"]:
return request["rows"]
rows, cursor = [], None
while True:
query = {"limit": str(ROWS_PAGE_MAX)}
if cursor:
query["cursor"] = cursor
status, page = client.call("GET", f"{request['links']['rows']}?{urllib.parse.urlencode(query)}", deadline=_deadline(request))
if status != 200:
raise RuntimeError(f"rows: {status} {(page or {}).get('code')}")
rows.extend(page["rows"])
cursor = page["next_cursor"]
if not cursor:
return rows
def build_response(request, rows, quote):
"""framework-agreement-price-response.v1: one row per product and region to offer. A row without a quote is left out."""
out = []
for row in rows:
offer = quote(row, request)
if not offer:
continue
item = {"sku": row["sku"]}
if row.get("region"):
item["region"] = row["region"]
item.update(price=offer["price"], start_date=offer["start_date"], days=offer["days"])
out.append(item)
return {"contract_version": "framework-agreement-price-response.v1", "rows": out}
def answer(client, request, quote):
"""Answers one request. Returns the 200 body (received, 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_rows(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:
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. It stays inside the rules of the Masnet review.
ERP_PRICES = {"1450921": 4390, "1451230": 2290}
def quote(row, request):
price = ERP_PRICES.get(row["sku"])
if not price or (row["base_price"] is not None and price > row["base_price"]):
return None
days_range = row.get("days_range") or {}
minimum = days_range.get("min") if days_range.get("min") is not None else 1
maximum = days_range.get("max") if days_range.get("max") is not None else 365
return {"price": price, "start_date": row.get("min_start_date") or request["today_cl"], "days": min(max(30, minimum), maximum)}
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 framework-agreement-price-requests.mjsorpython3 framework_agreement_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
- framework-agreement-price-request.v1: the request object, in the event and in the read.
- framework-agreement-price-response.v1: the answer body and the 200 result (
$defs/received). - The event
dataschemais framework_agreement_price_request, which describesdata. Both schemas are byte-for-byte copies of the ones Masnet validates.