# Unwaani for businesses: collect delivery addresses at checkout

Add an **"Enter your address"** button to your checkout. Your customer picks a saved Unwaani address (map pin, building and entrance photos, floor, delivery notes) or adds a new one. Your server then receives the details and can hand them to your courier as a link or a QR code.

- **Free** for every verified business.
- **White-label** (paid) shows your logo, name and colour to customers who don't use Unwaani yet. Existing Unwaani users always see Unwaani, with your name on the request.
- The customer chooses what to share and can turn it off at any time.

This guide covers everything a business needs. It is published at [unwaani.com/developers](https://unwaani.com/developers). To have an AI coding assistant do the work, give it the [AI integration prompt](ai-integration-prompt.md), served at `https://unwaani.com/developers/ai-integration-prompt.md`. Unwaani's own engineers keep the full reference in section 11 of the API contract.

---

## 1. Get your keys

1. Sign in at [unwaani.com](https://unwaani.com), create your business profile, and submit it for review.
2. Open **Dashboard → Integration** and add:
   - **Redirect URI.** The page on your site that Unwaani sends the customer back to, for example `https://shop.example.com/unwaani/callback`. It must be `https://`. `http://localhost` is allowed for development.
   - **Webhook URL** (optional). Unwaani tells your server here when an address changes or sharing ends.
3. Copy the **client secret** (`uwsk_…`). It is shown once. Keep it on your server only.

You'll use three values:

| Value | Where it lives |
|---|---|
| `client_id` (`uwc_…`) | Public. Used in your web page. |
| `client_secret` (`uwsk_…`) | Server only. Never in a browser, an app or a repository. |
| `webhook_secret` (`whsec_…`) | Server only. Used to check webhook signatures. |

**Sandbox:** until your business is verified, the integration is in sandbox. Everything works, but only your own Unwaani account can connect. Use it to test.

## 2. Add the button

```html
<button id="unwaani-address" type="button"></button>
<script src="https://unwaani.com/sdk/v1/unwaani.js"></script>
<script>
  Unwaani.button("#unwaani-address", {
    clientId: "uwc_…",
    redirectUri: "https://shop.example.com/unwaani/callback",
    onSuccess: async ({ code }) => {
      // Your server swaps the code for the address (step 3).
      const res = await fetch("/unwaani/exchange", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ code }),
      });
      const { address } = await res.json();
      fillCheckout(address); // your own function
    },
    onError: (err) => console.info("Unwaani:", err.code), // "closed", "access_denied"…
  });
</script>
```

- **Desktop:** the SDK opens a popup and resolves with `{ code, state }`.
- **Phones:** it uses a full-page redirect. If the Unwaani app is installed, the app opens.
- **After a redirect:** the customer comes back to `redirectUri?code=…&state=…`. On that page, call `Unwaani.handleRedirect()` to read and check it. If the customer cancelled, it gets `?error=access_denied`.
- **Your own button text:** put text inside the element. An empty button reads "Enter your address".

No JavaScript? Link to `https://unwaani.com/connect?client_id=…&redirect_uri=…&state=…` and handle the redirect on your server.

## 3. Exchange the code (your server)

```bash
curl -X POST https://api.unwaani.com/api/v1/partner/exchange?lang=ar \
  -H "Authorization: Bearer $UNWAANI_CLIENT_SECRET" \
  -H "Content-Type: application/json" \
  -d '{"code": "uwcode_…", "redirect_uri": "https://shop.example.com/unwaani/callback"}'
```

The response is a **grant**:

```json
{
  "id": "2b0c…",
  "status": "active",
  "customer": { "display_name": "Ahmed", "phone": "+201001234567" },
  "address": {
    "location": { "lat": 30.05, "lng": 31.33 },
    "written_address": "مدينة نصر، مبنى ١٢، القاهرة",
    "floor_text": "الطابق ٣", "apartment": "7",
    "delivery": { "where_text": "…", "alerts_text": ["…"], "note": "…" },
    "photos": [ { "url": "…", "thumb_url": "…" } ],
    "instructions": "البيت: البوابة الجانبية، الطابق ٣، شقة ٧. …"
  }
}
```

`customer.phone` can be `null`: some WhatsApp users have a username that hides their number, and they may not have added it to Unwaani. Don't make it required in your order system; use `address.contact_phone` when it is set.

- **The code:** works once and expires after 10 minutes.
- **What to store:** keep **`grant.id`** with the customer. It is how you read the address again.
- **The address itself:** you may store a copy for your order history. Photo and voice-note URLs expire, so read the grant again instead of saving them.
- **Language:** `?lang=` (`ar`, `en`, `es`, `fr`, `ur` or `hi`) sets the language of the `*_text` fields and of `instructions`.

## 4. Use it on later orders

```bash
curl https://api.unwaani.com/api/v1/partner/grants/$GRANT_ID?lang=en \
  -H "Authorization: Bearer $UNWAANI_CLIENT_SECRET"
```

- You always get the customer's current address, including any edits they made since.
- `410 grant_revoked` means the customer turned off sharing. Ask them to connect again.

## 5. Send the address to your courier

```bash
curl -X POST https://api.unwaani.com/api/v1/partner/grants/$GRANT_ID/driver-links \
  -H "Authorization: Bearer $UNWAANI_CLIENT_SECRET" \
  -H "Content-Type: application/json" \
  -d '{"order_ref": "ORD-1042", "expiry": "on_delivery", "lang": "ar"}'
```

You get back:

| Field | What it is |
|---|---|
| `url` | The driver page, with photos, map, Navigate, "I arrived" and "Delivered" |
| `qr_svg_url` and `qr_png_url` | QR codes to print on the order label |
| `message` | Ready-to-send text with the instructions first and the link last, for WhatsApp or SMS |

- **Expiry:** with `on_delivery`, the link closes when the driver taps Delivered.
- **Webhooks:** you get `delivery.arrived` and `delivery.completed`.
- **Status:** `GET /partner/driver-links/{id}` shows the current state, and `POST /partner/driver-links/{id}/close` closes the link.

## 6. Webhooks

Unwaani sends a `POST` to your webhook URL:

```json
{ "id": "evt_…", "type": "grant.updated", "created_at": "…", "data": { "grant": { … } } }
```

| Event | When |
|---|---|
| `grant.created` | A customer connected a new address |
| `grant.updated` | They changed the address, its photos or its voice note. Changes within a minute arrive as one event. |
| `grant.revoked` | Sharing ended. `reason` is `user`, `place_deleted`, `account_deleted`, `partner` or `staff`. Delete what you stored. |
| `delivery.arrived`, `delivery.completed` | The driver tapped "I arrived" or "Delivered" on a driver link |
| `ping` | You pressed "Send test event" in the dashboard |

To verify a webhook, check the `Unwaani-Signature: t=<unix>,v1=<hex>` header. `v1` is HMAC-SHA256 of `"<t>.<raw body>"` with your `webhook_secret`, written as hex. Refuse it when `t` is more than 5 minutes off.

```js
import crypto from "node:crypto";

function verifyUnwaani(rawBody, header, secret) {
  const parts = Object.fromEntries(header.split(",").map((p) => p.trim().split("=")));
  if (Math.abs(Date.now() / 1000 - Number(parts.t)) > 300) return false;
  const expected = crypto.createHmac("sha256", secret).update(`${parts.t}.${rawBody}`).digest("hex");
  return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(parts.v1 || ""));
}
```

```python
import hashlib, hmac, time

def verify_unwaani(raw_body: bytes, header: str, secret: str) -> bool:
    parts = dict(p.strip().split("=", 1) for p in header.split(","))
    if abs(time.time() - int(parts.get("t", 0))) > 300:
        return False
    expected = hmac.new(secret.encode(), f"{parts['t']}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts.get("v1", ""))
```

- **Answering:** reply with any 2xx within 5 seconds, and do the slow work afterwards.
- **Retries:** failed events are retried after 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours and 12 hours.
- **Duplicates:** the same event can arrive twice. Use `id` to ignore repeats.

## 7. White-label

Open **Dashboard → Integration → White-label**, pick monthly or yearly, and pay through ezPayments. Once it's paid:

- New customers who aren't signed in to Unwaani see your logo, your name and your brand colour on the address page.
- Customers who already use Unwaani, on the web or in the app, still see Unwaani, with your name on the request. This is so they don't get confused about who has their address.
- The address page and the driver page show your logo.

**Renewal:** Unwaani emails a renewal link 7 days before the period ends. If it isn't paid, your branding stays for a 7-day grace period, then the page goes back to Unwaani branding. **The integration itself keeps working.**

## Errors

Every error has the same shape: `{"error": {"code": "…", "message": "…"}}`.

| Code | Meaning |
|---|---|
| `invalid_client` (401) | Wrong or rotated client secret |
| `client_disabled` (403) | The integration was turned off. Contact Unwaani support. |
| `invalid_redirect_uri` (400) | The redirect URI isn't registered. It must match exactly. |
| `sandbox_owner_only` (403) | The business isn't verified yet, so only its owner can connect |
| `invalid_code` (400) | The code is unknown, used, expired, from another app, or the PKCE check failed |
| `grant_revoked` (410) | The customer ended sharing |
| `rate_limited` (429) | More than 600 requests a minute. Wait for `Retry-After`. |

## Security checklist

- **The client secret** stays on your server: in environment variables, never in front-end code or Git.
- **The code exchange** happens on your server, never in the browser.
- **The `state` value:** the SDK makes and checks it. If you build the link yourself, check it too.
- **Webhooks:** verify the signature before you trust the body.
- **Revoked grants:** delete what you stored on `grant.revoked`.
- **Customer consent:** use the address only for the customer's orders. They agreed to share it with you, not with others.
