> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cloudpay.africa/llms.txt
> Use this file to discover all available pages before exploring further.

# Quickstart

> From a test key to a paid M-Pesa prompt in five minutes.

By the end of this page you will have checked your key, sent an M-Pesa prompt to your own phone and read the result.

**You need:**

* A test key (`sk_test_…`) with the `read` and `collect` scopes. Create one in the dashboard under **Settings → API keys** while the environment switcher shows **Development**.
* Your merchant ID: the UUID in the dashboard address bar, `/m/{merchantID}`.
* A Safaricom or Airtel phone you hold.

> [!NOTE]
>
> Development prompts are **real**: they ring a real phone and move real money, capped at KES 100 per prompt. Use your own phone. The money is kept and moves to Production when your business is approved.

**1. Set your key and merchant**

```bash theme={null}
export CLOUDPAY_API=https://api.cloudpay.africa/cloudpay
export CLOUDPAY_KEY=sk_test_...
export MERCHANT_ID=757b7fe6-e214-4e3c-accf-3e40c93cfb5e
```

Keep keys server side, in a secret manager or environment variable. Never ship them in a browser, a mobile app or git.

**2. Check the key works**

```bash theme={null}
curl -i $CLOUDPAY_API/v1/merchants/$MERCHANT_ID \
  -H "Authorization: Bearer $CLOUDPAY_KEY"
```

Expect `200`, the header `X-CloudPay-Environment: test`, and your business under `data.merchant`. `data.actor` shows the key that answered.

| You got | Fix |
| - | - |
| `401 invalid_api_key` | The key is wrong or revoked. Copy it again; it is shown only once. |
| `403 permission_denied` | The merchant ID isn't the one the key belongs to. |
| `404` `no Route matched with those values` | The URL is missing `/cloudpay`. Use `$CLOUDPAY_API` exactly as above. |

**3. Send a prompt**

```bash cURL theme={null}
curl -X POST $CLOUDPAY_API/v1/merchants/$MERCHANT_ID/collections \
  -H "Authorization: Bearer $CLOUDPAY_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "msisdn": "0712345678",
    "amount": 1000,
    "reference": "order-1042",
    "idempotency_key": "order-1042-attempt-1"
  }'
```

```js Node.js theme={null}
const API = process.env.CLOUDPAY_API, KEY = process.env.CLOUDPAY_KEY, MID = process.env.MERCHANT_ID;

const res = await fetch(`${API}/v1/merchants/${MID}/collections`, {
  method: "POST",
  headers: { Authorization: `Bearer ${KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({
    msisdn: "0712345678",
    amount: 1000, // cents: KES 10.00
    reference: "order-1042",
    idempotency_key: "order-1042-attempt-1",
  }),
});
const { data, errors } = await res.json();
if (errors) throw new Error(`${errors.code}: ${errors.message}`);
console.log(data.id, data.status); // "…", "initiated"
```

```python Python theme={null}
import os, requests

API, KEY, MID = os.environ["CLOUDPAY_API"], os.environ["CLOUDPAY_KEY"], os.environ["MERCHANT_ID"]

r = requests.post(f"{API}/v1/merchants/{MID}/collections", timeout=30,
    headers={"Authorization": f"Bearer {KEY}"},
    json={"msisdn": "0712345678", "amount": 1000,  # cents: KES 10.00
          "reference": "order-1042", "idempotency_key": "order-1042-attempt-1"})
body = r.json()
if not body["status"]["ok"]:
    raise RuntimeError(f'{body["errors"]["code"]}: {body["errors"]["message"]}')
payment = body["data"]
print(payment["id"], payment["status"])  # "…", "initiated"
```

`amount` is in **cents** (`1000` is KES 10.00) and must be whole shillings. The answer comes back at once with `202`:

```json theme={null}
{
  "status": { "ok": true, "code": 202, "desc": "Accepted" },
  "data": {
    "id": "c9675a6e-e06e-4207-a9a9-fb7cf898a601",
    "status": "initiated",
    "provider": "paystack",
    "method": "charge",
    "msisdn": "254712345678",
    "amount": 1000,
    "fee": 10,
    "net": 990,
    "reference": "order-1042"
  }
}
```

The phone shows a prompt. The customer enters their PIN on their own phone; Cloudpay never sees it. `provider` and `method` show which rail sent it (see [Rails and networks](https://docs.cloudpay.africa/guides/rails.md)).

**4. Wait for the result**

```bash cURL theme={null}
curl $CLOUDPAY_API/v1/merchants/$MERCHANT_ID/collections/$ID \
  -H "Authorization: Bearer $CLOUDPAY_KEY"
```

```js Node.js theme={null}
async function waitFor(id) {
  for (let i = 0; i < 40; i++) {
    const r = await fetch(`${API}/v1/merchants/${MID}/collections/${id}`, { headers: { Authorization: `Bearer ${KEY}` } });
    const { data } = await r.json();
    if (["completed", "failed"].includes(data.status)) return data;
    await new Promise((ok) => setTimeout(ok, 5000));
  }
  return null; // still pending or in review: check again from a background job
}
```

```python Python theme={null}
import time

def wait_for(pid):
    for _ in range(40):
        p = requests.get(f"{API}/v1/merchants/{MID}/collections/{pid}", timeout=30,
                         headers={"Authorization": f"Bearer {KEY}"}).json()["data"]
        if p["status"] in ("completed", "failed"):
            return p
        time.sleep(5)
    return None  # still pending or in review: check again from a background job
```

Poll every 3 to 5 seconds; most prompts finish within a minute and the payer has about three. Stop on a final status:

| `status` | Meaning | Do |
| - | - | - |
| `completed` | Paid. `receipt` holds the provider receipt. | Fulfil the order |
| `failed` | Not paid. `failure_category` says why (`cancelled`, `insufficient_funds`, `timeout`…). | Show a friendly message; retry with a **new** key if the customer wants |
| `review` | Cloudpay is checking an unclear outcome. | Keep polling; it ends `completed` or `failed` |

> [!TIP]
>
> A request timed out or your process crashed? Send the **same** request with the **same**`idempotency_key`. You get the original payment back, never a second prompt. See [Idempotency](https://docs.cloudpay.africa/concepts/idempotency.md).

## Next

> [card] [Test your integration](https://docs.cloudpay.africa/testing.md)
>
> Scenarios to try in Development, and the go-live checklist.

> [card] [Rails and networks](https://docs.cloudpay.africa/guides/rails.md)
>
> Which provider prompts which network, and card checkout.

> [card] [Errors](https://docs.cloudpay.africa/errors/overview.md)
>
> A ready-made client that retries safely.

> [card] [API reference](https://docs.cloudpay.africa/api-reference/merchant-rails/collect-from-a-payer-on-the-merchants-collection-rail.md)
>
> Every endpoint and field.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.