#!/usr/bin/env bash
# Show what delivery costs to one town, then quote an order without placing it.
# Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).
set -euo pipefail
export LC_NUMERIC=C # printf reads and writes amounts with a decimal point
# api METHOD PATH [JSON]: sets $body, or prints the status and error code and stops.
api() {
local response status retry_after
response=$(curl --silent --show-error --max-time 30 --request "$1" \
--header @<(printf 'Authorization: Bearer %s\n' "$MART_API_KEY") --header 'Content-Type: application/json' \
${3:+--data "$3"} --write-out '\n%{http_code} %header{retry-after}' "$MART_API_BASE$2") || { echo "error: no answer" >&2; exit 1; }
read -r status retry_after <<<"${response##*$'\n'}"
body=${response%$'\n'*}
if [ "$status" -ge 300 ]; then
echo "error: $status $(jq -r '.error.code' <<<"$body" 2>/dev/null || echo '(not JSON)')${retry_after:+, try again after $retry_after s}" >&2
exit 1
fi
}
# 1. The town's fee brackets: a products total of at least "from" and less than "to" pays "fee".
# The towns and their fees change rarely: a storefront keeps this answer and reads it again
# on its own schedule, never once per visitor.
api GET /api/v1/states
fees=$(jq -c --argjson state "$MART_STATE_ID" '[.data.cities[].states[] | select(.id == $state)] | first | .delivery.fees' <<<"$body")
if [ "$fees" = null ]; then
echo "error: state $MART_STATE_ID is not a delivery town" >&2
exit 1
fi
echo "delivery fees for state $MART_STATE_ID:"
jq -r '.[] | "\(.from_total) \(.to_total) \(.fee)"' <<<"$fees" |
while read -r from to fee; do
if [ "$to" != null ]; then
printf ' from %.2f, less than %.2f: %.2f\n' "$from" "$to" "$fee"
else
printf ' from %.2f: %.2f\n' "$from" "$fee"
fi
done
# 2. The quote, for a real cart only: the same body as a real order. Nothing is created or
# reserved, but it counts against the same per-minute budget as creating orders.
order=$(jq -n --arg ref "quote-$(date +%s)" --argjson product "$MART_PRODUCT_ID" --argjson state "$MART_STATE_ID" '{
partner_reference: $ref,
payment_type: "cod",
products: [{product_id: $product, quantity: 1}],
shipping_address: {customer_name: "Test Buyer", phone: "0599000000", state_id: $state, address: "Main street 1"}
}')
api POST /api/v1/orders/validate "$order"
jq -r '"valid: \(.data.validation.valid)"' <<<"$body"
read -r products fee total < <(jq -r '.data.validation.quote | "\(.products_total) \(.shipping_fee) \(.order_total)"' <<<"$body")
printf 'products total: %.2f\ndelivery fee: %.2f\norder total: %.2f\n' "$products" "$fee" "$total"// Show what delivery costs to one town, then quote an order without placing it.
// Node 22.18 or later runs this .ts file as it is.
// Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).
const base = process.env.MART_API_BASE;
const key = process.env.MART_API_KEY;
if (!base || !key) throw new Error('Set MART_API_BASE and MART_API_KEY');
const productId = Number(process.env.MART_PRODUCT_ID);
const stateId = Number(process.env.MART_STATE_ID);
async function api(method: string, path: string, payload?: unknown): Promise<any> {
const response = await fetch(`${base}${path}`, {
method,
headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
body: payload === undefined ? undefined : JSON.stringify(payload),
signal: AbortSignal.timeout(30_000),
});
const body = await response.json().catch(() => null); // an edge error page is not JSON
if (!response.ok || body === null) {
const retryAfter = response.headers.get('retry-after');
console.error(`error: ${response.status} ${body?.error?.code ?? '(not JSON)'}${retryAfter ? `, try again after ${retryAfter} s` : ''}`);
process.exit(1);
}
return body;
}
// 1. The town's fee brackets: a products total of at least "from" and less than "to" pays "fee".
// The towns and their fees change rarely: a storefront keeps this answer and reads it again
// on its own schedule, never once per visitor.
const states = await api('GET', '/api/v1/states');
const town = states.data.cities.flatMap((city: any) => city.states).find((state: any) => state.id === stateId);
if (!town) {
console.error(`error: state ${stateId} is not a delivery town`);
process.exit(1);
}
console.log(`delivery fees for state ${stateId}:`);
for (const bracket of town.delivery.fees) {
const upper = bracket.to_total === null ? '' : `, less than ${bracket.to_total.toFixed(2)}`;
console.log(` from ${bracket.from_total.toFixed(2)}${upper}: ${bracket.fee.toFixed(2)}`);
}
// 2. The quote, for a real cart only: the same body as a real order. Nothing is created or
// reserved, but it counts against the same per-minute budget as creating orders.
const result = await api('POST', '/api/v1/orders/validate', {
partner_reference: `quote-${Date.now()}`,
payment_type: 'cod',
products: [{ product_id: productId, quantity: 1 }],
shipping_address: { customer_name: 'Test Buyer', phone: '0599000000', state_id: stateId, address: 'Main street 1' },
});
const quote = result.data.validation.quote;
console.log(`valid: ${result.data.validation.valid}`);
console.log(`products total: ${quote.products_total.toFixed(2)}`);
console.log(`delivery fee: ${quote.shipping_fee.toFixed(2)}`);
console.log(`order total: ${quote.order_total.toFixed(2)}`);
"""Show what delivery costs to one town, then quote an order without placing it. Python 3.9+, httpx.
Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).
"""
import os
import sys
import time
import httpx
TIMEOUT = 30
client = httpx.Client(
base_url=os.environ["MART_API_BASE"],
headers={"Authorization": f"Bearer {os.environ['MART_API_KEY']}"},
timeout=TIMEOUT,
)
product_id = int(os.environ["MART_PRODUCT_ID"])
state_id = int(os.environ["MART_STATE_ID"])
def body_of(response: httpx.Response):
"""The JSON body, or None for an answer that is not JSON (an edge error page)."""
try:
return response.json()
except ValueError:
return None
def check(response: httpx.Response) -> dict:
body = body_of(response)
if response.is_error or body is None:
code = body["error"]["code"] if body else "(not JSON)"
retry_after = response.headers.get("Retry-After")
sys.exit(f"error: {response.status_code} {code}" + (f", try again after {retry_after} s" if retry_after else ""))
return body
# 1. The town's fee brackets: a products total of at least "from" and less than "to" pays "fee".
# The towns and their fees change rarely: a storefront keeps this answer and reads it again
# on its own schedule, never once per visitor.
cities = check(client.get("/api/v1/states"))["data"]["cities"]
town = next((state for city in cities for state in city["states"] if state["id"] == state_id), None)
if town is None:
sys.exit(f"error: state {state_id} is not a delivery town")
print(f"delivery fees for state {state_id}:")
for bracket in town["delivery"]["fees"]:
upper = "" if bracket["to_total"] is None else f", less than {bracket['to_total']:.2f}"
print(f" from {bracket['from_total']:.2f}{upper}: {bracket['fee']:.2f}")
# 2. The quote, for a real cart only: the same body as a real order. Nothing is created or
# reserved, but it counts against the same per-minute budget as creating orders.
result = check(client.post("/api/v1/orders/validate", json={
"partner_reference": f"quote-{int(time.time())}",
"payment_type": "cod",
"products": [{"product_id": product_id, "quantity": 1}],
"shipping_address": {"customer_name": "Test Buyer", "phone": "0599000000", "state_id": state_id, "address": "Main street 1"},
}))["data"]["validation"]
print(f"valid: {str(result['valid']).lower()}")
print(f"products total: {result['quote']['products_total']:.2f}")
print(f"delivery fee: {result['quote']['shipping_fee']:.2f}")
print(f"order total: {result['quote']['order_total']:.2f}")
<?php
// Show what delivery costs to one town, then quote an order without placing it. PHP 7.4 or later,
// with the curl extension. Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID.
$base = getenv('MART_API_BASE');
$key = getenv('MART_API_KEY');
$productId = (int) getenv('MART_PRODUCT_ID');
$stateId = (int) getenv('MART_STATE_ID');
/**
* One request with the curl extension. Returns [status, headers (lower-case name => value), body];
* status 0 when there was no answer at all.
*/
function request(string $method, string $url, string $key, ?string $payload = null, int $timeout = 30): array
{
$headers = [];
$curl = curl_init($url);
curl_setopt_array($curl, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => ["Authorization: Bearer $key", 'Content-Type: application/json'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$headers): int {
$parts = explode(':', $line, 2);
if (count($parts) === 2) {
$headers[strtolower(trim($parts[0]))] = trim($parts[1]);
}
return strlen($line);
},
]);
if ($payload !== null) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
}
$body = curl_exec($curl);
$status = $body === false ? 0 : (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
curl_close($curl);
return [$status, $headers, (string) $body];
}
/** A GET that must succeed: the decoded body, or the status and error code, and stop. */
function get(string $url, string $key): array
{
[$status, $headers, $raw] = request('GET', $url, $key);
$body = json_decode($raw, true); // null for an answer that is not JSON (an edge error page)
if ($status < 200 || $status >= 300 || !is_array($body)) {
$code = $status === 0 ? 'no answer' : $status . ' ' . ($body['error']['code'] ?? '(not JSON)');
$wait = isset($headers['retry-after']) ? ", try again after {$headers['retry-after']} s" : '';
fwrite(STDERR, "error: $code$wait\n");
exit(1);
}
return $body;
}
// 1. The town's fee brackets: a products total of at least "from" and less than "to" pays "fee".
// The towns and their fees change rarely: a storefront keeps this answer and reads it again
// on its own schedule, never once per visitor.
$states = get("$base/api/v1/states", $key);
$town = null;
foreach ($states['data']['cities'] as $city) {
foreach ($city['states'] as $state) {
if ($state['id'] === $stateId) {
$town = $state;
}
}
}
if ($town === null) {
fwrite(STDERR, "error: state $stateId is not a delivery town\n");
exit(1);
}
echo "delivery fees for state $stateId:\n";
foreach ($town['delivery']['fees'] as $bracket) {
$upper = $bracket['to_total'] === null ? '' : sprintf(', less than %.2f', $bracket['to_total']);
printf(" from %.2f%s: %.2f\n", $bracket['from_total'], $upper, $bracket['fee']);
}
// 2. The quote, for a real cart only: the same body as a real order. Nothing is created or
// reserved, but it counts against the same per-minute budget as creating orders.
[$status, $headers, $raw] = request('POST', "$base/api/v1/orders/validate", $key, json_encode([
'partner_reference' => 'quote-' . time(),
'payment_type' => 'cod',
'products' => [['product_id' => $productId, 'quantity' => 1]],
'shipping_address' => ['customer_name' => 'Test Buyer', 'phone' => '0599000000', 'state_id' => $stateId, 'address' => 'Main street 1'],
]));
$result = json_decode($raw, true);
if ($status !== 200 || !is_array($result)) {
$wait = isset($headers['retry-after']) ? ", try again after {$headers['retry-after']} s" : '';
fwrite(STDERR, 'error: ' . ($status === 0 ? 'no answer' : $status . ' ' . ($result['error']['code'] ?? '(not JSON)')) . "$wait\n");
exit(1);
}
$validation = $result['data']['validation'];
echo 'valid: ' . ($validation['valid'] ? 'true' : 'false') . "\n";
printf("products total: %.2f\n", $validation['quote']['products_total']);
printf("delivery fee: %.2f\n", $validation['quote']['shipping_fee']);
printf("order total: %.2f\n", $validation['quote']['order_total']);
//go:build ignore
// Show what delivery costs to one town, then quote an order without placing it. Go 1.22 or later.
// Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).
// Run it with: go run delivery-prices-and-quote.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
"time"
)
var client = &http.Client{Timeout: 30 * time.Second}
func main() {
productID, _ := strconv.Atoi(os.Getenv("MART_PRODUCT_ID"))
stateID, _ := strconv.Atoi(os.Getenv("MART_STATE_ID"))
// 1. The town's fee brackets: a products total of at least "from" and less than "to" pays "fee".
// The towns and their fees change rarely: a storefront keeps this answer and reads it again
// on its own schedule, never once per visitor.
var tree struct {
Data struct {
Cities []struct {
States []struct {
ID int `json:"id"`
Delivery struct {
Fees []struct {
From float64 `json:"from_total"`
To *float64 `json:"to_total"` // null: no upper end
Fee float64 `json:"fee"`
} `json:"fees"`
} `json:"delivery"`
} `json:"states"`
} `json:"cities"`
} `json:"data"`
}
get("/api/v1/states", &tree)
found := false
for _, city := range tree.Data.Cities {
for _, state := range city.States {
if state.ID != stateID {
continue
}
found = true
fmt.Printf("delivery fees for state %d:\n", stateID)
for _, b := range state.Delivery.Fees {
if b.To != nil {
fmt.Printf(" from %.2f, less than %.2f: %.2f\n", b.From, *b.To, b.Fee)
} else {
fmt.Printf(" from %.2f: %.2f\n", b.From, b.Fee)
}
}
}
}
if !found {
fail(fmt.Errorf("state %d is not a delivery town", stateID))
}
// 2. The quote, for a real cart only: the same body as a real order. Nothing is created or
// reserved, but it counts against the same per-minute budget as creating orders.
order, err := json.Marshal(map[string]any{
"partner_reference": fmt.Sprintf("quote-%d", time.Now().Unix()),
"payment_type": "cod",
"products": []map[string]any{{"product_id": productID, "quantity": 1}},
"shipping_address": map[string]any{
"customer_name": "Test Buyer", "phone": "0599000000", "state_id": stateID, "address": "Main street 1",
},
})
if err != nil {
fail(err)
}
req, err := http.NewRequest(http.MethodPost, os.Getenv("MART_API_BASE")+"/api/v1/orders/validate", bytes.NewReader(order))
if err != nil {
fail(err)
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("MART_API_KEY"))
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
fail(fmt.Errorf("no answer: %v", err))
}
var result struct {
Data struct {
Validation struct {
Valid bool `json:"valid"`
Quote struct {
ProductsTotal float64 `json:"products_total"`
ShippingFee float64 `json:"shipping_fee"`
OrderTotal float64 `json:"order_total"`
} `json:"quote"`
} `json:"validation"`
} `json:"data"`
}
decode(resp, &result)
v := result.Data.Validation
fmt.Println("valid:", v.Valid)
fmt.Printf("products total: %.2f\ndelivery fee: %.2f\norder total: %.2f\n",
v.Quote.ProductsTotal, v.Quote.ShippingFee, v.Quote.OrderTotal)
}
// get sends one GET and decodes its answer into out.
func get(path string, out any) {
req, err := http.NewRequest(http.MethodGet, os.Getenv("MART_API_BASE")+path, nil)
if err != nil {
fail(err)
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("MART_API_KEY"))
resp, err := client.Do(req)
if err != nil {
fail(fmt.Errorf("no answer: %v", err))
}
decode(resp, out)
}
// decode reads an answer into out. An error answer, or one that is not JSON (an edge error page),
// stops with its status and error code.
func decode(resp *http.Response, out any) {
defer resp.Body.Close()
raw, err := io.ReadAll(resp.Body)
if err != nil {
fail(err)
}
var envelope struct {
Error *struct {
Code string `json:"code"`
} `json:"error"`
}
if resp.StatusCode >= 300 {
code := "(not JSON)"
if json.Unmarshal(raw, &envelope) == nil && envelope.Error != nil {
code = envelope.Error.Code
}
wait := ""
if after := resp.Header.Get("Retry-After"); after != "" {
wait = ", try again after " + after + " s"
}
fail(fmt.Errorf("%d %s%s", resp.StatusCode, code, wait))
}
if err := json.Unmarshal(raw, out); err != nil {
fail(fmt.Errorf("%d (not JSON)", resp.StatusCode))
}
}
func fail(err error) {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
// Show what delivery costs to one town, then quote an order without placing it. Java 17 or later, with Jackson.
// Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).
// Run it as a single file: java -cp <the Jackson jars> delivery-prices-and-quote.java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.Locale;
import java.util.Map;
class DeliveryPricesAndQuote {
static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
static final ObjectMapper JSON = new ObjectMapper();
public static void main(String[] args) throws Exception {
int productId = Integer.parseInt(System.getenv("MART_PRODUCT_ID"));
int stateId = Integer.parseInt(System.getenv("MART_STATE_ID"));
// 1. The town's fee brackets: a products total of at least "from" and less than "to" pays "fee".
// The towns and their fees change rarely: a storefront keeps this answer and reads it again
// on its own schedule, never once per visitor.
JsonNode town = null;
for (JsonNode city : get("/api/v1/states").path("data").path("cities")) {
for (JsonNode state : city.path("states")) {
if (state.path("id").asInt() == stateId) {
town = state;
}
}
}
if (town == null) {
fail("state " + stateId + " is not a delivery town");
}
System.out.println("delivery fees for state " + stateId + ":");
for (JsonNode bracket : town.path("delivery").path("fees")) {
String upper = bracket.path("to_total").isNull() ? ""
: String.format(Locale.ROOT, ", less than %.2f", bracket.path("to_total").asDouble());
System.out.printf(Locale.ROOT, " from %.2f%s: %.2f%n", bracket.path("from_total").asDouble(), upper,
bracket.path("fee").asDouble());
}
// 2. The quote, for a real cart only: the same body as a real order. Nothing is created or
// reserved, but it counts against the same per-minute budget as creating orders.
String order = JSON.writeValueAsString(Map.of(
"partner_reference", "quote-" + System.currentTimeMillis(),
"payment_type", "cod",
"products", List.of(Map.of("product_id", productId, "quantity", 1)),
"shipping_address", Map.of("customer_name", "Test Buyer", "phone", "0599000000",
"state_id", stateId, "address", "Main street 1")));
HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv("MART_API_BASE") + "/api/v1/orders/validate"))
.header("Authorization", "Bearer " + System.getenv("MART_API_KEY"))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(30))
.POST(HttpRequest.BodyPublishers.ofString(order))
.build();
HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
JsonNode result = parse(response.body());
if (response.statusCode() >= 300 || result == null) {
fail(response.statusCode() + " " + code(result) + when(response));
}
JsonNode validation = result.path("data").path("validation");
JsonNode quote = validation.path("quote");
System.out.println("valid: " + validation.path("valid").asBoolean());
System.out.printf(Locale.ROOT, "products total: %.2f%n", quote.path("products_total").asDouble());
System.out.printf(Locale.ROOT, "delivery fee: %.2f%n", quote.path("shipping_fee").asDouble());
System.out.printf(Locale.ROOT, "order total: %.2f%n", quote.path("order_total").asDouble());
}
/** One GET that must succeed: the decoded body, or the status and error code, and stop. */
static JsonNode get(String path) throws InterruptedException {
HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv("MART_API_BASE") + path))
.header("Authorization", "Bearer " + System.getenv("MART_API_KEY"))
.timeout(Duration.ofSeconds(30))
.GET()
.build();
HttpResponse<String> response;
try {
response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
} catch (IOException e) {
fail("no answer: " + e.getMessage());
return null;
}
JsonNode body = parse(response.body());
if (response.statusCode() >= 300 || body == null) {
fail(response.statusCode() + " " + code(body) + when(response));
}
return body;
}
/** The JSON body, or null for an answer that is not JSON (an edge error page). */
static JsonNode parse(String text) {
try {
return JSON.readTree(text);
} catch (IOException e) {
return null;
}
}
static void fail(String message) {
System.err.println("error: " + message);
System.exit(1);
}
static String code(JsonNode body) {
return body == null ? "(not JSON)" : body.path("error").path("code").asText();
}
/** ", try again after N s" when the answer says how long to wait (Retry-After), else nothing. */
static String when(HttpResponse<String> response) {
return response.headers().firstValue("Retry-After").map(s -> ", try again after " + s + " s").orElse("");
}
}
{
"status": "success",
"status_code": 200,
"message": "Order is valid",
"data": {
"validation": {
"valid": true,
"quote": {
"products_total": 240,
"shipping_fee": 35,
"free_shipping": true,
"order_total": 240,
"cod_total": 240,
"reward": {
"gross": 130.02,
"shipping_deduction": 35,
"net": 95.02
}
}
}
},
"meta": null,
"error": null
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}Validate an order without creating it
The dry-run twin of POST /api/v1/orders: same body, same validation pipeline, byte-identical error envelopes — but nothing is written, reserved or consumed. Idempotency is predicted, not processed. A valid order answers a quote: its products total, delivery fee, totals and reward exactly as a create with the same body would freeze them right now. A 200 is point-in-time: stock, prices and delivery fees can still move before the real create, and the create answer is the binding one. Details: https://mart.ps/api/docs#orders.
#!/usr/bin/env bash
# Show what delivery costs to one town, then quote an order without placing it.
# Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).
set -euo pipefail
export LC_NUMERIC=C # printf reads and writes amounts with a decimal point
# api METHOD PATH [JSON]: sets $body, or prints the status and error code and stops.
api() {
local response status retry_after
response=$(curl --silent --show-error --max-time 30 --request "$1" \
--header @<(printf 'Authorization: Bearer %s\n' "$MART_API_KEY") --header 'Content-Type: application/json' \
${3:+--data "$3"} --write-out '\n%{http_code} %header{retry-after}' "$MART_API_BASE$2") || { echo "error: no answer" >&2; exit 1; }
read -r status retry_after <<<"${response##*$'\n'}"
body=${response%$'\n'*}
if [ "$status" -ge 300 ]; then
echo "error: $status $(jq -r '.error.code' <<<"$body" 2>/dev/null || echo '(not JSON)')${retry_after:+, try again after $retry_after s}" >&2
exit 1
fi
}
# 1. The town's fee brackets: a products total of at least "from" and less than "to" pays "fee".
# The towns and their fees change rarely: a storefront keeps this answer and reads it again
# on its own schedule, never once per visitor.
api GET /api/v1/states
fees=$(jq -c --argjson state "$MART_STATE_ID" '[.data.cities[].states[] | select(.id == $state)] | first | .delivery.fees' <<<"$body")
if [ "$fees" = null ]; then
echo "error: state $MART_STATE_ID is not a delivery town" >&2
exit 1
fi
echo "delivery fees for state $MART_STATE_ID:"
jq -r '.[] | "\(.from_total) \(.to_total) \(.fee)"' <<<"$fees" |
while read -r from to fee; do
if [ "$to" != null ]; then
printf ' from %.2f, less than %.2f: %.2f\n' "$from" "$to" "$fee"
else
printf ' from %.2f: %.2f\n' "$from" "$fee"
fi
done
# 2. The quote, for a real cart only: the same body as a real order. Nothing is created or
# reserved, but it counts against the same per-minute budget as creating orders.
order=$(jq -n --arg ref "quote-$(date +%s)" --argjson product "$MART_PRODUCT_ID" --argjson state "$MART_STATE_ID" '{
partner_reference: $ref,
payment_type: "cod",
products: [{product_id: $product, quantity: 1}],
shipping_address: {customer_name: "Test Buyer", phone: "0599000000", state_id: $state, address: "Main street 1"}
}')
api POST /api/v1/orders/validate "$order"
jq -r '"valid: \(.data.validation.valid)"' <<<"$body"
read -r products fee total < <(jq -r '.data.validation.quote | "\(.products_total) \(.shipping_fee) \(.order_total)"' <<<"$body")
printf 'products total: %.2f\ndelivery fee: %.2f\norder total: %.2f\n' "$products" "$fee" "$total"// Show what delivery costs to one town, then quote an order without placing it.
// Node 22.18 or later runs this .ts file as it is.
// Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).
const base = process.env.MART_API_BASE;
const key = process.env.MART_API_KEY;
if (!base || !key) throw new Error('Set MART_API_BASE and MART_API_KEY');
const productId = Number(process.env.MART_PRODUCT_ID);
const stateId = Number(process.env.MART_STATE_ID);
async function api(method: string, path: string, payload?: unknown): Promise<any> {
const response = await fetch(`${base}${path}`, {
method,
headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
body: payload === undefined ? undefined : JSON.stringify(payload),
signal: AbortSignal.timeout(30_000),
});
const body = await response.json().catch(() => null); // an edge error page is not JSON
if (!response.ok || body === null) {
const retryAfter = response.headers.get('retry-after');
console.error(`error: ${response.status} ${body?.error?.code ?? '(not JSON)'}${retryAfter ? `, try again after ${retryAfter} s` : ''}`);
process.exit(1);
}
return body;
}
// 1. The town's fee brackets: a products total of at least "from" and less than "to" pays "fee".
// The towns and their fees change rarely: a storefront keeps this answer and reads it again
// on its own schedule, never once per visitor.
const states = await api('GET', '/api/v1/states');
const town = states.data.cities.flatMap((city: any) => city.states).find((state: any) => state.id === stateId);
if (!town) {
console.error(`error: state ${stateId} is not a delivery town`);
process.exit(1);
}
console.log(`delivery fees for state ${stateId}:`);
for (const bracket of town.delivery.fees) {
const upper = bracket.to_total === null ? '' : `, less than ${bracket.to_total.toFixed(2)}`;
console.log(` from ${bracket.from_total.toFixed(2)}${upper}: ${bracket.fee.toFixed(2)}`);
}
// 2. The quote, for a real cart only: the same body as a real order. Nothing is created or
// reserved, but it counts against the same per-minute budget as creating orders.
const result = await api('POST', '/api/v1/orders/validate', {
partner_reference: `quote-${Date.now()}`,
payment_type: 'cod',
products: [{ product_id: productId, quantity: 1 }],
shipping_address: { customer_name: 'Test Buyer', phone: '0599000000', state_id: stateId, address: 'Main street 1' },
});
const quote = result.data.validation.quote;
console.log(`valid: ${result.data.validation.valid}`);
console.log(`products total: ${quote.products_total.toFixed(2)}`);
console.log(`delivery fee: ${quote.shipping_fee.toFixed(2)}`);
console.log(`order total: ${quote.order_total.toFixed(2)}`);
"""Show what delivery costs to one town, then quote an order without placing it. Python 3.9+, httpx.
Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).
"""
import os
import sys
import time
import httpx
TIMEOUT = 30
client = httpx.Client(
base_url=os.environ["MART_API_BASE"],
headers={"Authorization": f"Bearer {os.environ['MART_API_KEY']}"},
timeout=TIMEOUT,
)
product_id = int(os.environ["MART_PRODUCT_ID"])
state_id = int(os.environ["MART_STATE_ID"])
def body_of(response: httpx.Response):
"""The JSON body, or None for an answer that is not JSON (an edge error page)."""
try:
return response.json()
except ValueError:
return None
def check(response: httpx.Response) -> dict:
body = body_of(response)
if response.is_error or body is None:
code = body["error"]["code"] if body else "(not JSON)"
retry_after = response.headers.get("Retry-After")
sys.exit(f"error: {response.status_code} {code}" + (f", try again after {retry_after} s" if retry_after else ""))
return body
# 1. The town's fee brackets: a products total of at least "from" and less than "to" pays "fee".
# The towns and their fees change rarely: a storefront keeps this answer and reads it again
# on its own schedule, never once per visitor.
cities = check(client.get("/api/v1/states"))["data"]["cities"]
town = next((state for city in cities for state in city["states"] if state["id"] == state_id), None)
if town is None:
sys.exit(f"error: state {state_id} is not a delivery town")
print(f"delivery fees for state {state_id}:")
for bracket in town["delivery"]["fees"]:
upper = "" if bracket["to_total"] is None else f", less than {bracket['to_total']:.2f}"
print(f" from {bracket['from_total']:.2f}{upper}: {bracket['fee']:.2f}")
# 2. The quote, for a real cart only: the same body as a real order. Nothing is created or
# reserved, but it counts against the same per-minute budget as creating orders.
result = check(client.post("/api/v1/orders/validate", json={
"partner_reference": f"quote-{int(time.time())}",
"payment_type": "cod",
"products": [{"product_id": product_id, "quantity": 1}],
"shipping_address": {"customer_name": "Test Buyer", "phone": "0599000000", "state_id": state_id, "address": "Main street 1"},
}))["data"]["validation"]
print(f"valid: {str(result['valid']).lower()}")
print(f"products total: {result['quote']['products_total']:.2f}")
print(f"delivery fee: {result['quote']['shipping_fee']:.2f}")
print(f"order total: {result['quote']['order_total']:.2f}")
<?php
// Show what delivery costs to one town, then quote an order without placing it. PHP 7.4 or later,
// with the curl extension. Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID.
$base = getenv('MART_API_BASE');
$key = getenv('MART_API_KEY');
$productId = (int) getenv('MART_PRODUCT_ID');
$stateId = (int) getenv('MART_STATE_ID');
/**
* One request with the curl extension. Returns [status, headers (lower-case name => value), body];
* status 0 when there was no answer at all.
*/
function request(string $method, string $url, string $key, ?string $payload = null, int $timeout = 30): array
{
$headers = [];
$curl = curl_init($url);
curl_setopt_array($curl, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => ["Authorization: Bearer $key", 'Content-Type: application/json'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$headers): int {
$parts = explode(':', $line, 2);
if (count($parts) === 2) {
$headers[strtolower(trim($parts[0]))] = trim($parts[1]);
}
return strlen($line);
},
]);
if ($payload !== null) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
}
$body = curl_exec($curl);
$status = $body === false ? 0 : (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
curl_close($curl);
return [$status, $headers, (string) $body];
}
/** A GET that must succeed: the decoded body, or the status and error code, and stop. */
function get(string $url, string $key): array
{
[$status, $headers, $raw] = request('GET', $url, $key);
$body = json_decode($raw, true); // null for an answer that is not JSON (an edge error page)
if ($status < 200 || $status >= 300 || !is_array($body)) {
$code = $status === 0 ? 'no answer' : $status . ' ' . ($body['error']['code'] ?? '(not JSON)');
$wait = isset($headers['retry-after']) ? ", try again after {$headers['retry-after']} s" : '';
fwrite(STDERR, "error: $code$wait\n");
exit(1);
}
return $body;
}
// 1. The town's fee brackets: a products total of at least "from" and less than "to" pays "fee".
// The towns and their fees change rarely: a storefront keeps this answer and reads it again
// on its own schedule, never once per visitor.
$states = get("$base/api/v1/states", $key);
$town = null;
foreach ($states['data']['cities'] as $city) {
foreach ($city['states'] as $state) {
if ($state['id'] === $stateId) {
$town = $state;
}
}
}
if ($town === null) {
fwrite(STDERR, "error: state $stateId is not a delivery town\n");
exit(1);
}
echo "delivery fees for state $stateId:\n";
foreach ($town['delivery']['fees'] as $bracket) {
$upper = $bracket['to_total'] === null ? '' : sprintf(', less than %.2f', $bracket['to_total']);
printf(" from %.2f%s: %.2f\n", $bracket['from_total'], $upper, $bracket['fee']);
}
// 2. The quote, for a real cart only: the same body as a real order. Nothing is created or
// reserved, but it counts against the same per-minute budget as creating orders.
[$status, $headers, $raw] = request('POST', "$base/api/v1/orders/validate", $key, json_encode([
'partner_reference' => 'quote-' . time(),
'payment_type' => 'cod',
'products' => [['product_id' => $productId, 'quantity' => 1]],
'shipping_address' => ['customer_name' => 'Test Buyer', 'phone' => '0599000000', 'state_id' => $stateId, 'address' => 'Main street 1'],
]));
$result = json_decode($raw, true);
if ($status !== 200 || !is_array($result)) {
$wait = isset($headers['retry-after']) ? ", try again after {$headers['retry-after']} s" : '';
fwrite(STDERR, 'error: ' . ($status === 0 ? 'no answer' : $status . ' ' . ($result['error']['code'] ?? '(not JSON)')) . "$wait\n");
exit(1);
}
$validation = $result['data']['validation'];
echo 'valid: ' . ($validation['valid'] ? 'true' : 'false') . "\n";
printf("products total: %.2f\n", $validation['quote']['products_total']);
printf("delivery fee: %.2f\n", $validation['quote']['shipping_fee']);
printf("order total: %.2f\n", $validation['quote']['order_total']);
//go:build ignore
// Show what delivery costs to one town, then quote an order without placing it. Go 1.22 or later.
// Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).
// Run it with: go run delivery-prices-and-quote.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
"time"
)
var client = &http.Client{Timeout: 30 * time.Second}
func main() {
productID, _ := strconv.Atoi(os.Getenv("MART_PRODUCT_ID"))
stateID, _ := strconv.Atoi(os.Getenv("MART_STATE_ID"))
// 1. The town's fee brackets: a products total of at least "from" and less than "to" pays "fee".
// The towns and their fees change rarely: a storefront keeps this answer and reads it again
// on its own schedule, never once per visitor.
var tree struct {
Data struct {
Cities []struct {
States []struct {
ID int `json:"id"`
Delivery struct {
Fees []struct {
From float64 `json:"from_total"`
To *float64 `json:"to_total"` // null: no upper end
Fee float64 `json:"fee"`
} `json:"fees"`
} `json:"delivery"`
} `json:"states"`
} `json:"cities"`
} `json:"data"`
}
get("/api/v1/states", &tree)
found := false
for _, city := range tree.Data.Cities {
for _, state := range city.States {
if state.ID != stateID {
continue
}
found = true
fmt.Printf("delivery fees for state %d:\n", stateID)
for _, b := range state.Delivery.Fees {
if b.To != nil {
fmt.Printf(" from %.2f, less than %.2f: %.2f\n", b.From, *b.To, b.Fee)
} else {
fmt.Printf(" from %.2f: %.2f\n", b.From, b.Fee)
}
}
}
}
if !found {
fail(fmt.Errorf("state %d is not a delivery town", stateID))
}
// 2. The quote, for a real cart only: the same body as a real order. Nothing is created or
// reserved, but it counts against the same per-minute budget as creating orders.
order, err := json.Marshal(map[string]any{
"partner_reference": fmt.Sprintf("quote-%d", time.Now().Unix()),
"payment_type": "cod",
"products": []map[string]any{{"product_id": productID, "quantity": 1}},
"shipping_address": map[string]any{
"customer_name": "Test Buyer", "phone": "0599000000", "state_id": stateID, "address": "Main street 1",
},
})
if err != nil {
fail(err)
}
req, err := http.NewRequest(http.MethodPost, os.Getenv("MART_API_BASE")+"/api/v1/orders/validate", bytes.NewReader(order))
if err != nil {
fail(err)
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("MART_API_KEY"))
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
fail(fmt.Errorf("no answer: %v", err))
}
var result struct {
Data struct {
Validation struct {
Valid bool `json:"valid"`
Quote struct {
ProductsTotal float64 `json:"products_total"`
ShippingFee float64 `json:"shipping_fee"`
OrderTotal float64 `json:"order_total"`
} `json:"quote"`
} `json:"validation"`
} `json:"data"`
}
decode(resp, &result)
v := result.Data.Validation
fmt.Println("valid:", v.Valid)
fmt.Printf("products total: %.2f\ndelivery fee: %.2f\norder total: %.2f\n",
v.Quote.ProductsTotal, v.Quote.ShippingFee, v.Quote.OrderTotal)
}
// get sends one GET and decodes its answer into out.
func get(path string, out any) {
req, err := http.NewRequest(http.MethodGet, os.Getenv("MART_API_BASE")+path, nil)
if err != nil {
fail(err)
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("MART_API_KEY"))
resp, err := client.Do(req)
if err != nil {
fail(fmt.Errorf("no answer: %v", err))
}
decode(resp, out)
}
// decode reads an answer into out. An error answer, or one that is not JSON (an edge error page),
// stops with its status and error code.
func decode(resp *http.Response, out any) {
defer resp.Body.Close()
raw, err := io.ReadAll(resp.Body)
if err != nil {
fail(err)
}
var envelope struct {
Error *struct {
Code string `json:"code"`
} `json:"error"`
}
if resp.StatusCode >= 300 {
code := "(not JSON)"
if json.Unmarshal(raw, &envelope) == nil && envelope.Error != nil {
code = envelope.Error.Code
}
wait := ""
if after := resp.Header.Get("Retry-After"); after != "" {
wait = ", try again after " + after + " s"
}
fail(fmt.Errorf("%d %s%s", resp.StatusCode, code, wait))
}
if err := json.Unmarshal(raw, out); err != nil {
fail(fmt.Errorf("%d (not JSON)", resp.StatusCode))
}
}
func fail(err error) {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
// Show what delivery costs to one town, then quote an order without placing it. Java 17 or later, with Jackson.
// Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).
// Run it as a single file: java -cp <the Jackson jars> delivery-prices-and-quote.java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.Locale;
import java.util.Map;
class DeliveryPricesAndQuote {
static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
static final ObjectMapper JSON = new ObjectMapper();
public static void main(String[] args) throws Exception {
int productId = Integer.parseInt(System.getenv("MART_PRODUCT_ID"));
int stateId = Integer.parseInt(System.getenv("MART_STATE_ID"));
// 1. The town's fee brackets: a products total of at least "from" and less than "to" pays "fee".
// The towns and their fees change rarely: a storefront keeps this answer and reads it again
// on its own schedule, never once per visitor.
JsonNode town = null;
for (JsonNode city : get("/api/v1/states").path("data").path("cities")) {
for (JsonNode state : city.path("states")) {
if (state.path("id").asInt() == stateId) {
town = state;
}
}
}
if (town == null) {
fail("state " + stateId + " is not a delivery town");
}
System.out.println("delivery fees for state " + stateId + ":");
for (JsonNode bracket : town.path("delivery").path("fees")) {
String upper = bracket.path("to_total").isNull() ? ""
: String.format(Locale.ROOT, ", less than %.2f", bracket.path("to_total").asDouble());
System.out.printf(Locale.ROOT, " from %.2f%s: %.2f%n", bracket.path("from_total").asDouble(), upper,
bracket.path("fee").asDouble());
}
// 2. The quote, for a real cart only: the same body as a real order. Nothing is created or
// reserved, but it counts against the same per-minute budget as creating orders.
String order = JSON.writeValueAsString(Map.of(
"partner_reference", "quote-" + System.currentTimeMillis(),
"payment_type", "cod",
"products", List.of(Map.of("product_id", productId, "quantity", 1)),
"shipping_address", Map.of("customer_name", "Test Buyer", "phone", "0599000000",
"state_id", stateId, "address", "Main street 1")));
HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv("MART_API_BASE") + "/api/v1/orders/validate"))
.header("Authorization", "Bearer " + System.getenv("MART_API_KEY"))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(30))
.POST(HttpRequest.BodyPublishers.ofString(order))
.build();
HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
JsonNode result = parse(response.body());
if (response.statusCode() >= 300 || result == null) {
fail(response.statusCode() + " " + code(result) + when(response));
}
JsonNode validation = result.path("data").path("validation");
JsonNode quote = validation.path("quote");
System.out.println("valid: " + validation.path("valid").asBoolean());
System.out.printf(Locale.ROOT, "products total: %.2f%n", quote.path("products_total").asDouble());
System.out.printf(Locale.ROOT, "delivery fee: %.2f%n", quote.path("shipping_fee").asDouble());
System.out.printf(Locale.ROOT, "order total: %.2f%n", quote.path("order_total").asDouble());
}
/** One GET that must succeed: the decoded body, or the status and error code, and stop. */
static JsonNode get(String path) throws InterruptedException {
HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv("MART_API_BASE") + path))
.header("Authorization", "Bearer " + System.getenv("MART_API_KEY"))
.timeout(Duration.ofSeconds(30))
.GET()
.build();
HttpResponse<String> response;
try {
response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
} catch (IOException e) {
fail("no answer: " + e.getMessage());
return null;
}
JsonNode body = parse(response.body());
if (response.statusCode() >= 300 || body == null) {
fail(response.statusCode() + " " + code(body) + when(response));
}
return body;
}
/** The JSON body, or null for an answer that is not JSON (an edge error page). */
static JsonNode parse(String text) {
try {
return JSON.readTree(text);
} catch (IOException e) {
return null;
}
}
static void fail(String message) {
System.err.println("error: " + message);
System.exit(1);
}
static String code(JsonNode body) {
return body == null ? "(not JSON)" : body.path("error").path("code").asText();
}
/** ", try again after N s" when the answer says how long to wait (Retry-After), else nothing. */
static String when(HttpResponse<String> response) {
return response.headers().firstValue("Retry-After").map(s -> ", try again after " + s + " s").orElse("");
}
}
{
"status": "success",
"status_code": 200,
"message": "Order is valid",
"data": {
"validation": {
"valid": true,
"quote": {
"products_total": 240,
"shipping_fee": 35,
"free_shipping": true,
"order_total": 240,
"cod_total": 240,
"reward": {
"gross": 130.02,
"shipping_deduction": 35,
"net": 95.02
}
}
}
},
"meta": null,
"error": null
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}Body
REQUIRED: exact lowercase cod or card — never normalized, never defaulted. card charges your saved card synchronously for the server-computed total and needs per-key enablement (card_not_enabled) plus a reusable saved card on file (card_not_on_file). See https://mart.ps/api/docs#payments.
cod, card "cod"
Your own order id and the idempotency key, stored and matched byte-for-byte. Letters, digits, dot, underscore, hyphen; max 64 characters; surrounding whitespace is rejected, never trimmed; unique per key. Identity is judged on a canonical form — https://mart.ps/api/docs#idempotency.
64"100245"
true = you absorb the delivery fee (needs your group's permission — free_shipping_not_allowed otherwise; free_shipping_not_covered when your margin cannot cover the fee, exact coverage passing). Rejected with card_free_shipping_not_allowed on card orders. See https://mart.ps/api/docs#orders.
Response
The order would be accepted, and this is what it would cost and earn. Point-in-time verdict — nothing was created or reserved.
