Sell motor insurance through the Moolre API

Environment: Live

Sell motor policies from your own app or back office: register an agent wallet, find the vehicle from its VIN, quote, collect the premium, buy with an idempotent reference, follow pending, deliver the policy, handle refunds and renewals, and reconcile the commission. With code in cURL, Node.js, Python and PHP.

# Sell motor insurance through the Moolre API

Sell motor policies from your own app or back office: register an agent wallet, find the vehicle from its VIN, quote, collect the premium, buy with an idempotent reference, follow pending, deliver the policy, handle refunds and renewals, and reconcile the commission. With code in cURL, Node.js, Python and PHP.

## Who this is for and what you build

This guide is for a merchant, broker or agent who wants to sell motor insurance from their own app, shop software or back office: take the customer's vehicle and details, price the cover, collect the premium, issue the policy and hand over the certificate and road sticker. Moolre issues the policy with the insurer, pays you a 10% commission on every issued policy, and answers every step through the Sales API.

Policies are sold in GHS, from a wallet that is registered as an insurance sales agent. The wallet pays the full premium to the insurer when you buy; you collect that money from your customer first.

| Step | Call | What it gives you |
| --- | --- | --- |
| 1 | Insurance Covers | The cover types and policy types you can sell (fixed lists, cache them) |
| 2 | Insurance VIN lookup (or Insurance Vehicles) | The insurer model code of the vehicle, from its VIN |
| 3 | Insurance Quote | The premium of each cover for the start date and seats |
| 4 | Mobile Money Collection and the payment webhook | The premium, in your wallet, paid by the customer |
| 5 | Sell Insurance (type 1) | The purchase, with a unique externalref |
| 6 | Sales Status | The final result of a pending purchase |
| 7 | Sales Status (policy) | Policy number, certificate and sticker links to give the customer |
| 8 | Sell Insurance (type 2) | A renewal by policy number |
| 9 | Sales Status (commission) | Commission earned and its payment status, for reconciliation |

## Before you start

Four things must be in place before the first call. None of them is code.

- An insurance sales agent wallet. Insurance is the Insurance sales product (product 2) on a wallet. In the Moolre App, create a Sell on Our Platform service, choose the Insurance product and link your GHS wallet; that registers the wallet as an insurance agent with a 10% commission. A wallet that sells airtime and data can be registered for Insurance as well. Moolre Support can also set it up. Until the wallet is registered, every call is refused with IQ04 or IS07.
- API access. Sales calls use your username and private key (X-API-USER and X-API-KEY). Collecting the premium and checking a payment use your public key (X-API-PUBKEY). Keep both on your server only. If your keys are limited to IP addresses, allow the server that makes these calls. See API keys and authentication.
- A funded GHS wallet. The wallet pays the premium when you buy, so it must hold the full premium at that moment (IS13 otherwise). Collecting the premium from your customer into this same wallet keeps the money and the policy together.
- A webhook URL for payment results, if you collect payments with Mobile Money Collection (recommended). See Webhooks and callbacks.

| Credential | Used for | Header |
| --- | --- | --- |
| Username | Every call | X-API-USER |
| Private key | Covers, VIN lookup, Vehicles, Quote, Sell Insurance, Sales Status, Account Status | X-API-KEY |
| Public key | Mobile Money Collection and Payment Status | X-API-PUBKEY |

- [API keys and authentication, step by step](https://docs.moolre.com/guides/api-keys)
- [Sales guide](https://docs.moolre.com/guides/sales)
- [Webhooks and callbacks](https://docs.moolre.com/guides/webhooks-and-callbacks)

## The flow at a glance

Each numbered step below is one section of this guide. The state of every sale lives in your own database: create the order and its two references (one for the payment, one for the policy) before you call anything, and move it forward only from what Moolre tells you.

Everything before the purchase is a read: a look-up or a quote never charges anything and can be repeated. Everything from the purchase on moves money, so it is written to be safe to repeat.

```diagram
Customer          Your server                 Moolre API                    Insurer
   |                   |                          |                           |
   | 1 VIN, details    |                          |                           |
   |------------------>| covers (once, cached)    |                           |
   |                   |------------------------->|                           |
   |                   | 2 insurance/vin          |  vehicle list             |
   |                   |------------------------->|-------------------------->|
   |                   |<-------------------------| best_match, candidates    |
   |  confirm vehicle  |                          |                           |
   |<------------------| 3 insurance/quote        |  price                    |
   |  pick a cover     |------------------------->|-------------------------->|
   |------------------>|<-------------------------| premium per cover         |
   |                   | 4 transact/payment       |                           |
   |  approve on phone |------------------------->| (wallet credited)         |
   |<------------------|<=== webhook: payment.succeeded, txstatus 1           |
   |                   | 5 insurance (externalref)|  create policy            |
   |                   |------------------------->|-------------------------->|
   |                   |<-------------------------| IS20 issued / IS21 pending|
   |                   | 6 sales/status, backoff  |                           |
   |                   |------------------------->|  (until txstatus 1 or 2)  |
   |  7 policy no.,    |<-------------------------| policy links, commission  |
   |  certificate,     |                          |                           |
   |  sticker links    |                          |                           |
   |<------------------|                          |                           |
```

## 1. List the covers

Call Insurance Covers once and keep the result: the lists are fixed. Use cover_type and pol_type exactly as returned. A private car is PRIVATE_INDIVIDUAL_X_1; taxis, ride hailing, buses and motor cycles have their own pol_type. Show the customer the cover names and descriptions so they know what the premium buys.

```curl
curl https://api.moolre.com/open/sales/insurance/covers \
  -H "Content-Type: application/json" \
  -H "X-API-USER: $MOOLRE_USER" \
  -H "X-API-KEY: $MOOLRE_KEY" \
  -d '{
    "accountnumber": "100000100002"
  }'
```

```nodejs
const res = await fetch('https://api.moolre.com/open/sales/insurance/covers', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', 'X-API-USER': process.env.MOOLRE_USER, 'X-API-KEY': process.env.MOOLRE_KEY },
  body: JSON.stringify({ accountnumber: process.env.MOOLRE_INSURANCE_WALLET }),
});
const covers = await res.json();
// covers.data.covers[].cover_type     -> policy.cover_type, matched against the quote
// covers.data.policy_types[].pol_type -> policy.pol_type
```

- [Insurance Covers](https://docs.moolre.com/api/sales/insurance/covers)

## 2. Find the vehicle from its VIN

The policy needs the insurer's own description of the vehicle: modelno, modeldesc, bodytype, engcc, tonnage and noseats. Ask for the VIN (the 17-character chassis number on the registration or the windscreen plate) and let Insurance VIN lookup decode it and find that model for you. Send seats if you know them: a VIN almost never carries the seat count, so 5 is assumed and a warning tells you so.

Read the answer in this order. code IQ23 means a vehicle was found: use data.best_match when data.confident is true, and show data.candidates for the person to choose when it is false. When the VIN is only partly decoded (many vehicles built for other markets: NHTSA names the make but not the model, or no engine size) the code is IQ24, status 1: data.decoded holds what was found, data.candidates lists vehicles of the make, and data.fallback says what to search with Insurance Vehicles and what to ask the person. Every reply that is not a confident match carries that fallback, so there is no dead end. Always read data.warnings: a warning such as 1 (the check digit does not calculate) is common on imported vehicles and does not mean the VIN is wrong, but it is a reason to check the make, model and year against the registration with the customer.

| Reply | Meaning | What to do |
| --- | --- | --- |
| IQ23, confident true | Decoded and one clear match | Show make, model and year to the customer to confirm, then use best_match |
| IQ23, confident false | Decoded, several close matches or a loose one | Show candidates and let the agent or customer choose |
| IQ24 | Partly decoded: the make is known but not the model, or the make and model but not the engine size (status 1) | Show data.candidates if any, ask the person for what data.fallback.ask_user names, then search with data.fallback.suggested (step 2b) |
| IQ13 | Decoded, the insurer lists no matching model (status 0) | Fall back to the vehicle search (step 2b) with data.fallback.suggested; data.candidates may list other models of the make |
| IQ12 | NHTSA could not name a make (status 0) | Check the VIN, then ask for the make, model and engine size from the registration and search (step 2b) |
| ASN01 or IQ11 | The VIN is not 17 letters and digits, or contains I, O or Q | Ask for the VIN again |
| ASN05, ASN06 or IQ09 | The decoder or the insurer did not answer | Wait a moment and ask again. Nothing was charged. After three tries use the vehicle search |

```curl
curl https://api.moolre.com/open/sales/insurance/vin \
  -H "Content-Type: application/json" \
  -H "X-API-USER: $MOOLRE_USER" \
  -H "X-API-KEY: $MOOLRE_KEY" \
  -d '{
    "accountnumber": "100000100002",
    "vin": "JTDKN3DU0A0000001",
    "seats": 5
  }'
```

```nodejs
async function findVehicle(vin, seats) {
  const reply = await call('/open/sales/insurance/vin', { accountnumber: WALLET, vin, seats });
  if (reply.code === 'IQ23' && reply.data.confident) return { vehicle: reply.data.best_match, decoded: reply.data.decoded, warnings: reply.data.warnings };
  // IQ23 not confident, IQ24 (partly decoded), IQ13 (no insurer model) and IQ12 (not decoded) all carry data.fallback:
  // what to search, and what the person still has to give. Candidates are shown for the person to choose.
  if (['IQ23', 'IQ24', 'IQ13', 'IQ12'].includes(reply.code)) {
    const d = reply.data;
    return { candidates: d.candidates, decoded: d.decoded, warnings: d.warnings, fallback: d.fallback };
    // then: searchVehicles(d.fallback.suggested.search_term, seats, engcc) once the person has filled d.fallback.ask_user
  }
  throw new Error(reply.code + ': ' + reply.message); // ASN01 bad VIN, ASN05 try again
}
```

> **What the VIN lookup relies on:** The VIN is decoded with the public NHTSA database, which knows vehicles built for the US market best. Many imported cars decode with warnings or only in part, and some European and Asian models are not found at all. That is why the vehicle search below is part of the flow and not an afterthought, and why every reply that is not a confident match tells you how to continue (data.fallback).

- [Insurance VIN lookup](https://docs.moolre.com/api/sales/insurance/vin)

## 2b. Fall back to the vehicle search

When the VIN cannot be decoded or matched, the VIN reply carries a fallback object. Start from fallback.suggested: search_term is the make and model that were decoded (null when none), engcc is the decoded engine size (or null) and seats is the seats used. Ask the person for whatever fallback.ask_user lists (make, model, engcc), fill the gaps from the registration and search the insurer list with Insurance Vehicles. Send search_term as the make and model (for example TOYOTA PRIUS), the seats and the engine capacity in cc. The insurer lists the models with that engine size, so if nothing is found try the nominal size (1800 rather than 1798) or a shorter search_term. Show the results and let the person choose; copy the chosen vehicle's modelno, modeldesc, bodytype, engcc, tonnage and noseats unchanged into policy.motor.

```curl
curl https://api.moolre.com/open/sales/insurance/vehicles \
  -H "Content-Type: application/json" \
  -H "X-API-USER: $MOOLRE_USER" \
  -H "X-API-KEY: $MOOLRE_KEY" \
  -d '{
    "accountnumber": "100000100002",
    "search_term": "TOYOTA PRIUS",
    "seats": 5,
    "engcc": 1800
  }'
```

```nodejs
async function searchVehicles(term, seats, engcc) {
  const reply = await call('/open/sales/insurance/vehicles', { accountnumber: WALLET, search_term: term, seats, engcc });
  if (reply.code === 'IQ22') return { vehicles: [] };            // nothing listed: try a shorter term or another engcc
  if (reply.code !== 'IQ21') throw new Error(reply.code + ': ' + reply.message);
  return { vehicles: reply.data.vehicles };                       // the agent picks one
}
```

- [Insurance Vehicles](https://docs.moolre.com/api/sales/insurance/vehicles)

## 3. Quote the cover

Ask for the premium with the start date of the policy (YYYY-MM-DD; a past date is priced as today) and the number of seats of the vehicle. The reply lists the premium of every cover that is available. Keep the premium of the cover the customer picks: it is the amount you will collect and the premium you send when you buy.

Use the same seats in the quote, in the VIN lookup and in policy.motor.noseats. A quote is good until the end of its start date and for at most 24 hours; prices change, so quote again if the customer comes back later. If you send a premium that no longer matches the insurer's price, the purchase is refused with IS10, the message states the current price, and nothing is charged.

```curl
curl https://api.moolre.com/open/sales/insurance/quote \
  -H "Content-Type: application/json" \
  -H "X-API-USER: $MOOLRE_USER" \
  -H "X-API-KEY: $MOOLRE_KEY" \
  -d '{
    "accountnumber": "100000100002",
    "start_date": "2026-12-01",
    "seats": 5
  }'
```

```nodejs
async function quote(startDate, seats) {
  const reply = await call('/open/sales/insurance/quote', { accountnumber: WALLET, start_date: startDate, seats });
  if (reply.code !== 'IQ20') throw new Error(reply.code + ': ' + reply.message); // IQ09 and ASQ05: try again
  // [{ cover_type: "third_party", cover_code: "T", premium: "1250.00" }, ...]
  return reply.data.covers;
}
```

- [Insurance Quote](https://docs.moolre.com/api/sales/insurance/quote)

## 4. Collect the premium from the customer

Collect the premium before you buy, into the insurance agent wallet, with Mobile Money Collection: the customer approves a prompt on their phone, Moolre credits the wallet, and your webhook tells you it happened (payment.succeeded, data.txstatus 1). Sell only after that callback, never on the strength of the customer saying they paid. A first payment from a number can ask for a one-time code (TP14); the Collect payments guide shows that step.

Fees matter here. The wallet is credited data.value, the amount after collection fees, which can be less than the amount the customer paid. The purchase needs the full premium in the wallet, so decide who carries the fee: collect the premium plus the fee from the customer, or carry it yourself and keep the wallet topped up. Your collection pricing is part of your agreement with Moolre; ask Moolre Support if you want the fee charged to you instead of deducted from the customer's payment.

Check the wallet before you buy. Compare the balance with the premium (Account Status) so that a short wallet shows up as a clear message to you, not as IS13 after the customer has been told the policy is on its way.

```curl
curl https://api.moolre.com/open/transact/payment \
  -H "Content-Type: application/json" \
  -H "X-API-USER: $MOOLRE_USER" \
  -H "X-API-PUBKEY: $MOOLRE_PUBKEY" \
  -H "Idempotency-Key: PAY-INS-1001" \
  -d '{
    "type": 1,
    "channel": "MTN",
    "currency": "GHS",
    "payer": "0240000001",
    "amount": "1255.00",
    "externalref": "PAY-INS-1001",
    "accountnumber": "100000100002"
  }'
```

```nodejs
// 1. Ask the customer to approve the payment on their phone. The money lands in the agent wallet.
async function collectPremium(order) {
  return fetch('https://api.moolre.com/open/transact/payment', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'X-API-USER': process.env.MOOLRE_USER, 'X-API-PUBKEY': process.env.MOOLRE_PUBKEY, 'Idempotency-Key': 'PAY-' + order.id },
    body: JSON.stringify({
      type: 1, channel: order.network, currency: 'GHS', payer: order.payerPhone,
      amount: order.collectAmount,          // premium plus any fee you pass on, see below
      externalref: 'PAY-' + order.id, accountnumber: WALLET,
    }),
  }).then((r) => r.json());
}

// 2. Moolre calls your webhook (payment.succeeded, data.txstatus 1). Only then sell.
const crypto = require('node:crypto');
function verifySignature(header, raw) {            // X-Moolre-Signature: t=<unix>,v1=<hex>, over t + "." + the raw body
  const parts = Object.fromEntries(String(header || '').split(',').map((p) => p.trim().split('=', 2)));
  const t = Number(parts.t);
  if (!Number.isInteger(t) || !parts.v1 || Math.abs(Date.now() / 1000 - t) > 300) return false;
  const expected = crypto.createHmac('sha256', process.env.MOOLRE_WALLET_SECRET).update(t + '.' + raw).digest('hex');
  const a = Buffer.from(expected), b = Buffer.from(parts.v1);
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

app.post('/webhooks/moolre', express.raw({ type: '*/*' }), async (req, res) => {
  const raw = req.body.toString('utf8');
  if (!verifySignature(req.get('X-Moolre-Signature'), raw)) return res.sendStatus(400);
  res.sendStatus(200);                                              // answer fast, work after
  const event = JSON.parse(raw);
  if (event.event !== 'payment.succeeded' || event.data.txstatus !== 1) return;
  const order = await db.orders.findByPaymentRef(event.data.externalref);
  if (!order || order.state !== 'awaiting_payment') return;         // unknown, or a repeat (event_id is the same on retries)
  await db.orders.update(order.id, { state: 'paid', credited: event.data.value });
  await sellPolicy(order);                                          // steps 5 to 7
});
```

- [Mobile Money Collection](https://docs.moolre.com/api/payments/initiate)
- [Collect payments, step by step](https://docs.moolre.com/guides/collect-payments)
- [Payment webhook](https://docs.moolre.com/api/payments/webhook)

## Check that the wallet can pay

The balance check is a safeguard, not a reservation: another sale can spend the money between the check and the purchase. Treat IS13 as a normal outcome (nothing is charged) and top up.

```curl
curl https://api.moolre.com/open/account/status \
  -H "Content-Type: application/json" \
  -H "X-API-USER: $MOOLRE_USER" \
  -H "X-API-KEY: $MOOLRE_KEY" \
  -d '{
    "type": 1,
    "accountnumber": "100000100002"
  }'
```

```nodejs
// The wallet must hold the full premium before you sell (IS13 otherwise).
async function walletCovers(premium) {
  const reply = await call('/open/account/status', { type: 1, accountnumber: WALLET });
  return reply.status == 1 && Number(reply.data.balance) >= Number(premium);
}
```

- [Account Status](https://docs.moolre.com/api/accounts/status)

## 5. Buy the policy with an idempotent externalref

Create the policy reference when you create the order, store it, and use that same value as externalref on every attempt to buy this one policy. It must be unique within your wallet and at most 128 characters; INS-<your order id> works. That reference is what makes the purchase idempotent: a second request with it is refused (ASL08, whatever else the body says), never charges again and does not return the first sale, so read that with Sales Status. Also send it as the Idempotency-Key header: a repeat with the same key returns the first response.

The body carries the premium from the quote, the policy type and cover, the start and end dates as DD/MM/YYYY (the cover runs 12 months, so the end date is one day short of a year after the start), the customer, and the motor object built from the VIN lookup: modelno, modeldesc, bodytype, engcc, tonnage and noseats from best_match, the VIN as chasno, and the year of manufacture, colour, registration number and certificate reference from the registration. If a field is wrong the reply is IS06 with errors naming every invalid field, and nothing is charged.

The insurer can take up to a minute to answer, so set your own timeout above 62 seconds. A timeout is not a failure: it means you do not know yet.

| Reply | txstatus | Meaning | Do |
| --- | --- | --- | --- |
| IS20 | 1 | Policy issued | Read data.policy and deliver it (step 7) |
| IS21 | 0 | The insurer has not answered definitively; the wallet is charged | Wait and check Sales Status (step 6). Do not buy again |
| ASL11 or a timeout | 0 | No readable answer in time; the sale may still go through | The same: pending, check Sales Status |
| IS22 | 2 | Not issued, the charge was refunded | See refunds (step 8) |
| IS23 | 0 | Not issued, the refund is being processed | Keep checking until txstatus 2 |
| IS06, IS10, IS13 and the other refusals | none | Nothing was charged | Fix what the code names and send again with the same externalref |

```curl
curl https://api.moolre.com/open/sales/insurance \
  -H "Content-Type: application/json" \
  -H "X-API-USER: $MOOLRE_USER" \
  -H "X-API-KEY: $MOOLRE_KEY" \
  -H "Idempotency-Key: INS-1001" \
  -d '{
    "type": 1,
    "accountnumber": "100000100002",
    "externalref": "INS-1001",
    "premium": "1250.00",
    "currency": "GHS",
    "policy": {
      "pol_type": "PRIVATE_INDIVIDUAL_X_1",
      "cover_type": "third_party",
      "com_date": "01/12/2026",
      "exp_date": "30/11/2027",
      "sum_insured": 200000,
      "benefits": [],
      "customer": {
        "nationality": "GH",
        "client_type": "I",
        "gender": "M",
        "first_name": "Kwame",
        "last_name": "Mensah",
        "phone_number": "0240000000",
        "ghana_card_no": "GHA-000000000-0",
        "ghana_card_exp_date": "01/01/2030",
        "dob": "01/01/1990",
        "digital_address": "GA-000-0000",
        "home_address": "12 Example Street, Accra",
        "occupation": "Trader"
      },
      "motor": {
        "vehregno": "GR-1234-26",
        "yrmanuf": 2010,
        "color": "WHITE",
        "chasno": "JTDKN3DU0A0000001",
        "certref": "CERT-0001",
        "modelno": "TO23",
        "modeldesc": "TOYOTA PRIUS 1800",
        "bodytype": "SALOON",
        "engcc": 1800,
        "tonnage": ".00",
        "noseats": 5,
        "tariff": 1,
        "vehuse": 1,
        "vehregyear": "2010"
      }
    }
  }'
```

```nodejs
async function purchase(order) {
  const body = {
    type: 1, accountnumber: WALLET, currency: "GHS",
    externalref: order.policyRef,          // fixed for this policy for ever, e.g. INS-<orderId>
    premium: order.premium,                // exactly the quoted premium, as "1250.00"
    policy: order.policy,
  };
  try {
    // the insurer can take up to a minute: wait longer than the API does (62 s)
    return await call('/open/sales/insurance', body, { timeoutMs: 75000, headers: { 'Idempotency-Key': order.policyRef } });
  } catch (e) {
    return { code: 'TIMEOUT', data: null };  // the sale may still go through: treat as pending, never as failed
  }
}
```

- [Sell Insurance](https://docs.moolre.com/api/sales/insurance)

## 6. Handle pending with status polling

Pending is a normal state and never a failure. A purchase is pending when the reply is IS21 or ASL11, when the request timed out, when you got IS30 or ASL06 (unknown, it may be charged), or whenever Sales Status shows txstatus 0. In every one of those cases the one correct action is to look the sale up with Sales Status (idtype 1 and your original externalref) and wait for txstatus 1 or 2.

Poll with a backoff: first after 15 seconds, then 15, 30, 60, 120 and 300 seconds, and then every 5 minutes. Stop after about two hours and hand the sale to support with the request ID and your externalref. There is no need to poll faster than every 15 seconds. The stage field says where the sale is: awaiting_insurer (waiting for the insurer), needs_review (Moolre is checking it), refund_pending (not issued, the refund is on its way), then issued or refunded.

Never send the purchase again with a new externalref while the first one is pending. That is the one mistake that can charge the wallet twice. Only txstatus 2 makes a new purchase safe.

| txstatus | stage | Meaning | Do |
| --- | --- | --- | --- |
| 0 | awaiting_insurer | Waiting for the insurer | Keep polling |
| 0 | needs_review | Moolre is checking the sale | Keep polling; contact support if it stays so for hours |
| 0 | refund_pending | Not issued, refund being processed (IS23, ASS09) | Keep polling until txstatus 2 |
| 1 | issued | Policy issued (ASS01) | Deliver the policy |
| 2 | refunded | Not issued, charge refunded (ASS02) | A new purchase is now safe |
| 3 | none | No sale found for that lookup | Check the wallet and the reference. Do not buy again until you know |

```curl
curl https://api.moolre.com/open/sales/status \
  -H "Content-Type: application/json" \
  -H "X-API-USER: $MOOLRE_USER" \
  -H "X-API-KEY: $MOOLRE_KEY" \
  -d '{
    "type": 1,
    "accountnumber": "100000100002",
    "idtype": 1,
    "id": "INS-1001"
  }'
```

```nodejs
const DELAYS = [15, 15, 30, 60, 120, 300];        // seconds; after that every 300 s for about 2 hours
const sleep = (s) => new Promise((r) => setTimeout(r, s * 1000));

async function waitForFinal(policyRef) {
  const give_up_at = Date.now() + 2 * 60 * 60 * 1000;
  for (let i = 0; Date.now() < give_up_at; i++) {
    await sleep(DELAYS[Math.min(i, DELAYS.length - 1)]);
    const r = await call('/open/sales/status', { type: 1, accountnumber: WALLET, idtype: 1, id: policyRef });
    const tx = r.data && r.data.txstatus;
    if (tx === 1 || tx === 2) return r;           // issued, or not issued and refunded: final
    // tx 0: awaiting_insurer, needs_review or refund_pending. Pending is not a failure. Keep waiting.
    // tx 3 or a failed lookup: not found. Check the wallet and the reference, do not buy again.
  }
  return null; // still pending after 2 hours: hand it to support with the request ID, do not resell
}
```

- [Sales Status](https://docs.moolre.com/api/sales/status)

## 7. Read the policy and deliver it to the customer

When txstatus is 1 the reply (and every later Sales Status call) carries data.policy: the policy number (pol_no), the certificate link (certificate_url), the road sticker number and link (sticker_no, sticker_url) and the brown card link (brown_card_url). A link is null when the insurer has not supplied it yet; do not send a broken link, read Sales Status again a little later.

Store the policy in your records, then deliver it to the customer the way they will actually receive it: an SMS or WhatsApp message with the policy number and the certificate link, an e-mail, or a printout at the counter. Moolre does not message your customer for you.

```json
{
  "pol_no": "POLICY-NUMBER",
  "certificate_url": "https://example.com/certificate",
  "sticker_no": "STICKER-NUMBER",
  "sticker_url": "https://example.com/sticker",
  "brown_card_url": "https://example.com/brown-card"
}
```

```nodejs
function policyLinks(statusReply) {
  const p = statusReply.data.policy;            // null until the policy is issued
  if (!p) return null;
  return {
    policyNumber: p.pol_no,
    certificate: p.certificate_url,              // each link can be null when the insurer has not supplied it:
    sticker: p.sticker_url, stickerNo: p.sticker_no, // read Sales Status again later instead of sending a broken link
    brownCard: p.brown_card_url,
  };
}

// Deliver it yourself: SMS, WhatsApp or e-mail, and keep a copy in your records.
await notifyCustomer(order.customerPhone,
  'Your motor policy ' + links.policyNumber + ' is active. Certificate: ' + links.certificate);
```

- [Send SMS](https://docs.moolre.com/api/sms/send)
- [Sales Status](https://docs.moolre.com/api/sales/status)

## 8. Handle refunds

When the insurer refuses a policy the charge is returned to your wallet automatically: the reply is IS22 (txstatus 2, stage refunded) and refundid identifies the refund. If the refund cannot be made straight away the sale shows IS23 (or ASS09 in Sales Status, txstatus 0 with stage refund_pending) and the refund is retried; it is never marked failed in the meantime. Keep polling until txstatus is 2.

The wallet is made whole, but your customer's payment is not returned by Moolre: collections are not reversed for you. Decide what to do with the customer's money and tell them: sell again with a new externalref after fixing the cause (a new policy reference, the same customer payment), or pay the customer back yourself with a Mobile Money transfer. Moolre has no function to cancel or refund a policy that was issued; contact Moolre Support.

```json
{
  "status": "0",
  "code": "IS22",
  "message": "The policy could not be issued. You have not been charged.",
  "data": {
    "txstatus": 2,
    "stage": "refunded",
    "externalref": "INS-1001",
    "premium": "1250.00",
    "charged": "1250.00",
    "refundid": 123456790,
    "policy": null,
    "provider_message": "Policy could not be created"
  },
  "go": null,
  "meta": {
    "requestid": "req_c68f4c66115c26725c796242",
    "notices": []
  }
}
```

```nodejs
async function onFinal(order, r) {
  const d = r.data;
  if (d.txstatus === 1) return issue(order, d);                      // deliver the policy
  if (d.txstatus === 2) {                                            // IS22 / ASS02: charge refunded to your wallet (refundid)
    await db.orders.update(order.id, { state: 'refunded', refundId: d.refundid });
    return offerCustomer(order);                                     // pay the customer back, or sell again with a NEW reference
  }
  // d.stage === 'refund_pending' (IS23 / ASS09): not issued, refund on its way. Keep polling until txstatus 2.
}
```

- [Initiate Transfer](https://docs.moolre.com/api/transfers/initiate)

## 9. Renew a policy by its policy number

A renewal is Sell Insurance with type 2, the policy number to renew and the payment date (DD/MM/YYYY). Each renewal needs its own new externalref (INS-1001-R1, INS-1001-R2) and its own collection from the customer. There is no quote for a renewal: send the renewal premium that is due, and know that the amount you send is the amount charged.

A renewal behaves exactly like a new policy from there: IS20 issued, IS21 or ASL11 pending, then Sales Status until txstatus 1 or 2, then the updated certificate and sticker links, and the same 10% commission when it is issued.

```curl
curl https://api.moolre.com/open/sales/insurance \
  -H "Content-Type: application/json" \
  -H "X-API-USER: $MOOLRE_USER" \
  -H "X-API-KEY: $MOOLRE_KEY" \
  -H "Idempotency-Key: INS-1001-R1" \
  -d '{
    "type": 2,
    "accountnumber": "100000100002",
    "externalref": "INS-1001-R1",
    "premium": "1250.00",
    "currency": "GHS",
    "policy": {
      "pol_no": "POLICY-NUMBER",
      "payment_date": "01/12/2027"
    }
  }'
```

```nodejs
async function renew(polNo, renewalPremium, paymentDate, renewalRef) {
  // Collect renewalPremium from the customer first (step 4). The amount you send is the amount charged.
  return call('/open/sales/insurance', {
    type: 2, accountnumber: WALLET, currency: 'GHS',
    externalref: renewalRef,                 // a new reference for every renewal, e.g. INS-1001-R1
    premium: renewalPremium,                 // the renewal premium due, "1250.00"
    policy: { pol_no: polNo, payment_date: paymentDate }, // DD/MM/YYYY
  }, { timeoutMs: 75000, headers: { "Idempotency-Key": renewalRef } });
  // then follow it exactly like a new policy: IS20, IS21, ASL11, waitForFinal(renewalRef)
}
```

## 10. Commission and reconciliation

You are charged the full premium and paid a 10% commission on every issued policy, new or renewal. The commission is a separate credit to the same wallet, made after the policy is issued, so it is not netted from the premium. A policy that is not issued earns none.

Sales Status shows it for every sale: commission is the amount (0.00 until the policy is issued) and commission_status is paid, pending or null. Pending means the credit has not been made yet and will be paid without any action from you; null means there is nothing to pay (the policy is not issued). Do not treat a pending commission as lost.

Reconcile every night. For each order in your database that is not final, and each issued policy whose commission is not yet paid, read Sales Status with the original externalref and update your records. Match your wallet statement the same way: one premium debit and, once issued, one commission credit per policy.

```curl
curl https://api.moolre.com/open/sales/status \
  -H "Content-Type: application/json" \
  -H "X-API-USER: $MOOLRE_USER" \
  -H "X-API-KEY: $MOOLRE_KEY" \
  -d '{
    "type": 1,
    "accountnumber": "100000100002",
    "idtype": 1,
    "id": "INS-1001"
  }'
```

```json
{
  "status": "1",
  "code": "ASS01",
  "message": "Policy Issued",
  "data": {
    "txstatus": 1,
    "stage": "issued",
    "reference": "SALE-REFERENCE",
    "transactionid": 123456789,
    "externalref": "INS-1001",
    "accountnumber": "100000100002",
    "premium": "1250.00",
    "charged": "1250.00",
    "commission": "125.00",
    "commission_status": "paid",
    "refundid": null,
    "provider_message": "Policy created",
    "policy": {
      "pol_no": "POLICY-NUMBER",
      "certificate_url": "https://example.com/certificate",
      "sticker_no": "STICKER-NUMBER",
      "sticker_url": "https://example.com/sticker",
      "brown_card_url": "https://example.com/brown-card"
    },
    "product": "insurance",
    "network": "enterprise",
    "cover_code": "T",
    "thirdpartyref": "POLICY-NUMBER"
  },
  "go": null,
  "meta": {
    "requestid": "req_c68f4c66115c26725c796242",
    "notices": []
  }
}
```

```nodejs
// Nightly: every policy that is not final in your records, and every issued policy whose commission is not paid yet.
async function reconcile() {
  for (const order of await db.orders.open()) {
    const r = await call('/open/sales/status', { type: 1, accountnumber: WALLET, idtype: 1, id: order.policyRef });
    const d = r.data || {};
    if (d.txstatus === 1) {
      await db.orders.update(order.id, {
        state: 'issued', policy: d.policy,
        commission: d.commission, commissionStatus: d.commission_status, // 'paid' | 'pending'
      });
    } else if (d.txstatus === 2) {
      await db.orders.update(order.id, { state: 'refunded', refundId: d.refundid });
    }                                                                  // 0: still pending, 3: not found: flag it
  }
}
```

- [List Transactions](https://docs.moolre.com/api/accounts/transactions)

## Error handling: every code a client must handle

Codes are application codes in the response body (status, code, message, data), not HTTP statuses. Branch on code, show message to people, and use data to find the field to fix. The full tables are in Errors and status codes; these are the ones this flow meets.

| Code | Meaning | What your client does |
| --- | --- | --- |
| ASN00, ASQ00, ASV00, ASC00 | Authentication error | Stop. Check the username, the private key and the accountnumber |
| IQ02, IS02 | Not authorised | accountnumber is not your own wallet, or the request did not use your credentials. Stop |
| IQ04, IS07 | The wallet is not a registered insurance sales agent (or is not a GHS wallet) | Register the wallet for Insurance (see Before you start) or contact Moolre Support |
| IS08 | A problem with your agent setup | Contact Moolre Support. Nothing is charged |
| ASN01, IQ11 | Invalid VIN | Ask for the VIN again |
| IQ12, IQ13, IQ24 | VIN not decoded, no insurer model, or only partly decoded | Use the vehicle search with data.fallback.suggested (step 2b) |
| ASN05, ASQ05, ASV05, IQ09, ASN06, IQ30 | No readable answer, or an unknown error, on a look-up | Try again with a short delay; nothing was charged |
| IQ10, IS09 | The insurer has no price | Check the start date and seats, or choose another cover; try again later |
| ASQ01, ASQ02, ASV01 to ASV03, IQ05 to IQ08 | A look-up field is missing or invalid | Fix the field named in data |
| ASL16, ASL17, IS03, IS04, IS05 | The purchase request is incomplete: premium, policy, type or externalref | Fix the request. Nothing is charged |
| IS06 | The policy details are invalid | Read errors: it lists every invalid field by its path. Fix them all, send again with the same externalref. Nothing is charged |
| IS10 | The premium is not the current price | Quote again, collect the difference if the price rose, send the new premium. Nothing is charged |
| IS13 | The wallet balance is below the premium | Top up the wallet and send again with the same externalref. Nothing is charged |
| IS01, IS11, IS12, IS14, IS17 | Sales are busy or unavailable for a moment | Wait and send again with the same externalref. Nothing was charged |
| ASL08, IS15 | The externalref is missing or already used | If this is your own repeat, read Sales Status with it; never invent a new reference to get past it. Use a new one only for a different policy |
| IS16 | The same request is being processed in parallel | Do not send it again. Read Sales Status with the externalref |
| IS21, ASL11, ASS03 | Pending | Poll Sales Status. Never a failure |
| ASL06, IS30 | Unknown error: the policy may have been bought | Treat as pending. Read Sales Status with the original externalref |
| IS20, ASS01 | Policy issued | Deliver it and record the commission |
| IS22, ASS02 | Not issued, charge refunded | Record refundid; handle the customer (step 8) |
| IS23, ASS09 | Not issued, refund pending | Keep polling until txstatus 2 |

- [Errors and status codes](https://docs.moolre.com/guides/errors-and-status-codes)

## Idempotency and retry strategy

The rule that keeps money safe is simple: one policy, one externalref, for ever. Everything else follows from it.

| Situation | Same externalref? | Action |
| --- | --- | --- |
| Refused before charging (IS01 to IS17 except IS15 and IS16) | Yes | Fix or wait, then send again |
| Timeout, ASL11, IS21, ASL06, IS30 | Not applicable | Never send again; poll Sales Status |
| Pending after about two hours | Not applicable | Contact support with the request ID and the externalref |
| txstatus 2 (refunded) | No | A new purchase needs a new externalref |
| txstatus 1 (issued) | Not applicable | Done. A second purchase would be a second policy |

1. Create the order, the payment reference (PAY-<order>) and the policy reference (INS-<order>) in your database before you call Moolre, and never regenerate them.
2. Look-ups and quotes (steps 1 to 3) are reads. Retry them as often as you like, with a short delay. They are cached for you, so repeating is cheap.
3. The collection (step 4) is keyed by its own externalref and an Idempotency-Key. A repeat of the same request returns the first answer instead of sending a second prompt. Ask the customer to pay again only with a new payment reference and only after the first is known to have failed.
4. The purchase (step 5) is retried with the same externalref only when nothing was charged: IS01, IS11, IS12, IS14, IS17, IS13 (after a top-up), IS10 (after a new quote and the new premium) and IS06 (after fixing the policy). In those cases a repeat is the same sale.
5. After a timeout, IS21, ASL11, ASL06 or IS30 do not retry the purchase at all. Ask Sales Status with the externalref until it is final.
6. Make your webhook handler idempotent too: move the order from awaiting_payment to paid with one conditional update, and dedupe on event_id, which is the same on every retry of a callback.
7. Only txstatus 2 (or a refusal that said nothing was charged) frees you to send a new purchase, and then it carries a new externalref that you also store.

- [Idempotency and references](https://docs.moolre.com/guides/idempotency-and-references)
- [Safe retries](https://docs.moolre.com/guides/safe-retries)

## Full implementation: Node.js

One file with every call of this guide: the look-ups with retry, the policy builder, the purchase with an idempotent reference and a long timeout, and the status wait with backoff. It uses only the built-in fetch of Node.js 18 or later.

```nodejs
// moolre-insurance.js  (Node.js 18 or later, no dependencies)
const BASE = 'https://api.moolre.com';
const WALLET = process.env.MOOLRE_INSURANCE_WALLET;   // your insurance agent wallet (GHS)

async function call(path, body, { timeoutMs = 40000, headers = {}, key = "private" } = {}) {
  const auth = key === 'public' ? { 'X-API-PUBKEY': process.env.MOOLRE_PUBKEY } : { 'X-API-KEY': process.env.MOOLRE_KEY };
  const res = await fetch(BASE + path, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'X-API-USER': process.env.MOOLRE_USER, ...auth, ...headers },
    body: JSON.stringify(body),
    signal: AbortSignal.timeout(timeoutMs),
  });
  return res.json(); // always an envelope: status, code, message, data. Branch on code.
}

// Look-ups never move money: retry them freely.
async function lookup(path, body) {
  for (let attempt = 1; attempt <= 3; attempt++) {
    try {
      const r = await call(path, body);
      if (!['IQ09', 'ASN05', 'ASQ05', 'ASV05'].includes(r.code)) return r;   // those four mean: try again
    } catch (e) { /* timeout: try again */ }
    await new Promise((ok) => setTimeout(ok, attempt * 2000));
  }
  throw new Error('The insurer look-up is not answering, try again in a moment');
}

const findByVin = (vin, seats) => lookup("/open/sales/insurance/vin", { accountnumber: WALLET, vin, seats });
const searchVehicles = (term, seats, engcc) => lookup("/open/sales/insurance/vehicles", { accountnumber: WALLET, search_term: term, seats, engcc });
const quote = (startDate, seats) => lookup("/open/sales/insurance/quote", { accountnumber: WALLET, start_date: startDate, seats });

const ddmmyyyy = (d) => String(d.getUTCDate()).padStart(2, "0") + "/" + String(d.getUTCMonth() + 1).padStart(2, "0") + "/" + d.getUTCFullYear();

// vehicle: best_match (or the chosen candidate) from the VIN look-up; v: { vin, year, regno, color, ... } from your form
function buildPolicy({ coverType, startDate, customer, vehicle, v }) {
  const start = new Date(startDate + "T00:00:00Z");
  const end = new Date(start); end.setUTCFullYear(end.getUTCFullYear() + 1); end.setUTCDate(end.getUTCDate() - 1);
  return {
    pol_type: 'PRIVATE_INDIVIDUAL_X_1', cover_type: coverType,
    com_date: ddmmyyyy(start), exp_date: ddmmyyyy(end), sum_insured: 200000, benefits: [],
    customer,
    motor: {
      vehregno: v.regno, yrmanuf: v.year, color: v.color, chasno: v.vin, certref: v.certref, vehregyear: String(v.year),
      modelno: vehicle.modelno, modeldesc: vehicle.modeldesc, bodytype: vehicle.bodytype, engcc: vehicle.engcc,
      tonnage: vehicle.tonnage, noseats: vehicle.noseats, tariff: 1, vehuse: 1,
    },
  };
}

async function purchase({ policyRef, premium, policy }) {
  const body = { type: 1, accountnumber: WALLET, currency: 'GHS', externalref: policyRef, premium, policy };
  try {
    return await call('/open/sales/insurance', body, { timeoutMs: 75000, headers: { 'Idempotency-Key': policyRef } });
  } catch (e) {
    return { code: 'TIMEOUT' };   // may still go through: pending, never failed, never resent with a new reference
  }
}

const status = (policyRef) => call("/open/sales/status", { type: 1, accountnumber: WALLET, idtype: 1, id: policyRef });

async function waitForFinal(policyRef) {
  const delays = [15, 15, 30, 60, 120, 300];
  const stop = Date.now() + 2 * 60 * 60 * 1000;
  for (let i = 0; Date.now() < stop; i++) {
    await new Promise((ok) => setTimeout(ok, delays[Math.min(i, delays.length - 1)] * 1000));
    const r = await status(policyRef);
    const tx = r.data && r.data.txstatus;
    if (tx === 1 || tx === 2) return r;
  }
  return null; // still pending: ask support with the request ID, do not resell
}

module.exports = { call, findByVin, searchVehicles, quote, buildPolicy, purchase, status, waitForFinal };
```

```python
# moolre_insurance.py  (Python 3.9 or later, pip install requests)
import os, time, datetime, requests

BASE = "https://api.moolre.com"
WALLET = os.environ["MOOLRE_INSURANCE_WALLET"]  # your insurance agent wallet (GHS)


def call(path, body, timeout=40, headers=None, key="private"):
    auth = {"X-API-PUBKEY": os.environ["MOOLRE_PUBKEY"]} if key == "public" else {"X-API-KEY": os.environ["MOOLRE_KEY"]}
    h = {"Content-Type": "application/json", "X-API-USER": os.environ["MOOLRE_USER"], **auth, **(headers or {})}
    return requests.post(BASE + path, json=body, headers=h, timeout=timeout).json()  # an envelope: branch on code


def lookup(path, body):
    """Look-ups never move money: retry them freely."""
    for attempt in range(1, 4):
        try:
            r = call(path, body)
            if r.get("code") not in ("IQ09", "ASN05", "ASQ05", "ASV05"):  # those four mean: try again
                return r
        except requests.RequestException:
            pass
        time.sleep(attempt * 2)
    raise RuntimeError("The insurer look-up is not answering, try again in a moment")


def find_by_vin(vin, seats=None):
    body = {"accountnumber": WALLET, "vin": vin}
    if seats:
        body["seats"] = seats  # optional: without it 5 is assumed and a warning says so
    return lookup("/open/sales/insurance/vin", body)


def search_vehicles(term, seats, engcc):
    return lookup("/open/sales/insurance/vehicles", {"accountnumber": WALLET, "search_term": term, "seats": seats, "engcc": engcc})


def quote(start_date, seats):
    return lookup("/open/sales/insurance/quote", {"accountnumber": WALLET, "start_date": start_date, "seats": seats})


def build_policy(cover_type, start_date, customer, vehicle, v):
    start = datetime.date.fromisoformat(start_date)
    end = start.replace(year=start.year + 1) - datetime.timedelta(days=1)  # (29 February: use 28 February)
    return {
        "pol_type": "PRIVATE_INDIVIDUAL_X_1", "cover_type": cover_type,
        "com_date": start.strftime("%d/%m/%Y"), "exp_date": end.strftime("%d/%m/%Y"), "sum_insured": 200000, "benefits": [],
        "customer": customer,
        "motor": {
            "vehregno": v["regno"], "yrmanuf": v["year"], "color": v["color"], "chasno": v["vin"], "certref": v["certref"], "vehregyear": str(v["year"]),
            "modelno": vehicle["modelno"], "modeldesc": vehicle["modeldesc"], "bodytype": vehicle["bodytype"], "engcc": vehicle["engcc"],
            "tonnage": vehicle["tonnage"], "noseats": vehicle["noseats"], "tariff": 1, "vehuse": 1,
        },
    }


def purchase(policy_ref, premium, policy):
    body = {"type": 1, "accountnumber": WALLET, "currency": "GHS", "externalref": policy_ref, "premium": premium, "policy": policy}
    try:
        return call("/open/sales/insurance", body, timeout=75, headers={"Idempotency-Key": policy_ref})
    except requests.RequestException:
        return {"code": "TIMEOUT"}  # may still go through: pending, never failed, never resent with a new reference


def status(policy_ref):
    return call("/open/sales/status", {"type": 1, "accountnumber": WALLET, "idtype": 1, "id": policy_ref})


def wait_for_final(policy_ref):
    delays = [15, 15, 30, 60, 120, 300]
    stop = time.time() + 2 * 60 * 60
    i = 0
    while time.time() < stop:
        time.sleep(delays[min(i, len(delays) - 1)])
        i += 1
        r = status(policy_ref)
        if (r.get("data") or {}).get("txstatus") in (1, 2):
            return r
    return None  # still pending: ask support with the request ID, do not resell
```

```php
<?php
// moolre_insurance.php  (PHP 8 with the curl extension)
const BASE = "https://api.moolre.com";

function call(string $path, array $body, int $timeout = 40, array $headers = [], string $key = "private"): ?array
{
    $auth = $key === "public" ? "X-API-PUBKEY: " . getenv("MOOLRE_PUBKEY") : "X-API-KEY: " . getenv("MOOLRE_KEY");
    $h = array_merge(["Content-Type: application/json", "X-API-USER: " . getenv("MOOLRE_USER"), $auth], $headers);
    $ch = curl_init(BASE . $path);
    curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($body), CURLOPT_HTTPHEADER => $h,
        CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => $timeout]);
    $raw = curl_exec($ch);
    curl_close($ch);
    return $raw === false ? null : json_decode($raw, true); // null: timeout or unreadable
}

// Look-ups never move money: retry them freely.
function lookup(string $path, array $body): array
{
    for ($attempt = 1; $attempt <= 3; $attempt++) {
        $r = call($path, $body);
        if ($r !== null && !in_array($r["code"] ?? "", ["IQ09", "ASN05", "ASQ05", "ASV05"], true)) {
            return $r; // those four mean: try again
        }
        sleep($attempt * 2);
    }
    throw new RuntimeException("The insurer look-up is not answering, try again in a moment");
}

function findByVin(string $wallet, string $vin, ?int $seats = null): array
{
    $body = ["accountnumber" => $wallet, "vin" => $vin];
    if ($seats) { $body["seats"] = $seats; } // optional: without it 5 is assumed and a warning says so
    return lookup("/open/sales/insurance/vin", $body);
}

function searchVehicles(string $wallet, string $term, int $seats, int $engcc): array
{
    return lookup("/open/sales/insurance/vehicles", ["accountnumber" => $wallet, "search_term" => $term, "seats" => $seats, "engcc" => $engcc]);
}

function quote(string $wallet, string $startDate, int $seats): array
{
    return lookup("/open/sales/insurance/quote", ["accountnumber" => $wallet, "start_date" => $startDate, "seats" => $seats]);
}

function purchase(string $wallet, string $policyRef, string $premium, array $policy): array
{
    $body = ["type" => 1, "accountnumber" => $wallet, "currency" => "GHS", "externalref" => $policyRef, "premium" => $premium, "policy" => $policy];
    // null = timeout: the sale may still go through. Pending, never failed, never resent with a new reference.
    return call("/open/sales/insurance", $body, 75, ["Idempotency-Key: " . $policyRef]) ?? ["code" => "TIMEOUT"];
}

function salesStatus(string $wallet, string $policyRef): ?array
{
    return call("/open/sales/status", ["type" => 1, "accountnumber" => $wallet, "idtype" => 1, "id" => $policyRef]);
}

function waitForFinal(string $wallet, string $policyRef): ?array
{
    $delays = [15, 15, 30, 60, 120, 300];
    $stop = time() + 2 * 3600;
    for ($i = 0; time() < $stop; $i++) {
        sleep($delays[min($i, count($delays) - 1)]);
        $r = salesStatus($wallet, $policyRef);
        if (in_array($r["data"]["txstatus"] ?? null, [1, 2], true)) { return $r; }
    }
    return null; // still pending: ask support with the request ID, do not resell
}
```

## A minimal end-to-end script

The script below uses the implementation above to sell one policy from a VIN to a policy number: look up the vehicle (with the fall-back), quote, collect the premium from the customer, buy with a fixed reference, wait out a pending result and print the policy and commission. In production the payment wait is your webhook and the order state lives in your database; the script polls Payment Status instead so that it can run on its own. Set the environment variables, put real customer and vehicle details in order and run it against a wallet with a small test cover.

```nodejs
// sell-policy.js: one motor policy from VIN to policy number. Run: node sell-policy.js
// Needs moolre-insurance.js (previous section) and MOOLRE_USER, MOOLRE_KEY, MOOLRE_PUBKEY, MOOLRE_INSURANCE_WALLET.
const m = require('./moolre-insurance');

const order = {
  id: '1001', vin: 'JTDKN3DU0A0000001', seats: 5, startDate: '2026-12-01', coverType: 'third_party',
  payerPhone: '0240000001', network: 'MTN',
  customer: { nationality: 'GH', client_type: 'I', gender: 'M', first_name: 'Kwame', last_name: 'Mensah', phone_number: '0240000000',
    ghana_card_no: 'GHA-000000000-0', ghana_card_exp_date: '01/01/2030', dob: '01/01/1990', digital_address: 'GA-000-0000', home_address: '12 Example Street, Accra' },
  vehicle: { regno: 'GR-1234-26', year: 2010, color: 'WHITE', certref: 'CERT-0001' },
};

(async () => {
  // 1. VIN look-up, with the fall-back to the vehicle search
  const v = await m.findByVin(order.vin, order.seats);
  let vehicle = v.code === 'IQ23' ? v.data.best_match : null;
  if (v.code === 'IQ23' && !v.data.confident) console.log('Not sure: check with the agent', v.data.candidates);
  if (v.data && v.data.fallback && (v.code !== 'IQ23' || !v.data.confident)) {
    // IQ24, IQ13 or IQ12: search with what is known; ask the agent for what is missing (fallback.ask_user)
    const f = v.data.fallback.suggested;
    if (f.search_term && f.engcc) {
      const s = await m.searchVehicles(f.search_term, f.seats, f.engcc);
      vehicle = s.data && s.data.vehicles ? s.data.vehicles[0] : vehicle;
    }
  }
  if (!vehicle) throw new Error('Vehicle not found: search it by hand (code ' + v.code + ')');

  // 2. Quote: the premium of the chosen cover, for the same start date and seats as the policy
  const q = await m.quote(order.startDate, order.seats);
  const cover = q.data.covers.find((c) => c.cover_type === order.coverType);
  if (!cover) throw new Error('No price for ' + order.coverType);
  const premium = cover.premium;

  // 3. Collect the premium (plus any fee you pass on) from the customer, into the agent wallet
  const pay = await m.call("/open/transact/payment", {
    type: 1, channel: order.network, currency: 'GHS', payer: order.payerPhone, amount: premium,
    externalref: 'PAY-' + order.id, accountnumber: process.env.MOOLRE_INSURANCE_WALLET,
  }, { key: 'public', headers: { 'Idempotency-Key': 'PAY-' + order.id } });
  console.log('Payment prompt sent:', pay.code, '(the customer approves on their phone)');
  for (;;) {                                  // in production a webhook does this: payment.succeeded
    await new Promise((ok) => setTimeout(ok, 10000));
    const p = await m.call("/open/transact/status", { type: 1, idtype: 1, id: "PAY-" + order.id, accountnumber: process.env.MOOLRE_INSURANCE_WALLET }, { key: "public" });
    if (p.data && p.data.txstatus === 1) break;
    if (p.data && p.data.txstatus === 2) throw new Error('The customer did not pay');
  }

  // 4. Buy. The reference is fixed for this policy: a repeat can never be charged twice.
  const policyRef = 'INS-' + order.id;
  const policy = m.buildPolicy({ coverType: order.coverType, startDate: order.startDate, customer: order.customer, vehicle, v: { ...order.vehicle, vin: order.vin } });
  let r = await m.purchase({ policyRef, premium, policy });
  console.log('Purchase:', r.code);

  // 5. Pending is normal (IS21, ASL11, a timeout): wait for a final answer, never buy again
  if (!r.data || r.data.txstatus !== 1) r = await m.waitForFinal(policyRef);
  if (!r) throw new Error('Still pending after 2 hours: contact support with ' + policyRef);

  // 6. Final
  if (r.data.txstatus === 1) console.log('Issued', r.data.policy, 'commission', r.data.commission, r.data.commission_status);
  else console.log('Not issued, refunded (refundid ' + r.data.refundid + '). Pay the customer back or sell again with a new reference.');
})().catch((e) => { console.error(e.message); process.exit(1); });
```

```python
# sell_policy.py: one motor policy from VIN to policy number. Run: python sell_policy.py
# Needs moolre_insurance.py (previous section) and MOOLRE_USER, MOOLRE_KEY, MOOLRE_PUBKEY, MOOLRE_INSURANCE_WALLET.
import os, time
import moolre_insurance as m

order = {
    "id": "1001", "vin": "JTDKN3DU0A0000001", "seats": 5, "start_date": "2026-12-01", "cover_type": "third_party",
    "payer_phone": "0240000001", "network": "MTN",
    "customer": {"nationality": "GH", "client_type": "I", "gender": "M", "first_name": "Kwame", "last_name": "Mensah",
                 "phone_number": "0240000000", "ghana_card_no": "GHA-000000000-0", "ghana_card_exp_date": "01/01/2030",
                 "dob": "01/01/1990", "digital_address": "GA-000-0000", "home_address": "12 Example Street, Accra"},
    "vehicle": {"regno": "GR-1234-26", "year": 2010, "color": "WHITE", "certref": "CERT-0001"},
}

# 1. VIN look-up, with the fall-back to the vehicle search
v = m.find_by_vin(order["vin"], order["seats"])
vehicle = v["data"]["best_match"] if v["code"] == "IQ23" else None
if v["code"] == "IQ23" and not v["data"]["confident"]:
    print("Not sure: check with the agent", v["data"]["candidates"])
fallback = (v.get("data") or {}).get("fallback")
if fallback and (v["code"] != "IQ23" or not v["data"]["confident"]):
    # IQ24, IQ13 or IQ12: search with what is known; ask the agent for what is missing (fallback["ask_user"])
    f = fallback["suggested"]
    if f["search_term"] and f["engcc"]:
        s = m.search_vehicles(f["search_term"], f["seats"], f["engcc"])
        vehicle = ((s.get("data") or {}).get("vehicles") or [vehicle])[0]
if not vehicle:
    raise SystemExit("Vehicle not found: search it by hand (code %s)" % v["code"])

# 2. Quote: the premium of the chosen cover, for the same start date and seats as the policy
q = m.quote(order["start_date"], order["seats"])
cover = next((c for c in q["data"]["covers"] if c["cover_type"] == order["cover_type"]), None)
if cover is None:
    raise SystemExit("No price for " + order["cover_type"])
premium = cover["premium"]

# 3. Collect the premium (plus any fee you pass on) from the customer, into the agent wallet
pay = m.call("/open/transact/payment", {
    "type": 1, "channel": order["network"], "currency": "GHS", "payer": order["payer_phone"], "amount": premium,
    "externalref": "PAY-" + order["id"], "accountnumber": m.WALLET,
}, key="public", headers={"Idempotency-Key": "PAY-" + order["id"]})
print("Payment prompt sent:", pay["code"], "(the customer approves on their phone)")
while True:  # in production a webhook does this: payment.succeeded
    time.sleep(10)
    p = m.call("/open/transact/status", {"type": 1, "idtype": 1, "id": "PAY-" + order["id"], "accountnumber": m.WALLET}, key="public")
    tx = (p.get("data") or {}).get("txstatus")
    if tx == 1:
        break
    if tx == 2:
        raise SystemExit("The customer did not pay")

# 4. Buy. The reference is fixed for this policy: a repeat can never be charged twice.
policy_ref = "INS-" + order["id"]
policy = m.build_policy(order["cover_type"], order["start_date"], order["customer"], vehicle, {**order["vehicle"], "vin": order["vin"]})
r = m.purchase(policy_ref, premium, policy)
print("Purchase:", r.get("code"))

# 5. Pending is normal (IS21, ASL11, a timeout): wait for a final answer, never buy again
if (r.get("data") or {}).get("txstatus") != 1:
    r = m.wait_for_final(policy_ref)
if r is None:
    raise SystemExit("Still pending after 2 hours: contact support with " + policy_ref)

# 6. Final
if r["data"]["txstatus"] == 1:
    print("Issued", r["data"]["policy"], "commission", r["data"]["commission"], r["data"]["commission_status"])
else:
    print("Not issued, refunded (refundid %s). Pay the customer back or sell again with a new reference." % r["data"]["refundid"])
```

## Before you go live



- [ ] The wallet is registered as an insurance sales agent (a test quote and a test VIN lookup return IQ20 and IQ23, not IQ04).
- [ ] Keys are on your server only, the private key for sales calls and the public key for collections.
- [ ] Covers and policy types come from Insurance Covers, not from a hard-coded list.
- [ ] The VIN lookup handles every reply: confident, not confident, IQ24 (partly decoded), IQ13, IQ12, invalid VIN and a decoder that is not answering, and the vehicle search fallback (data.fallback) works.
- [ ] Seats are asked for when known, and the same value is used in the VIN lookup, the quote and policy.motor.noseats.
- [ ] The premium you collect covers the premium and the collection fee, and the wallet holds the full premium at purchase.
- [ ] You sell only after the payment webhook says txstatus 1, and the webhook handler verifies the signature and ignores repeats.
- [ ] One externalref per policy, created before the first call and stored; the same value is sent as the Idempotency-Key.
- [ ] Your client timeout for the purchase is above 62 seconds, and a timeout is stored as pending, not as failed.
- [ ] Pending is polled with a backoff and never retried as a new purchase; sales that stay pending for hours are escalated with the request ID.
- [ ] Policy numbers and links are stored and delivered to the customer, and a null link is read again later.
- [ ] Refunded sales (IS22) and pending refunds (IS23) have a customer-facing handling process.
- [ ] A nightly reconciliation reads Sales Status for every open order and every unpaid commission, and matches the wallet statement.
- [ ] Support knows where to find the externalref, the policy number and the request ID of a sale.

- [Go-live checklist](https://docs.moolre.com/guides/go-live-checklist)
- [Insurance VIN lookup](https://docs.moolre.com/api/sales/insurance/vin)
- [Sell Insurance](https://docs.moolre.com/api/sales/insurance)
- [Sales Status](https://docs.moolre.com/api/sales/status)

Back to the Moolre AI documentation index