// Backend only; Node.js 20+. Never bundle this module into browser JavaScript. // Save your merchant order, key and exact request JSON in YOUR database BEFORE purchase(). const base = process.env.SAVDOLAR_API_URL || 'https://apishop.nexa.uz'; const token = process.env.SAVDOLAR_API_TOKEN; export async function request(path, { method = 'GET', body, key } = {}) { if (!token) throw new Error('Set SAVDOLAR_API_TOKEN on the server'); const response = await fetch(base + '/v1' + path, { method, signal: AbortSignal.timeout(20000), headers: { Authorization: `Bearer ${token}`, ...(body ? { 'Content-Type': 'application/json' } : {}), ...(key ? { 'Idempotency-Key': key } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}) }); let result; try { result = await response.json(); } catch { throw new Error(`API response uncertain (${response.status}); recover the ORIGINAL order key`); } if (!response.ok || !result.ok) { const e = new Error(result.error?.description || 'API unavailable'); e.code = result.error?.code; e.status = response.status; e.requestId = result.request_id; e.retryAfter = response.headers.get('Retry-After'); throw e; // Do not log token, request headers, or delivery data. } return result; } export const products = service => request('/products?service_id=' + encodeURIComponent(service)); export const quote = productId => request('/quotes', {method:'POST', body:{product_id:productId,quantity:1}}); export const purchase = (storedBody, storedKey) => request('/orders', {method:'POST',body:storedBody,key:storedKey}); export const lookup = storedKey => request('/orders/lookup?idempotency_key=' + encodeURIComponent(storedKey)); export const order = id => request('/orders/' + encodeURIComponent(id)); export const delivery = id => request('/orders/' + encodeURIComponent(id) + '/delivery'); // After an uncertain purchase: lookup(storedKey), then if necessary purchase(theExactStoredBody,storedKey). // Poll order(id) at 5-second intervals. Only completed allows delivery(id). // Authorize YOUR customer before returning their own order or delivery from your backend.