Libraries and samples

A small library for each language, and a working example for each framework.

The libraries are not yet published to npm, PyPI or NuGet. Each is a single file with no dependencies, so until they are, copy the file into your project. The libraries and samples are MIT licensed: use and change them freely.

Configuration

Every library and example reads the same three values from your server's environment:

.env
CSHPAY_BASE_URL=https://cshpay.cksolutionshub.com
CSHPAY_API_KEY=cpk_test_...
CSHPAY_WEBHOOK_SECRET=whsec_...

Using a library

Node.js / TypeScript
import { Cshpay } from './cshpay';

const cshpay = new Cshpay();   // reads the three environment variables

const payment = await cshpay.payments.create(
  { amount: 968.62, reference: 'ORDER-14', returnUrl: 'https://your-site.com/thanks' },
  { idempotencyKey: 'ORDER-14' },
);
// redirect the customer to payment.checkoutUrl

// in your webhook route, with the RAW request body:
const event = cshpay.webhooks.constructEvent(rawBody, request.headers.get('Cshpay-Signature'));
if (event.type === 'payment.succeeded') { /* mark event.data.payment.reference paid */ }
Python
from CSHPay import Cshpay

client = Cshpay()   # reads the three environment variables

payment = client.create_payment(amount=968.62, reference="ORDER-14",
                                return_url="https://your-site.com/thanks", idempotency_key="ORDER-14")
# redirect the customer to payment["checkoutUrl"]

# in your webhook route, with the RAW request body:
event = client.construct_event(raw_body, request.headers.get("Cshpay-Signature"))
if event["type"] == "payment.succeeded":
    ...  # mark event["data"]["payment"]["reference"] paid
C#
var cshpay = new CshpayClient();   // reads the three environment variables

var payment = await cshpay.CreatePaymentAsync(
    new CreatePaymentRequest(968.62m, "ORDER-14", "https://your-site.com/thanks"), idempotencyKey: "ORDER-14");
// redirect the customer to payment.CheckoutUrl

// in your webhook route, with the RAW request body:
var evt = cshpay.ConstructEvent(rawBody, Request.Headers["Cshpay-Signature"]);
if (evt.Type == "payment.succeeded") { /* mark evt.Payment.Reference paid */ }

constructEvent verifies the signature and the timestamp and throws if either is wrong, so an event you receive from it is genuine.

The files

Node.js and TypeScript libraryOne file, no dependencies, Node.js 18 or later. Works in Next.js, Express and any other Node.js server.
sdk/node/src/index.ts
/**
 * cshpay for Node.js and TypeScript.
 *
 * One file, no dependencies, Node.js 18 or later (uses the built-in fetch).
 * SERVER ONLY: an API key must never be sent to a browser.
 *
 *   const cshpay = new Cshpay();   // reads CSHPAY_BASE_URL, CSHPAY_API_KEY, CSHPAY_WEBHOOK_SECRET
 *   const payment = await cshpay.payments.create(
 *     { amount: 968.62, reference: 'ORDER-14', returnUrl: 'https://your-site.com/thanks' },
 *     { idempotencyKey: 'ORDER-14' });
 */
import { createHmac, timingSafeEqual } from 'node:crypto';

export type PaymentStatus = 'pending' | 'succeeded' | 'failed' | 'expired' | 'refund_pending' | 'refunded' | 'refund_failed';

export interface Payment {
  id: string;
  object: 'payment';
  mode: 'test' | 'live';
  reference: string;
  /** What you asked for, as a string with two decimals. */
  amount: string;
  currency: string;
  description: string | null;
  customer: { email: string | null; name: string | null };
  status: PaymentStatus;
  /** Where to send the customer to pay. Null once the payment can no longer be paid. */
  checkoutUrl: string | null;
  returnUrl: string;
  metadata: Record<string, string>;
  gateway: {
    order: string | null;
    approvalCode: string | null;
    /** What Kina Bank authorized; can exceed `amount` if the acquirer adds a fee. */
    authorizedAmount: string | null;
    rrn: string | null;
    reference: string | null;
    responseCode: string | null;
    message: string | null;
  };
  paidAt: string | null;
  refundedAt: string | null;
  expiresAt: string | null;
  createdAt: string | null;
}

export interface CreatePaymentInput {
  /** Greater than 0, at most two decimals. */
  amount: number;
  /** Your own id for the order. */
  reference: string;
  /** Where the customer is sent afterwards. https in live mode. */
  returnUrl: string;
  description?: string;
  customer?: { email?: string; name?: string };
  /** Seconds the payment stays payable (300 to 604800). Default one day. */
  expiresIn?: number;
  metadata?: Record<string, string>;
}

export interface KinaFields {
  paymentId: string;
  mode: 'test' | 'live';
  /** Post the fields here. */
  action: string;
  method: 'POST';
  /** Send every one of these, unchanged, as a hidden form input. */
  fields: Record<string, string>;
  kinaScriptUrl: string;
  kinaCssUrl: string;
  /** Ask again after this; Kina Bank rejects older fields. */
  fieldsExpireAt: string;
}

export interface WebhookEndpoint {
  id: string;
  mode: 'test' | 'live';
  url: string;
  description: string | null;
  events: string[];
  secretHint: string;
  active: boolean;
  createdAt: string;
  /** Present only in the response to create. Shown once. */
  secret?: string;
}

export type WebhookEventType = 'payment.succeeded' | 'payment.failed' | 'payment.expired' | 'refund.succeeded' | 'refund.failed';

export interface WebhookEvent {
  /** Stable across redeliveries: store it to ignore duplicates. */
  id: string;
  type: WebhookEventType;
  mode: 'test' | 'live';
  createdAt: string;
  data: { payment: Payment };
}

/** An error response from the API. `code` is stable; `message` is for people. */
export class CshpayError extends Error {
  constructor(
    public readonly status: number,
    public readonly code: string,
    message: string,
    /** Per-field problems, on a VALIDATION error. */
    public readonly fields?: Record<string, string[]>,
  ) {
    super(message);
    this.name = 'CshpayError';
  }
}

/** Thrown by webhooks.constructEvent when a delivery is not genuine. */
export class CshpaySignatureError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'CshpaySignatureError';
  }
}

export interface CshpayOptions {
  /** Default: process.env.CSHPAY_API_KEY */
  apiKey?: string;
  /** Default: process.env.CSHPAY_BASE_URL */
  baseUrl?: string;
  /** Default: process.env.CSHPAY_WEBHOOK_SECRET */
  webhookSecret?: string;
  /** Milliseconds before a request is abandoned. Default 30000. */
  timeoutMs?: number;
}

/**
 * Verify a webhook signature. `rawBody` must be the exact body received, not a
 * re-serialised object. Header format: "t=<unix seconds>,v1=<hex>".
 */
export function verifyWebhookSignature(
  rawBody: string | Buffer,
  signatureHeader: string | null | undefined,
  secret: string,
  toleranceSeconds = 300,
  nowSeconds: number = Math.floor(Date.now() / 1000),
): boolean {
  if (!signatureHeader || !secret) return false;
  const parts = new Map<string, string>();
  for (const p of signatureHeader.split(',')) {
    const i = p.indexOf('=');
    if (i > 0) parts.set(p.slice(0, i).trim(), p.slice(i + 1).trim());
  }
  const t = Number(parts.get('t'));
  const v1 = parts.get('v1') ?? '';
  if (!Number.isInteger(t) || !/^[0-9a-f]{64}$/.test(v1)) return false;
  if (Math.abs(nowSeconds - t) > toleranceSeconds) return false; // stale: possible replay
  const body = typeof rawBody === 'string' ? rawBody : rawBody.toString('utf8');
  const expected = createHmac('sha256', secret).update(`${t}.${body}`, 'utf8').digest();
  return timingSafeEqual(expected, Buffer.from(v1, 'hex'));
}

export class Cshpay {
  private readonly apiKey: string;
  private readonly baseUrl: string;
  private readonly webhookSecret: string | undefined;
  private readonly timeoutMs: number;

  constructor(options: CshpayOptions = {}) {
    this.apiKey = options.apiKey ?? process.env.CSHPAY_API_KEY ?? '';
    this.baseUrl = (options.baseUrl ?? process.env.CSHPAY_BASE_URL ?? '').replace(/\/+$/, '');
    this.webhookSecret = options.webhookSecret ?? process.env.CSHPAY_WEBHOOK_SECRET;
    this.timeoutMs = options.timeoutMs ?? 30_000;
    if (!this.apiKey) throw new Error('cshpay: no API key (set CSHPAY_API_KEY or pass apiKey)');
    if (!this.baseUrl) throw new Error('cshpay: no base URL (set CSHPAY_BASE_URL or pass baseUrl)');
    if (typeof window !== 'undefined') throw new Error('cshpay: this library must only run on a server');
  }

  private async request<T>(method: string, path: string, body?: unknown, headers: Record<string, string> = {}): Promise<T> {
    const res = await fetch(`${this.baseUrl}/api/v1${path}`, {
      method,
      headers: { Authorization: `Bearer ${this.apiKey}`, 'Content-Type': 'application/json', ...headers },
      body: body === undefined ? undefined : JSON.stringify(body),
      signal: AbortSignal.timeout(this.timeoutMs),
    });
    const text = await res.text();
    let json: unknown = null;
    try { json = text ? JSON.parse(text) : null; } catch { /* not JSON */ }
    if (!res.ok) {
      const e = (json as { error?: { code?: string; message?: string; fields?: Record<string, string[]> } } | null)?.error;
      throw new CshpayError(res.status, e?.code ?? 'HTTP_ERROR', e?.message ?? `cshpay answered ${res.status}`, e?.fields);
    }
    return json as T;
  }

  readonly payments = {
    /** Create a payment. Pass `idempotencyKey` (e.g. your order id) so a retry returns the same payment. */
    create: (input: CreatePaymentInput, opts: { idempotencyKey?: string } = {}): Promise<Payment> =>
      this.request<Payment>('POST', '/payments', input, opts.idempotencyKey ? { 'Idempotency-Key': opts.idempotencyKey } : {}),

    /** The authoritative state of one payment. */
    get: (id: string): Promise<Payment> => this.request<Payment>('GET', `/payments/${encodeURIComponent(id)}`),

    /** Newest first. */
    list: async (query: { reference?: string; limit?: number } = {}): Promise<Payment[]> => {
      const q = new URLSearchParams();
      if (query.reference) q.set('reference', query.reference);
      if (query.limit) q.set('limit', String(query.limit));
      const qs = q.toString();
      return (await this.request<{ data: Payment[] }>('GET', `/payments${qs ? `?${qs}` : ''}`)).data;
    },

    /** Drop-in checkout: the signed Kina Bank form fields. Call when the customer clicks Pay. */
    kinaFields: (id: string, style: 'iframe' | 'redirect' = 'iframe'): Promise<KinaFields> =>
      this.request<KinaFields>('POST', `/payments/${encodeURIComponent(id)}/kina-fields`, { style }),

    /** Reverse a succeeded payment in full. Check the returned status: refunded, refund_failed or refund_pending. */
    refund: (id: string): Promise<Payment> => this.request<Payment>('POST', `/payments/${encodeURIComponent(id)}/refund`),
  };

  readonly webhookEndpoints = {
    /** The returned `secret` is shown once; store it. */
    create: (input: { url: string; events?: Array<WebhookEventType | '*'>; description?: string }): Promise<WebhookEndpoint> =>
      this.request<WebhookEndpoint>('POST', '/webhook-endpoints', input),
    list: async (): Promise<WebhookEndpoint[]> => (await this.request<{ data: WebhookEndpoint[] }>('GET', '/webhook-endpoints')).data,
    remove: (id: string): Promise<{ id: string; active: boolean }> =>
      this.request('DELETE', `/webhook-endpoints/${encodeURIComponent(id)}`),
  };

  readonly webhooks = {
    /** True if the delivery is genuine and recent. `rawBody` must be the exact body received. */
    verify: (rawBody: string | Buffer, signatureHeader: string | null | undefined): boolean =>
      verifyWebhookSignature(rawBody, signatureHeader, this.requireWebhookSecret()),

    /** Verify, then parse. Throws CshpaySignatureError if the delivery is not genuine. */
    constructEvent: (rawBody: string | Buffer, signatureHeader: string | null | undefined): WebhookEvent => {
      if (!verifyWebhookSignature(rawBody, signatureHeader, this.requireWebhookSecret())) {
        throw new CshpaySignatureError('cshpay: webhook signature is missing, wrong or too old');
      }
      return JSON.parse(typeof rawBody === 'string' ? rawBody : rawBody.toString('utf8')) as WebhookEvent;
    },
  };

  private requireWebhookSecret(): string {
    if (!this.webhookSecret) throw new Error('cshpay: no webhook secret (set CSHPAY_WEBHOOK_SECRET or pass webhookSecret)');
    return this.webhookSecret;
  }
}

export default Cshpay;
Python libraryOne file, standard library only, Python 3.9 or later. Works in FastAPI, Django and Flask.
sdk/python/cshpay/__init__.py
"""cshpay for Python.

One file, standard library only, Python 3.9 or later. Works in FastAPI, Django,
Flask or a plain script. SERVER ONLY: an API key must never reach a browser.

    from cshpay import Cshpay

    client = Cshpay()   # reads CSHPAY_BASE_URL, CSHPAY_API_KEY, CSHPAY_WEBHOOK_SECRET
    payment = client.create_payment(amount=968.62, reference="ORDER-14",
                                    return_url="https://your-site.com/thanks",
                                    idempotency_key="ORDER-14")
"""
import hashlib
import hmac
import json
import os
import re
import time
import urllib.error
import urllib.parse
import urllib.request

__version__ = "0.1.0"
__all__ = ["Cshpay", "CshpayError", "CshpaySignatureError", "verify_webhook_signature"]


class CshpayError(Exception):
    """An error response from the API. ``code`` is stable; the message is for people."""

    def __init__(self, status, code, message, fields=None):
        super().__init__(message)
        self.status = status
        self.code = code
        self.fields = fields  # per-field problems, on a VALIDATION error


class CshpaySignatureError(Exception):
    """Raised by construct_event when a webhook delivery is not genuine."""


def verify_webhook_signature(raw_body, signature_header, secret, tolerance_seconds=300, now=None):
    """True if the delivery is genuine and recent.

    ``raw_body`` must be the exact bytes (or text) received, not a re-serialised
    object. Header format: ``t=<unix seconds>,v1=<hex>``.
    """
    if not signature_header or not secret:
        return False
    if isinstance(raw_body, str):
        raw_body = raw_body.encode("utf-8")
    parts = dict(p.strip().split("=", 1) for p in signature_header.split(",") if "=" in p)
    t, v1 = parts.get("t", ""), parts.get("v1", "")
    if not t.isdigit() or not re.fullmatch(r"[0-9a-f]{64}", v1):
        return False
    if abs((int(time.time()) if now is None else now) - int(t)) > tolerance_seconds:
        return False  # stale: possible replay
    expected = hmac.new(secret.encode("utf-8"), t.encode("ascii") + b"." + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, v1)


class Cshpay:
    def __init__(self, api_key=None, base_url=None, webhook_secret=None, timeout=30):
        self.api_key = api_key if api_key is not None else os.environ.get("CSHPAY_API_KEY", "")
        self.base_url = (base_url if base_url is not None else os.environ.get("CSHPAY_BASE_URL", "")).rstrip("/")
        self.webhook_secret = webhook_secret if webhook_secret is not None else os.environ.get("CSHPAY_WEBHOOK_SECRET")
        self.timeout = timeout
        if not self.api_key:
            raise ValueError("cshpay: no API key (set CSHPAY_API_KEY or pass api_key)")
        if not self.base_url:
            raise ValueError("cshpay: no base URL (set CSHPAY_BASE_URL or pass base_url)")

    def _request(self, method, path, body=None, headers=None):
        req = urllib.request.Request(
            f"{self.base_url}/api/v1{path}",
            method=method,
            data=json.dumps(body).encode("utf-8") if body is not None else None,
            headers={"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json", **(headers or {})},
        )
        try:
            with urllib.request.urlopen(req, timeout=self.timeout) as res:
                text = res.read()
                return json.loads(text) if text else None
        except urllib.error.HTTPError as e:
            try:
                err = (json.loads(e.read() or b"{}") or {}).get("error") or {}
            except ValueError:
                err = {}
            raise CshpayError(e.code, err.get("code", "HTTP_ERROR"), err.get("message", f"cshpay answered {e.code}"), err.get("fields")) from None

    # -- payments ----------------------------------------------------------

    def create_payment(self, amount, reference, return_url, description=None, customer=None,
                       expires_in=None, metadata=None, idempotency_key=None):
        """Create a payment. Pass ``idempotency_key`` (e.g. your order id) so a retry returns the same payment."""
        body = {"amount": amount, "reference": reference, "returnUrl": return_url}
        if description is not None:
            body["description"] = description
        if customer is not None:
            body["customer"] = customer
        if expires_in is not None:
            body["expiresIn"] = expires_in
        if metadata is not None:
            body["metadata"] = metadata
        return self._request("POST", "/payments", body, {"Idempotency-Key": idempotency_key} if idempotency_key else None)

    def get_payment(self, payment_id):
        """The authoritative state of one payment."""
        return self._request("GET", f"/payments/{urllib.parse.quote(payment_id, safe='')}")

    def list_payments(self, reference=None, limit=None):
        """Newest first."""
        q = {k: v for k, v in (("reference", reference), ("limit", limit)) if v is not None}
        qs = f"?{urllib.parse.urlencode(q)}" if q else ""
        return self._request("GET", f"/payments{qs}")["data"]

    def kina_fields(self, payment_id, style="iframe"):
        """Drop-in checkout: the signed Kina Bank form fields. Call when the customer clicks Pay."""
        return self._request("POST", f"/payments/{urllib.parse.quote(payment_id, safe='')}/kina-fields", {"style": style})

    def refund_payment(self, payment_id):
        """Reverse a succeeded payment in full. Check the returned status: refunded, refund_failed or refund_pending."""
        return self._request("POST", f"/payments/{urllib.parse.quote(payment_id, safe='')}/refund")

    # -- webhook endpoints -------------------------------------------------

    def create_webhook_endpoint(self, url, events=None, description=None):
        """The returned ``secret`` is shown once; store it."""
        body = {"url": url}
        if events is not None:
            body["events"] = events
        if description is not None:
            body["description"] = description
        return self._request("POST", "/webhook-endpoints", body)

    def list_webhook_endpoints(self):
        return self._request("GET", "/webhook-endpoints")["data"]

    def delete_webhook_endpoint(self, endpoint_id):
        return self._request("DELETE", f"/webhook-endpoints/{urllib.parse.quote(endpoint_id, safe='')}")

    # -- receiving webhooks ------------------------------------------------

    def _secret(self):
        if not self.webhook_secret:
            raise ValueError("cshpay: no webhook secret (set CSHPAY_WEBHOOK_SECRET or pass webhook_secret)")
        return self.webhook_secret

    def verify_webhook(self, raw_body, signature_header):
        """True if the delivery is genuine and recent. ``raw_body`` must be the exact body received."""
        return verify_webhook_signature(raw_body, signature_header, self._secret())

    def construct_event(self, raw_body, signature_header):
        """Verify, then parse. Raises CshpaySignatureError if the delivery is not genuine."""
        if not verify_webhook_signature(raw_body, signature_header, self._secret()):
            raise CshpaySignatureError("cshpay: webhook signature is missing, wrong or too old")
        return json.loads(raw_body)
.NET libraryOne file for .NET 8 or later. Works in ASP.NET Core.
sdk/dotnet/Cshpay/CshpayClient.cs
// cshpay for .NET 8 or later.
//
// One file, no dependencies beyond the framework. SERVER ONLY: an API key must
// never be sent to a browser.
//
//   var cshpay = new CshpayClient();   // reads CSHPAY_BASE_URL, CSHPAY_API_KEY, CSHPAY_WEBHOOK_SECRET
//   var payment = await cshpay.CreatePaymentAsync(
//       new CreatePaymentRequest(968.62m, "ORDER-14", "https://your-site.com/thanks"), idempotencyKey: "ORDER-14");
//
// NOTE: this file has been reviewed but not compiled in the environment it was
// written in. Build it and run the checks in README.md before relying on it.
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Cshpay;

public sealed record Customer(
    [property: JsonPropertyName("email")] string? Email = null,
    [property: JsonPropertyName("name")] string? Name = null);

public sealed record CreatePaymentRequest(
    [property: JsonPropertyName("amount")] decimal Amount,
    [property: JsonPropertyName("reference")] string Reference,
    [property: JsonPropertyName("returnUrl")] string ReturnUrl,
    [property: JsonPropertyName("description")] string? Description = null,
    [property: JsonPropertyName("customer")] Customer? Customer = null,
    [property: JsonPropertyName("expiresIn")] int? ExpiresIn = null,
    [property: JsonPropertyName("metadata")] Dictionary<string, string>? Metadata = null);

public sealed record GatewayDetails(
    [property: JsonPropertyName("order")] string? Order,
    [property: JsonPropertyName("approvalCode")] string? ApprovalCode,
    [property: JsonPropertyName("authorizedAmount")] string? AuthorizedAmount,
    [property: JsonPropertyName("rrn")] string? Rrn,
    [property: JsonPropertyName("reference")] string? Reference,
    [property: JsonPropertyName("responseCode")] string? ResponseCode,
    [property: JsonPropertyName("message")] string? Message);

/// <summary>Status is one of: pending, succeeded, failed, expired, refund_pending, refunded, refund_failed.</summary>
public sealed record Payment(
    [property: JsonPropertyName("id")] string Id,
    [property: JsonPropertyName("mode")] string Mode,
    [property: JsonPropertyName("reference")] string Reference,
    [property: JsonPropertyName("amount")] string Amount,
    [property: JsonPropertyName("currency")] string Currency,
    [property: JsonPropertyName("description")] string? Description,
    [property: JsonPropertyName("customer")] Customer? Customer,
    [property: JsonPropertyName("status")] string Status,
    [property: JsonPropertyName("checkoutUrl")] string? CheckoutUrl,
    [property: JsonPropertyName("returnUrl")] string ReturnUrl,
    [property: JsonPropertyName("metadata")] Dictionary<string, string>? Metadata,
    [property: JsonPropertyName("gateway")] GatewayDetails? Gateway,
    [property: JsonPropertyName("paidAt")] DateTimeOffset? PaidAt,
    [property: JsonPropertyName("refundedAt")] DateTimeOffset? RefundedAt,
    [property: JsonPropertyName("expiresAt")] DateTimeOffset? ExpiresAt,
    [property: JsonPropertyName("createdAt")] DateTimeOffset? CreatedAt);

public sealed record KinaFields(
    [property: JsonPropertyName("paymentId")] string PaymentId,
    [property: JsonPropertyName("mode")] string Mode,
    [property: JsonPropertyName("action")] string Action,
    [property: JsonPropertyName("method")] string Method,
    [property: JsonPropertyName("fields")] Dictionary<string, string> Fields,
    [property: JsonPropertyName("kinaScriptUrl")] string KinaScriptUrl,
    [property: JsonPropertyName("kinaCssUrl")] string KinaCssUrl,
    [property: JsonPropertyName("fieldsExpireAt")] DateTimeOffset FieldsExpireAt);

/// <summary>A verified webhook event. Id is stable across redeliveries: store it to ignore duplicates.</summary>
public sealed record WebhookEvent(string Id, string Type, string Mode, DateTimeOffset CreatedAt, Payment Payment);

/// <summary>An error response from the API. Code is stable; Message is for people.</summary>
public sealed class CshpayException : Exception
{
    public int Status { get; }
    public string Code { get; }
    public CshpayException(int status, string code, string message) : base(message) { Status = status; Code = code; }
}

/// <summary>Thrown by ConstructEvent when a webhook delivery is not genuine.</summary>
public sealed class CshpaySignatureException : Exception
{
    public CshpaySignatureException(string message) : base(message) { }
}

public sealed class CshpayClient
{
    private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web)
    {
        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
    };

    private readonly HttpClient _http;
    private readonly string? _webhookSecret;

    /// <param name="http">Optional: your own HttpClient (for IHttpClientFactory). Its BaseAddress and Authorization are set here.</param>
    public CshpayClient(string? apiKey = null, string? baseUrl = null, string? webhookSecret = null, HttpClient? http = null)
    {
        apiKey ??= Environment.GetEnvironmentVariable("CSHPAY_API_KEY");
        baseUrl ??= Environment.GetEnvironmentVariable("CSHPAY_BASE_URL");
        _webhookSecret = webhookSecret ?? Environment.GetEnvironmentVariable("CSHPAY_WEBHOOK_SECRET");
        if (string.IsNullOrWhiteSpace(apiKey)) throw new ArgumentException("cshpay: no API key (set CSHPAY_API_KEY or pass apiKey)");
        if (string.IsNullOrWhiteSpace(baseUrl)) throw new ArgumentException("cshpay: no base URL (set CSHPAY_BASE_URL or pass baseUrl)");

        _http = http ?? new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
        _http.BaseAddress = new Uri(baseUrl.TrimEnd('/') + "/api/v1/");
        _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
    }

    private async Task<T> SendAsync<T>(HttpMethod method, string path, object? body, string? idempotencyKey, CancellationToken ct)
    {
        using var req = new HttpRequestMessage(method, path);
        if (body is not null) req.Content = JsonContent.Create(body, body.GetType(), options: Json);
        if (!string.IsNullOrEmpty(idempotencyKey)) req.Headers.Add("Idempotency-Key", idempotencyKey);

        using var res = await _http.SendAsync(req, ct).ConfigureAwait(false);
        var text = await res.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
        if (!res.IsSuccessStatusCode)
        {
            string code = "HTTP_ERROR", message = $"cshpay answered {(int)res.StatusCode}";
            try
            {
                using var doc = JsonDocument.Parse(text);
                if (doc.RootElement.TryGetProperty("error", out var e))
                {
                    if (e.TryGetProperty("code", out var c)) code = c.GetString() ?? code;
                    if (e.TryGetProperty("message", out var m)) message = m.GetString() ?? message;
                }
            }
            catch (JsonException) { /* not JSON */ }
            throw new CshpayException((int)res.StatusCode, code, message);
        }
        return JsonSerializer.Deserialize<T>(text, Json) ?? throw new CshpayException((int)res.StatusCode, "EMPTY_RESPONSE", "cshpay returned an empty response");
    }

    /// <summary>Create a payment. Pass idempotencyKey (e.g. your order id) so a retry returns the same payment.</summary>
    public Task<Payment> CreatePaymentAsync(CreatePaymentRequest request, string? idempotencyKey = null, CancellationToken ct = default) =>
        SendAsync<Payment>(HttpMethod.Post, "payments", request, idempotencyKey, ct);

    /// <summary>The authoritative state of one payment.</summary>
    public Task<Payment> GetPaymentAsync(string id, CancellationToken ct = default) =>
        SendAsync<Payment>(HttpMethod.Get, $"payments/{Uri.EscapeDataString(id)}", null, null, ct);

    /// <summary>Newest first.</summary>
    public async Task<IReadOnlyList<Payment>> ListPaymentsAsync(string? reference = null, int? limit = null, CancellationToken ct = default)
    {
        var q = new List<string>();
        if (reference is not null) q.Add("reference=" + Uri.EscapeDataString(reference));
        if (limit is not null) q.Add("limit=" + limit);
        var list = await SendAsync<ListOf<Payment>>(HttpMethod.Get, "payments" + (q.Count > 0 ? "?" + string.Join("&", q) : ""), null, null, ct).ConfigureAwait(false);
        return list.Data;
    }

    /// <summary>Drop-in checkout: the signed Kina Bank form fields. Call when the customer clicks Pay. style is "iframe" or "redirect".</summary>
    public Task<KinaFields> KinaFieldsAsync(string id, string style = "iframe", CancellationToken ct = default) =>
        SendAsync<KinaFields>(HttpMethod.Post, $"payments/{Uri.EscapeDataString(id)}/kina-fields", new { style }, null, ct);

    /// <summary>Reverse a succeeded payment in full. Check the returned Status: refunded, refund_failed or refund_pending.</summary>
    public Task<Payment> RefundPaymentAsync(string id, CancellationToken ct = default) =>
        SendAsync<Payment>(HttpMethod.Post, $"payments/{Uri.EscapeDataString(id)}/refund", null, null, ct);

    /// <summary>
    /// True if the delivery is genuine and recent. rawBody must be the exact body received, not a re-serialised object.
    /// Header format: "t=&lt;unix seconds&gt;,v1=&lt;hex&gt;".
    /// </summary>
    public static bool VerifyWebhookSignature(string rawBody, string? signatureHeader, string secret, int toleranceSeconds = 300, long? nowSeconds = null)
    {
        if (string.IsNullOrEmpty(signatureHeader) || string.IsNullOrEmpty(secret)) return false;
        var parts = signatureHeader.Split(',')
            .Select(p => p.Split('=', 2)).Where(kv => kv.Length == 2)
            .GroupBy(kv => kv[0].Trim()).ToDictionary(g => g.Key, g => g.First()[1].Trim());
        if (!parts.TryGetValue("t", out var tText) || !long.TryParse(tText, out var t)) return false;
        if (!parts.TryGetValue("v1", out var v1) || v1.Length != 64) return false;
        var now = nowSeconds ?? DateTimeOffset.UtcNow.ToUnixTimeSeconds();
        if (Math.Abs(now - t) > toleranceSeconds) return false; // stale: possible replay

        byte[] given;
        try { given = Convert.FromHexString(v1); } catch (FormatException) { return false; }
        using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret));
        var expected = hmac.ComputeHash(Encoding.UTF8.GetBytes($"{t}.{rawBody}"));
        return CryptographicOperations.FixedTimeEquals(expected, given);
    }

    public bool VerifyWebhook(string rawBody, string? signatureHeader) =>
        VerifyWebhookSignature(rawBody, signatureHeader, RequireWebhookSecret());

    /// <summary>Verify, then parse. Throws CshpaySignatureException if the delivery is not genuine.</summary>
    public WebhookEvent ConstructEvent(string rawBody, string? signatureHeader)
    {
        if (!VerifyWebhookSignature(rawBody, signatureHeader, RequireWebhookSecret()))
            throw new CshpaySignatureException("cshpay: webhook signature is missing, wrong or too old");
        using var doc = JsonDocument.Parse(rawBody);
        var root = doc.RootElement;
        var payment = root.GetProperty("data").GetProperty("payment").Deserialize<Payment>(Json)
            ?? throw new CshpaySignatureException("cshpay: webhook body has no payment");
        return new WebhookEvent(
            root.GetProperty("id").GetString()!, root.GetProperty("type").GetString()!, root.GetProperty("mode").GetString()!,
            root.GetProperty("createdAt").GetDateTimeOffset(), payment);
    }

    private string RequireWebhookSecret() =>
        string.IsNullOrEmpty(_webhookSecret)
            ? throw new InvalidOperationException("cshpay: no webhook secret (set CSHPAY_WEBHOOK_SECRET or pass webhookSecret)")
            : _webhookSecret;

    private sealed record ListOf<T>([property: JsonPropertyName("data")] List<T> Data);
}
Checkout page (HTML and CSS)The complete drop-in checkout page. Works with any backend.
samples/dropin-checkout/checkout.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <!-- Kina Bank guide p.9: do not cache the order confirmation page. -->
  <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
  <meta http-equiv="Pragma" content="no-cache">
  <meta http-equiv="Expires" content="0">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Checkout</title>
  <style>
    :root { --brand: #0f172a; --ink: #0f172a; --muted: #64748b; --line: #e2e8f0; --bg: #f8fafc; }
    * { box-sizing: border-box; }
    body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 16px;
           background: var(--bg); color: var(--ink); font: 16px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
    .card { width: 100%; max-width: 420px; background: #fff; border: 1px solid var(--line); border-radius: 16px;
            overflow: hidden; box-shadow: 0 10px 30px rgb(15 23 42 / .08); }
    .card header { background: var(--brand); color: #fff; padding: 22px 24px; text-align: center; }
    .card header h1 { margin: 0; font-size: 20px; }
    .card header p { margin: 4px 0 0; font-size: 12px; letter-spacing: .08em; text-transform: uppercase; opacity: .8; }
    .body { padding: 24px; display: grid; gap: 18px; }
    .amount { text-align: center; }
    .amount small { display: block; color: var(--muted); font-size: 14px; }
    .amount strong { font-size: 36px; font-variant-numeric: tabular-nums; }
    .amount strong span { font-size: 18px; color: var(--muted); margin-right: 4px; }
    dl { margin: 0; border: 1px solid var(--line); border-radius: 12px; font-size: 14px; }
    dl div { display: flex; justify-content: space-between; gap: 16px; padding: 10px 14px; }
    dl div + div { border-top: 1px solid var(--line); }
    dt { color: var(--muted); } dd { margin: 0; font-weight: 600; text-align: right; }
    button.pay { width: 100%; border: 0; border-radius: 12px; padding: 14px; font: inherit; font-weight: 600;
                 color: #fff; background: var(--brand); cursor: pointer; }
    button.pay:disabled { opacity: .6; cursor: default; }
    .note { margin: 0; text-align: center; font-size: 12px; color: var(--muted); }
    .error { margin: 0; text-align: center; font-size: 13px; color: #b91c1c; }

    /* Kina's overlay, sized so the card form fits and scrolls on a phone.
       kbl-ec.js toggles `display`; nothing here touches it. */
    #kbliframediv { position: fixed !important; inset: 0 !important; z-index: 60 !important; padding: 12px !important;
                    overflow-y: auto !important; background: rgb(15 23 42 / .72) !important; text-align: center; }
    #kbliframeinnerdiv { display: inline-block !important; width: min(430px, 100%) !important; height: min(700px, 92vh) !important;
                         margin: max(8px, 2vh) auto !important; border: 0 !important; border-radius: 14px !important;
                         overflow: hidden !important; background: transparent !important; }
    #kblpaymentiframe { display: block !important; width: 100% !important; height: 100% !important; border: 0 !important; }
    @media (max-width: 480px) {
      #kbliframediv { padding: 0 !important; }
      #kbliframeinnerdiv { width: 100% !important; height: 100dvh !important; margin: 0 !important; border-radius: 0 !important; }
    }
  </style>
</head>
<body>
  <!--
    cshpay drop-in checkout.

    Your server renders this page for one payment and fills in the four values
    in CHECKOUT below. When the customer clicks Pay, the page asks YOUR server
    for the signed Kina fields (your server calls cshpay with its API key — the
    key must never be in this page), then posts them to Kina Bank.

    Card details are typed on Kina Bank's page inside the frame. They never
    touch this page, your server, or cshpay.
  -->
  <main class="card">
    <header>
      <h1 id="merchant-name">Your Store</h1>
      <p>Secure payment</p>
    </header>
    <div class="body">
      <div class="amount">
        <small>Amount due</small>
        <strong><span id="currency">PGK</span><span id="amount" style="font-size:inherit;color:inherit;margin:0">0.00</span></strong>
      </div>
      <dl>
        <div><dt>Reference</dt><dd id="reference">—</dd></div>
      </dl>
      <button class="pay" id="pay-button" type="button">Pay by card</button>
      <p class="error" id="error" role="alert" hidden></p>
      <p class="note">Your card details are entered on Kina Bank's secure page.</p>
    </div>
  </main>

  <!-- Kina guide p.9: the form posted into the iframe, and the overlay markup. -->
  <form id="kblPaymentForm" method="POST" target="kblpaymentiframe"></form>
  <div id="kbliframediv" class="kbliframeoverlay" style="display:none">
    <div id="kbliframeinnerdiv">
      <iframe id="kblpaymentiframe" name="kblpaymentiframe" title="Kina Bank secure card payment"></iframe>
    </div>
  </div>

  <script>
    // ---- Filled in by your server when it renders this page -----------------
    const CHECKOUT = {
      paymentId: 'REPLACE_WITH_PAYMENT_ID',   // id returned by POST /api/v1/payments
      merchantName: 'Your Store',
      amount: '0.00',
      currency: 'PGK',
      reference: 'ORDER-1',
      // Your own endpoint that calls POST /api/v1/payments/{id}/kina-fields.
      fieldsUrl: '/api/kina-fields',
      // Your cshpay base URL, e.g. https://pay.example.com (used to trust its messages).
      cshpayOrigin: 'https://REPLACE_WITH_CSHPAY_HOST',
    };
    // -------------------------------------------------------------------------

    document.getElementById('merchant-name').textContent = CHECKOUT.merchantName;
    document.getElementById('amount').textContent = CHECKOUT.amount;
    document.getElementById('currency').textContent = CHECKOUT.currency;
    document.getElementById('reference').textContent = CHECKOUT.reference;

    const button = document.getElementById('pay-button');
    const errorBox = document.getElementById('error');
    const form = document.getElementById('kblPaymentForm');
    const overlay = document.getElementById('kbliframediv');

    function loadKinaAssets(scriptUrl, cssUrl) {
      return new Promise((resolve) => {
        if (window.submitPaymentForm2) return resolve();
        const css = document.createElement('link');
        css.rel = 'stylesheet';
        css.href = cssUrl;
        document.head.appendChild(css);
        const js = document.createElement('script');
        js.src = scriptUrl + '?' + Date.now();      // guide p.9: avoid a cached copy
        js.onload = resolve;
        js.onerror = resolve;                        // fall back to our own overlay
        document.head.appendChild(js);
      });
    }

    button.addEventListener('click', async () => {
      button.disabled = true;
      button.textContent = 'Starting secure payment…';
      errorBox.hidden = true;
      try {
        // Ask at click time: Kina rejects fields signed more than an hour ago.
        const res = await fetch(CHECKOUT.fieldsUrl, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ paymentId: CHECKOUT.paymentId }),
        });
        if (!res.ok) throw new Error('Could not start the payment. Please try again.');
        const signed = await res.json();   // { action, fields, kinaScriptUrl, kinaCssUrl }

        form.action = signed.action;
        form.replaceChildren(...Object.entries(signed.fields).map(([name, value]) => {
          const input = document.createElement('input');
          input.type = 'hidden';
          input.name = name;
          input.value = value;
          return input;
        }));

        await loadKinaAssets(signed.kinaScriptUrl, signed.kinaCssUrl);
        if (typeof window.submitPaymentForm2 === 'function') {
          window.submitPaymentForm2();              // Kina: show the overlay, submit the form into it
        } else {
          overlay.style.display = 'block';          // Kina's script unavailable: same overlay, shown here
          form.submit();
        }
      } catch (e) {
        errorBox.textContent = e.message;
        errorBox.hidden = false;
      } finally {
        button.disabled = false;
        button.textContent = 'Pay by card';
      }
    });

    // When the customer finishes, cshpay's return page (inside the frame) posts
    // the result here. Use it only to move the customer on — it is NOT proof of
    // payment. Fulfil the order from your webhook handler.
    window.addEventListener('message', (event) => {
      if (event.origin !== CHECKOUT.cshpayOrigin) return;
      const msg = event.data;
      if (!msg || msg.source !== 'cshpay' || msg.type !== 'payment.result') return;
      window.location.href = msg.returnUrl;
    });
  </script>
</body>
</html>
Next.js exampleRoute handlers for hosted checkout, signed fields and the webhook.
samples/nextjs/app/api/checkout/route.ts
// Hosted checkout: POST here from your cart, the customer is redirected to cshpay.
import { NextResponse } from 'next/server';
import { createPayment } from '@/lib/cshpay';

export async function POST(request: Request) {
  const order = { id: 'ORDER-14', total: 968.62 };   // from your own database, never from the browser
  const payment = await createPayment({
    amount: order.total,
    reference: order.id,
    description: `Order ${order.id}`,
    returnUrl: new URL('/thanks', request.url).toString(),
  }, order.id);
  return NextResponse.redirect(payment.checkoutUrl!, 303);
}
samples/nextjs/app/api/kina-fields/route.ts
// Drop-in checkout: your checkout page calls this at click time.
import { NextResponse } from 'next/server';
import { kinaFields } from '@/lib/cshpay';

export async function POST(request: Request) {
  const { paymentId } = (await request.json()) as { paymentId: string };
  // Check here that this customer is allowed to pay this payment.
  return NextResponse.json(await kinaFields(paymentId), { headers: { 'Cache-Control': 'no-store' } });
}
samples/nextjs/app/api/webhooks/cshpay/route.ts
// Webhook receiver. Register this URL with POST /api/v1/webhook-endpoints.
import { verifyWebhook } from '@/lib/cshpay';

export async function POST(request: Request) {
  const raw = await request.text();   // the raw body: verify BEFORE parsing
  if (!verifyWebhook(raw, request.headers.get('Cshpay-Signature'))) {
    return new Response('bad signature', { status: 400 });
  }
  const event = JSON.parse(raw) as { id: string; type: string; data: { payment: { reference: string; amount: string } } };

  // Deliveries can repeat: make this idempotent, e.g. by storing event.id.
  if (event.type === 'payment.succeeded') {
    // TODO: mark the order paid and fulfil it.
    console.warn('PAID', event.data.payment.reference, event.data.payment.amount);
  }
  return new Response(null, { status: 200 });   // answer 2xx quickly; anything else is retried
}
Express exampleThe same three steps in plain JavaScript.
samples/node-express/server.js
// Express example:  npm install express  &&  node server.js
//
//   CSHPAY_BASE_URL=https://pay.example.com
//   CSHPAY_API_KEY=cpk_test_...
//   CSHPAY_WEBHOOK_SECRET=whsec_...
const express = require('express');
const cshpay = require('./cshpay');

const app = express();

// The webhook route needs the RAW body to verify the signature, so it is
// registered before express.json().
app.post('/webhooks/cshpay', express.raw({ type: 'application/json' }), (req, res) => {
  const raw = req.body.toString('utf8');
  if (!cshpay.verifyWebhook(raw, req.get('Cshpay-Signature'))) return res.status(400).send('bad signature');

  const event = JSON.parse(raw);
  // Deliveries can repeat: make this idempotent, e.g. by storing event.id.
  if (event.type === 'payment.succeeded') {
    const payment = event.data.payment;
    console.log('PAID', payment.reference, payment.amount, payment.currency);
    // TODO: mark your order paid and fulfil it.
  }
  res.sendStatus(200);   // answer 2xx quickly; anything else is retried
});

app.use(express.json());

// 1. Hosted checkout: create a payment and send the customer to cshpay.
app.post('/checkout', async (req, res) => {
  const order = { id: 'ORDER-14', total: 968.62 };   // from your own database, never from the browser
  const payment = await cshpay.createPayment({
    amount: order.total,
    reference: order.id,
    description: `Order ${order.id}`,
    returnUrl: `${req.protocol}://${req.get('host')}/thanks`,
  }, order.id);
  res.redirect(303, payment.checkoutUrl);
});

// 2. Drop-in checkout: the browser asks for signed Kina fields at click time.
//    Check here that this customer is allowed to pay this payment.
app.post('/api/kina-fields', async (req, res) => {
  res.json(await cshpay.kinaFields(req.body.paymentId));
});

// 3. Where the customer lands afterwards. The query string is only a hint:
//    read the payment from the API (or rely on the webhook) before believing it.
app.get('/thanks', async (req, res) => {
  const payment = await cshpay.getPayment(req.query.payment_id);
  res.send(payment.status === 'succeeded' ? 'Thank you, payment received.' : `Payment ${payment.status}.`);
});

app.use((err, _req, res, _next) => { console.error(err); res.status(502).json({ error: 'payment service error' }); });
app.listen(3001, () => console.log('listening on :3001'));
FastAPI exampleThe same three steps in Python.
samples/python-fastapi/main.py
"""FastAPI example:  pip install fastapi uvicorn  &&  uvicorn main:app --port 3001

  CSHPAY_BASE_URL=https://pay.example.com
  CSHPAY_API_KEY=cpk_test_...
  CSHPAY_WEBHOOK_SECRET=whsec_...

The same three steps work in Django or Flask: cshpay.py has no framework imports.
"""
import json

from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import RedirectResponse

import cshpay

app = FastAPI()


@app.post("/checkout")
def checkout(request: Request):
    """Hosted checkout: create a payment and send the customer to cshpay."""
    order = {"id": "ORDER-14", "total": 968.62}  # from your own database, never from the browser
    payment = cshpay.create_payment(
        amount=order["total"],
        reference=order["id"],
        description=f"Order {order['id']}",
        return_url=str(request.url_for("thanks")),
        idempotency_key=order["id"],
    )
    return RedirectResponse(payment["checkoutUrl"], status_code=303)


@app.post("/api/kina-fields")
async def kina_fields(request: Request):
    """Drop-in checkout: the browser asks for signed Kina fields at click time."""
    body = await request.json()
    # Check here that this customer is allowed to pay this payment.
    return cshpay.kina_fields(body["paymentId"])


@app.get("/thanks", name="thanks")
def thanks(payment_id: str):
    """The query string is only a hint: read the payment before believing it."""
    payment = cshpay.get_payment(payment_id)
    return {"message": "Thank you, payment received." if payment["status"] == "succeeded" else f"Payment {payment['status']}."}


@app.post("/webhooks/cshpay")
async def webhook(request: Request):
    raw = await request.body()  # the raw bytes: verify BEFORE parsing
    if not cshpay.verify_webhook(raw, request.headers.get("Cshpay-Signature")):
        raise HTTPException(status_code=400, detail="bad signature")
    event = json.loads(raw)
    # Deliveries can repeat: make this idempotent, e.g. by storing event["id"].
    if event["type"] == "payment.succeeded":
        payment = event["data"]["payment"]
        print("PAID", payment["reference"], payment["amount"], payment["currency"])
        # TODO: mark your order paid and fulfil it.
    return {"ok": True}  # answer 2xx quickly; anything else is retried
ASP.NET Core exampleThe same three steps as a minimal API.
samples/aspnetcore/Program.cs
// ASP.NET Core 8 minimal API example:  dotnet new web  → replace Program.cs  → dotnet run
//
//   CSHPAY_BASE_URL=https://pay.example.com
//   CSHPAY_API_KEY=cpk_test_...
//   CSHPAY_WEBHOOK_SECRET=whsec_...
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient("cshpay", c =>
{
    c.BaseAddress = new Uri(Environment.GetEnvironmentVariable("CSHPAY_BASE_URL")!.TrimEnd('/') + "/api/v1/");
    c.DefaultRequestHeaders.Authorization =
        new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("CSHPAY_API_KEY")); // server only!
});
var app = builder.Build();
var webhookSecret = Environment.GetEnvironmentVariable("CSHPAY_WEBHOOK_SECRET")!;

// 1. Hosted checkout: create a payment and send the customer to cshpay.
app.MapPost("/checkout", async (HttpContext ctx, IHttpClientFactory http) =>
{
    var order = new { Id = "ORDER-14", Total = 968.62m };   // from your own database, never from the browser
    using var req = new HttpRequestMessage(HttpMethod.Post, "payments")
    {
        Content = JsonContent.Create(new
        {
            amount = order.Total,
            reference = order.Id,
            description = $"Order {order.Id}",
            returnUrl = $"{ctx.Request.Scheme}://{ctx.Request.Host}/thanks",
        }),
    };
    req.Headers.Add("Idempotency-Key", order.Id);            // a retry returns the same payment
    using var res = await http.CreateClient("cshpay").SendAsync(req);
    res.EnsureSuccessStatusCode();
    var payment = await res.Content.ReadFromJsonAsync<JsonElement>();
    return Results.Redirect(payment.GetProperty("checkoutUrl").GetString()!);
});

// 2. Drop-in checkout: the browser asks for signed Kina fields at click time.
//    Check here that this customer is allowed to pay this payment.
app.MapPost("/api/kina-fields", async (KinaFieldsRequest body, IHttpClientFactory http) =>
{
    using var res = await http.CreateClient("cshpay")
        .PostAsync($"payments/{Uri.EscapeDataString(body.PaymentId)}/kina-fields", null);
    res.EnsureSuccessStatusCode();
    return Results.Content(await res.Content.ReadAsStringAsync(), "application/json");
});

// 3. Where the customer lands afterwards. The query string is only a hint:
//    read the payment from the API (or rely on the webhook) before believing it.
app.MapGet("/thanks", async (string payment_id, IHttpClientFactory http) =>
{
    var payment = await http.CreateClient("cshpay")
        .GetFromJsonAsync<JsonElement>($"payments/{Uri.EscapeDataString(payment_id)}");
    var status = payment.GetProperty("status").GetString();
    return status == "succeeded" ? "Thank you, payment received." : $"Payment {status}.";
});

// 4. Webhook receiver. Register this URL with POST /api/v1/webhook-endpoints.
app.MapPost("/webhooks/cshpay", async (HttpRequest request) =>
{
    using var reader = new StreamReader(request.Body, Encoding.UTF8);
    var raw = await reader.ReadToEndAsync();                 // the raw body: verify BEFORE parsing
    if (!Cshpay.VerifyWebhook(raw, request.Headers["Cshpay-Signature"], webhookSecret))
        return Results.BadRequest("bad signature");

    using var doc = JsonDocument.Parse(raw);
    // Deliveries can repeat: make this idempotent, e.g. by storing the event id.
    if (doc.RootElement.GetProperty("type").GetString() == "payment.succeeded")
    {
        var payment = doc.RootElement.GetProperty("data").GetProperty("payment");
        Console.WriteLine($"PAID {payment.GetProperty("reference")} {payment.GetProperty("amount")}");
        // TODO: mark your order paid and fulfil it.
    }
    return Results.Ok();                                     // answer 2xx quickly; anything else is retried
});

app.Run();

record KinaFieldsRequest(string PaymentId);

static class Cshpay
{
    /// <summary>Header: "t=&lt;unix seconds&gt;,v1=&lt;hex&gt;". rawBody must be the exact text received.</summary>
    public static bool VerifyWebhook(string rawBody, string? signatureHeader, string secret, int toleranceSeconds = 300)
    {
        var parts = (signatureHeader ?? "").Split(',')
            .Select(p => p.Split('=', 2)).Where(kv => kv.Length == 2)
            .ToDictionary(kv => kv[0].Trim(), kv => kv[1].Trim());
        if (!parts.TryGetValue("t", out var tText) || !long.TryParse(tText, out var t)) return false;
        if (!parts.TryGetValue("v1", out var v1) || v1.Length != 64) return false;
        if (Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - t) > toleranceSeconds) return false; // stale: possible replay

        using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret));
        var expected = hmac.ComputeHash(Encoding.UTF8.GetBytes($"{t}.{rawBody}"));
        byte[] given;
        try { given = Convert.FromHexString(v1); } catch (FormatException) { return false; }
        return CryptographicOperations.FixedTimeEquals(expected, given);
    }
}