Lunixi

Lunixi Elixir SDK

Version 1.0.1 uses canonical minor-unit strings for money. This is a breaking change from 0.x; update request and response handling together. See migration.

Historical release record: Verified Hex.pm release: 0.1.1. The published archive was downloaded and its checksum verified on 2026-11-01.

The source patch adds a concrete merchant-site presentation example. Embedded checkout is the default: load only the official Lunixi bundle and mount the existing form; methods and multi-card choices stay in the Lunixi panel. Optional hosted mode uses the backend paymentPageUrl after exact HTTPS pay.lunixi.com/payment/ validation. Its token may differ from the embedded token. Missing URLs keep embedded available and hosted on hold/reconciliation with the original attempt/key. Never derive a URL from the browser token. Authorize the customer/order and native browser CSRF before rendering, send Cache-Control: private, no-store, preserve the merchant CSP nonce and keep tokens/HTML/redirect URLs out of logs. Generic response data preserves paymentPageUrl (every product now has a typed client).

CI License: MIT

Documentation · Türkçe · Changelog · Security

Server-side Elixir SDK for Lunixi payments and merchant APIs. Uses OTP's vetted Ed25519/HMAC primitives and Req's verified TLS transport. Works with Phoenix, Plug, LiveView server processes and ordinary supervised OTP applications. Requires Elixir 1.20+ and Erlang/OTP 29+.

Installation

Install the published 1.0.1 release: add the dependency to deps/0, then run mix deps.get:

{:lunixi, "~> 1.0.1"}

For the optional native SQLite inbox, also add {:exqlite, "~> 0.43.0"} to your application dependencies. Exqlite provides a native SQLite driver; a C compiler is required if a precompiled NIF is unavailable. No database driver is required for payments, signing or webhook verification.

Supervise one client per merchant key

config = %Lunixi.Config{
  base_url: "https://api-gateway.lunixi.com",
  key_id: System.fetch_env!("LUNIXI_KEY_ID"),
  private_key: System.fetch_env!("LUNIXI_PRIVATE_KEY_PEM"),
  max_retries: 2
}

children = [{Lunixi.Client, name: MyApp.Lunixi, config: config}]
Supervisor.start_link(children, strategy: :one_for_one)

Register the Ed25519 public key in the dashboard; keep the private key on your server/secret manager. PKCS8 PEM, base64 PKCS8 DER, base64 32-byte seed and validated base64 64-byte keypair encodings are supported. The key selects TEST/LIVE; there is no environment flag. Never send private credentials to the browser.

Each supervised client owns exactly one merchant credential and token cache. Use distinct names or Registry entries for separate merchants. Token acquisition is lazy, coalesced and renewed before expiry. Signing/token refresh run in the client process; protected HTTP calls run concurrently in caller processes. A supervised restart discards the token and safely reacquires it. Access tokens are never persisted.

Config Inspect/JSON, response Inspect/JSON and OTP client status redact credentials/bodies; client crash status also redacts state/message fields. Raw maps, explicit response data and event raw accessors can contain sensitive information. Do not log them or expose process state/debugging to untrusted callers. BEAM immutable memory is garbage-collected; the SDK does not promise memory zeroization.

Configuration Default Bounds / behavior
timeout 30,000 ms Positive, up to 120,000 ms; connect is at most 10 seconds
max_retries 0 0–5; GET or caller-persisted key only
max_response_bytes 8 MiB Up to 32 MiB; streaming accumulation stops at this bound
allow_insecure_localhost false Explicit HTTP tests on localhost/literal loopback only
additional_ca_certificates empty Trusted DER CA certificates; verification stays enabled

BaseURL is a trusted HTTPS origin without path, credentials or query. Redirects and Req automatic retries are disabled. Certificate and hostname verification remain enabled; caller-supplied transport options cannot disable them. Use an application-level deadline for an overall workflow containing authentication/retries. Client process unavailability returns a redacted error.

Checkout: embedded by default, optional hosted mode

Read the order and basket from your server-side records. Persist the attempt key before the call and reuse the same key/body after an uncertain result.

alias Lunixi.Payment.{Intent, BasketItem}

intent = %Intent{
  amount: "10050",
  currency: "TRY",
  order_id: "ORD-1001",
  callback_url: "https://merchant.example/payment/return",
  # Order details every payment requires (take them from your checkout, never a placeholder).
  # The buyer IP is optional on an intent: the Lunixi form takes it from the browser.
  buyer: %{
    "name" => "Ada", "surname" => "Yilmaz", "identityNumber" => "11111111111",
    "email" => "ada@example.com", "gsmNumber" => "+905350000000",
    "city" => "Istanbul", "country" => "Turkey", "zipCode" => "34000"
  },
  billing_address: %{
    "contactName" => "Ada Yilmaz", "address" => "Example Street 1",
    "city" => "Istanbul", "country" => "Turkey", "zipCode" => "34000"
  },
  basket_items: [
    %BasketItem{id: "line-1", name: "Gift card", category1: "Digital", item_type: "VIRTUAL", price: "10050"}
  ],
  # Optional: the form offers at most 3 installments for this order.
  enabled_installments: [1, 2, 3]
}

with {:ok, response} <- Lunixi.Payments.create_intent(MyApp.Lunixi, intent, persisted_attempt_key),
     %{"token" => token} when is_binary(token) and token != "" <- response.data do
  Lunixi.CheckoutHTML.render(token, nonce: server_generated_csp_nonce)
end

Authenticate the order's customer before returning the HTML/token and send Cache-Control: no-store. CheckoutHTML loads only https://cdn.lunixi.com/lunixi-checkout.min.js, mounts the existing Lunixi form, HTML-escapes token JSON and validates an optional CSP nonce. Serve the fragment within your merchant page; never construct custom script URLs or echo arbitrary returned HTML. The form handles enabled card/alternative methods. No default sample collects PAN/CVV.

Money is positive canonical minor-unit strings up to 9223372036854775807: 10050 = 100.50 TRY. Basket price is the line total and must sum to intent amount. Removed root fields price, paidPrice, autoCapture fail locally, including through generic requests. Installment selection and fees belong to the form; enabled_installments only narrows the installment counts the form offers for this payment ([1] = single payment only). The form shows only the counts your panel settings, the card and the platform maximum also allow; nil means no restriction. Counts are integers 1–36, distinct and include 1, otherwise create_intent returns {:error, %Lunixi.Error{code: "ENABLED_INSTALLMENTS"}} before any request; the list is sent as enabledInstallments in ascending order. Buyer/address and documented insurance basket details are passed as public string-keyed gateway schemas. Optional BasketItem.product_category (sent as productCategory) is the Lunixi product category, used by payment methods with legal installment limits (e.g. shopping loan) and other platform features; Lunixi.Payment.ProductCategory.all/0 lists the codes known to this version. nil omits the field and keeps today's behaviour; an unknown code is rejected by the API with HTTP 400. The dictionary only grows, so the field stays a string. preauth/force_3d preserve explicit boolean false. Method restrictions only narrow methods already enabled in the Lunixi panel.

Every payment body carries the order details (Lunixi.Payment.OrderDetails): buyer (name, surname, identityNumber — Turkish ID or passport number, email — ASCII, gsmNumber, city, country, zipCode, ip — the buyer's browser IP), billingAddress (contactName, address, city, country, zipCode) and at least one basket item (id, name, category1, itemType, price; the prices add up to the amount); a PHYSICAL item also needs shippingAddress. On Intent and the marketplace intents ip may be left out: the Lunixi form takes it from the buyer's browser. create_intent, create_marketplace_intent, direct_method_payment, split, Lunixi.Marketplace checkout intents and card charges, store_card (buyer and billing address only) and the wallet card top-up return {:error, %Lunixi.Error{kind: :invalid, code: "ORDER_DETAILS_REQUIRED", fields: paths}} naming the missing paths (buyer.email, basketItems.0.category1, shippingAddress …) before sending; Lunixi.Payment.OrderDetails.missing/2 returns the same list. The gateway answers a missing field with 400 payment.order.field_required and an invalid one with payment.order.field_invalid (OrderDetails.error_codes/0, OrderDetails.reasons/0); the failing paths are in Lunixi.Error.fields.

A token, browser completion, HTTP success or AUTHORIZED status is not proof of capture. Fulfill only after authenticating the gateway result and matching stored merchant/order/payment ID, expected amount/currency and final capture/reconciliation state. Handle refund, void and dispute transitions separately.

API coverage

Module Methods
Lunixi.Payments create_intent, get, list, methods / list_payment_methods, capture, capture_remaining, refund, refund_remaining, void
Lunixi.Payments payment methods direct_method_payment, confirm_payment_action, resend_payment_action
Lunixi.Payments promissory notes get_promissory_notes, cancel_promissory_notes, download_promissory_note_document
Lunixi.Payments bank transfer list_bank_transfer_exceptions, accept_bank_transfer_exception, mark_bank_transfer_exception_refunded
Lunixi.Payments split split, get_split, list_splits, refund_split
Lunixi.Payments cards and installments bin_info, installment_options, card_taxonomy, store_card, list_stored_cards, get_stored_card, deactivate_stored_card
Lunixi.Payments marketplace and analytics create_marketplace_intent, failover_recovery_analytics, provider_credential_analytics
Lunixi.PaymentLinks create, list, get, update, pause, resume, deactivate, action, send, qr, list_attempts, list_payments, create_image_upload, confirm_image_upload, upload_image
Lunixi.Reference list_provinces, list_districts, list_neighborhoods
Lunixi.PhysicalPos create_payment, create_reversal, cancel_payment, get_payment, list_payments, list_transactions, get_transaction, list_ambiguous_payments, get_sales_summary, get_tax_summary, list_settlements, start_settlement, list_settlement_runs, get_settlement_run, iterate_*, new_idempotency_key, parse_webhook_event
Lunixi.PhysicalPosManagement Stores, registers, terminals with bank and provider rows and device links, devices, device keys, activation codes, end-of-day policies, catalog and overview
Lunixi.PhysicalPos.* values Values, Events, CardData
Lunixi.Payment.* values Method, ActionType, ProviderSelection, ProviderSelectionMode, PromissoryNote, BankTransfer, Events, PaymentLink
Lunixi.Wallet ping; Programs, EndUsers, Wallets, Deposits, Corporate, Fees, Transfers, Withdrawals, Operations, Topups, Payments, Qr, BulkPayouts
Lunixi.BankConnect list_banks, list_connections, get_connection, list_accounts, get_account, request_sync, list_balances, list_transactions, get_transaction, iterate_*; Transfers (list_purposes, create, list, get), Fx (list_rates, create_quote, create_order, list_orders, get_order)
Lunixi.Sanction screen_name, screen_wallet, screen_account, screen_transaction, screen_public_procurement_ban, screen_adverse_media, evaluate_behavioral_alert, list_screening_history, register_monitoring, list_monitoring_alerts, list_monitored_entities, list_monitoring_matches, get_dataset_freshness, search_entities, get_entity_profile, get_entity_graph, get_indirect_exposure, get_ownership_aggregation, list_blacklist_entries, iterate_*, clear_screening?
Lunixi.Insurance list_products, search_products, list_reference_values, create_quote, get_quote, create_order, list_orders, get_order, bind_payment, confirm_payment, issue_policy, cancel_order, refund_premium, create_lead, list_leads, get_lead, get_policy_document, get_policy_receipt, get_policy_certificate, get_reconciliation_summary, list_reconciliation_orders, export_reconciliation, iterate_*, consent_from_quote, premium_basket_item
Lunixi.Fraud evaluate, record_event, record_batch, decisions, decision, latest_for_payment
Lunixi.Subscriptions create, get, list, cancel, pause, resume, change_plan, audit_logs, active?, terminal?, portal_url; Plans, Customers, Cards, Invoices, Portal, Products, Features, Addons, Usage; Values, Events
Lunixi.Kyc create_session, get_session, list_sessions, set_jurisdiction, set_primary_document, upload_document, timeline, submit, manual_review, evidence_request, merchant_policy, update_merchant_policy, rotate_webhook_secret, webhook_outbox, retry_webhook_event, erasure_requests, session_terminal?, assurance_rank, assurance_meets?; Values, Events
Lunixi.Identity analyze_sync, analyze, account_links, get_session, related_sessions, timeline, top_sources, list_sessions, device_shared?, link_reasons
Lunixi.Marketplace create_checkout_intent, charge_marketplace_card, charge_marketplace_card2d, charge_marketplace_card3d, sub-dealers (create_dealer, bulk_create_dealers, list_dealers, get_dealer, update_dealer_status, onboarding_token, dealer_application, submit_dealer_application, set_dealer_terms, sign_dealer_contract, activate_dealer, record_dealer_kyc_result), payout_ledger, transactions, commission_rules, upsert_commission_rule, preview_commission_rule, resolve_commission, create_payout, mark_payout_paid, bulk_mark_payouts_paid, audit_log, verify_audit_log, onboarding_url
Lunixi.request Signed access to other documented /api/v1/ merchant APIs
Lunixi.Webhook Raw v2 verification, rotation, freshness and ID/type binding
Lunixi.SqliteInbox Optional transactional durable replay processing
Lunixi.Payments.get(MyApp.Lunixi, payment_id)
Lunixi.Payments.refund(MyApp.Lunixi, payment_id, "2500", "Customer return", persisted_refund_key)
Lunixi.Payments.capture_remaining(MyApp.Lunixi, payment_id, persisted_capture_key)
Lunixi.Payments.refund_remaining(MyApp.Lunixi, payment_id, "Customer return", persisted_refund_key)
# Explicit nil amounts are invalid. void releases an authorization.

Split validates integer total/leg amounts, 1–5 legs and exact balance; the body carries only Lunixi.Payment.Split.fields/0 (SPLIT_FIELD), the order details (buyer, billingAddress, basketItems, shippingAddress for a PHYSICAL item) included and required. A card leg carries no method block; a non-card leg carries only its own mobileBilling, wallet or promissoryNote block with a providerCode (a promissory-note leg uses noteCount); meal card, open banking, shopping loan and bank transfer cannot be legs (SPLIT_LEG_BLOCK). Other method-specific schema validation stays in the gateway. list_splits/2 takes status and currency (a value or a list), createdFrom, createdTo, orderId, ownerRef, limit (1–100) and after. Pending split states can return a response with HTTP 400 and must remain unpaid. Compensation, partial refunds and reconciliation-required states need explicit handling.

Payment methods

list_payment_methods/2 (same as methods/2) lists the methods open for the account, each with its blockName, providerSelection, providerSelectionMode and providers with their inputFields. Always read the provider code from this list. QR is sent as QR_CODE; a value that is not an upper-case method code fails locally with PAYMENT_METHOD.

direct_method_payment/3 starts a payment with any method from your server. Build the body with Lunixi.Payment.DirectMethodPayment (or pass a raw string-keyed map, checked with the same rules). The idempotency key is required. Only the chosen method's block is sent; card fields (card, installment, installmentQuoteToken, force3D) belong to CARD only; block fields follow the shape limits of Lunixi.Payment.MethodFields; a shopping loan needs 1–100 basket items. The order details are required (with_buyer/2, with_billing_address/2, with_basket_items/2, with_shipping_address/2 for a PHYSICAL item).

alias Lunixi.Payment.{DirectMethodPayment, Method}

request =
  DirectMethodPayment.new("10000", "TRY", "order-1001")
  |> DirectMethodPayment.with_method_fields(Method.mobile_billing(), provider_code, %{
    "gsmNumber" => "+905321234567"
  })

{:ok, response} = Lunixi.Payments.direct_method_payment(MyApp.Lunixi, request, persisted_key)

When data.action is present (Lunixi.Payment.ActionType), complete it with confirm_payment_action(client, payment_id, action_id, %{"otp" => "123456"}) (otp, consentAccepted and/or fields only) or request a new code with resend_payment_action/3.

Promissory notes

Give the plan with with_promissory_note_schedule/2 (1–24 rows %{"amount" => ..., "dueDate" => "YYYY-MM-DD"} in date order, adding up to amount) or with_promissory_note_count/2 (1–24), never both. get_promissory_notes/2 lists the notes, cancel_promissory_notes/4 cancels all open notes or the given serial numbers, and download_promissory_note_document/3 returns the printable PDF in response.bytes (locale "tr-TR" or "en-GB"). Note events are in Lunixi.Payment.Events (promissory_note_paid/0, …).

Bank transfer

A bank transfer payment carries only the buyer's bank: with_method_fields("BANK_TRANSFER", nil, %{"bankCode" => "0062"}); a provider code is refused locally. Lunixi.Payment.BankTransfer.other_banks_code/0 ("9999") is the "Other banks" option. The DISPLAY action holds the transfer instruction to show the buyer:

case Lunixi.Payment.BankTransfer.instruction(response) do
  %Lunixi.Payment.BankTransfer.Instruction{} = instruction -> show_transfer(instruction)
  nil -> :no_transfer_instruction
end

The transfer is matched to the payment by the payment code in its description. Late, short and excess transfers are exceptions: list_bank_transfer_exceptions(client, environment: "LIVE", status: "PENDING_DECISION", limit: 50), then accept_bank_transfer_exception/2 or mark_bank_transfer_exception_refunded/2 with the exception UUID. The payment.bank_transfer.* events (Lunixi.Payment.Events) do not change the payment status; fulfill only on an authenticated payment.captured.

Cards, installments and stored cards

bin_info/2 reads card, bank and installment eligibility of a 6/8-digit BIN or a card number prefix (6–19 digits, otherwise BIN_OR_PAN locally). installment_options/2 returns the installment table; with installment above 1 and a BIN it also returns the quoteToken for DirectMethodPayment.with_installment/3. enabled_installments follows the same rule as the checkout intent and is sent in ascending order:

alias Lunixi.Payment.{InstallmentOptions, StoreCard}

{:ok, table} =
  Lunixi.Payments.installment_options(MyApp.Lunixi, %InstallmentOptions{
    amount: "150000",
    currency: "TRY",
    bin_or_pan: "45431100",
    enabled_installments: [1, 3, 6]
  })

{:ok, stored} =
  Lunixi.Payments.store_card(
    MyApp.Lunixi,
    %StoreCard{
      card: card_fields,
      card_user_key: buyer_card_key,
      callback_url: callback_url,
      buyer: buyer,
      billing_address: billing_address
    },
    persisted_key
  )

store_card/3 requires the card holder's buyer and billing address (no basket) and, like deactivate_stored_card/3, an idempotency key; list_stored_cards/2 and get_stored_card/2 read the buyer's cards. Card numbers never appear in inspect/1 output or in an error. card_taxonomy/1 returns the brand, family and bank reference lists.

Marketplace and analytics

create_marketplace_intent/3 takes the intent fields (order details included) plus sellers (%{"subDealerId" => ..., "amountMinor" => "6000"}) and an optional multiSellerPolicy. The sellers' amountMinor values must add up to amount (MARKETPLACE_TOTAL locally); the idempotency key is required. failover_recovery_analytics/2 and provider_credential_analytics/3 send their filters as given (from, to, range, …).

Lunixi.PaymentLinks manages links with string-keyed bodies (Lunixi.Payment.PaymentLink.spec_fields/0); value sets, minor-unit amount strings, nested objects and checkout.enabledInstallments are checked before any request. create/3 and send/5 require an idempotency key (8–200 printable characters); update/5 takes the link's current rowVersion and cannot change usage, amountMode or currency. buyerFields values are REQUIRED only (PaymentLink.buyer_field_requirements/0): the link page always asks all five buyer fields, as payment providers require them.

{:ok, link} =
  Lunixi.PaymentLinks.create(
    MyApp.Lunixi,
    %{
      "usage" => "SINGLE_USE",
      "amountMode" => "FIXED",
      "currency" => "TRY",
      "title" => "Invoice 1001",
      "amountMinor" => "150000"
    },
    persisted_key
  )

{:ok, page} = Lunixi.PaymentLinks.list(MyApp.Lunixi, state: ["ACTIVE", "PAUSED"], limit: 20)
{:ok, qr} = Lunixi.PaymentLinks.qr(MyApp.Lunixi, link.data["id"], format: "png", size: 512)

List paging is in response.page_info (hasMore, nextCursor). qr/3 returns the image in response.bytes. A link image is uploaded in three steps, or in one call with upload_image/4:

{:ok, image} = Lunixi.PaymentLinks.upload_image(MyApp.Lunixi, "cover.png", "image/png", bytes)
image.data["assetId"] # use as "imageAssetId"

The image PUT goes straight to the storage host behind the presigned URL with only the returned uploadHeaders; it never carries the access token or the request signature. A failed PUT is not retried and returns the storage status and code (for example AccessDenied after the URL expired); call upload_image/4 again.

Physical POS

Lunixi.PhysicalPos starts payments on your card terminals and reads transactions, reports and end-of-day results; Lunixi.PhysicalPosManagement manages stores, registers, terminals, devices and end-of-day policies. Bodies and filters use the gateway's camelCase names (string or atom keys); money is a minor-unit string, counts are integers. The field and filter lists are closed (Lunixi.PhysicalPos.Values) and checked before any request. Card data is never sent: the card is read on the device, and a card-looking field or card number returns Lunixi.PhysicalPos.CardDataRejectedError locally.

A payment write is asynchronous: 202 means accepted, not paid. Store the idempotency key with your order first; it is required for create_payment/3 and create_reversal/4 and is sent exactly as given (8–200 printable characters):

key = Lunixi.PhysicalPos.new_idempotency_key()
:ok = save_pos_key(order, key)

request = %{
  "operation" => "SALE",
  "target" => %{"deviceId" => device_id},
  "amountMinor" => "4500",
  "currency" => "TRY",
  "merchantReference" => order.reference,
  "allowDuplicateReference" => false
}

case Lunixi.PhysicalPos.create_payment(MyApp.Lunixi, request, key) do
  {:ok, %Lunixi.PhysicalPos.PaymentWriteResult{payment: payment, replayed: replayed}} ->
    {:accepted, payment, replayed}

  {:error, %Lunixi.PhysicalPos.OutcomeUnknownError{}} ->
    # The payment may exist: call again later with the SAME key and body.
    :retry_with_same_key
end

Payment writes make their own 1 + max_retries attempts with the same key and body. No answer, a 2xx without a payment or a 5xx that does not say "not started" ends in OutcomeUnknownError; never use a new key for that payment. RateLimitError carries retry_after; VoidAfterSettlementError means the payment is in an end-of-day, so return it with a REFUND. Lists return %Lunixi.PhysicalPos.Page{items, has_more, next_cursor, total_count}; the iterate_* functions stream every page. Management writes that need a key take an optional one (a new UUID when nil) and return %Lunixi.PhysicalPos.WriteResult{} with the key sent.

Lunixi.PhysicalPos.parse_webhook_event(raw, headers, secrets: [secret]) verifies the signature first, then reads a physical_pos.* event (Lunixi.PhysicalPos.Events): category, history_seq (nil for end-of-day events), original, cashier (nil without a cashier session) and device_sale.

Wallet, bank connect, sanction and insurance

These modules follow one pattern. Bodies and filters are maps or keyword lists with the gateway's camelCase names; money is a minor-unit string. Wallet, sanction and bank transfer / FX calls go through a single route table each (Lunixi.Wallet.Values.routes/0, Lunixi.Sanction.Values.routes/0, Lunixi.BankConnect.Values.transfer_routes/0, the same tables as the other Lunixi SDKs), so an unknown field, a missing field, a value outside its set or a missing idempotency key returns {:error, %Lunixi.Error{kind: :invalid}} before any request. Lists return %Lunixi.Page{items, has_more, next_cursor, total_count, data}; the iterate* functions stream every page.

transfer = %{
  endUserId: end_user_id,
  sourceWalletAccountId: account_id,
  destinationWalletNo: wallet_no,
  amount: "12550",
  currency: "TRY"
}

{:ok, fee} = Lunixi.Wallet.Transfers.quote_w2w(MyApp.Lunixi, transfer)
transfer = Map.put(transfer, :scheduleVersionId, fee["scheduleVersionId"])
{:ok, started} = Lunixi.Wallet.Transfers.initiate_w2w(MyApp.Lunixi, transfer, stored_key)

{:ok, _} =
  Lunixi.Wallet.Transfers.complete_w2w(MyApp.Lunixi, started["operationId"], %{
    endUserId: end_user_id,
    integrityHash: started["integrityHash"],
    nonce: started["nonce"]
  }, stored_complete_key)

Wallet writes that move money or create records require a stable key (1–128 printable characters). Bank transfers and exchange orders send a new UUID v4 when you pass no key, and retry a network error or 5xx with the same key; pass your own payout id to retry across processes. A transfer whose outcome is unknown stays SUBMITTED with outcomeUnknown: true: do not send it again with a new key.

Sanction screening returns matches, not verdicts. Lunixi.Sanction.clear_screening?/1 is true only when nothing was found and, where coverage is reported, coverageStatus is COMPLETE; a screening that could not run is an error, never an empty result.

Insurance orders, payment confirmation, policy issue, cancel, premium refund and leads require a key (8–200 printable ASCII characters); a quote takes its basket from paymentIntentId or context.items, never both. consent_from_quote/2 builds the order consent and premium_basket_item/2 the premium line of a payment that collects it. Policy files come back as PDF bytes in Lunixi.Response.bytes; the reconciliation export is %Lunixi.Insurance.ReconciliationExport{truncated, next_cursor, aborted}.

Webhook data readers take an event verified with Lunixi.Webhook.verify/3 and return only the delivered fields: Lunixi.BankConnect.Events.transaction_received/1, Lunixi.BankConnect.TransferEvents.data/1 (bank_transfer.*, not the payment.bank_transfer.* payment events), Lunixi.Insurance.Events.order_data/1 and lead_data/1.

Subscriptions, KYC, identity and marketplace

These modules call one route table each (Lunixi.Subscriptions.Values.routes/0, Lunixi.Kyc.Values.routes/0, Lunixi.Identity.Values.routes/0, Lunixi.Marketplace.Values.routes/0, the same tables as the other Lunixi SDKs). A route lists its body fields or takes a free map the gateway validates, its filters and its Idempotency-Key rule; an unknown field or filter, a missing field, a value outside its set or a key the route does not take returns {:error, %Lunixi.Error{kind: :invalid}} before any request (SUBSCRIPTION_FIELD, KYC_FILTER, MARKETPLACE_VALUE, IDEMPOTENCY_KEY_NOT_ACCEPTED …). Subscription and marketplace amounts are minor-unit strings in bodies, filters and answers ("0" is a free plan). Lists return %Lunixi.Page{}; on the subscription, plan, customer, card, invoice and audit-log lists send next_cursor back as pageToken.

# Renewals take the buyer from this record: identity and billing details are required.
{:ok, customer} =
  Lunixi.Subscriptions.Customers.upsert(MyApp.Lunixi, %{
    externalId: user.id,
    name: user.first_name,
    surname: user.last_name,
    email: user.email,
    gsmNumber: user.phone,
    identityNumber: user.identity_number,
    billingAddress: user.billing.address,
    billingCity: user.billing.city,
    billingCountry: user.billing.country,
    billingZipCode: user.billing.zip_code
  })

{:ok, subscription} =
  Lunixi.Subscriptions.create(
    MyApp.Lunixi,
    %{customerId: customer["id"], planId: plan_id, paymentCardId: card_id},
    stored_subscription_key
  )

Lunixi.Subscriptions.active?(subscription)
{:ok, _} = Lunixi.Subscriptions.cancel(MyApp.Lunixi, subscription["id"], atPeriodEnd: true)

Customers.upsert/3 requires name, surname, email, gsmNumber, identityNumber, billingAddress, billingCity, billingCountry and billingZipCode (billingContactName and the shipping fields are optional; phone, locale and metadata are not accepted); the gateway answers a missing or invalid field with Lunixi.Subscriptions.Values.customer_error_codes/0. Creating a subscription requires a stable key, sent in the header and the body; plan, customer, card, plan-change and charge-retry writes and KYC sessions accept one (1–255 printable characters). Cards are added from the checkout SDK's paymentMethodToken; a card number field is refused. Lunixi.Subscriptions.Portal.create_sdk_session/4 returns the four values the browser portal SDK needs, and Lunixi.Subscriptions.portal_url/2 the hosted portal URL of a link.

Lunixi.Kyc.create_session/3 takes person or company (sent as customer with its customerType) and metadata (sent as evidenceContextJson); list_sessions/2 accepts only limit and cursor. The kyc.* webhook (Lunixi.Kyc.Events) is the authority for the result; Lunixi.Kyc.assurance_meets?/2 compares assurance levels. Lunixi.Identity returns device and account-linking signals for a traceId, not a verdict; Lunixi.Identity.device_shared?/2 flags a device used by several accounts.

sellers = [
  %{subDealerId: "d_alice", amountMinor: "60000"},
  %{subDealerId: "d_bob", amountMinor: "40000"}
]

{:ok, response} =
  Lunixi.Marketplace.create_checkout_intent(MyApp.Lunixi, intent, sellers, "ALL_OR_NOTHING", stored_key)

The seller legs must add up to amount (MARKETPLACE_TOTAL) and are passed as an argument, never inside the body. A checkout answer without a token is an error instead of an empty page. charge_marketplace_card2d/5 and charge_marketplace_card3d/5 need the full commercial context (amount, currency, orderId, card, buyer with ip, billingAddress, basketItems, shippingAddress for a PHYSICAL item; missing order fields return ORDER_DETAILS_REQUIRED with the paths); card data is never logged or part of an error. The split checkout requires an idempotency key, the card charges accept one (16–128 printable characters without spaces, as for payments).

Address dictionary

Lunixi.Reference.list_provinces/1, list_districts/2 ("01"–"81") and list_neighborhoods/2 return the codes for ADDRESS input fields. An empty list means that level is not published yet.

Responses preserve envelope, data, page_info, content type, request ID and binary bytes. JSON money amounts remain canonical minor-unit strings and unknown fields/states remain available. {:error, %Lunixi.Error{}} retains safe kind/code/status/request ID without upstream messages, bodies, URLs or credentials. Do not log returned data/raw bodies.

Other documented merchant APIs are reachable with the generic signed transport:

Lunixi.request(MyApp.Lunixi, :get, "/api/v1/payments", query: [{"limit", "20"}])

Canonical bodies match JavaScript numeric-index key order, UTF-8 escaping and ECMAScript-style shortest number formatting. Duplicate keys, excessive nesting and unsafe integer numbers fail locally. Queries are encoded separately and included in the signature. Authentication has no body/Digest header.

Known payment mutations and financial helpers require a saved 16–128 character non-space printable ASCII idempotency key. GET/keyed requests may retry bounded transient transport/read failures or 429/500/502/503/504, preserving body/key with fresh nonce. Safe calls may refresh a rejected token once. Unkeyed mutations never automatically retry. Reconcile an unknown outcome before opening another payment attempt.

Raw webhooks and durable processing

Read the bounded raw bytes before JSON middleware. Keep all delivery header pairs so duplicates can be rejected:

{:ok, event} = Lunixi.Webhook.verify(raw_body, request_headers,
  secrets: [System.fetch_env!("LUNIXI_WEBHOOK_SECRET")])

The v2 HMAC binds event ID, exact ISO timestamp and raw bytes; OTP :crypto.hash_equals compares fixed-length MACs in constant time. Timestamp tolerance defaults to five minutes, can be 1–900 seconds and cannot be disabled. :now is a trusted test-clock option, never the caller's timestamp. A signed body type is required; an unsigned type header cannot authorize an action. Duplicate JSON/header fields and ID/type mismatches fail closed. Up to three current/previous secrets support rotation.

Verification does not consume an event ID. With optional Exqlite:

:ok = Lunixi.SqliteInbox.ensure_schema(connection) # startup/migration only
{:ok, applied} = Lunixi.SqliteInbox.process(connection, merchant_scope, event, fn transaction ->
  apply_verified_order_transition(transaction, event)
end)

apply_verified_order_transition is your application adapter that matches financial fields and uses the supplied connection for order/outbox updates. The connection must be exclusively owned for the whole transaction; independent processes use separate connections. Keep native busy timeouts modest (the sample uses 100 ms) and return a retryable HTTP failure on storage/lock errors. Do not block all NIF workers with long SQLite busy waits.

Marker and state commit together. Duplicates skip the callback; reused IDs with changed payload fail closed. Callback/commit/storage failure rolls back the marker for safe retry. Scope by merchant, retain markers for your replay policy and send external effects through an outbox. Do not acknowledge failed persistence with 2xx. For another database implement the same unique event/hash + financial update transaction contract. Use only authenticated events returned by verify.

The durable receipt example consumes authentic stdin/header data and records only event IDs/types; it does not fulfill orders. The TEST checkout example omits tokens from console output. Request a fresh dashboard replay for old deliveries rather than disabling freshness.

Examples and verification

mix run examples/checkout.exs
mix run examples/durable_webhook.exs < raw-webhook.json

Checkout requires LUNIXI_BASE_URL, TEST-only LUNIXI_KEY_ID, LUNIXI_PRIVATE_KEY_PEM, and saved LUNIXI_ORDER_ID / LUNIXI_ATTEMPT_KEY. The receipt requires LUNIXI_WEBHOOK_SECRET, LUNIXI_EVENT_ID, LUNIXI_SIGNATURE_TIMESTAMP, LUNIXI_SIGNATURE from an authentic delivery. Supply secrets securely; .env is not loaded automatically.

mix deps.get --check-locked
mix format --check-formatted
mix compile --warnings-as-errors
mix test
mix credo --strict --only warning
mix deps.audit
mix hex.audit
mix hex.build

Tests use real TLS with a generated synthetic CA, Node.js JSON/Ed25519/HMAC golden vectors, concurrent token acquisition, malicious form data and persistent SQLite rollback/restart/concurrency. OpenSSL CLI is used only to generate test certificates. Fixture credentials are deliberately synthetic; no live payment calls are needed. Credo runs its warning/security checks; this is not a Dialyzer type proof. Contributing · MIT.

Merchant-page integration example

The source CheckoutPresentation adapter calls the existing Lunixi.CheckoutHTML.render/2. present(response.data, nonce: nonce) defaults to {:ok, {:html, fragment}}; explicit mode: :hosted returns only a validated {:ok, {:redirect, url}}. Require this example from your authorized merchant controller and enforce native CSRF/no-store there. The existing client response already preserves paymentPageUrl; its browser and hosted tokens are independent.

Before upgrading from 0.x, follow the money-string migration.