Skip to content

Use Cases

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.

StepCallWhat it gives you
1Insurance CoversThe cover types and policy types you can sell (fixed lists, cache them)
2Insurance VIN lookup (or Insurance Vehicles)The insurer model code of the vehicle, from its VIN
3Insurance QuoteThe premium of each cover for the start date and seats
4Mobile Money Collection and the payment webhookThe premium, in your wallet, paid by the customer
5Sell Insurance (type 1)The purchase, with a unique externalref
6Sales StatusThe final result of a pending purchase
7Sales Status (policy)Policy number, certificate and sticker links to give the customer
8Sell Insurance (type 2)A renewal by policy number
9Sales 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.
CredentialUsed forHeader
UsernameEvery callX-API-USER
Private keyCovers, VIN lookup, Vehicles, Quote, Sell Insurance, Sales Status, Account StatusX-API-KEY
Public keyMobile Money Collection and Payment StatusX-API-PUBKEY

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.

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 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"  }'

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.

ReplyMeaningWhat to do
IQ23, confident trueDecoded and one clear matchShow make, model and year to the customer to confirm, then use best_match
IQ23, confident falseDecoded, several close matches or a loose oneShow candidates and let the agent or customer choose
IQ24Partly 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)
IQ13Decoded, 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
IQ12NHTSA 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 IQ11The VIN is not 17 letters and digits, or contains I, O or QAsk for the VIN again
ASN05, ASN06 or IQ09The decoder or the insurer did not answerWait a moment and ask again. Nothing was charged. After three tries use the vehicle search

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  }'

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).

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 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  }'

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 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"  }'

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 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"  }'

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.

ReplytxstatusMeaningDo
IS201Policy issuedRead data.policy and deliver it (step 7)
IS210The insurer has not answered definitively; the wallet is chargedWait and check Sales Status (step 6). Do not buy again
ASL11 or a timeout0No readable answer in time; the sale may still go throughThe same: pending, check Sales Status
IS222Not issued, the charge was refundedSee refunds (step 8)
IS230Not issued, the refund is being processedKeep checking until txstatus 2
IS06, IS10, IS13 and the other refusalsnoneNothing was chargedFix what the code names and send again with the same externalref

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"      }    }  }'

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.

txstatusstageMeaningDo
0awaiting_insurerWaiting for the insurerKeep polling
0needs_reviewMoolre is checking the saleKeep polling; contact support if it stays so for hours
0refund_pendingNot issued, refund being processed (IS23, ASS09)Keep polling until txstatus 2
1issuedPolicy issued (ASS01)Deliver the policy
2refundedNot issued, charge refunded (ASS02)A new purchase is now safe
3noneNo sale found for that lookupCheck the wallet and the reference. Do not buy again until you know

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"  }'

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.

{  "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"}

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.

{  "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": []  }}

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 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"    }  }'

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 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"  }'

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.

CodeMeaningWhat your client does
ASN00, ASQ00, ASV00, ASC00Authentication errorStop. Check the username, the private key and the accountnumber
IQ02, IS02Not authorisedaccountnumber is not your own wallet, or the request did not use your credentials. Stop
IQ04, IS07The 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
IS08A problem with your agent setupContact Moolre Support. Nothing is charged
ASN01, IQ11Invalid VINAsk for the VIN again
IQ12, IQ13, IQ24VIN not decoded, no insurer model, or only partly decodedUse the vehicle search with data.fallback.suggested (step 2b)
ASN05, ASQ05, ASV05, IQ09, ASN06, IQ30No readable answer, or an unknown error, on a look-upTry again with a short delay; nothing was charged
IQ10, IS09The insurer has no priceCheck the start date and seats, or choose another cover; try again later
ASQ01, ASQ02, ASV01 to ASV03, IQ05 to IQ08A look-up field is missing or invalidFix the field named in data
ASL16, ASL17, IS03, IS04, IS05The purchase request is incomplete: premium, policy, type or externalrefFix the request. Nothing is charged
IS06The policy details are invalidRead errors: it lists every invalid field by its path. Fix them all, send again with the same externalref. Nothing is charged
IS10The premium is not the current priceQuote again, collect the difference if the price rose, send the new premium. Nothing is charged
IS13The wallet balance is below the premiumTop up the wallet and send again with the same externalref. Nothing is charged
IS01, IS11, IS12, IS14, IS17Sales are busy or unavailable for a momentWait and send again with the same externalref. Nothing was charged
ASL08, IS15The externalref is missing or already usedIf 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
IS16The same request is being processed in parallelDo not send it again. Read Sales Status with the externalref
IS21, ASL11, ASS03PendingPoll Sales Status. Never a failure
ASL06, IS30Unknown error: the policy may have been boughtTreat as pending. Read Sales Status with the original externalref
IS20, ASS01Policy issuedDeliver it and record the commission
IS22, ASS02Not issued, charge refundedRecord refundid; handle the customer (step 8)
IS23, ASS09Not issued, refund pendingKeep polling until txstatus 2

Idempotency and retry strategy

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

  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.
SituationSame externalref?Action
Refused before charging (IS01 to IS17 except IS15 and IS16)YesFix or wait, then send again
Timeout, ASL11, IS21, ASL06, IS30Not applicableNever send again; poll Sales Status
Pending after about two hoursNot applicableContact support with the request ID and the externalref
txstatus 2 (refunded)NoA new purchase needs a new externalref
txstatus 1 (issued)Not applicableDone. A second purchase would be a second policy

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.

// 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 formfunction 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 };

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.

// 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); });

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.