# Kwik Pay Ecommerce Integration Specification (AI Prompt & Context)

> **Context for AI Coding Assistants (Cursor, Claude Code, ChatGPT, GitHub Copilot, Gemini, Windsurf):**  
> Use this document as the single source of truth to implement, debug, or verify Kwik Pay payment gateway integration in any programming language (Node.js, Python, PHP, C#/.NET, Go, Java, Ruby).

---

## 1. Overview & Architecture

Kwik Pay is a Central Bank of Kuwait (CBK) licensed digital payment service provider in Kuwait.

- **Currency:** `KWD` (Kuwaiti Dinar). Amounts are standard decimal numbers (e.g., `1.500` is 1.500 KWD).
- **Architecture:** Server-to-server REST API.
- **Security Rule:** Sensitive secrets (`KWIKPAY_CLIENT_SECRET`, `KWIKPAY_WEBHOOK_SECRET`, OAuth Access Token) **must remain strictly on your backend server**. Never expose them in browser bundles, mobile client apps, or frontend code.
- **Payment Lifecycle:**
  1. Shopper confirms cart -> Shop server calls Kwik Pay API to create payment.
  2. Shop server stores `paymentId` with local order and redirects shopper's browser to `data.paymentUrl`.
  3. Shopper pays via KNET, Visa/Mastercard, or Apple Pay.
  4. Kwik Pay redirects shopper back to your `redirectUrl` with `?merchantRef=...&result=CAPTURED&paymentId=...`.
  5. Kwik Pay POSTs a signed webhook to `callbackUrl` with HMAC-SHA256 signature.
  6. Shop server verifies signature or calls Inquiry API, then marks order paid.

---

## 2. Environments & API Endpoints

| Setting | UAT (Sandbox / Testing) | Production (Live) |
| :--- | :--- | :--- |
| **Merchant Portal** | `https://bptest2.qp.com.kw` | `https://bpl2.kwikpay.com.kw` |
| **API Base URL** | `https://mpostest2.qp.com.kw` (or `https://botest2.qp.com.kw`) | `https://mposl2.kwikpay.com.kw` |

### Required Server Environment Variables
```bash
KWIKPAY_API_BASE="https://mpostest2.qp.com.kw" # UAT or Production base
KWIKPAY_CLIENT_ID="gw_..."                     # From ecommerce terminal
KWIKPAY_CLIENT_SECRET="..."                    # From ecommerce terminal (Server only)
KWIKPAY_TENANT_ID="..."                        # From Kwik Pay representative
KWIKPAY_WEBHOOK_SECRET="..."                   # From ecommerce terminal (Server only)
PUBLIC_BASE_URL="https://shop.example"         # Public HTTPS origin of your shop
```

---

## 3. Terminal & Payment Method Choices

When creating an ECOMMERCE terminal in the Merchant Portal:
- **KNET:** Enables local debit cards (KNET direct & on checkout page).
- **Visa / Mastercard:** Enables local and international debit & credit cards.
- **Apple Pay:** Enables Apple Pay on checkout page.
- **Kwik Pay Wallet:** Enables wallet balance payments.

### The 3 Checkout Options:
1. **Kwik Pay Hosted Checkout:** Omit `paymentMethodCode`. Shopper is presented with KNET, Cards, Apple Pay, and Wallet options.
2. **Direct KNET:** Pass `"paymentMethodCode": "KNET"`. Browser redirects straight to KNET portal (local debit cards only).
3. **Direct Visa / Mastercard:** Pass `"paymentMethodCode": "VISA"`. Browser redirects directly to card entry page.

---

## 4. API Endpoints & Request / Response Formats

### 4.1 Obtain Access Token (OAuth2 Client Credentials)
- **Endpoint:** `POST {KWIKPAY_API_BASE}/api/v1/external/auth/token`
- **Headers:** `Content-Type: application/json`, `Origin: https://shop.example` (if domain-allowlisted)
- **Request Body:**
```json
{
  "grantType": "client_credentials",
  "clientId": "gw_...",
  "clientSecret": "...",
  "tenantId": "..."
}
```
- **Response:**
```json
{
  "success": true,
  "data": {
    "accessToken": "ey...",
    "tokenType": "Bearer",
    "expiresInSeconds": 3600
  }
}
```
*Note: Cache and reuse `accessToken` until shortly before `expiresInSeconds`.*

---

### 4.2 Create Payment
- **Endpoint:** `POST {KWIKPAY_API_BASE}/api/v1/external/channel/ecommerce/payments`
- **Headers:** `Authorization: Bearer {accessToken}`, `Content-Type: application/json`
- **Request Body:**
```json
{
  "amount": 1.500,
  "currencyCode": "KWD",
  "merchantRef": "ORD-100245",
  "redirectUrl": "https://shop.example/checkout/return?merchantRef=ORD-100245",
  "callbackUrl": "https://shop.example/api/kwikpay/callback",
  "udf1": "board:1",
  "paymentMethodCode": "VISA"
}
```
- **Field Specifications:**
  - `amount`: Number > 0, in Kuwaiti Dinars.
  - `currencyCode`: Always `"KWD"`.
  - `merchantRef`: Unique order string (1–80 chars). Do not reuse on retries (returns 409).
  - `redirectUrl`: Your return URL. Always include `merchantRef` in query string. Kwik Pay appends `&result=CAPTURED&paymentId={uuid}`.
  - `callbackUrl`: Public HTTPS webhook URL reachable from Kwik Pay servers.
  - `paymentMethodCode`: Omit for multi-choice checkout, or use `"KNET"`, `"VISA"`.
  - `udf1` - `udf5`: Optional custom strings (max 120 chars each).
- **Response:**
```json
{
  "success": true,
  "data": {
    "paymentId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "paymentUrl": "https://...",
    "status": "INITIATED"
  }
}
```
*Rule: Save `data.paymentId` to your database order record before redirecting customer browser to `data.paymentUrl`.*

---

### 4.3 Handling Customer Return URL
Kwik Pay sends customer back to:
```
https://shop.example/checkout/return?merchantRef=ORD-100245&result=CAPTURED&paymentId=3fa85f64-5717-4562-b3fc-2c963f66afa6&udf1=board:1
```
**Paid Order Rule:** Mark order as paid when ALL THREE conditions are true:
1. `result === "CAPTURED"`
2. `merchantRef` matches an order created by your system.
3. `paymentId` matches the ID previously recorded on that order.

---

### 4.4 Verifying Signed Callback (Webhook)
Kwik Pay sends a POST request with headers:
- `X-KwikPay-Timestamp`: Unix epoch seconds when signed.
- `X-KwikPay-Signature`: `v1=` + hex HMAC-SHA256 of `{timestamp}.{rawBody}` using `KWIKPAY_WEBHOOK_SECRET`.

**Verification Algorithm (Node.js):**
```javascript
const crypto = require("crypto");

function verifyKwikPayWebhook(rawBody, signatureHeader, timestampHeader, webhookSecret) {
  // 1. Anti-replay check: maximum 300s clock drift
  if (Math.abs(Math.floor(Date.now() / 1000) - parseInt(timestampHeader, 10)) > 300) {
    return false;
  }
  // 2. Compute HMAC-SHA256
  const data = `${timestampHeader}.${rawBody}`;
  const expected = "v1=" + crypto.createHmac("sha256", webhookSecret).update(data).digest("hex");
  // 3. Constant-time comparison
  return crypto.timingSafeEqual(Buffer.from(signatureHeader), Buffer.from(expected));
}
```

---

### 4.5 Inquiry API (Status Check)
- **Endpoint:** `GET {KWIKPAY_API_BASE}/api/v1/external/channel/ecommerce/payments/{paymentId}`
- **Headers:** `Authorization: Bearer {accessToken}`
- **Statuses:**
  - `COMPLETED`: Payment succeeded. Confirm amount and `KWD` match before shipping.
  - `CAPTURED`: Paid via bank portal.
  - `PROCESSING` / `INITIATED`: Awaiting customer action.
  - `FAILED` / `EXPIRED`: Transaction failed or timed out.
  - `REVERSED`: Transaction refunded.

---

### 4.6 Refund API
- **Endpoint:** `POST {KWIKPAY_API_BASE}/api/v1/external/channel/ecommerce/payments/{paymentId}/refund`
- **Headers:** `Authorization: Bearer {accessToken}`, `Content-Type: application/json`
- **Request Body:**
```json
{
  "reason": "REVERSE"
}
```
*Note: Full refund only. Only call after Inquiry returns `COMPLETED`. Reason must be `"REVERSE"` or `"CHARGEBACK"`.*

---

## 5. UAT Test Sandbox Cards

| Method | Card Number | Expiry | PIN / CVV | Expected Outcome |
| :--- | :--- | :--- | :--- | :--- |
| **KNET** (KNET1) | `8888880000000001` | `09/30` | PIN: `1234` | `CAPTURED` |
| **Visa** | `4508750015741019` | `01/39` | CVV: `100` | `CAPTURED` |
| **Mastercard** | `5123450000000008` | `01/39` | CVV: `100` | `CAPTURED` |

---

## 6. Common Error Codes & Troubleshooting

- `401 Unauthorized`: Bad `clientId`, `clientSecret`, or `tenantId`.
- `403 Forbidden`: Origin not allowlisted on terminal, terminal not ECOMMERCE/ACTIVE, or custom User-Agent blocked. Send standard `Origin` header.
- `409 Conflict`: `merchantRef` already exists. Generate a fresh ID for every attempt.
- `BR-PAY-HOSTED-SEL-002`: Terminal priority conflict between Visa and Mastercard. Contact Kwik Pay support.
- Webhook signature failure: Ensure using the raw unparsed request body string (do not re-stringify parsed JSON).
