lunixi

package module
v1.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 31 Imported by: 0

README

Lunixi

Lunixi Go SDK

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

Version 1.0.0 includes 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 Go reference

Documentation · Türkçe · Changelog · Security

Server-side Go client for Lunixi payments. Works with net/http, Gin, Echo, Fiber and other Go frameworks without a framework dependency. The SDK uses the Go standard library only. Go 1.26 or newer is required.

Installation

Install the published immutable v1.0.0 module:

go get github.com/Lunixi-Payment/lunixi-go@v1.0.0

Keep go.sum and verify the module through the Go proxy and checksum database. The 0.x versions use the previous money contract.

Create one client per merchant

import (
    "os"
    "time"
    lunixi "github.com/Lunixi-Payment/lunixi-go"
)

client, err := lunixi.New(lunixi.Config{
    BaseURL:    "https://api-gateway.lunixi.com",
    KeyID:      os.Getenv("LUNIXI_KEY_ID"),
    PrivateKey: os.Getenv("LUNIXI_PRIVATE_KEY_PEM"),
    Timeout:    30 * time.Second,
    MaxRetries: 2,
})
if err != nil { return err }

Register the public key in your Lunixi dashboard. Keep its Ed25519 private key on your server or secret manager. PKCS8 PEM, base64 PKCS8 DER, base64 32-byte seed and a validated base64 64-byte Ed25519 private key are accepted. The merchant key selects TEST/LIVE; there is no client-side environment switch. Never put a LIVE key in a sample application.

The client is safe to share between goroutines. Token acquisition is lazy, cached with an expiry margin and coalesced during concurrent refresh. Merchant requests are signed, including GET requests. The subscription, KYC, identity and marketplace dealer routes are sent with the access token only, as the gateway authenticates them; the marketplace split charges stay signed. Canonicalization matches the gateway's JSON.stringify numeric-key order, compact UTF-8 and number format; unsafe JSON integers and duplicate keys are rejected.

Setting Default Bounds / behavior
Timeout 30 seconds Up to 2 minutes per HTTP request; pass an overall context deadline
MaxRetries 0 0–5; GET or a supplied stable idempotency key only
MaxResponseBytes 8 MiB Up to 32 MiB; request JSON is limited to 8 MiB
HTTPClient Standard client Copied; redirects always disabled; never use insecure TLS in production
AllowInsecureLocalhost false HTTP allowed only for explicit localhost / literal loopback testing

BaseURL must be a trusted HTTPS origin, without credentials, path or query. Merchant API paths cannot change origin, traverse directories or call the token endpoint through Do.

Start checkout

Load the basket and order from your server-side records. Persist the attempt key before calling, then reuse that key and body after a timeout.

ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
defer cancel()

response, err := client.Payments.CreateIntent(ctx, lunixi.IntentRequest{
    Amount:      "10050", // 100.50 TRY, canonical minor-unit strings
    Currency:    "TRY",
    OrderID:     "ORD-1001",
    CallbackURL: "https://merchant.example/payment/return",
    BasketItems: []lunixi.BasketItem{
        {ID: "line-1", Name: "Example product", ItemType: "PHYSICAL", Price: "10050"},
    },
}, persistedAttemptKey)
if err != nil { return err }

var checkout struct { Token string `json:"token"` }
if err := response.DecodeData(&checkout); err != nil { return err }
if checkout.Token == "" { return errors.New("missing checkout token") }
// Send Token only to this order's authenticated customer, with
// Cache-Control: no-store. Initialize the existing Lunixi checkout form.

Amounts are string minor units, positive and no greater than 9223372036854775807. Basket Price is the line total; line totals must equal Amount. Do not send the removed root fields price, paidPrice, autoCapture. Installment selection and fees belong to the Lunixi form; EnabledInstallments can only narrow the counts the form offers for this payment (for example []int{1, 2, 3} for at most 3, []int{1} for a 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 1–36, distinct and include 1, otherwise CreateIntent returns ErrConfiguration before any request; the list is sent in ascending order. Buyer/address and documented insurance basket details can be supplied on IntentRequest; optional method restrictions can narrow the methods already enabled in the Lunixi panel. BasketItem.ProductCategory (productCategory) is the optional Lunixi product category, used by payment methods with legal installment limits (e.g. shopping loan) and other platform features; use a ProductCategory* constant (ProductCategories() lists the codes known to this version). Empty 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 plain string.

The existing Lunixi form handles cards and enabled alternative methods; this SDK does not build another form or collect PAN/CVV. A checkout token, a browser return, HTTP 200 or an authorization is not proof of capture. Finalize only from an authenticated gateway result after checking your stored order ID, merchant, payment ID, expected amount/currency and final capture/reconciliation state. Apply corresponding refund, void and dispute transitions separately.

Payment lifecycle

payment, err := client.Payments.Get(ctx, paymentID)
partial := int64(2500)
refund, err := client.Payments.Refund(ctx, paymentID, &partial, "Customer return", persistedRefundKey)
// nil amount requests the full capture/refund; Void releases an authorization.
Helper Coverage
Payments CreateIntent, Get, List, Methods, ListPaymentMethods, Capture, Refund, Void
Payments methods DirectMethodPayment, ConfirmPaymentAction, ResendPaymentAction
Payments promissory notes GetPromissoryNotes, CancelPromissoryNotes, DownloadPromissoryNoteDocument
Payments bank transfer ListBankTransferExceptions, AcceptBankTransferException, MarkBankTransferExceptionRefunded
Payments split Split, GetSplit, ListSplits, RefundSplit
Payments cards BinInfo, InstallmentOptions, CardTaxonomy, StoreCard, ListStoredCards, GetStoredCard, DeactivateStoredCard
Payments marketplace and reporting CreateMarketplaceIntent, FailoverRecoveryAnalytics, ProviderCredentialAnalytics
PaymentLinks Create, List, Get, Update, Pause, Resume, Deactivate, Action, Send, QR, ListAttempts, ListPayments, CreateImageUpload, ConfirmImageUpload, UploadImage
Reference ListProvinces, ListDistricts, ListNeighborhoods
Fraud Evaluate, RecordEvent, RecordBatch, Decisions, Decision, LatestForPayment
Client.Do Signed requests to other documented /api/v1/ merchant endpoints
WebhookVerifier, SQLInbox Raw v2 verification and durable transactional deduplication

Split accepts the documented gateway map and locally checks safe total/leg amounts, 1–5 legs and the leg sum. A card leg (paymentMethod empty or CARD) carries no method block; a non-card leg is a MOBILE_BILLING, WALLET or PROMISSORY_NOTE method with exactly its own block (SplitLegBlockFields()), including providerCode, and no card fields; a promissory-note leg gives noteCount, not a schedule. MEAL_CARD, OPEN_BANKING, SHOPPING_LOAN and BANK_TRANSFER cannot be legs. Other method-specific fields remain governed by the API schema. ListSplits takes SplitListFilters (status and currency lists, created range, order, owner, limit 1–100, After cursor). A pending split may return a Response with HTTP 400; inspect StatusCode and signed gateway status. AUTHORIZED, AWAITING_*, COMPENSATING, partial refunds and reconciliation-required states do not imply a fulfilled order. Root SDK responses preserve the original envelope, Data, PageInfo and binary Bytes; DecodeData uses json.Number for interface values.

Every product has a typed client (see the sections below). Client.Do remains for any other documented /api/v1/ endpoint, with the same signed transport. For example:

response, err := client.Do(ctx, lunixi.Request{
    Method: "GET",
    Path: "/api/v1/payments",
    Query: url.Values{"limit": {"20"}},
})

Retries keep the exact body and idempotency key and use a new signature nonce. Mutation helpers require 16–128 non-space printable ASCII characters as the key (8–200 for payment links). GET and keyed calls can retry transient network failures / 429 / 500 / 502 / 503 / 504 within the configured bound, with capped exponential delay; safe operations can refresh a rejected token once. Unkeyed mutations never automatically retry. Reconcile an unknown payment outcome before creating another attempt.

APIError provides StatusCode, Code and RequestID. Error strings omit upstream messages and request/response bodies. Responses can contain customer data or tokens; do not log Response, headers, raw webhook bytes or credentials.

Cards, installments and marketplace intents

quote, err := client.Payments.InstallmentOptions(ctx, lunixi.InstallmentOptionsRequest{
    Amount: "120000", Currency: "TRY", BinOrPan: bin, Installment: 3,
    EnabledInstallments: []int{1, 2, 3},
})
stored, err := client.Payments.StoreCard(ctx, lunixi.StoreCardRequest{
    Card: cardFields, CardUserKey: buyerKey, CallbackURL: "https://merchant.example/cards/return",
}, persistedStoreKey)

BinInfo takes a 6 or 8 digit BIN or a card number prefix (digits only); the SDK never puts card numbers or security codes in error messages, and you must not log card fields either. InstallmentOptions needs Amount (with Currency) or IntentID; EnabledInstallments follows the IntentRequest rule and is sent in ascending order. With Installment greater than 1 and a BIN the answer carries the quoteToken for DirectMethodPaymentRequest.WithInstallment. StoreCard and DeactivateStoredCard require an idempotency key; ListStoredCards(cardUserKey) and GetStoredCard(token) read stored cards.

CreateMarketplaceIntent takes a MarketplaceIntentRequest: the IntentRequest fields plus Sellers (SubDealerID, AmountMinor as positive minor-unit text, optional Scenario object) and MultiSellerPolicy. The sellers' amounts must add up to Amount; any other total is refused before sending. The key is optional; pass a stable one per attempt to make retries safe. FailoverRecoveryAnalytics and ProviderCredentialAnalytics(credentialID, filters) read merchant reporting.

link, err := client.PaymentLinks.Create(ctx, lunixi.PaymentLinkRequest{
    Usage: lunixi.PaymentLinkUsageSingleUse, AmountMode: lunixi.PaymentLinkAmountModeFixed,
    Currency: "TRY", AmountMinor: "150000", Title: "Invoice 42",
    Recipient: &lunixi.PaymentLinkRecipient{Email: "buyer@example.com"},
}, persistedLinkKey)
image, err := client.PaymentLinks.UploadImage(ctx, "logo.png", lunixi.PaymentLinkImageContentTypePNG, pngBytes)

Every payment-link call is signed, reads included; the signing key decides the environment, so a TEST key sees only TEST links. Create and Send require an idempotency key (8–200 printable ASCII characters); Update, Pause, Resume and Deactivate accept one. Usage, amount mode and currency are fixed at creation: Update(ctx, linkID, expectedRowVersion, changes, key) takes only PaymentLinkSpecFields() names, refuses PaymentLinkImmutableFields(), clears a field given nil and sends a time.Time as RFC 3339 UTC. Value sets are the PaymentLink*, BuyerFieldRequirement* and CustomFieldType* constants; unknown values are refused before sending, and business rules are left to the API (422 payment_link.validation.invalid). List, ListAttempts and ListPayments return Data.items with PageInfo; pass pageInfo.nextCursor as Cursor. QR returns the SVG or PNG image in Response.Bytes.

A link image takes three steps: CreateImageUpload returns the upload target, the file is PUT to UploadURL with exactly UploadHeaders, and ConfirmImageUpload publishes it (PNG, JPEG or WebP, at most 2 MiB). UploadImage runs all three. The PUT goes to the storage host through your configured HTTP client but not through the signed transport: no access token, signature, digest or idempotency header is sent there. A failed PUT returns an APIError with the storage status and code (for example AccessDenied after the URL expires) and is not retried; call UploadImage again.

Payment methods from the server

ListPaymentMethods lists the methods open for your account with each method's blockName, providerSelection, providerSelectionMode and the providers' inputFields; pass a code (lunixi.PaymentMethodMobileBilling) to list one method, or "" for all. Always read provider codes from this answer.

request := lunixi.NewDirectMethodPaymentRequest("10000", "TRY", "ORD-1001").
    WithMethodFields(lunixi.PaymentMethodMobileBilling, providerCode, map[string]any{
        "gsmNumber": "+905321234567",
    })
response, err := client.Payments.DirectMethodPayment(ctx, request, persistedAttemptKey)
if err != nil { return err }
// HTTP 202 with data.action when the buyer must act (PaymentActionType*).
accepted := true
_, err = client.Payments.ConfirmPaymentAction(ctx, paymentID, actionID, lunixi.PaymentActionConfirmRequest{
    OTP: "123456", ConsentAccepted: &accepted,
})

DirectMethodPayment requires the idempotency key. Before sending, it checks (also for raw Client.Do bodies to /api/v1/payments/direct/payment): known fields only; paymentMethod, amount, currency, orderId; card fields (CardOnlyFields()) only with CARD; exactly the block of the chosen method (BlockNameOf, MethodBlockFields()); a block of at most 32 fields whose values are text (at most 1024 characters), numbers, booleans, ADDRESS objects or GROUP lists of at most 10 objects; 1–100 basket items for SHOPPING_LOAN. A method without a block cannot be paid this way yet. Cards use WithCard (and WithForce3D(true) for 3D Secure). ConfirmPaymentAction sends only otp (digits), consentAccepted and fields; ResendPaymentAction asks for a new code and closes the previous action.

Promissory notes

Give the plan either as a schedule or as a note count, never both:

request := lunixi.NewDirectMethodPaymentRequest("120000", "TRY", "ORD-1002").
    WithMethodFields(lunixi.PaymentMethodPromissoryNote, providerCode, debtorFields).
    WithPromissoryNoteSchedule([]lunixi.PromissoryNoteScheduleRow{
        {Amount: "60000", DueDate: "2027-01-15"},
        {Amount: "60000", DueDate: "2027-02-15"},
    })
// or .WithPromissoryNoteCount(3)

A schedule has 1–24 rows with positive minor-unit amounts that add up to the payment amount and YYYY-MM-DD calendar due dates in ascending order; that a date is in the future is checked by the API. GetPromissoryNotes returns the notes and their status, CancelPromissoryNotes cancels the listed serial numbers (nil cancels every open note) and DownloadPromissoryNoteDocument returns the printable PDF in Response.Bytes (locale PromissoryNoteDocumentLocaleTR or PromissoryNoteDocumentLocaleEN). The document is not stored; download it when needed. Note changes arrive as PromissoryNoteEvent* webhooks. ADDRESS fields take codes from client.Reference.ListProvinces, ListDistricts(provinceCode) and ListNeighborhoods(districtCode).

Para Transferi (bank transfer)
request := lunixi.NewDirectMethodPaymentRequest("125000", "TRY", "ORD-1003").
    WithMethodFields(lunixi.PaymentMethodBankTransfer, "", map[string]any{"bankCode": buyerBankCode})
response, err := client.Payments.DirectMethodPayment(ctx, request, persistedAttemptKey)
if err != nil { return err }
if instruction := response.BankTransferInstruction(); instruction != nil {
    // Show IBAN, HolderName, AmountMinor, PaymentCode and ExpiresAt to the buyer.
}

The buyer sends the money from their own bank to your bank account; it does not pass through Lunixi. bankCode comes from the method's options in ListPaymentMethods; BankTransferOtherBanksCode ("9999") means a bank that is not listed. The block takes no provider code. The instruction is display data; the payment is paid only when the gateway reports it captured. Late, short and excess transfers are listed by ListBankTransferExceptions (BankTransferExceptionFilters: TEST / LIVE, BankTransferExceptionStatus*, limit 1–200) and decided with AcceptBankTransferException or MarkBankTransferExceptionRefunded (after you refund the sender yourself). Related webhooks are PaymentBankTransferEvent*.

Physical POS

client.PhysicalPos starts card payments on your own devices, reverses or cancels them, starts end-of-day and reads payments, transaction trees, sales and tax summaries and end-of-day results. client.PhysicalPosManagement manages stores, registers, logical terminals (bank rows, payment-provider rows, device links), devices and their identity keys, and the end-of-day policy at account, store and device level.

key := lunixi.NewPhysicalPosIdempotencyKey()
// Store key with your order BEFORE the call.
result, err := client.PhysicalPos.CreatePayment(ctx, map[string]any{
    "operation":         lunixi.PhysicalPosOperationSale,
    "target":            map[string]any{"deviceId": deviceID},
    "amountMinor":       "4500",
    "currency":          "TRY",
    "merchantReference": orderID,
}, key)
var unknown *lunixi.PhysicalPosOutcomeUnknownError
if errors.As(err, &unknown) {
    // The payment may exist: call again later with the SAME key.
}
// result.StatusCode is 202 for a new payment, 200 with result.Replayed for a repeat.

Requests and filters are maps with the gateway's field names (PhysicalPosRequestFields, PhysicalPosFilters); an unknown field, a missing required field, a wrong type, a numeric amount or a page limit outside 1–100 returns ErrConfiguration before sending. Amounts are canonical minor-unit text; counts, line numbers, quantities and rowVersion are integers. nil clears a nullable field (for example city in UpdateStore); "" leaves an optional field out. A time.Time filter is sent as UTC ISO-8601, and dateFrom / dateTo as its own calendar day.

Card data never goes to this API: the card is read on the device. A card-data field name (pan, cardNumber, cvv, expiry, track2 …) anywhere in a request, or a card number in merchantReference, an item name or tax group code, or the merchantReference / q filters, returns *PhysicalPosCardDataRejectedError with the field path, never the value, and nothing is sent.

A payment write is accepted, not paid: follow it with the PhysicalPosEvent* webhooks or GetPayment. CreatePayment and CreateReversal require the key and send it exactly as given (8–200 printable ASCII characters); CancelPayment, StartSettlement and the management creates accept "" and then send a new UUID, returned as IdempotencyKey. Payment writes retry themselves (MaxRetries) with the same key and body. When any attempt got no answer, a 2xx without the payment, or a 5xx that does not say nothing started, the call returns *PhysicalPosOutcomeUnknownError; never use a new key for that payment. A void after the device's end-of-day is *PhysicalPosVoidAfterSettlementError (refund instead), a 429 is *PhysicalPosRateLimitError with RetryAfter, and other errors of a keyed write are *PhysicalPosWriteError carrying the key. Lists return PhysicalPosPage (Items, HasMore, NextCursor, TotalCount with includeTotal); every list also has an Iterate… form that follows the cursor.

verifier.VerifyPhysicalPos(rawBody, headers) verifies a webhook and reads it as PhysicalPosWebhookEvent: Category (payment, fiscal_document, settlement, other), HistorySeq (nil for end-of-day events; deduplicate those by ID), Original for reversals, Cashier for payments started in a device cashier session, and IsDeviceSale for a sale made directly on the device. Amounts in the payload are checked after the signature.

Wallet

client.Wallet is the merchant surface of the closed-loop wallet, grouped by area: Programs, EndUsers, Wallets, Deposits, Corporate, Fees, Transfers (wallet to wallet and to an IBAN), Withdrawals, Operations, Topups, Payments, QR and BulkPayouts. Every call is signed; the key needs the WALLET_SERVICE product and the wallet permission behind the route.

quote, err := client.Wallet.Transfers.QuoteW2W(ctx, map[string]any{
    "endUserId": endUserID, "sourceWalletAccountId": accountID,
    "destinationWalletNo": walletNo, "amount": "12550", "currency": "TRY",
})
started, err := client.Wallet.Transfers.InitiateW2W(ctx, request, key)
// Commit with the integrityHash and nonce of the answer (and otpCode when otpRequired):
done, err := client.Wallet.Transfers.CompleteW2W(ctx, operationID, map[string]any{
    "endUserId": endUserID, "integrityHash": hash, "nonce": nonce, "otpCode": otp,
}, completeKey)

Requests and filters are maps checked against WalletRoutes() (the same route table as the other Lunixi SDKs) before sending: an unknown field, a missing required field, an amount that is not minor-unit digit text ("12550"), a bad row in ImportEmployees / OffboardEmployees / bulk payout items, or a missing Idempotency-Key on a route that requires it returns ErrConfiguration. Wallet keys are 1–128 printable ASCII characters. Complete… calls put operationId into the body themselves. QR.Image returns the SVG or PNG in Response.Bytes. Lists return CursorPage; Iterate follows the cursor.

Bank accounts, transfers and currency exchange

client.BankConnect reads your connected bank accounts: ListBanks, ListConnections / GetConnection, ListAccounts / GetAccount, ListBalances, ListTransactions / GetTransaction (each list with an Iterate… form) and RequestSync. Connecting a bank happens in the Lunixi dashboard only. Filters are checked against BankConnectFilters() before sending: known filters only, values from their sets, limit 1–100, at most 100 account ids, minor-unit text amounts with minAmountMinor ≤ maxAmountMinor, bookedTo only with bookedFrom, and at most 92 days between them.

client.BankConnect.Transfers (ListPurposes, Create, List / Iterate, Get) and client.BankConnect.FX (ListRates, CreateQuote, CreateOrder, ListOrders / IterateOrders, GetOrder) move money on connections that offer it; they need the bank-connect:transfer scope and a key with an IP allowlist. Bodies are checked against BankTransferRoutes().

result, err := client.BankConnect.Transfers.Create(ctx, map[string]any{
    "accountId": accountID, "receiverIban": iban, "receiverName": "Ada Lovelace",
    "amountMinor": "150075", "paymentPurpose": purposeCode,
}, payoutID) // "" generates a UUID, returned as result.IdempotencyKey

Create and CreateOrder check your key (8–200 printable ASCII characters) or generate one, and retry a network error or a 5xx (MaxRetries) with the same key and body; the same key with the same body answers Replayed. A quote takes exactly one of sourceAmountMinor / targetAmountMinor and two different accounts. Webhooks: ParseBankAccountTransactionReceived reads BankConnectEventTransactionReceived, ParseBankTransferWebhook reads the BankTransferEvent* events (bank_transfer.*, not the payment.bank_transfer.* events of a bank transfer payment).

Sanctions screening

client.Sanction screens names, wallets, accounts, transactions, public procurement bans and adverse media, evaluates behavioural alerts, registers ongoing monitoring and reads alerts, matches, monitored entities, dataset freshness, entity intelligence and your deny list. Bodies and filters are checked against SanctionRoutes(), SanctionNestedFields() and SanctionValueSets() before sending.

result, err := client.Sanction.ScreenName(ctx, map[string]any{
    "name": "Ada Lovelace", "subjectType": lunixi.SanctionSubjectTypePerson,
    "riskDomains": []string{lunixi.SanctionRiskDomainSanctions, lunixi.SanctionRiskDomainPep},
})
if err == nil && lunixi.IsClearScreening(result) {
    // nothing found in a COMPLETE screening
}

Screening returns matches, not verdicts. IsClearScreening is true only without any match, hit or blocking flag and, where coverage is reported, with coverageStatus COMPLETE; PARTIAL, DEGRADED or missing coverage is never clear. A screening that could not run (HTTP 503, or a 2xx whose status is not success) is an *APIError, never an empty result.

Insurance

client.Insurance lists and searches insurance products for a basket, prices them (CreateQuote), turns a quote into an order (CreateOrder), binds or confirms the premium payment, issues and cancels policies, refunds the premium, submits leads for types sold by request only, downloads policy documents, receipts and certificates (Response.Bytes) and reads reconciliation (ExportReconciliation returns the CSV with Truncated, NextCursor and Aborted).

quote, err := client.Insurance.CreateQuote(ctx, map[string]any{
    "insuranceType": "TICKET_CANCELLATION", "currency": "TRY", "paymentIntentId": intentID,
}, "")
consent, err := client.Insurance.ConsentFromQuote(option, acceptedAt)
order, err := client.Insurance.CreateOrder(ctx, map[string]any{"quoteId": quoteID, "consent": consent}, orderKey)
item, err := client.Insurance.PremiumBasketItem(order, "Ticket insurance", "Insurance", "")

Fields and filters are checked against InsuranceQuoteFields(), InsuranceLeadFields(), InsuranceFilters() and the other field lists before sending; the rules inside an insurance type's own object stay with the gateway (422 with every field error at once). A quote takes its basket from paymentIntentId or context.items, not both. CreateOrder, ConfirmPayment, IssuePolicy, CancelOrder, RefundPremium and CreateLead require an Idempotency-Key (8–200 printable ASCII characters); CreateQuote and BindPayment accept "". Webhooks: ParseInsuranceWebhook reads the order events, ParseInsuranceLeadWebhook the InsuranceEventLeadSubmitted event.

Subscriptions

client.Subscriptions creates and manages subscriptions (Create, Get, List / Iterate, Cancel, Pause, Resume, ChangePlan, AuditLogs) and hangs the related resources off Plans, Customers, Cards, Invoices, Portal, Products, Features, Addons and Usage.

customer, err := client.Subscriptions.Customers.Upsert(ctx, map[string]any{"externalId": userID, "email": email}, "")
plan, err := client.Subscriptions.Plans.Create(ctx, map[string]any{
    "productId": productID, "code": "pro", "name": "Pro", "price": "9900", "currency": "TRY",
    "billing": map[string]any{"frequency": lunixi.SubscriptionBillingFrequencyMonthly},
}, "")
sub, err := client.Subscriptions.Create(ctx, map[string]any{
    "customerId": customerID, "planId": planID, "paymentCardId": cardID,
}, subscriptionKey) // required; sent in the header and the body

Requests and filters are maps checked against SubscriptionRoutes() (the same route table as the other Lunixi SDKs) before sending: an unknown field or filter, a missing required field, a value outside its set (collection method, billing frequency, card verification mode, plan-change behavior, portal SDK mode) or a missing key returns ErrConfiguration, naming the field and never its value. Money members are canonical minor-unit strings in bodies, filters and answers ("0" is a free plan). Create requires an Idempotency-Key (1–200 printable ASCII characters); plan, customer, card, plan-change and charge-retry writes accept one. Cards.Add takes the checkout SDK's paymentMethodToken; a card number is refused. The subscription, plan, customer, card, invoice and audit-log lists return CursorPage with the nextPageToken in NextCursor (sent back as pageToken by Iterate) and PageSize. Portal.CreateSdkSession returns the session proof for the browser portal SDK; Portal.CreatePortalLink returns a hosted link (SubscriptionPortalURL). IsSubscriptionActive, IsSubscriptionTerminal and the SubscriptionEvent* webhook names come with it.

KYC and identity signals

client.Kyc creates KYC, KYB and evidence sessions (CreateSession, EvidenceRequest), reads and lists them (GetSession, ListSessions / IterateSessions, Timeline), sets the jurisdiction and primary document, uploads a document from your server, submits, sends to manual review, and reads or updates your KYC policy, webhook deliveries and erasure requests. person or company is sent as customer with its customerType, metadata as evidenceContextJson; ttlMinutes is 1–1440. The kyc.* webhook (KycEvent*) is the authority for the result; IsKycSessionTerminal and KycAssuranceMeets read the decision.

client.Identity reads the device and account-linking signals of the browser fingerprint SDK: AnalyzeSync / Analyze, AccountLinks, GetSession, RelatedSessions, Timeline, TopSources and ListSessions. IsIdentityDeviceShared(links, 2) reports a device shared by two or more accounts; IdentityLinkReasons lists why. These are signals, not an allow / block verdict.

Marketplace sub-dealers

client.Marketplace splits charges across sub-dealers and runs the sub-dealer lifecycle, commissions, payouts and the audit log.

legs := []lunixi.MarketplaceSeller{{SubDealerID: "d_alice", AmountMinor: "6050"}, {SubDealerID: "d_bob", AmountMinor: "4000"}}
intent, err := client.Marketplace.CreateCheckoutIntent(ctx, intentRequest, legs, lunixi.MarketplaceMultiSellerPolicyAllOrNothing, attemptKey)
dealer, err := client.Marketplace.CreateDealer(ctx, map[string]any{"legalName": "Acme Ltd", "dealerType": lunixi.MarketplaceDealerTypeLegalEntity})
link, err := client.Marketplace.OnboardingToken(ctx, dealerID)
onboardingURL := lunixi.MarketplaceOnboardingURL(link, "")

The split charges (CreateCheckoutIntent, ChargeMarketplaceCard2d, ChargeMarketplaceCard3d, ChargeMarketplaceCard) are signed and take an optional payment key (16–128 printable ASCII characters). The seller legs must add up to amount with positive minor-unit shares; a card charge also needs currency, orderId, card, buyer, billingAddress and at least one basket item, and refuses price / paidPrice and a non-boolean preauth. Card data is sent as given and never appears in an error message; most marketplaces use the hosted CreateCheckoutIntent, which returns an *APIError when the answer carries no token. Dealer, commission, payout and audit routes are bearer-only and checked against MarketplaceRoutes(); money members are canonical minor-unit strings in bodies, filters and answers.

Verify webhooks and consume them transactionally

verifier, err := lunixi.NewWebhookVerifier(lunixi.WebhookConfig{
    Secrets: []string{os.Getenv("LUNIXI_WEBHOOK_SECRET")},
})
if err != nil { return err }
event, err := verifier.VerifyRequest(ctx, request)
if err != nil { return err } // return a non-2xx response

inbox, err := lunixi.NewSQLInbox(db, "lunixi_webhook_inbox", merchantScope)
if err != nil { return err }
// Apply inbox.EnsureSchema(ctx) during migrations / startup, not per request.
applied, err := inbox.Process(ctx, event, func(tx *sql.Tx) error {
    // Validate the authenticated event against your stored order and payment.
    // Apply the order transition AND any outbox rows using this same tx.
    return applyVerifiedOrderTransition(ctx, tx, event)
})

The signature is HMAC-SHA256 over eventId + "." + exactTimestamp + "." + rawBody. Verification uses constant-time comparison, checks timestamp freshness (default 5 minutes, configurable up to 15 minutes), rejects duplicate headers/JSON keys and matches the signed body ID/type against the headers. The event body must contain type; an unsigned type header cannot authorize a financial action. Raw bytes must reach the verifier before any JSON middleware. Secrets can include up to three active/previous secrets during rotation. Use a fresh delivery/replay from the dashboard for an old event; do not disable timestamp checks.

SQLInbox supports PostgreSQL and SQLite through database/sql; supply your own driver. Each merchant/integration gets a separate scope. The callback and event marker commit together. A duplicate skips the callback; a different payload reusing the ID fails closed. Callback/database failure rolls back the marker, allowing safe provider retry. Retain markers for your event replay policy; do not prune within the provider's delivery/replay horizon. External effects require a transactional outbox.

The runnable SQLite receipt server includes actual rollback, crash/restart, duplicate, collision, concurrent replay and HTTP tests. It records verified notifications only; it does not fulfill orders. Add your order state adapter after matching all financial fields. The database contains no webhook body, card data or customer details. Place the loopback HTTP listener behind your trusted HTTPS reverse proxy.

Examples and checks

# Main SDK and TEST checkout example
go test -race ./...
go vet ./...
go build ./...
go run ./examples/checkout

# Standalone durable receipt server; the SQLite example requires CGO/C compiler.
cd examples/webhook
go test -race ./...
go vet ./...
go run .

The checkout example requires LUNIXI_BASE_URL, LUNIXI_KEY_ID (TEST only), LUNIXI_PRIVATE_KEY_PEM, and persisted LUNIXI_ORDER_ID / LUNIXI_ATTEMPT_KEY. The receipt server requires LUNIXI_WEBHOOK_SECRET. Supply secrets from your shell/secret manager without committing them. .env files are ignored and are not loaded automatically.

go run golang.org/x/vuln/cmd/govulncheck@v1.9.0 ./...

Run that audit in both modules. CI checks Go 1.26/1.27, formatting, vet, the race detector, builds and vulnerability reachability. Tests use real TLS test servers and independently produced Node.js Ed25519/JSON/HMAC fixtures. All fixture keys/secrets are synthetic and unusable for merchant access. Tests require no merchant credentials or network payment calls.

Security policy · Contributing · MIT license

Merchant-page integration example

The source example defines RenderCheckoutHTML(token, nonce) and HostedCheckoutURL(paymentPageUrl) in presentation.go. Copy/adapt these helpers inside your existing authorized, CSRF-protected merchant controller. The CLI defaults to LUNIXI_CHECKOUT_MODE=embedded; hosted validates the backend URL. It renders/validates internally and intentionally prints neither HTML, token nor URL. These example functions are not new SDK client methods.

Before upgrading from 0.x, follow the migration guide.

Documentation

Overview

Package lunixi is a server-side client for Lunixi's signed merchant APIs.

The client signs requests with Ed25519, caches short-lived access tokens, preserves integer minor-unit money, and verifies raw-body v2 webhooks. Secret keys belong on the merchant server; browser checkout uses the short-lived token returned by Payments.CreateIntent.

Index

Constants

View Source
const (
	BankConnectionStatusPendingDocuments = "PENDING_DOCUMENTS"
	BankConnectionStatusUnderReview      = "UNDER_REVIEW"
	BankConnectionStatusPendingSetup     = "PENDING_SETUP"
	BankConnectionStatusActive           = "ACTIVE"
	BankConnectionStatusDegraded         = "DEGRADED"
	BankConnectionStatusSuspended        = "SUSPENDED"
	BankConnectionStatusDisconnected     = "DISCONNECTED"
)

Status of a bank connection. Data is read only while a connection is ACTIVE or DEGRADED (DEGRADED: the last reads from the bank failed, so the data may be older; see the account's freshness). RequestSync on any other status is 409 bank_connect.connection.not_active.

View Source
const (
	BankAccountStatusActive   = "ACTIVE"
	BankAccountStatusInactive = "INACTIVE"
)

Status of a connected bank account.

View Source
const (
	BankTransactionDirectionCredit = "CREDIT"
	BankTransactionDirectionDebit  = "DEBIT"
)

Direction of a bank transaction: money in (CREDIT) or out (DEBIT). amountMinor is always positive.

View Source
const (
	BankTransactionTypeTransferIn          = "TRANSFER_IN"
	BankTransactionTypeTransferOut         = "TRANSFER_OUT"
	BankTransactionTypeInternalIn          = "INTERNAL_IN"
	BankTransactionTypeInternalOut         = "INTERNAL_OUT"
	BankTransactionTypePosSettlement       = "POS_SETTLEMENT"
	BankTransactionTypePosSettlementRefund = "POS_SETTLEMENT_REFUND"
	BankTransactionTypeFee                 = "FEE"
	BankTransactionTypeTax                 = "TAX"
	BankTransactionTypeCashIn              = "CASH_IN"
	BankTransactionTypeCashOut             = "CASH_OUT"
	BankTransactionTypeCard                = "CARD"
	BankTransactionTypeLoan                = "LOAN"
	BankTransactionTypeFX                  = "FX"
	BankTransactionTypeInterest            = "INTEREST"
	BankTransactionTypeOther               = "OTHER"
)

Lunixi's bank-independent transaction type (canonicalType).

View Source
const (
	BankAvailabilityAvailable  = "AVAILABLE"
	BankAvailabilityComingSoon = "COMING_SOON"
)

Availability of a bank in the catalogue. AVAILABLE: the bank can be connected (connections are started in the Lunixi dashboard).

View Source
const (
	BankCapabilityAccountList      = "ACCOUNT_LIST"
	BankCapabilityBalance          = "BALANCE"
	BankCapabilityTransactions     = "TRANSACTIONS"
	BankCapabilityOutgoingTransfer = "OUTGOING_TRANSFER"
	BankCapabilityFXExchange       = "FX_EXCHANGE"
)

What a bank or a connection offers (capabilities). OUTGOING_TRANSFER and FX_EXCHANGE: the connection can send transfers (BankConnect.Transfers) and exchange currency (BankConnect.FX).

View Source
const (
	BankSyncStatusQueued    = "QUEUED"
	BankSyncStatusScheduled = "SCHEDULED"
)

Answer of RequestSync. QUEUED: the read starts now or is already waiting. SCHEDULED: it runs at scheduledAt.

View Source
const (
	BankTransferStatusPendingOtp = "PENDING_OTP"
	BankTransferStatusSubmitted  = "SUBMITTED"
	BankTransferStatusProcessing = "PROCESSING"
	BankTransferStatusCompleted  = "COMPLETED"
	BankTransferStatusFailed     = "FAILED"
	BankTransferStatusReturned   = "RETURNED"
	BankTransferStatusCanceled   = "CANCELED"
)

Status of an outgoing bank transfer. PENDING_OTP: started in the dashboard, waiting for the user's e-mail code (an API-key transfer never has it). SUBMITTED: approved and queued or sent to the bank. PROCESSING: the bank is processing it. COMPLETED: the bank completed it; it can still become RETURNED if the receiving bank sends it back. FAILED, RETURNED and CANCELED are final.

View Source
const (
	BankTransferRailInternal  = "INTERNAL"
	BankTransferRailIntrabank = "INTRABANK"
	BankTransferRailFast      = "FAST"
	BankTransferRailEft       = "EFT"
	BankTransferRailUnknown   = "UNKNOWN"
)

The rail the bank chose: own accounts, same bank, FAST, EFT; UNKNOWN until it says.

View Source
const (
	BankTransferInitiatedViaPanel = "PANEL"
	BankTransferInitiatedViaAPI   = "API"
)

Where a transfer or an exchange order was started.

View Source
const (
	BankFXOrderStatusSubmitted = "SUBMITTED"
	BankFXOrderStatusCompleted = "COMPLETED"
	BankFXOrderStatusFailed    = "FAILED"
)

Status of a currency exchange order. An order is created SUBMITTED.

View Source
const (
	BankFXRequestedSideSource = "SOURCE"
	BankFXRequestedSideTarget = "TARGET"
)

Which amount of an exchange quote you fixed: SOURCE (the amount you sell) or TARGET (the amount you buy).

View Source
const (
	// BankTransferEventCreated: a transfer was created (API: SUBMITTED;
	// dashboard: PENDING_OTP).
	BankTransferEventCreated = "bank_transfer.created"
	// BankTransferEventCompleted: the bank completed the transfer.
	BankTransferEventCompleted = "bank_transfer.completed"
	// BankTransferEventFailed: the transfer failed; failureCode says why.
	BankTransferEventFailed = "bank_transfer.failed"
	// BankTransferEventReturned: the receiving bank sent a completed
	// transfer back.
	BankTransferEventReturned = "bank_transfer.returned"
)

Transfer webhook events (product BANK_CONNECT, bank_transfer.*), one per transfer and type; the event id is the same on every redelivery. Read the data with ParseBankTransferWebhook. They are not the payment events of a BANK_TRANSFER payment (PaymentBankTransferEvent*, payment.bank_transfer.*). Exchange orders have no webhook.

View Source
const (
	// BankConnectMaxLimit is the largest page (limit 1–100; the gateway's
	// default is 25).
	BankConnectMaxLimit = 100
	// BankConnectMaxAccountFilter is the most account ids one accountId
	// filter may carry.
	BankConnectMaxAccountFilter = 100
	// BankConnectBookedRangeMaxDays is the widest bookedFrom … bookedTo
	// window of one transaction request.
	BankConnectBookedRangeMaxDays = 92
	// BankTransferDescriptionMax is the longest description of a transfer or
	// an exchange order (characters).
	BankTransferDescriptionMax = 140
	// BankTransferReceiverNameMin and BankTransferReceiverNameMax bound
	// receiverName (characters).
	BankTransferReceiverNameMin = 2
	BankTransferReceiverNameMax = 140
	// BankTransferIBANMax is the longest receiverIban the gateway accepts
	// (spaces included); the service checks the TR IBAN checksum.
	BankTransferIBANMax = 42
)

Limits of the bank-connect lists and transfer bodies.

View Source
const (
	// BankTransferExceptionKindLate: arrived after the deadline (within 7 days).
	BankTransferExceptionKindLate = "LATE"
	// BankTransferExceptionKindUnderpaid: the deadline passed with less than
	// expected; the payment waits for your decision.
	BankTransferExceptionKindUnderpaid = "UNDERPAID"
	// BankTransferExceptionKindOverpaid: more than expected arrived; refund the excess.
	BankTransferExceptionKindOverpaid = "OVERPAID"
)

Kind of a bank transfer exception.

View Source
const (
	BankTransferExceptionStatusPendingDecision = "PENDING_DECISION"
	BankTransferExceptionStatusAccepted        = "ACCEPTED"
	BankTransferExceptionStatusRefundPending   = "REFUND_PENDING"
	BankTransferExceptionStatusRefunded        = "REFUNDED"
)

Status of a bank transfer exception.

View Source
const (
	PaymentBankTransferEventPartiallyReceived = "payment.bank_transfer.partially_received"
	PaymentBankTransferEventUnderpaid         = "payment.bank_transfer.underpaid"
	PaymentBankTransferEventOverpaid          = "payment.bank_transfer.overpaid"
	PaymentBankTransferEventLateArrival       = "payment.bank_transfer.late_arrival"
)

Bank transfer webhook events of a BANK_TRANSFER payment (payment.* envelope, payload bankTransfer: { expectedMinor, receivedMinor, remainingMinor, excessMinor, currency, late, transfers[] }; events that open an exception also carry exceptionId, kind and amountMinor). They do not change the payment's status: the outcome is still payment.captured / payment.failed. The names differ from Bank Connect's bank_transfer.* events.

View Source
const (
	InsurancePremiumCollectedByMerchant = "MERCHANT"
	InsurancePremiumCollectedByProvider = "PROVIDER"
)

Who collects the premium (premiumCollectedBy). PROVIDER orders cannot be completed through this API yet.

View Source
const (
	InsuranceQuoteStatusRequested = "REQUESTED"
	InsuranceQuoteStatusQuoted    = "QUOTED"
	InsuranceQuoteStatusExpired   = "EXPIRED"
	InsuranceQuoteStatusRejected  = "REJECTED"
	InsuranceQuoteStatusError     = "ERROR"
)

Status of a quote option. Only a QUOTED option that has not expired becomes an order.

View Source
const (
	InsuranceOrderStatusCreated         = "CREATED"
	InsuranceOrderStatusProcessing      = "PROCESSING"
	InsuranceOrderStatusActionRequired  = "ACTION_REQUIRED"
	InsuranceOrderStatusPartiallyActive = "PARTIALLY_ACTIVE"
	InsuranceOrderStatusActive          = "ACTIVE"
	InsuranceOrderStatusFailed          = "FAILED"
	InsuranceOrderStatusCancelled       = "CANCELLED"
	InsuranceOrderStatusRefunded        = "REFUNDED"
)

The order's overall status. It is not stored: every read derives it from the four axes, in this order — REFUNDED, CANCELLED, FAILED, ACTION_REQUIRED, PROCESSING, PARTIALLY_ACTIVE, ACTIVE, CREATED.

View Source
const (
	InsuranceCollectionStatusNotStarted     = "NOT_STARTED"
	InsuranceCollectionStatusPending        = "PENDING"
	InsuranceCollectionStatusActionRequired = "ACTION_REQUIRED"
	InsuranceCollectionStatusCollected      = "COLLECTED"
	InsuranceCollectionStatusFailed         = "FAILED"
	InsuranceCollectionStatusUnknown        = "UNKNOWN"
)

Premium collection axis (collectionStatus).

View Source
const (
	InsurancePolicyStatusNotRequested    = "NOT_REQUESTED"
	InsurancePolicyStatusPending         = "PENDING"
	InsurancePolicyStatusPartiallyIssued = "PARTIALLY_ISSUED"
	InsurancePolicyStatusIssued          = "ISSUED"
	InsurancePolicyStatusFailedRetryable = "FAILED_RETRYABLE"
	InsurancePolicyStatusFailedFinal     = "FAILED_FINAL"
	InsurancePolicyStatusUnknown         = "UNKNOWN"
	InsurancePolicyStatusCancelPending   = "CANCEL_PENDING"
	InsurancePolicyStatusCancelled       = "CANCELLED"
)

Policy axis (policyStatus) of an order and of each of its policies.

View Source
const (
	InsuranceRefundStatusNone     = "NONE"
	InsuranceRefundStatusRequired = "REQUIRED"
	InsuranceRefundStatusPending  = "PENDING"
	InsuranceRefundStatusRefunded = "REFUNDED"
	InsuranceRefundStatusFailed   = "FAILED"
)

Premium refund axis (refundStatus).

View Source
const (
	InsuranceDocumentStatusNotAvailable = "NOT_AVAILABLE"
	InsuranceDocumentStatusPending      = "PENDING"
	InsuranceDocumentStatusAvailable    = "AVAILABLE"
	InsuranceDocumentStatusFailed       = "FAILED"
)

Policy document axis (documentStatus); it does not change the overall status.

View Source
const (
	InsurancePaymentModeLunixiPayment   = "LUNIXI_PAYMENT"
	InsurancePaymentModeExternalPayment = "EXTERNAL_PAYMENT"
	InsurancePaymentModeNoPayment       = "NO_PAYMENT"
)

How the premium of an order is paid (paymentMode).

View Source
const (
	InsuranceOrderSurfaceMerchantAPI  = "MERCHANT_API"
	InsuranceOrderSurfaceCheckoutForm = "CHECKOUT_FORM"
	InsuranceOrderSurfacePanel        = "PANEL"
)

Where an order was created (surface).

View Source
const (
	InsuranceLeadStatusPending   = "PENDING"
	InsuranceLeadStatusSubmitted = "SUBMITTED"
	InsuranceLeadStatusUnknown   = "UNKNOWN"
	InsuranceLeadStatusFailed    = "FAILED"
)

Status of a lead: what Lunixi knows about sending it to the insurance provider (the provider does not report back on a lead). PENDING: the provider call is still running. SUBMITTED: the provider received it (insurance.lead.submitted). UNKNOWN: the request reached the provider but the outcome is not known; it is never sent again — open a new lead with a new Idempotency-Key if needed. FAILED: the provider refused it or it never reached the provider (errorCode).

View Source
const (
	InsuranceReferenceKindCountry               = "COUNTRY"
	InsuranceReferenceKindCity                  = "CITY"
	InsuranceReferenceKindDistrict              = "DISTRICT"
	InsuranceReferenceKindDeviceBrand           = "DEVICE_BRAND"
	InsuranceReferenceKindDeviceModel           = "DEVICE_MODEL"
	InsuranceReferenceKindVehicleBrand          = "VEHICLE_BRAND"
	InsuranceReferenceKindVehicleModel          = "VEHICLE_MODEL"
	InsuranceReferenceKindVehicleType           = "VEHICLE_TYPE"
	InsuranceReferenceKindProductCategory       = "PRODUCT_CATEGORY"
	InsuranceReferenceKindVehicleUsage          = "VEHICLE_USAGE"
	InsuranceReferenceKindLiabilityLimit        = "LIABILITY_LIMIT"
	InsuranceReferenceKindOccupation            = "OCCUPATION"
	InsuranceReferenceKindPetBreed              = "PET_BREED"
	InsuranceReferenceKindDwellingType          = "DWELLING_TYPE"
	InsuranceReferenceKindDwellingFloor         = "DWELLING_FLOOR"
	InsuranceReferenceKindBank                  = "BANK"
	InsuranceReferenceKindBankBranch            = "BANK_BRANCH"
	InsuranceReferenceKindFinanceInstitution    = "FINANCE_INSTITUTION"
	InsuranceReferenceKindMedicalProcedureCover = "MEDICAL_PROCEDURE_COVER"
)

Lunixi reference code lists (ListReferenceValues). DISTRICT, DEVICE_MODEL, VEHICLE_MODEL, BANK_BRANCH and PET_BREED need parentCode (province, brand, bank, CAT | DOG); COUNTRY, CITY and BANK take none. National standards are the codes as they are (ISO 3166-1 alpha-2 country, licence-plate province code 01–81); the others are Lunixi codes.

View Source
const (
	// InsuranceEventPolicyIssued: the order's policies were issued.
	InsuranceEventPolicyIssued = "insurance.policy.issued"
	// InsuranceEventPolicyFailed: the policy could not be issued or the
	// premium was not collected; data.errorCode says why.
	InsuranceEventPolicyFailed = "insurance.policy.failed"
	// InsuranceEventRefundRequired: the collected premium has to be
	// refunded; data.errorCode says why.
	InsuranceEventRefundRequired = "insurance.refund.required"
	// InsuranceEventPolicyDocumentReady: a policy document can be downloaded
	// (policies[].documentUrl).
	InsuranceEventPolicyDocumentReady = "insurance.policy.document_ready"
	// InsuranceEventPolicyCancelled: the provider confirmed the cancellation.
	InsuranceEventPolicyCancelled = "insurance.policy.cancelled"
	// InsuranceEventRefundCompleted: the premium refund completed.
	InsuranceEventRefundCompleted = "insurance.refund.completed"
	// InsuranceEventLeadSubmitted: the insurance provider received a lead.
	// data is a lead summary, not an order.
	InsuranceEventLeadSubmitted = "insurance.lead.submitted"
)

Insurance webhook events (subscription insurance.*). Dedupe on the event id (data.eventId is the same value). Order events are read with ParseInsuranceWebhook, the lead event with ParseInsuranceLeadWebhook.

View Source
const (
	// InsuranceMaxLimit is the largest page (limit 1–100).
	InsuranceMaxLimit = 100
	// InsuranceMaxContextItems is the most basket items one context.items
	// may carry.
	InsuranceMaxContextItems = 100
	// InsuranceExportOrderCap is the most orders in one reconciliation CSV
	// file; a longer export ends with a continuation line.
	InsuranceExportOrderCap = 20000
	// InsuranceLeadNoteMaxLength is the longest lead note (characters).
	InsuranceLeadNoteMaxLength = 1000
)

Limits of the insurance requests.

View Source
const (
	// KycSessionTypeKYC verifies a person's identity.
	KycSessionTypeKYC = "KYC"
	// KycSessionTypeKYB verifies a company and its beneficial owners.
	KycSessionTypeKYB      = "KYB"
	KycSessionTypeEvidence = "EVIDENCE"
)

Session types. EVIDENCE is proof-of-X (address, funds, card ownership …), not only onboarding.

View Source
const (
	KycSessionStatusCreated                    = "CREATED"
	KycSessionStatusInitiated                  = "INITIATED"
	KycSessionStatusDocumentSubmitted          = "DOCUMENT_SUBMITTED"
	KycSessionStatusProcessing                 = "PROCESSING"
	KycSessionStatusAwaitingProviderCallback   = "AWAITING_PROVIDER_CALLBACK"
	KycSessionStatusAwaitingAdditionalDocument = "AWAITING_ADDITIONAL_DOCUMENT"
	KycSessionStatusAwaitingUserAction         = "AWAITING_USER_ACTION"
	KycSessionStatusUnderReview                = "UNDER_REVIEW"
	KycSessionStatusPendingAdditionalInfo      = "PENDING_ADDITIONAL_INFO"
	KycSessionStatusRescreenRequired           = "RESCREEN_REQUIRED"
	KycSessionStatusReopened                   = "REOPENED"
	KycSessionStatusApproved                   = "APPROVED"
	KycSessionStatusRejected                   = "REJECTED"
	KycSessionStatusManualReview               = "MANUAL_REVIEW"
	KycSessionStatusExpired                    = "EXPIRED"
	KycSessionStatusAbandoned                  = "ABANDONED"
	KycSessionStatusCancelled                  = "CANCELLED"
)

Status of a KYC session.

View Source
const (
	KycEvidencePurposeIdentityVerification   = "IDENTITY_VERIFICATION"
	KycEvidencePurposeBusinessVerification   = "BUSINESS_VERIFICATION"
	KycEvidencePurposeProofOfFunds           = "PROOF_OF_FUNDS"
	KycEvidencePurposeProofOfAddress         = "PROOF_OF_ADDRESS"
	KycEvidencePurposeSourceOfFunds          = "SOURCE_OF_FUNDS"
	KycEvidencePurposeSourceOfWealth         = "SOURCE_OF_WEALTH"
	KycEvidencePurposeTransactionEvidence    = "TRANSACTION_EVIDENCE"
	KycEvidencePurposeCardOwnership          = "CARD_OWNERSHIP"
	KycEvidencePurposePaymentMethodOwnership = "PAYMENT_METHOD_OWNERSHIP"
	KycEvidencePurposePayoutEvidence         = "PAYOUT_EVIDENCE"
	KycEvidencePurposeMerchantOnboarding     = "MERCHANT_ONBOARDING"
)

evidencePurpose of an EVIDENCE session.

View Source
const (
	KycAssuranceLevelNone         = "NONE"
	KycAssuranceLevelNotPerformed = "NOT_PERFORMED"
	KycAssuranceLevelLow          = "LOW"
	KycAssuranceLevelSubstantial  = "SUBSTANTIAL"
	KycAssuranceLevelHigh         = "HIGH"
)

Assurance ladder (rank-aligned with NIST 800-63 IAL / eIDAS LoA). A gate passes when achieved >= required (KycAssuranceMeets).

View Source
const (
	KycAssuranceDomainIdentity      = "identity_evidence_strength"
	KycAssuranceDomainDocument      = "document_authenticity_level"
	KycAssuranceDomainBiometric     = "possession_biometric_binding"
	KycAssuranceDomainAuthoritative = "authoritative_source_level"
	KycAssuranceDomainAddress       = "address_assurance"
	KycAssuranceDomainAML           = "aml_freshness"
	KycAssuranceDomainHumanReview   = "human_review_level"
)

Domains of the achieved assurance snapshot (session.decision.assuranceSnapshot.achieved), each an assurance level.

View Source
const (
	KycEventSessionCreated                = "kyc.session.created"
	KycEventSessionInitiated              = "kyc.session.initiated"
	KycEventSessionExpired                = "kyc.session.expired"
	KycEventSessionAbandoned              = "kyc.session.abandoned"
	KycEventSessionCancelled              = "kyc.session.cancelled"
	KycEventDocumentReceived              = "kyc.document.received"
	KycEventDocumentRejected              = "kyc.document.rejected"
	KycEventLivenessCompleted             = "kyc.liveness.completed"
	KycEventProcessingStarted             = "kyc.processing.started"
	KycEventManualReviewRequired          = "kyc.manual_review.required"
	KycEventApproved                      = "kyc.approved"
	KycEventRejected                      = "kyc.rejected"
	KycEventRescreenRequired              = "kyc.rescreen.required"
	KycEventKybSessionCreated             = "kyb.session.created"
	KycEventKybCompanyVerified            = "kyb.company.verified"
	KycEventKybCompanyNotFound            = "kyb.company.not_found"
	KycEventKybUboPending                 = "kyb.ubo.pending"
	KycEventKybRelatedKycRequired         = "kyb.related_kyc.required"
	KycEventKybRelatedKycCompleted        = "kyb.related_kyc.completed"
	KycEventKybManualReviewRequired       = "kyb.manual_review.required"
	KycEventKybApproved                   = "kyb.approved"
	KycEventKybRejected                   = "kyb.rejected"
	KycEventScreeningMatchDetected        = "screening.match.detected"
	KycEventScreeningFalsePositiveCleared = "screening.false_positive.cleared"
	KycEventMonitoringAlertCreated        = "ongoing_monitoring.alert.created"
)

Webhook event types of KYC (the same signed envelope as payment events). data always carries sessionId and externalCustomerId; terminal events carry the decision. A rescreen or screening hit on an approved session must revoke access.

View Source
const (
	MarketplaceDealerStatusDraft      = "DRAFT"
	MarketplaceDealerStatusPendingKyc = "PENDING_KYC"
	MarketplaceDealerStatusActive     = "ACTIVE"
	MarketplaceDealerStatusSuspended  = "SUSPENDED"
	MarketplaceDealerStatusHold       = "HOLD"
	MarketplaceDealerStatusClosed     = "CLOSED"
)

Sub-dealer lifecycle. Only ACTIVE dealers can receive a split.

View Source
const (
	MarketplaceDealerTypeLegalEntity = "LEGAL_ENTITY"
	MarketplaceDealerTypeIndividual  = "INDIVIDUAL"
)

dealerType of a sub-dealer.

View Source
const (
	MarketplaceMultiSellerPolicyAllOrNothing   = "ALL_OR_NOTHING"
	MarketplaceMultiSellerPolicyPartialAllowed = "PARTIAL_ALLOWED"
)

multiSellerPolicy of a split charge: every seller leg must be eligible, or the eligible legs may go through without the others.

View Source
const (
	// PaymentLinkUsageSingleUse can be paid once (an invoice or a personal
	// payment request).
	PaymentLinkUsageSingleUse = "SINGLE_USE"
	// PaymentLinkUsageMultiUse can be paid many times (donations, tickets, a
	// product page).
	PaymentLinkUsageMultiUse = "MULTI_USE"
)

Payment link usage, fixed at creation.

View Source
const (
	// PaymentLinkAmountModeFixed: the merchant sets amountMinor.
	PaymentLinkAmountModeFixed = "FIXED"
	// PaymentLinkAmountModeOpen: the buyer enters the amount within
	// minAmountMinor and maxAmountMinor.
	PaymentLinkAmountModeOpen = "OPEN"
	// PaymentLinkAmountModeItemized: the buyer picks quantities of items.
	PaymentLinkAmountModeItemized = "ITEMIZED"
)

Payment link amount modes, fixed at creation.

View Source
const (
	PaymentLinkStateActive      = "ACTIVE"
	PaymentLinkStatePaused      = "PAUSED"
	PaymentLinkStateCompleted   = "COMPLETED"
	PaymentLinkStateExpired     = "EXPIRED"
	PaymentLinkStateDeactivated = "DEACTIVATED"
	// PaymentLinkStateTakenDown: removed by Lunixi; every write on the link
	// answers 409 payment_link.link.taken_down.
	PaymentLinkStateTakenDown = "TAKEN_DOWN"
)

Payment link states.

View Source
const (
	PaymentLinkAttemptStateOpen        = "OPEN"
	PaymentLinkAttemptStateBound       = "BOUND"
	PaymentLinkAttemptStateSucceeded   = "SUCCEEDED"
	PaymentLinkAttemptStateFailed      = "FAILED"
	PaymentLinkAttemptStateExpired     = "EXPIRED"
	PaymentLinkAttemptStateAbandoned   = "ABANDONED"
	PaymentLinkAttemptStateNeedsReview = "NEEDS_REVIEW"
)

Payment link attempt states.

View Source
const (
	PaymentLinkEnvironmentTest = "TEST"
	PaymentLinkEnvironmentLive = "LIVE"
)

Payment link environments. The signing key decides the environment; an explicit value must match it.

View Source
const (
	BuyerFieldRequirementHidden   = "HIDDEN"
	BuyerFieldRequirementOptional = "OPTIONAL"
	BuyerFieldRequirementRequired = "REQUIRED"
)

Requirement of a buyer field on the payment page.

View Source
const (
	CustomFieldTypeText     = "TEXT"
	CustomFieldTypeNumber   = "NUMBER"
	CustomFieldTypeEmail    = "EMAIL"
	CustomFieldTypePhone    = "PHONE"
	CustomFieldTypeDate     = "DATE"
	CustomFieldTypeSelect   = "SELECT"
	CustomFieldTypeCheckbox = "CHECKBOX"
	CustomFieldTypeTCKN     = "TCKN"
	CustomFieldTypeVKN      = "VKN"
)

Types of a payment link custom field (no file uploads).

View Source
const (
	PaymentLinkButtonLabelPay    = "PAY"
	PaymentLinkButtonLabelDonate = "DONATE"
	PaymentLinkButtonLabelBuy    = "BUY"
	PaymentLinkButtonLabelBook   = "BOOK"
)

Payment link button labels.

View Source
const (
	PaymentLinkDeliveryChannelEmail = "EMAIL"
	PaymentLinkDeliveryChannelSMS   = "SMS"
)

Payment link delivery channels of Send and of the buyer verification.

View Source
const (
	PaymentLinkQRFormatSVG = "svg"
	PaymentLinkQRFormatPNG = "png"
)

Payment link QR image formats.

View Source
const (
	PaymentLinkLocaleTR = "tr"
	PaymentLinkLocaleEN = "en"
)

Payment page languages.

View Source
const (
	PaymentLinkImageContentTypePNG  = "image/png"
	PaymentLinkImageContentTypeJPEG = "image/jpeg"
	PaymentLinkImageContentTypeWebP = "image/webp"
)

Image types a payment link image can be declared as. Confirmation checks the stored bytes against the declared type; SVG is never accepted.

View Source
const (
	PaymentLinkQRMinSize = 128
	PaymentLinkQRMaxSize = 2048
)

Bounds of the QR image size in pixels.

View Source
const (
	PaymentMethodCard           = "CARD"
	PaymentMethodBNPL           = "BNPL"
	PaymentMethodShoppingLoan   = "SHOPPING_LOAN"
	PaymentMethodPromissoryNote = "PROMISSORY_NOTE"
	PaymentMethodMealCard       = "MEAL_CARD"
	PaymentMethodGiftCard       = "GIFT_CARD"
	PaymentMethodCash           = "CASH"
	PaymentMethodCashOnDelivery = "CASH_ON_DELIVERY"
	PaymentMethodWallet         = "WALLET"
	PaymentMethodBankTransfer   = "BANK_TRANSFER"
	PaymentMethodOpenBanking    = "OPEN_BANKING"
	// PaymentMethodMobileBilling charges the buyer's mobile phone bill.
	PaymentMethodMobileBilling = "MOBILE_BILLING"
	PaymentMethodQRCode        = "QR_CODE"
	PaymentMethodCrypto        = "CRYPTO"
	PaymentMethodOther         = "OTHER"
)

Public payment method codes (paymentMethod). "QR" is accepted as an alias of PaymentMethodQRCode by ListPaymentMethods and NormalizePaymentMethod.

View Source
const (
	// PaymentActionTypeOTP: send the one-time code with ConfirmPaymentAction.
	PaymentActionTypeOTP = "OTP"
	// PaymentActionTypeRedirect: send the buyer to action.redirect.url (for
	// cards, the bank's 3D Secure page).
	PaymentActionTypeRedirect = "REDIRECT"
	// PaymentActionTypeDisplay: show the buyer something to act on outside the
	// page, such as bank transfer details (Response.BankTransferInstruction) or
	// a code.
	PaymentActionTypeDisplay = "DISPLAY"
	// PaymentActionTypeAppApproval: the buyer approves in the provider's app;
	// the result arrives by webhook.
	PaymentActionTypeAppApproval = "APP_APPROVAL"
	// PaymentActionTypeInput: send the fields listed in action.input.fields
	// with ConfirmPaymentAction.
	PaymentActionTypeInput = "INPUT"
)

What the buyer must do when a payment response carries action (action.type).

View Source
const (
	// ProviderSelectionRouted: card routing picks the provider; providerCode
	// is not sent.
	ProviderSelectionRouted = "ROUTED"
	// ProviderSelectionOptional: providerCode may be omitted.
	ProviderSelectionOptional = "OPTIONAL"
	// ProviderSelectionRequired: more than one provider is connected and the
	// buyer picks the brand; providerCode must be sent.
	ProviderSelectionRequired = "REQUIRED"
)

providerSelection of a method in ListPaymentMethods.

View Source
const (
	// ProviderSelectionModeBuyer: the buyer picks the brand. With more than one
	// provider connected providerCode is required (400 payment.provider.required).
	ProviderSelectionModeBuyer = "BUYER"
	// ProviderSelectionModePlatform: providerCode is optional; without it the
	// platform picks one of the connected providers before any money moves
	// (422 payment.provider.none_eligible when none can take the payment).
	ProviderSelectionModePlatform = "PLATFORM"
)

providerSelectionMode of a method in ListPaymentMethods: who picks the provider.

View Source
const (
	MinEnabledInstallment = 1
	MaxEnabledInstallment = 36
)

Bounds of an EnabledInstallments entry.

View Source
const (
	PhysicalPosOperationSale            = "SALE"
	PhysicalPosOperationPreauthOpen     = "PREAUTH_OPEN"
	PhysicalPosOperationRefundUnmatched = "REFUND_UNMATCHED"
	PhysicalPosOperationVoid            = "VOID"
	PhysicalPosOperationRefund          = "REFUND"
	PhysicalPosOperationPreauthClose    = "PREAUTH_CLOSE"
	PhysicalPosOperationPreauthCancel   = "PREAUTH_CANCEL"
)

Physical POS payment operations. SALE, PREAUTH_OPEN and REFUND_UNMATCHED start a payment (CreatePayment); VOID, REFUND, PREAUTH_CLOSE and PREAUTH_CANCEL reverse one (CreateReversal).

View Source
const (
	PhysicalPosStatusNotStarted        = "NOT_STARTED"
	PhysicalPosStatusInProgress        = "IN_PROGRESS"
	PhysicalPosStatusApproved          = "APPROVED"
	PhysicalPosStatusPartiallyApproved = "PARTIALLY_APPROVED"
	PhysicalPosStatusDeclined          = "DECLINED"
	PhysicalPosStatusCancelled         = "CANCELLED"
	PhysicalPosStatusExpired           = "EXPIRED"
	PhysicalPosStatusFailed            = "FAILED"
	PhysicalPosStatusUnknown           = "UNKNOWN"
	PhysicalPosStatusManualReview      = "MANUAL_REVIEW"
)

Physical POS payment statuses (paymentStatus).

View Source
const (
	PhysicalPosReversalStatusNone              = "NONE"
	PhysicalPosReversalStatusPartiallyRefunded = "PARTIALLY_REFUNDED"
	PhysicalPosReversalStatusRefunded          = "REFUNDED"
	PhysicalPosReversalStatusVoided            = "VOIDED"
	PhysicalPosReversalStatusPreauthClosed     = "PREAUTH_CLOSED"
	PhysicalPosReversalStatusPreauthCancelled  = "PREAUTH_CANCELLED"
	PhysicalPosReversalStatusPreauthExpired    = "PREAUTH_EXPIRED"
)

Physical POS reversal statuses of a root payment (reversalStatus).

View Source
const (
	PhysicalPosEventPaymentApproved              = "physical_pos.payment.approved"
	PhysicalPosEventPaymentPartiallyApproved     = "physical_pos.payment.partially_approved"
	PhysicalPosEventPaymentDeclined              = "physical_pos.payment.declined"
	PhysicalPosEventPaymentCancelled             = "physical_pos.payment.cancelled"
	PhysicalPosEventPaymentExpired               = "physical_pos.payment.expired"
	PhysicalPosEventPaymentFailed                = "physical_pos.payment.failed"
	PhysicalPosEventPaymentUnknown               = "physical_pos.payment.unknown"
	PhysicalPosEventPaymentManualReview          = "physical_pos.payment.manual_review"
	PhysicalPosEventPaymentDeviceSale            = "physical_pos.payment.device_sale"
	PhysicalPosEventFiscalDocumentIssued         = "physical_pos.fiscal_document.issued"
	PhysicalPosEventFiscalDocumentFailed         = "physical_pos.fiscal_document.failed"
	PhysicalPosEventFiscalDocumentCancelled      = "physical_pos.fiscal_document.cancelled"
	PhysicalPosEventFiscalDocumentActionRequired = "physical_pos.fiscal_document.action_required"
	PhysicalPosEventSettlementCompleted          = "physical_pos.settlement.completed"
	PhysicalPosEventSettlementFailed             = "physical_pos.settlement.failed"
	PhysicalPosEventSettlementOverdue            = "physical_pos.settlement.overdue"
	PhysicalPosEventSettlementSkipped            = "physical_pos.settlement.skipped"
	// PhysicalPosEventPattern subscribes to every physical POS event.
	PhysicalPosEventPattern = "physical_pos.*"
)

Physical POS webhook event types. physical_pos.payment.created and .in_progress are internal and never delivered. Reversals (void, refund, pre-authorisation close / cancel) use the same payment events; tell them apart with data.operation and data.rootPaymentId, and the original payment's source with data.original.origin.

PhysicalPosEventPaymentDeviceSale reports a sale made directly on the device (origin DEVICE_DIRECT): it arrives approved, with deviceOccurredAt; no approved event is sent for it.

End-of-day events (physical_pos.settlement.*) have their own payloads: completed (the device's result with its bank lines; any source), failed (a scheduled run could not finish in its window), skipped (a scheduled run was skipped for a reason you can fix) and overdue (no result within the policy's threshold). They carry no historySeq; deduplicate them by the event id.

View Source
const (
	PhysicalPosWebhookCategoryPayment        = "payment"
	PhysicalPosWebhookCategoryFiscalDocument = "fiscal_document"
	PhysicalPosWebhookCategorySettlement     = "settlement"
	PhysicalPosWebhookCategoryOther          = "other"
)

Categories of a physical POS webhook event (PhysicalPosWebhookEvent.Category).

View Source
const (
	// PhysicalPosMaxLimit is the largest page size of a physical POS list.
	PhysicalPosMaxLimit = 100
	// PhysicalPosRowVersionMax is the largest rowVersion / expectedRowVersion.
	PhysicalPosRowVersionMax int64 = 2147483647
)

Physical POS limits.

View Source
const (
	// PhysicalPosCardDataRejectedCode: the request carried card data.
	PhysicalPosCardDataRejectedCode = "physical_pos.payment.card_data_rejected"
	// PhysicalPosVoidAfterSettlementCode: the payment is already in a device
	// end-of-day and can only be refunded.
	PhysicalPosVoidAfterSettlementCode = "physical_pos.payment.void_after_settlement"
)

Error codes with their own error type.

View Source
const (
	ProductCategoryMobilePhone          = "MOBILE_PHONE"
	ProductCategoryTablet               = "TABLET"
	ProductCategoryComputer             = "COMPUTER"
	ProductCategoryTVAudio              = "TV_AUDIO"
	ProductCategoryWhiteGoods           = "WHITE_GOODS"
	ProductCategorySmallAppliance       = "SMALL_APPLIANCE"
	ProductCategoryCamera               = "CAMERA"
	ProductCategoryGameConsole          = "GAME_CONSOLE"
	ProductCategoryWearable             = "WEARABLE"
	ProductCategoryElectronicsAccessory = "ELECTRONICS_ACCESSORY"
	ProductCategoryElectronicsOther     = "ELECTRONICS_OTHER"
	ProductCategoryGold                 = "GOLD"
	ProductCategoryJewelry              = "JEWELRY"
	ProductCategoryWatch                = "WATCH"
	ProductCategoryApparel              = "APPAREL"
	ProductCategoryShoesBags            = "SHOES_BAGS"
	ProductCategoryCosmetics            = "COSMETICS"
	ProductCategoryFurniture            = "FURNITURE"
	ProductCategoryHomeLiving           = "HOME_LIVING"
	ProductCategoryGrocery              = "GROCERY"
	ProductCategoryBooksMedia           = "BOOKS_MEDIA"
	ProductCategoryToys                 = "TOYS"
	ProductCategorySportsOutdoor        = "SPORTS_OUTDOOR"
	ProductCategoryPetSupplies          = "PET_SUPPLIES"
	ProductCategoryAutoParts            = "AUTO_PARTS"
	ProductCategoryMusicalInstrument    = "MUSICAL_INSTRUMENT"
	ProductCategoryMicromobility        = "MICROMOBILITY"
	ProductCategoryVehicle              = "VEHICLE"
	ProductCategoryTransportTicket      = "TRANSPORT_TICKET"
	ProductCategoryEventTicket          = "EVENT_TICKET"
	ProductCategoryAccommodation        = "ACCOMMODATION"
	ProductCategoryTravelPackage        = "TRAVEL_PACKAGE"
	ProductCategoryHealthService        = "HEALTH_SERVICE"
	ProductCategoryEducation            = "EDUCATION"
	ProductCategoryShippingService      = "SHIPPING_SERVICE"
	ProductCategoryDigitalGoods         = "DIGITAL_GOODS"
	ProductCategoryGiftCard             = "GIFT_CARD"
	ProductCategorySubscription         = "SUBSCRIPTION"
	ProductCategoryServiceOther         = "SERVICE_OTHER"
	ProductCategoryOther                = "OTHER"
)

Lunixi product category codes for BasketItem.ProductCategory. Payment methods with legal installment limits (e.g. shopping loan) and other platform features use them. The dictionary only grows by appending, so the field stays a plain string: a newer code can be sent before this SDK declares a constant for it. Unknown codes are rejected by the API (400).

View Source
const (
	PromissoryNoteStatusIssued    = "ISSUED"
	PromissoryNoteStatusPaid      = "PAID"
	PromissoryNoteStatusProtested = "PROTESTED"
	PromissoryNoteStatusCancelled = "CANCELLED"
)

Status of one note (notes[].status).

View Source
const (
	PromissoryNoteDocumentTypePromissoryNote = "PROMISSORY_NOTE"
	PromissoryNoteDocumentTypePaymentOrder   = "PAYMENT_ORDER"
)

Document type of the issued notes, from your provider connection settings.

View Source
const (
	PromissoryNoteCancelResultCancelled = "CANCELLED"
	// PromissoryNoteCancelResultAlreadyClosed: the note was already cancelled.
	PromissoryNoteCancelResultAlreadyClosed = "ALREADY_CLOSED"
	// PromissoryNoteCancelResultNotCancellable: the note was collected or
	// protested; it cannot be cancelled.
	PromissoryNoteCancelResultNotCancellable = "NOT_CANCELLABLE"
	// PromissoryNoteCancelResultFailed: the note was not cancelled; errorCode
	// tells whether to try again.
	PromissoryNoteCancelResultFailed = "FAILED"
)

Per-note result of CancelPromissoryNotes (cancelResults[].result).

View Source
const (
	// PromissoryNoteCancelErrorNotCancellable: the note was collected or cannot
	// be cancelled (NOT_CANCELLABLE).
	PromissoryNoteCancelErrorNotCancellable = "payment.promissory_note.not_cancellable"
	// PromissoryNoteCancelErrorProviderUnavailable is temporary: cancel again
	// later (FAILED).
	PromissoryNoteCancelErrorProviderUnavailable = "payment.promissory_note.provider_unavailable"
	// PromissoryNoteCancelErrorCancelRejected is permanent: the cancellation
	// was refused (FAILED).
	PromissoryNoteCancelErrorCancelRejected = "payment.promissory_note.cancel_rejected"
)

cancelResults[].errorCode: a Lunixi code, never the provider's; null for CANCELLED and ALREADY_CLOSED.

View Source
const (
	PromissoryNoteDocumentLocaleTR = "tr-TR"
	PromissoryNoteDocumentLocaleEN = "en-GB"
)

Language of the printable notes (DownloadPromissoryNoteDocument).

View Source
const (
	PromissoryNoteEventPaid      = "payment.promissory_note.paid"
	PromissoryNoteEventProtested = "payment.promissory_note.protested"
	PromissoryNoteEventCancelled = "payment.promissory_note.cancelled"
)

Webhook events of a note. The payload adds promissoryNote: { serialNumber, sequence, amountMinor, dueDate, status, occurredAt }. Statuses are polled, so an event arrives some time after the due date.

View Source
const (
	SanctionRiskDomainSanctions  = "sanctions"
	SanctionRiskDomainPep        = "pep"
	SanctionRiskDomainRca        = "rca"
	SanctionRiskDomainWanted     = "wanted"
	SanctionRiskDomainRegulatory = "regulatory"
	SanctionRiskDomainDebarment  = "debarment"
	SanctionRiskDomainOwnership  = "ownership"
	SanctionRiskDomainVessel     = "vessel"
	SanctionRiskDomainSecurities = "securities"
)

Risk domains a screening can be narrowed to (riskDomains). Omitted: every domain.

View Source
const (
	SanctionScreenModeSanctionsOnly = "sanctions_only"
	SanctionScreenModeSanctionsPep  = "sanctions_pep"
	SanctionScreenModeFullRisk      = "full_risk"
)

Name-screening presets (mode). Sent with riskDomains, their intersection is screened.

View Source
const (
	SanctionWalletScreenModeSanctions = "wallet_sanctions"
	SanctionWalletScreenModeRisk      = "wallet_risk"
	SanctionWalletScreenModeFullAML   = "wallet_full_aml"
)

Wallet-screening depth (mode); the wider modes add exposure and crypto-intelligence hits.

View Source
const (
	SanctionSubjectTypePerson       = "person"
	SanctionSubjectTypeOrganization = "organization"
)

Subject of a name screening or a monitoring registration (subjectType).

View Source
const (
	SanctionCoverageStatusComplete = "COMPLETE"
	SanctionCoverageStatusPartial  = "PARTIAL"
	SanctionCoverageStatusDegraded = "DEGRADED"
)

How much of the requested scope a screening covered (coverageStatus). COMPLETE: every requested risk domain was screened. PARTIAL: some requested domain has no list (uncoveredRiskDomains, uncoveredSources); no match is clear only for what was screened. DEGRADED: the candidate search was limited; run the screening again.

View Source
const (
	SanctionHitTypeExact    = "exact"
	SanctionHitTypeProbable = "probable"
	SanctionHitTypePossible = "possible"
)

Strength of a screening hit (hitType).

View Source
const (
	SanctionEventMatchDetected          = "screening.match.detected"
	SanctionEventFalsePositiveCleared   = "screening.false_positive.cleared"
	SanctionEventMonitoringAlertCreated = "ongoing_monitoring.alert.created"
	SanctionEventMonitoringClear        = "ongoing_monitoring.clear"
)

Sanction webhook events.

View Source
const (
	SplitPaymentStatusComposing              = "COMPOSING"
	SplitPaymentStatusAuthorizing            = "AUTHORIZING"
	SplitPaymentStatusAwaiting3DS            = "AWAITING_3DS"
	SplitPaymentStatusAwaitingAction         = "AWAITING_ACTION"
	SplitPaymentStatusAwaitingCreditApproval = "AWAITING_CREDIT_APPROVAL"
	SplitPaymentStatusAwaitingReplacement    = "AWAITING_REPLACEMENT_CARD"
	SplitPaymentStatusAuthorized             = "AUTHORIZED"
	SplitPaymentStatusCapturing              = "CAPTURING"
	// SplitPaymentStatusCompleted: every leg was charged.
	SplitPaymentStatusCompleted    = "COMPLETED"
	SplitPaymentStatusCompensating = "COMPENSATING"
	SplitPaymentStatusVoided       = "VOIDED"
	SplitPaymentStatusFailed       = "FAILED"
	// SplitPaymentStatusReconciliationRequired: the non-reversible leg was
	// charged but the rest could not be collected; you decide on delivery.
	SplitPaymentStatusReconciliationRequired = "RECONCILIATION_REQUIRED"
)

Status of a split payment (status).

View Source
const (
	SplitPaymentEventCompleted    = "payment.split.completed"
	SplitPaymentEventVoided       = "payment.split.voided"
	SplitPaymentEventCompensating = "payment.split.compensating"
	// SplitPaymentEventOutcomePending: the non-reversible leg's result is being
	// confirmed; card holds are kept until then.
	SplitPaymentEventOutcomePending = "payment.split.outcome_pending"
	// SplitPaymentEventReconciliationRequired: the order could not be fully
	// collected (shortfallAmountMinor, reason).
	SplitPaymentEventReconciliationRequired = "payment.split.reconciliation_required"
	// SplitPaymentEventLegRefundPending: a charged leg is being refunded and
	// retried until it succeeds.
	SplitPaymentEventLegRefundPending = "payment.split.leg_refund_pending"
)

Webhook event types of a split payment. The result of the main payment arrives as payment.captured / payment.failed with settlementMode SPLIT and legs[]; deliver the order on that event.

View Source
const (
	// SubscriptionStatusPending: startsAt is in the future.
	SubscriptionStatusPending  = "PENDING"
	SubscriptionStatusTrialing = "TRIALING"
	SubscriptionStatusActive   = "ACTIVE"
	// SubscriptionStatusPastDue: a charge failed; dunning runs.
	SubscriptionStatusPastDue = "PAST_DUE"
	// SubscriptionStatusUnpaid: dunning exhausted; grace period.
	SubscriptionStatusUnpaid = "UNPAID"
	// SubscriptionStatusPaused: paused by the merchant; no charges.
	SubscriptionStatusPaused     = "PAUSED"
	SubscriptionStatusUpgraded   = "UPGRADED"
	SubscriptionStatusDowngraded = "DOWNGRADED"
	SubscriptionStatusCanceled   = "CANCELED"
	// SubscriptionStatusExpired: the recurrence ran out.
	SubscriptionStatusExpired = "EXPIRED"
)

Status of a subscription.

View Source
const (
	SubscriptionInvoiceStatusDraft         = "DRAFT"
	SubscriptionInvoiceStatusOpen          = "OPEN"
	SubscriptionInvoiceStatusPaid          = "PAID"
	SubscriptionInvoiceStatusUncollectible = "UNCOLLECTIBLE"
	SubscriptionInvoiceStatusVoid          = "VOID"
)

Status of a subscription invoice: DRAFT → OPEN → PAID | UNCOLLECTIBLE | VOID.

View Source
const (
	// SubscriptionCollectionMethodAutoCharge charges the saved card each
	// cycle (the default).
	SubscriptionCollectionMethodAutoCharge = "AUTO_CHARGE"
	// SubscriptionCollectionMethodSendInvoice finalises the invoice without
	// charging it.
	SubscriptionCollectionMethodSendInvoice = "SEND_INVOICE"
	// SubscriptionCollectionMethodManual leaves collection to the merchant.
	SubscriptionCollectionMethodManual = "MANUAL"
)

How invoices are collected (collectionMethod).

View Source
const (
	SubscriptionBillingFrequencyDaily   = "DAILY"
	SubscriptionBillingFrequencyWeekly  = "WEEKLY"
	SubscriptionBillingFrequencyMonthly = "MONTHLY"
	SubscriptionBillingFrequencyYearly  = "YEARLY"
)

billing.frequency of a plan.

View Source
const (
	SubscriptionCardVerificationModeNone        = "NONE"
	SubscriptionCardVerificationModeOnAdd       = "ON_ADD"
	SubscriptionCardVerificationModeFirstCharge = "FIRST_CHARGE"
)

verificationMode of a saved card.

View Source
const (
	SubscriptionPlanChangeBehaviorImmediate  = "IMMEDIATE"
	SubscriptionPlanChangeBehaviorNextPeriod = "NEXT_PERIOD"
)

behavior of a plan change: now (prorated) or at the next period.

View Source
const (
	SubscriptionPortalSdkModeFull     = "FULL"
	SubscriptionPortalSdkModeHeadless = "HEADLESS"
	SubscriptionPortalSdkModeHybrid   = "HYBRID"
)

sdkMode of a portal SDK session.

View Source
const (
	SubscriptionEventCreated              = "subscription.created"
	SubscriptionEventActivated            = "subscription.activated"
	SubscriptionEventTrialWillEnd         = "subscription.trial_will_end"
	SubscriptionEventPaused               = "subscription.paused"
	SubscriptionEventResumed              = "subscription.resumed"
	SubscriptionEventCancelScheduled      = "subscription.cancel_scheduled"
	SubscriptionEventCanceled             = "subscription.canceled"
	SubscriptionEventUpgraded             = "subscription.upgraded"
	SubscriptionEventDowngraded           = "subscription.downgraded"
	SubscriptionEventPlanChangeScheduled  = "subscription.plan_change_scheduled"
	SubscriptionEventPendingChangeApplied = "subscription.pending_change_applied"
	SubscriptionEventPaymentCardSwapped   = "subscription.payment_card_swapped"
	SubscriptionEventPaymentMethodLost    = "subscription.payment_method_lost"
	SubscriptionEventInvoiceCreated       = "invoice.created"
	SubscriptionEventInvoicePaid          = "invoice.paid"
	SubscriptionEventInvoicePaymentFailed = "invoice.payment_failed"
	SubscriptionEventInvoiceVoided        = "invoice.voided"
	SubscriptionEventCardAdded            = "card.added"
	SubscriptionEventCardSetDefault       = "card.set_default"
	SubscriptionEventCardUpdated          = "card.updated"
	SubscriptionEventCardDeactivated      = "card.deactivated"
	SubscriptionEventCardExpiringSoon     = "card.expiring_soon"
	SubscriptionEventCardExpired          = "card.expired"
)

Webhook event types of subscriptions (the same signed envelope as payment events; data amounts are minor-unit strings).

View Source
const (
	WalletAccountTypePersonal = "PERSONAL"
	WalletAccountTypeBusiness = "BUSINESS"
)

Account type of a wallet end user.

View Source
const (
	WalletEndUserStatusActive = "ACTIVE"
	WalletEndUserStatusFrozen = "FROZEN"
	WalletEndUserStatusClosed = "CLOSED"
)

Status of a wallet end user.

View Source
const (
	WalletKycLevelNone        = "NONE"
	WalletKycLevelLow         = "LOW"
	WalletKycLevelSubstantial = "SUBSTANTIAL"
	WalletKycLevelHigh        = "HIGH"
)

KYC level of a wallet end user.

View Source
const (
	WalletOtpChannelEmail = "EMAIL"
	WalletOtpChannelSMS   = "SMS"
	WalletOtpChannelPush  = "PUSH"
)

Channel of a wallet one-time code (otpChannel).

View Source
const (
	WalletQRTypeP2PStatic       = "P2P_STATIC"
	WalletQRTypeP2PDynamic      = "P2P_DYNAMIC"
	WalletQRTypeMerchantStatic  = "MERCHANT_STATIC"
	WalletQRTypeMerchantDynamic = "MERCHANT_DYNAMIC"
)

Type of a wallet QR code. Static codes carry no amount; dynamic ones require it.

View Source
const (
	WalletQRImageFormatSVG = "svg"
	WalletQRImageFormatPNG = "png"
)

Image format of WalletQR.Image.

View Source
const (
	WalletBulkTargetTypeWallet = "WALLET"
	WalletBulkTargetTypeIBAN   = "IBAN"
)

Target of a bulk payout item (targetType).

View Source
const (
	WalletCorporateAccountStatusActive   = "ACTIVE"
	WalletCorporateAccountStatusArchived = "ARCHIVED"
)

Status of a wallet corporate account.

View Source
const BankConnectEventPattern = "bank_account.*"

BankConnectEventPattern is the subscription pattern of every bank-account event.

View Source
const BankConnectEventTransactionReceived = "bank_account.transaction.received"

BankConnectEventTransactionReceived: a new transaction (CREDIT or DEBIT) was read from one of your connected accounts. Sent once per transaction, for transactions first seen by a regular read after the connection became active; the history loaded when an account is first connected does not send it. The event id is the same on every redelivery: dedupe on it. Read the data with ParseBankAccountTransactionReceived.

View Source
const BankTransferEventPattern = "bank_transfer.*"

BankTransferEventPattern is the subscription pattern of every transfer event.

View Source
const BankTransferExceptionLimitMax = 200

BankTransferExceptionLimitMax is the largest limit of ListBankTransferExceptions.

View Source
const BankTransferOtherBanksCode = "9999"

BankTransferOtherBanksCode is the "other banks" option of the bankCode field: the buyer pays by EFT/FAST from a bank that is not listed.

View Source
const FraudEventBatchLimit = 500

FraudEventBatchLimit is the largest number of events RecordBatch sends in one request; the gateway rejects a larger batch as a whole.

View Source
const InsuranceEventPattern = "insurance.*"

InsuranceEventPattern is the subscription pattern of every insurance event.

View Source
const KycSessionTTLMaxMinutes = 1440

KycSessionTTLMaxMinutes is the longest session lifetime ttlMinutes accepts (one day).

View Source
const MarketplaceDealerOnboardingHostedBase = "https://altbayi.lunixi.com"

MarketplaceDealerOnboardingHostedBase is the hosted dealer onboarding wizard (MarketplaceOnboardingURL when the answer carries no url).

View Source
const MaxSafeInteger int64 = 9007199254740991

MaxSafeInteger is the largest integer JSON.stringify preserves exactly.

View Source
const PromissoryNoteMaxScheduleItems = 24

PromissoryNoteMaxScheduleItems is the most rows of a promissory-note schedule, and the most notes of one payment.

View Source
const ShoppingLoanMaxBasketItems = 100

ShoppingLoanMaxBasketItems is the most basket items a SHOPPING_LOAN payment can carry. The basket is required: the lender sets the loan term from the items' product categories.

View Source
const SplitLegEventsSubscription = "payment.split.leg_events"

SplitLegEventsSubscription is put into a webhook endpoint's event types to also receive the events of each leg. It is not an event type and payment.* does not include it.

View Source
const SubscriptionPortalHostedBase = "https://portal.lunixi.com"

SubscriptionPortalHostedBase is the hosted customer portal; a portal link's token opens it (SubscriptionPortalURL).

View Source
const Version = "1.3.0"

Version is the SDK semantic version.

View Source
const WalletIdempotencyKeyMax = 128

WalletIdempotencyKeyMax is the longest wallet Idempotency-Key (the gateway accepts 1–128 characters).

Variables

View Source
var (
	// ErrConfiguration indicates invalid configuration or a rejected request.
	ErrConfiguration = errors.New("lunixi: invalid configuration or request")
	// ErrWebhook indicates an invalid, stale, or mismatched webhook.
	ErrWebhook = errors.New("lunixi: webhook verification failed")
)
View Source
var ErrInbox = errors.New("lunixi: webhook inbox persistence failed")

ErrInbox indicates a durable database failure. Return a retryable HTTP status, not a successful webhook acknowledgement, when it occurs.

Functions

func BankAccountStatuses added in v1.3.0

func BankAccountStatuses() []string

BankAccountStatuses lists the account statuses in wire order.

func BankCapabilities added in v1.3.0

func BankCapabilities() []string

BankCapabilities lists the bank and connection capabilities in wire order.

func BankConnectEventTypes added in v1.3.0

func BankConnectEventTypes() []string

BankConnectEventTypes lists the bank-account webhook events.

func BankConnectFilters added in v1.3.0

func BankConnectFilters() map[string][]string

BankConnectFilters returns a copy of the query filters each bank-account read accepts (route name → filter names).

func BankConnectionStatuses added in v1.3.0

func BankConnectionStatuses() []string

BankConnectionStatuses lists the connection statuses in wire order.

func BankFXOrderStatuses added in v1.3.0

func BankFXOrderStatuses() []string

BankFXOrderStatuses lists the exchange order statuses in wire order.

func BankTransactionDirections added in v1.3.0

func BankTransactionDirections() []string

BankTransactionDirections lists the transaction directions in wire order.

func BankTransactionTypes added in v1.3.0

func BankTransactionTypes() []string

BankTransactionTypes lists the canonical transaction types in wire order.

func BankTransferEventTypes added in v1.3.0

func BankTransferEventTypes() []string

BankTransferEventTypes lists the transfer webhook events.

func BankTransferRails added in v1.3.0

func BankTransferRails() []string

BankTransferRails lists the transfer rails in wire order.

func BankTransferRoutes added in v1.3.0

func BankTransferRoutes() map[string]Route

BankTransferRoutes returns a copy of the transfer and exchange route table (route name → Route), the same table as the other Lunixi SDKs.

func BankTransferStatuses added in v1.3.0

func BankTransferStatuses() []string

BankTransferStatuses lists the transfer statuses in wire order.

func BlockNameOf added in v1.3.0

func BlockNameOf(paymentMethod string) (string, error)

BlockNameOf returns the name of a method's block in the request body: the camelCase form of the method code (BANK_TRANSFER becomes bankTransfer). It is also returned as blockName by ListPaymentMethods.

func CanonicalJSON

func CanonicalJSON(value any) ([]byte, error)

CanonicalJSON produces compact JSON with JavaScript's numeric-index key ordering, UTF-8 strings, and number formatting. Unsafe integer numbers and duplicate object keys are rejected; use strings where an API specifies them.

func CanonicalRequest

func CanonicalRequest(method, path, date, nonce, digest string) string

CanonicalRequest returns the exact string signed by the gateway protocol.

func CardOnlyFields added in v1.3.0

func CardOnlyFields() []string

CardOnlyFields returns the fields that belong to a CARD payment only. The returned slice is a fresh copy.

func DecimalToMinor added in v1.0.0

func DecimalToMinor(value, currency string) (string, error)

DecimalToMinor converts decimal text with a supported currency exponent, without floating point.

func Digest

func Digest(body []byte) string

Digest returns the gateway's SHA-256 digest header value.

func DirectMethodPaymentFields added in v1.3.0

func DirectMethodPaymentFields() []string

DirectMethodPaymentFields returns every body field of POST /payments/direct/payment, method blocks included. The returned slice is a fresh copy.

func IdentityAnalyzeFields added in v1.3.0

func IdentityAnalyzeFields() []string

IdentityAnalyzeFields returns the body fields of Analyze and AnalyzeSync.

func IdentityLinkReasons added in v1.3.0

func IdentityLinkReasons(accountLinks json.RawMessage) []string

IdentityLinkReasons returns the distinct linkReasons of an AccountLinks answer's sessions (same_device_cluster, same_fingerprint, …), in the order they first appear.

func IdentityRoutes added in v1.3.0

func IdentityRoutes() map[string]Route

IdentityRoutes returns a copy of the identity route table, keyed by operation name.

func InsuranceConsentFields added in v1.3.0

func InsuranceConsentFields() []string

InsuranceConsentFields returns the fields of CreateOrder's consent.

func InsuranceEventTypes added in v1.3.0

func InsuranceEventTypes() []string

InsuranceEventTypes lists every insurance webhook event.

func InsuranceExternalPaymentFields added in v1.3.0

func InsuranceExternalPaymentFields() []string

InsuranceExternalPaymentFields returns the fields of ConfirmPayment (a premium collected outside Lunixi).

func InsuranceExternalRefundFields added in v1.3.0

func InsuranceExternalRefundFields() []string

InsuranceExternalRefundFields returns the fields of RefundPremium's externalRefund (a premium collected outside Lunixi).

func InsuranceFilters added in v1.3.0

func InsuranceFilters() map[string][]string

InsuranceFilters returns a copy of the query filters each insurance read accepts (route name → filter names).

func InsuranceLeadEventTypes added in v1.3.0

func InsuranceLeadEventTypes() []string

InsuranceLeadEventTypes lists the events about a lead; their data is InsuranceLeadWebhookData.

func InsuranceLeadFields added in v1.3.0

func InsuranceLeadFields() []string

InsuranceLeadFields returns the top-level fields CreateLead accepts: the type body of a quote without the basket, currency and order fields, plus shipment and company (lead schemas only) and the free note.

func InsuranceLeadStatuses added in v1.3.0

func InsuranceLeadStatuses() []string

InsuranceLeadStatuses lists the lead statuses in wire order.

func InsuranceOrderEventTypes added in v1.3.0

func InsuranceOrderEventTypes() []string

InsuranceOrderEventTypes lists the events about an order; their data is InsuranceWebhookData.

func InsuranceOrderFields added in v1.3.0

func InsuranceOrderFields() []string

InsuranceOrderFields returns the fields CreateOrder accepts.

func InsuranceOrderStatuses added in v1.3.0

func InsuranceOrderStatuses() []string

InsuranceOrderStatuses lists the overall order statuses in wire order.

func InsurancePolicyStatuses added in v1.3.0

func InsurancePolicyStatuses() []string

InsurancePolicyStatuses lists the policy statuses in wire order.

func InsuranceProductSearchFields added in v1.3.0

func InsuranceProductSearchFields() []string

InsuranceProductSearchFields returns the fields SearchProducts accepts.

func InsuranceQuoteFields added in v1.3.0

func InsuranceQuoteFields() []string

InsuranceQuoteFields returns the top-level fields CreateQuote accepts: after the person fields come the type objects, one per insurance type — tickets (a list) and the single objects stay, device, product, vehicle, trip, rental, instrument, event, accident, procedure, pet, residence, abroadStay. The field rules inside a type object are the gateway's.

func InsuranceReferenceKinds added in v1.3.0

func InsuranceReferenceKinds() []string

InsuranceReferenceKinds lists the reference kinds in wire order.

func IsClearScreening added in v1.3.0

func IsClearScreening(result json.RawMessage) bool

IsClearScreening reports whether a screening result (the data a screening method returned) can be read as "nothing found".

True only when the result has no match or hit of any kind (matches, hits, publicationHits), no isSanctioned, isBlacklisted, matched or caseRequired flag, no blocking decision (block, reject, review, hit, escalate …) and, when it reports coverage, coverageStatus COMPLETE. A PARTIAL or DEGRADED screening and a replay without coverage (null) are never clear. Account and adverse-media screening do not report coverage; for them the hits and flags decide.

func IsIdentityDeviceShared added in v1.3.0

func IsIdentityDeviceShared(accountLinks json.RawMessage, threshold int) bool

IsIdentityDeviceShared reports whether the device of an AccountLinks answer is shared by at least threshold accounts, counting the current one (linkedAccounts excludes it). A threshold below 2 is 2: a second account on the device trips it.

func IsKycSessionTerminal added in v1.3.0

func IsKycSessionTerminal(status string) bool

IsKycSessionTerminal reports APPROVED, REJECTED, MANUAL_REVIEW, EXPIRED, ABANDONED and CANCELLED (case-insensitive).

func IsSubscriptionActive added in v1.3.0

func IsSubscriptionActive(status string) bool

IsSubscriptionActive reports whether a subscription in this status may be billed (TRIALING, ACTIVE, PAST_DUE).

func IsSubscriptionTerminal added in v1.3.0

func IsSubscriptionTerminal(status string) bool

IsSubscriptionTerminal reports UPGRADED, DOWNGRADED, CANCELED and EXPIRED.

func KycAssuranceDomains added in v1.3.0

func KycAssuranceDomains() []string

KycAssuranceDomains returns the domains of the achieved assurance snapshot.

func KycAssuranceLevels added in v1.3.0

func KycAssuranceLevels() []string

KycAssuranceLevels returns the assurance ladder, lowest first.

func KycAssuranceMeets added in v1.3.0

func KycAssuranceMeets(achieved, required string) bool

KycAssuranceMeets reports whether achieved meets or exceeds required.

func KycAssuranceRank added in v1.3.0

func KycAssuranceRank(level string) int

KycAssuranceRank is the rank of a level on the assurance ladder: HIGH 3, SUBSTANTIAL 2, LOW 1, anything else 0 (case-insensitive).

func KycEventTypes added in v1.3.0

func KycEventTypes() []string

KycEventTypes returns every KYC webhook event type.

func KycEvidencePurposes added in v1.3.0

func KycEvidencePurposes() []string

KycEvidencePurposes returns every evidence purpose.

func KycRoutes added in v1.3.0

func KycRoutes() map[string]Route

KycRoutes returns a copy of the KYC route table, keyed by operation name.

func KycSessionStatuses added in v1.3.0

func KycSessionStatuses() []string

KycSessionStatuses returns every session status.

func KycSessionTerminalStates added in v1.3.0

func KycSessionTerminalStates() []string

KycSessionTerminalStates returns the terminal session states.

func KycSessionTypes added in v1.3.0

func KycSessionTypes() []string

KycSessionTypes returns every session type.

func ListSplitPaymentsFilters added in v1.3.0

func ListSplitPaymentsFilters() []string

ListSplitPaymentsFilters returns the filter names of GET /payments/split. The returned slice is a fresh copy.

func MarketplaceChargeRequiredFields added in v1.3.0

func MarketplaceChargeRequiredFields() []string

MarketplaceChargeRequiredFields returns the fields a split card charge requires.

func MarketplaceDealerStatuses added in v1.3.0

func MarketplaceDealerStatuses() []string

MarketplaceDealerStatuses returns every sub-dealer status.

func MarketplaceDealerTypes added in v1.3.0

func MarketplaceDealerTypes() []string

MarketplaceDealerTypes returns every sub-dealer type.

func MarketplaceMultiSellerPolicies added in v1.3.0

func MarketplaceMultiSellerPolicies() []string

MarketplaceMultiSellerPolicies returns every multi-seller policy.

func MarketplaceOnboardingURL added in v1.3.0

func MarketplaceOnboardingURL(link json.RawMessage, base string) string

MarketplaceOnboardingURL is the onboarding URL of an OnboardingToken answer: its url, else the hosted wizard with its token. base "" is MarketplaceDealerOnboardingHostedBase.

func MarketplaceRoutes added in v1.3.0

func MarketplaceRoutes() map[string]Route

MarketplaceRoutes returns a copy of the marketplace route table, keyed by operation name.

func MarketplaceSellerFields added in v1.3.0

func MarketplaceSellerFields() []string

MarketplaceSellerFields returns the fields of a seller leg.

func MethodBlockFields added in v1.3.0

func MethodBlockFields() []string

MethodBlockFields returns the method blocks POST /payments/direct/payment accepts besides card. The block of the chosen method is required and a block for another method is rejected. The returned slice is a fresh copy.

func NewPhysicalPosIdempotencyKey added in v1.3.0

func NewPhysicalPosIdempotencyKey() string

NewPhysicalPosIdempotencyKey returns a new Idempotency-Key (a random UUID v4). Store it with your order before you call, and use the same key to retry that operation.

func NormalizePaymentMethod added in v1.3.0

func NormalizePaymentMethod(code string) (string, error)

NormalizePaymentMethod checks a payment method code and returns its canonical form; "QR" becomes "QR_CODE".

func PaymentActionConfirmFields added in v1.3.0

func PaymentActionConfirmFields() []string

PaymentActionConfirmFields returns the confirm body fields a merchant server sends. Checkout token fields (token, checkoutSessionProof) are never sent by this SDK. The returned slice is a fresh copy.

func PaymentLinkImmutableFields added in v1.3.0

func PaymentLinkImmutableFields() []string

PaymentLinkImmutableFields returns a copy of the fields fixed at creation (usage, amountMode, currency); Update refuses them.

func PaymentLinkSpecFields added in v1.3.0

func PaymentLinkSpecFields() []string

PaymentLinkSpecFields returns a copy of the payment-link definition fields in the gateway's order.

func PhysicalPosEventTypes added in v1.3.0

func PhysicalPosEventTypes() []string

PhysicalPosEventTypes returns every delivered physical POS event type.

func PhysicalPosFilters added in v1.3.0

func PhysicalPosFilters(route string) []string

PhysicalPosFilters returns the query parameters a physical POS list or report accepts, by route name (listPayments, listTransactions, listAmbiguousPayments, getSalesSummary, getTaxSummary, listSettlements, listSettlementRuns, listDeviceModels, listStores, listRegisters, listTerminals, listTerminalAcquirers, listTerminalProviders, listDevices, and history for the audit, link, assignment and key lists). Nil for an unknown name.

func PhysicalPosNotStartedCodes added in v1.3.0

func PhysicalPosNotStartedCodes() []string

PhysicalPosNotStartedCodes returns the 5xx error codes that guarantee a payment write started nothing.

func PhysicalPosPaymentTargetFields added in v1.3.0

func PhysicalPosPaymentTargetFields() []string

PhysicalPosPaymentTargetFields returns the fields of a payment target: exactly one of deviceId, vendorCode + serialNumber, or externalRef.

func PhysicalPosRefundItemFields added in v1.3.0

func PhysicalPosRefundItemFields() []string

PhysicalPosRefundItemFields returns the fields of a refund item (createReversal items).

func PhysicalPosRequestFields added in v1.3.0

func PhysicalPosRequestFields(operation string) []string

PhysicalPosRequestFields returns the body fields of a physical POS request in the gateway's order, by operation name: createPayment, createReversal, createStore, updateStore, statusChange (archive / restore / close / retire bodies), createRegister, updateRegister, createTerminal, updateTerminal, addTerminalAcquirer, updateTerminalAcquirer, addTerminalProvider, updateTerminalProvider, changeTerminalDevice, createDevice, updateDevice, assignDevice, changeDeviceLifecycle, revokeDeviceKey, revertDeviceEnrollment, revokeActivationCode, setSettlementPolicy. Nil for an unknown name.

func PhysicalPosSaleItemFields added in v1.3.0

func PhysicalPosSaleItemFields() []string

PhysicalPosSaleItemFields returns the fields of a sale item (createPayment items).

func ProductCategories added in v1.2.0

func ProductCategories() []string

ProductCategories returns the product category codes known to this SDK version, in dictionary order. The returned slice is a fresh copy.

func SanctionCoverageStatuses added in v1.3.0

func SanctionCoverageStatuses() []string

SanctionCoverageStatuses lists the coverage statuses in wire order.

func SanctionHitTypes added in v1.3.0

func SanctionHitTypes() []string

SanctionHitTypes lists the hit types in wire order.

func SanctionNestedFields added in v1.3.0

func SanctionNestedFields() map[string]NestedFields

SanctionNestedFields returns a copy of the fields of the nested lists ("route.field" → fields).

func SanctionRiskDomains added in v1.3.0

func SanctionRiskDomains() []string

SanctionRiskDomains lists the risk domains in wire order.

func SanctionRoutes added in v1.3.0

func SanctionRoutes() map[string]Route

SanctionRoutes returns a copy of the sanction route table (route name → Route), the same table as the other Lunixi SDKs.

func SanctionScreenModes added in v1.3.0

func SanctionScreenModes() []string

SanctionScreenModes lists the name-screening modes in wire order.

func SanctionSubjectTypes added in v1.3.0

func SanctionSubjectTypes() []string

SanctionSubjectTypes lists the subject types in wire order.

func SanctionValueSets added in v1.3.0

func SanctionValueSets() map[string][]string

SanctionValueSets returns a copy of the value sets checked before sending ("route.field" → values).

func SanctionWalletScreenModes added in v1.3.0

func SanctionWalletScreenModes() []string

SanctionWalletScreenModes lists the wallet-screening modes in wire order.

func SplitLegBlockFields added in v1.3.0

func SplitLegBlockFields() []string

SplitLegBlockFields returns the method blocks a non-card split leg can carry. Meal card, open banking, shopping loan and bank transfer cannot be split legs. The returned slice is a fresh copy.

func SplitPaymentLegFields added in v1.3.0

func SplitPaymentLegFields() []string

SplitPaymentLegFields returns the fields of one split leg. The returned slice is a fresh copy.

func SubscriptionActiveStates added in v1.3.0

func SubscriptionActiveStates() []string

SubscriptionActiveStates returns the live states: the subscription may be billed.

func SubscriptionBillingFrequencies added in v1.3.0

func SubscriptionBillingFrequencies() []string

SubscriptionBillingFrequencies returns every billing frequency.

func SubscriptionBillingRuleFields added in v1.3.0

func SubscriptionBillingRuleFields() []string

SubscriptionBillingRuleFields returns the fields of a plan's billing rule.

func SubscriptionCardVerificationModes added in v1.3.0

func SubscriptionCardVerificationModes() []string

SubscriptionCardVerificationModes returns every card verification mode.

func SubscriptionCollectionMethods added in v1.3.0

func SubscriptionCollectionMethods() []string

SubscriptionCollectionMethods returns every collection method.

func SubscriptionEventTypes added in v1.3.0

func SubscriptionEventTypes() []string

SubscriptionEventTypes returns every subscription webhook event type.

func SubscriptionInvoiceStatuses added in v1.3.0

func SubscriptionInvoiceStatuses() []string

SubscriptionInvoiceStatuses returns every invoice status.

func SubscriptionPlanChangeBehaviors added in v1.3.0

func SubscriptionPlanChangeBehaviors() []string

SubscriptionPlanChangeBehaviors returns every plan-change behavior.

func SubscriptionPortalSdkModes added in v1.3.0

func SubscriptionPortalSdkModes() []string

SubscriptionPortalSdkModes returns every portal SDK mode.

func SubscriptionPortalURL added in v1.3.0

func SubscriptionPortalURL(link json.RawMessage, base string) string

SubscriptionPortalURL is the hosted portal URL of a portal link: link is the Portal.CreatePortalLink answer (its token is read) or the token as a JSON string. base "" is SubscriptionPortalHostedBase.

func SubscriptionRoutes added in v1.3.0

func SubscriptionRoutes() map[string]Route

SubscriptionRoutes returns a copy of the subscription route table, keyed by operation name ("plans.create").

func SubscriptionStatuses added in v1.3.0

func SubscriptionStatuses() []string

SubscriptionStatuses returns every subscription status.

func SubscriptionTerminalStates added in v1.3.0

func SubscriptionTerminalStates() []string

SubscriptionTerminalStates returns the states without a further transition.

func WalletAccountTypes added in v1.3.0

func WalletAccountTypes() []string

WalletAccountTypes lists the account types in wire order.

func WalletBulkTargetTypes added in v1.3.0

func WalletBulkTargetTypes() []string

WalletBulkTargetTypes lists the bulk payout target types in wire order.

func WalletCorporateAccountStatuses added in v1.3.0

func WalletCorporateAccountStatuses() []string

WalletCorporateAccountStatuses lists the corporate account statuses in wire order.

func WalletEndUserStatuses added in v1.3.0

func WalletEndUserStatuses() []string

WalletEndUserStatuses lists the end-user statuses in wire order.

func WalletKycLevels added in v1.3.0

func WalletKycLevels() []string

WalletKycLevels lists the KYC levels in wire order.

func WalletNestedFields added in v1.3.0

func WalletNestedFields() map[string]NestedFields

WalletNestedFields returns a copy of the row fields of the list bodies (importCorporateEmployees and offboardCorporateEmployees rows, createBulkPayout items).

func WalletOtpChannels added in v1.3.0

func WalletOtpChannels() []string

WalletOtpChannels lists the one-time code channels in wire order.

func WalletQRImageFormats added in v1.3.0

func WalletQRImageFormats() []string

WalletQRImageFormats lists the QR image formats in wire order.

func WalletQRTypes added in v1.3.0

func WalletQRTypes() []string

WalletQRTypes lists the QR code types in wire order.

func WalletRoutes added in v1.3.0

func WalletRoutes() map[string]Route

WalletRoutes returns a copy of the wallet route table (route name → Route), the same table as the other Lunixi SDKs.

Types

type APIError

type APIError struct {
	StatusCode int
	Code       string
	RequestID  string
}

APIError exposes safe diagnostics without including a request body, access token, private key, customer information, or an upstream error message.

func (*APIError) Error

func (e *APIError) Error() string

type Address

type Address struct {
	ContactName string `json:"contactName,omitempty"`
	Address     string `json:"address,omitempty"`
	City        string `json:"city,omitempty"`
	Country     string `json:"country,omitempty"`
	ZipCode     string `json:"zipCode,omitempty"`
}

Address is a billing or shipping address accepted by the payment API.

type BankAccountTransactionReceivedData added in v1.3.0

type BankAccountTransactionReceivedData struct {
	TransactionID          string  `json:"transactionId"`
	AccountID              string  `json:"accountId"`
	ConnectionID           string  `json:"connectionId"`
	BankEftCode            string  `json:"bankEftCode"`
	BankName               string  `json:"bankName"`
	Direction              string  `json:"direction"`
	AmountMinor            string  `json:"amountMinor"`
	Currency               string  `json:"currency"`
	BookedAt               string  `json:"bookedAt"`
	ValueAt                *string `json:"valueAt"`
	ReceivedAt             string  `json:"receivedAt"`
	CanonicalType          string  `json:"canonicalType"`
	Description            *string `json:"description"`
	CounterpartyNameMasked *string `json:"counterpartyNameMasked"`
	CounterpartyIbanMasked *string `json:"counterpartyIbanMasked"`
	ReceiptNo              *string `json:"receiptNo"`
}

BankAccountTransactionReceivedData is the data of a bank_account.transaction.received webhook.

func ParseBankAccountTransactionReceived added in v1.3.0

func ParseBankAccountTransactionReceived(event *WebhookEvent) (*BankAccountTransactionReceivedData, error)

ParseBankAccountTransactionReceived reads a verified bank_account.transaction.received event.

type BankConnectClient added in v1.3.0

type BankConnectClient struct {

	// Transfers sends outgoing transfers from a connected account.
	Transfers *BankTransferClient
	// FX exchanges currency between two of your accounts on one connection.
	FX *BankFXClient
	// contains filtered or unexported fields
}

BankConnectClient — read your connected bank accounts, balances and transactions (/api/v1/bank-connect, product BANK_CONNECT).

Every call is signed, reads included. Scopes: bank-connect:view for banks, connections, accounts and RequestSync; bank-connect:transactions:view for balances and transactions (403 API_INSUFFICIENT_SCOPE otherwise). The key decides the environment: a TEST key reads only test-environment accounts, a LIVE key only live ones. Connecting a bank and entering bank credentials happen in the Lunixi dashboard only. Another organisation's or the other environment's record is 404, the same as a record that does not exist.

Money movement lives on two sub-clients, available when the connection offers it (capabilities OUTGOING_TRANSFER / FX_EXCHANGE): Transfers and FX. They need the bank-connect:transfer scope and a key with an IP allowlist.

Filters are maps checked against BankConnectFilters before anything is sent: an unknown filter, a value outside its set, a limit outside 1–100, more than 100 account ids, an amount that is not minor-unit text, a minimum above the maximum, bookedTo without bookedFrom or a window over 92 days returns ErrConfiguration. Single records are returned as the envelope's data; lists as CursorPage.

func (*BankConnectClient) GetAccount added in v1.3.0

func (b *BankConnectClient) GetAccount(ctx context.Context, accountID string) (json.RawMessage, error)

GetAccount reads one account; 404 bank_connect.account.not_found for an unknown one.

func (*BankConnectClient) GetConnection added in v1.3.0

func (b *BankConnectClient) GetConnection(ctx context.Context, connectionID string) (json.RawMessage, error)

GetConnection reads one connection; 404 bank_connect.connection.not_found for an unknown one.

func (*BankConnectClient) GetTransaction added in v1.3.0

func (b *BankConnectClient) GetTransaction(ctx context.Context, transactionID string) (json.RawMessage, error)

GetTransaction reads one transaction with its detail fields (balanceAfterMinor, documentNo, bank).

func (*BankConnectClient) IterateAccounts added in v1.3.0

func (b *BankConnectClient) IterateAccounts(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateAccounts yields every account matching the filters.

func (*BankConnectClient) IterateBalances added in v1.3.0

func (b *BankConnectClient) IterateBalances(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateBalances yields every balance matching the filters.

func (*BankConnectClient) IterateBanks added in v1.3.0

func (b *BankConnectClient) IterateBanks(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateBanks yields every bank of the catalogue, page by page.

func (*BankConnectClient) IterateConnections added in v1.3.0

func (b *BankConnectClient) IterateConnections(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateConnections yields every connection matching the filters.

func (*BankConnectClient) IterateTransactions added in v1.3.0

func (b *BankConnectClient) IterateTransactions(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateTransactions yields every transaction matching the filters.

func (*BankConnectClient) ListAccounts added in v1.3.0

func (b *BankConnectClient) ListAccounts(ctx context.Context, filters map[string]any) (*CursorPage, error)

ListAccounts lists your connected accounts, newest first, each with its data freshness. Filters: limit, cursor, connectionId, bankId, currency, status (BankAccountStatus*).

func (*BankConnectClient) ListBalances added in v1.3.0

func (b *BankConnectClient) ListBalances(ctx context.Context, filters map[string]any) (*CursorPage, error)

ListBalances lists the latest balance of each account (scope bank-connect:transactions:view); without accountId every active account of the key's environment. Filters: limit, cursor, accountId (one id or a list of at most 100), currency.

func (*BankConnectClient) ListBanks added in v1.3.0

func (b *BankConnectClient) ListBanks(ctx context.Context, filters map[string]any) (*CursorPage, error)

ListBanks lists the bank catalogue: whether each bank can be connected and what is read from it. Filters: limit, cursor.

func (*BankConnectClient) ListConnections added in v1.3.0

func (b *BankConnectClient) ListConnections(ctx context.Context, filters map[string]any) (*CursorPage, error)

ListConnections lists your bank connections, newest first. Filters: limit, cursor, status (one BankConnectionStatus* value or a list), bankId.

func (*BankConnectClient) ListTransactions added in v1.3.0

func (b *BankConnectClient) ListTransactions(ctx context.Context, filters map[string]any) (*CursorPage, error)

ListTransactions lists transactions, newest recorded first (scope bank-connect:transactions:view).

The order is receivedAt (when Lunixi recorded the transaction), which never changes, so paging forward never skips a transaction that arrives late with an older bank date. bookedFrom (inclusive) / bookedTo (exclusive) filter on the bank date: a time.Time or ISO-8601 text with a time zone, at most 92 days apart; bookedTo needs bookedFrom (bookedFrom alone runs up to now). minAmountMinor / maxAmountMinor are inclusive minor-unit text. Also limit, cursor, accountId (one id or a list), direction, canonicalType (one BankTransactionType* value or a list).

func (*BankConnectClient) RequestSync added in v1.3.0

func (b *BankConnectClient) RequestSync(ctx context.Context, accountID string) (json.RawMessage, error)

RequestSync asks for a fresh read of the account from the bank (HTTP 202).

It never reads earlier than the bank's minimum interval: when the interval has not passed the answer is SCHEDULED with scheduledAt, and a request while one is already waiting joins it. Nothing is written, so no Idempotency-Key is needed. New transactions arrive by the bank_account.transaction.received webhook. 409 bank_connect.connection.not_active when the connection is not ACTIVE or DEGRADED; 429 RATE_LIMITED when the key sent too many sync requests in the last minute.

type BankConnectWriteResult added in v1.3.0

type BankConnectWriteResult struct {
	// Data is the whole data object ({transfer, stepUp, replayed} or
	// {order, replayed}).
	Data           json.RawMessage
	Replayed       bool
	StatusCode     int
	IdempotencyKey string
	RequestID      string
}

BankConnectWriteResult is the answer of a keyed bank-connect write (Transfers.Create, FX.CreateOrder): HTTP 201, Replayed true when the same key and body were sent before. IdempotencyKey is the key that was sent (yours, or the generated one); keep it to retry the same operation.

func (*BankConnectWriteResult) DecodeData added in v1.3.0

func (r *BankConnectWriteResult) DecodeData(target any) error

DecodeData decodes Data using json.Number for interface values.

func (*BankConnectWriteResult) Order added in v1.3.0

Order returns data.order of FX.CreateOrder.

func (*BankConnectWriteResult) Record added in v1.3.0

func (r *BankConnectWriteResult) Record(name string) json.RawMessage

Record returns one field of Data, nil when absent or null.

func (*BankConnectWriteResult) Transfer added in v1.3.0

func (r *BankConnectWriteResult) Transfer() json.RawMessage

Transfer returns data.transfer of Transfers.Create.

type BankFXClient added in v1.3.0

type BankFXClient struct {
	// contains filtered or unexported fields
}

BankFXClient — currency exchange between two of your accounts, Client.BankConnect.FX (/api/v1/bank-connect/fx, product BANK_CONNECT).

Available on a connection whose capabilities include FX_EXCHANGE. The two accounts are active accounts of the same connection in different currencies. Same scope and IP allowlist rule as transfers.

Flow: ListRates (optional) → CreateQuote → CreateOrder with the quote id before quote.expiresAt (the bank sets the validity, typically under two minutes; see validForSeconds). The order is SUBMITTED and queued; follow it with GetOrder. There is no webhook for exchange orders.

func (*BankFXClient) CreateOrder added in v1.3.0

func (f *BankFXClient) CreateOrder(ctx context.Context, request map[string]any, idempotencyKey string) (*BankConnectWriteResult, error)

CreateOrder executes a quote (HTTP 201); Data is {order, replayed}. request: quoteId, optional description (at most 140 characters). The key follows the same rule as Transfers.Create and is generated when "". 409 bank_connect.fx.quote_expired / bank_connect.fx.quote_used: ask for a new quote.

func (*BankFXClient) CreateQuote added in v1.3.0

func (f *BankFXClient) CreateQuote(ctx context.Context, request map[string]any) (json.RawMessage, error)

CreateQuote quotes an exchange (HTTP 201). request: sourceAccountId (you sell from it), targetAccountId (you buy into it) and exactly one of sourceAmountMinor / targetAmountMinor (positive minor-unit text of that account's currency). Nothing is booked; a quote is used by one order.

func (*BankFXClient) GetOrder added in v1.3.0

func (f *BankFXClient) GetOrder(ctx context.Context, orderID string) (json.RawMessage, error)

GetOrder reads one exchange order; 404 bank_connect.fx.order_not_found for an unknown id.

func (*BankFXClient) IterateOrders added in v1.3.0

func (f *BankFXClient) IterateOrders(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateOrders yields every exchange order matching the filters.

func (*BankFXClient) ListOrders added in v1.3.0

func (f *BankFXClient) ListOrders(ctx context.Context, filters map[string]any) (*CursorPage, error)

ListOrders lists exchange orders, newest first. Filters: status (one BankFXOrderStatus* value or a list), limit, cursor.

func (*BankFXClient) ListRates added in v1.3.0

func (f *BankFXClient) ListRates(ctx context.Context, connectionID string) (json.RawMessage, error)

ListRates reads the current rates on the connection: {items, refreshSeconds, fetchedAt}; rates are decimal text.

type BankTransferClient added in v1.3.0

type BankTransferClient struct {
	// contains filtered or unexported fields
}

BankTransferClient — outgoing bank transfers, Client.BankConnect.Transfers (/api/v1/bank-connect/transfers, product BANK_CONNECT).

Available on a connection whose capabilities include OUTGOING_TRANSFER. Every route, reads included, is signed and needs the bank-connect:transfer scope; the key must have an IP allowlist and the request must come from a listed IP (403 bank_connect.auth.ip_allowlist_required / bank_connect.auth.ip_not_allowed).

With an API key there is no e-mail code: the key's scope, the signature and the source IP approve the transfer, so Create answers SUBMITTED and the transfer is queued for the bank. Follow it with Get or the BankTransferEvent* webhooks. The bank chooses the rail (own account, same bank, FAST or EFT); Lunixi does not check the balance — the bank decides. When the outcome at the bank is unknown the transfer stays SUBMITTED with outcomeUnknown true and Lunixi settles it; do not send it again.

func (*BankTransferClient) Create added in v1.3.0

func (t *BankTransferClient) Create(ctx context.Context, request map[string]any, idempotencyKey string) (*BankConnectWriteResult, error)

Create creates an outgoing transfer (HTTP 201); Data is {transfer, stepUp, replayed}.

request: accountId (source account), receiverIban (TR IBAN), receiverName (2–140 characters), amountMinor (positive minor-unit text: "150075" is 1,500.75 TRY), optional currency (TRY), paymentPurpose (a ListPurposes code) and description (at most 140 characters).

idempotencyKey (8–200 printable ASCII characters) is generated (UUID v4) when "" and returned as IdempotencyKey; a network error or a 5xx is retried (MaxRetries) with the same key and body. Keep your own key (e.g. your payout id) to retry safely across processes: the same key with the same body answers the existing transfer with Replayed true, the same key with another body is 409 bank_connect.transfer.idempotency_conflict.

func (*BankTransferClient) Get added in v1.3.0

func (t *BankTransferClient) Get(ctx context.Context, transferID string) (json.RawMessage, error)

Get reads one transfer; 404 bank_connect.transfer.not_found for an unknown id.

func (*BankTransferClient) Iterate added in v1.3.0

func (t *BankTransferClient) Iterate(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

Iterate yields every transfer matching the filters, page by page.

func (*BankTransferClient) List added in v1.3.0

func (t *BankTransferClient) List(ctx context.Context, filters map[string]any) (*CursorPage, error)

List lists transfers, newest first. Filters: accountId, status (one BankTransferStatus* value or a list), createdFrom (inclusive) / createdTo (exclusive) as a time.Time or ISO-8601 text, limit 1–100, cursor.

func (*BankTransferClient) ListPurposes added in v1.3.0

func (t *BankTransferClient) ListPurposes(ctx context.Context, connectionID string) (json.RawMessage, error)

ListPurposes lists the payment purpose codes the bank accepts on this connection: {items: [{code, name, order}]}. Pass one as paymentPurpose to Create; leave it out for the bank's default.

type BankTransferExceptionFilters added in v1.3.0

type BankTransferExceptionFilters struct {
	Environment string
	Status      string
	Limit       *int
}

BankTransferExceptionFilters narrows ListBankTransferExceptions. Empty fields are not sent. Environment is "TEST" or "LIVE"; Status is a BankTransferExceptionStatus* value; Limit, when set, is 1–200.

type BankTransferWebhookData added in v1.3.0

type BankTransferWebhookData struct {
	TransferID         string  `json:"transferId"`
	ConnectionID       string  `json:"connectionId"`
	AccountID          string  `json:"accountId"`
	BankEftCode        string  `json:"bankEftCode"`
	BankName           string  `json:"bankName"`
	Status             string  `json:"status"`
	Rail               *string `json:"rail"`
	AmountMinor        string  `json:"amountMinor"`
	Currency           string  `json:"currency"`
	ReceiverIbanMasked string  `json:"receiverIbanMasked"`
	ReceiverNameMasked string  `json:"receiverNameMasked"`
	PaymentPurpose     *string `json:"paymentPurpose"`
	Description        *string `json:"description"`
	FailureCode        *string `json:"failureCode"`
	IdempotencyKey     string  `json:"idempotencyKey"`
	CreatedAt          string  `json:"createdAt"`
	CompletedAt        *string `json:"completedAt"`
	FailedAt           *string `json:"failedAt"`
	ReturnedAt         *string `json:"returnedAt"`
}

BankTransferWebhookData is the data of a bank_transfer.* webhook.

func ParseBankTransferWebhook added in v1.3.0

func ParseBankTransferWebhook(event *WebhookEvent) (*BankTransferWebhookData, error)

ParseBankTransferWebhook reads a verified bank_transfer.* event.

type BasketItem

type BasketItem struct {
	ID                string         `json:"id"`
	Name              string         `json:"name"`
	ItemType          string         `json:"itemType"`
	Price             string         `json:"price"`
	Category1         string         `json:"category1,omitempty"`
	Category2         string         `json:"category2,omitempty"`
	InsuranceData     map[string]any `json:"insuranceData,omitempty"`
	InsuranceCategory string         `json:"insuranceCategory,omitempty"`
	InsuranceTypes    []string       `json:"insuranceTypes,omitempty"`
	// ProductCategory is the optional Lunixi product category code, one of
	// the ProductCategory* constants. Payment methods with legal installment
	// limits (e.g. shopping loan) and other platform features use it. Empty
	// omits the field; an unknown code is rejected by the API.
	ProductCategory string `json:"productCategory,omitempty"`
}

BasketItem is a checkout basket line; Price is an integer minor-unit line total, not a per-unit float. Additional insurance data follows the gateway schema and is passed without guessing insurance-specific field rules.

type Buyer

type Buyer struct {
	ID                  string `json:"id,omitempty"`
	Name                string `json:"name,omitempty"`
	Surname             string `json:"surname,omitempty"`
	IdentityNumber      string `json:"identityNumber,omitempty"`
	Email               string `json:"email,omitempty"`
	GSMNumber           string `json:"gsmNumber,omitempty"`
	IP                  string `json:"ip,omitempty"`
	City                string `json:"city,omitempty"`
	Country             string `json:"country,omitempty"`
	ZipCode             string `json:"zipCode,omitempty"`
	RegistrationDate    string `json:"registrationDate,omitempty"`
	LastLoginDate       string `json:"lastLoginDate,omitempty"`
	RegistrationAddress string `json:"registrationAddress,omitempty"`
}

Buyer holds the documented buyer details used by hosted checkout. Values are sent to Lunixi only and must never be copied to application logs.

type Client

type Client struct {
	Payments     *PaymentClient
	PaymentLinks *PaymentLinkClient
	Fraud        *FraudClient
	Reference    *ReferenceClient
	// PhysicalPos starts and reverses card payments on your devices and
	// reads payments, transactions, reports and end-of-day results.
	PhysicalPos *PhysicalPosClient
	// PhysicalPosManagement manages stores, registers, terminals, devices,
	// device keys and end-of-day policies.
	PhysicalPosManagement *PhysicalPosManagementClient
	// Wallet is the merchant surface of the closed-loop wallet: end users,
	// transfers, withdrawals, top-ups, payments, QR codes and bulk payouts.
	Wallet *WalletClient
	// BankConnect reads your connected bank accounts, balances and
	// transactions, and sends transfers and currency exchange orders.
	BankConnect *BankConnectClient
	// Sanction screens names, wallets, accounts and transactions and runs
	// ongoing monitoring.
	Sanction *SanctionClient
	// Insurance offers, sells and services insurance and submits leads.
	Insurance *InsuranceClient
	// Subscriptions bills customers on plans: subscriptions, plans,
	// customers, saved cards, invoices, the customer portal, catalog
	// products, features, add-ons and metered usage.
	Subscriptions *SubscriptionsClient
	// Kyc runs KYC, KYB and evidence sessions and reads your KYC policy and
	// webhook deliveries.
	Kyc *KycClient
	// Identity reads device and account-linking signals of the browser
	// fingerprint SDK.
	Identity *IdentityClient
	// Marketplace splits charges across sub-dealers and manages the
	// sub-dealers, commissions, payouts and the audit log.
	Marketplace *MarketplaceClient
	// contains filtered or unexported fields
}

Client is safe for concurrent use. Create one client per merchant key.

func New

func New(config Config) (*Client, error)

New validates configuration without making a network request.

func (*Client) Do

func (c *Client) Do(ctx context.Context, in Request) (*Response, error)

Do calls a documented merchant endpoint through the same signed transport as the high-level clients. It does not invent service-specific validation; callers using this escape hatch must follow the endpoint's public schema.

func (*Client) InvalidateToken

func (c *Client) InvalidateToken()

InvalidateToken clears the in-memory token cache, for example after key permissions change. Key rotation itself requires constructing a new client.

type Config

type Config struct {
	BaseURL          string
	KeyID            string `json:"-"`
	PrivateKey       string `json:"-"`
	HTTPClient       *http.Client
	Timeout          time.Duration
	MaxRetries       int
	MaxResponseBytes int64
	// AllowInsecureLocalhost permits HTTP only for literal loopback addresses
	// and localhost. It is intended for local test servers, never production.
	AllowInsecureLocalhost bool
	// Now provides a deterministic clock for tests. Nil uses time.Now.
	Now func() time.Time
}

Config configures one merchant's client. Do not reuse a client across keys or merchants. HTTPClient is copied and redirects are always disabled.

func (Config) GoString

func (c Config) GoString() string

func (Config) MarshalJSON

func (c Config) MarshalJSON() ([]byte, error)

MarshalJSON intentionally excludes configuration secrets from structured logs.

func (Config) String

func (c Config) String() string

String and GoString keep routine configuration logging from exposing keys.

type CursorPage added in v1.3.0

type CursorPage struct {
	Items      []json.RawMessage
	HasMore    bool
	NextCursor string
	TotalCount *int64
	PageSize   *int64
	Raw        json.RawMessage
	RequestID  string
}

CursorPage is one page of a cursor-paged list (wallet, bank accounts and transfers, sanction, insurance, subscriptions, KYC, identity, marketplace). Items are the rows in wire order. Send NextCursor back verbatim as the cursor filter (pageToken on the subscription, plan, customer, card, invoice and audit-log lists); HasMore is true only with a non-empty cursor. TotalCount is set when the list reports it. PageSize is the page size the subscription lists report (the row count when they do not), nil on the other lists. Raw is the whole data object of the answer (wallet and sanction lists carry other fields next to the rows, such as runsToday on the screening history).

type DirectMethodPaymentRequest added in v1.3.0

type DirectMethodPaymentRequest struct {
	// contains filtered or unexported fields
}

DirectMethodPaymentRequest builds the body of POST /payments/direct/payment: a payment with any method started from the merchant server. Create it with NewDirectMethodPaymentRequest, choose the method with WithMethodFields or WithCard and add options with the other With methods. Each With method returns the request for chaining; the first invalid value is kept and reported by Body and DirectMethodPayment, before any request is sent.

func NewDirectMethodPaymentRequest added in v1.3.0

func NewDirectMethodPaymentRequest(amount, currency, orderID string) *DirectMethodPaymentRequest

NewDirectMethodPaymentRequest starts a direct method payment body. amount is positive minor-unit text (the basket total without a provider fee), currency a three-letter code and orderID your order reference.

func (*DirectMethodPaymentRequest) Body added in v1.3.0

func (r *DirectMethodPaymentRequest) Body() (map[string]any, error)

Body returns the request body, or the first invalid value. The raw body rules of DirectMethodPayment and Client.Do are applied again when sending.

func (*DirectMethodPaymentRequest) WithBasketItems added in v1.3.0

WithBasketItems sets the basket. SHOPPING_LOAN requires 1 to 100 items.

func (*DirectMethodPaymentRequest) WithBillingAddress added in v1.3.0

func (r *DirectMethodPaymentRequest) WithBillingAddress(value Address) *DirectMethodPaymentRequest

WithBillingAddress sets the billing address.

func (*DirectMethodPaymentRequest) WithBuyer added in v1.3.0

WithBuyer sets the buyer; values are sent to Lunixi only.

func (*DirectMethodPaymentRequest) WithCallbackURL added in v1.3.0

WithCallbackURL is where the buyer's browser returns after a REDIRECT action.

func (*DirectMethodPaymentRequest) WithCard added in v1.3.0

WithCard pays by card: new card fields, or cardUserKey and cardToken of a stored card. Add WithForce3D(true) for 3D Secure.

func (*DirectMethodPaymentRequest) WithCustomerID added in v1.3.0

WithCustomerID sets your customer reference.

func (*DirectMethodPaymentRequest) WithDescription added in v1.3.0

WithDescription sets the payment description.

func (*DirectMethodPaymentRequest) WithForce3D added in v1.3.0

WithForce3D is card only; true charges with 3D Secure and the response carries a REDIRECT action.

func (*DirectMethodPaymentRequest) WithInstallment added in v1.3.0

func (r *DirectMethodPaymentRequest) WithInstallment(count int, quoteToken string) *DirectMethodPaymentRequest

WithInstallment is card only. quoteToken ("" to leave it out) binds the charge to an installment quote; the quoted fee is added to amount.

func (*DirectMethodPaymentRequest) WithLocale added in v1.3.0

WithLocale sets the locale of buyer-facing texts.

func (*DirectMethodPaymentRequest) WithMetadata added in v1.3.0

WithMetadata sets merchant metadata.

func (*DirectMethodPaymentRequest) WithMethodFields added in v1.3.0

func (r *DirectMethodPaymentRequest) WithMethodFields(paymentMethod, providerCode string, fields map[string]any) *DirectMethodPaymentRequest

WithMethodFields pays with a method other than card. fields are the values of the provider's inputFields from ListPaymentMethods (for example {"gsmNumber": "+905321234567"} for mobile billing, {"bankCode": "0062"} for BANK_TRANSFER); nil or an empty map when the provider asks for nothing. providerCode is "" to leave it out; it is required when the method lists more than one provider (providerSelection REQUIRED) and is always read from ListPaymentMethods. BANK_TRANSFER takes no providerCode. For PROMISSORY_NOTE give the plan with WithPromissoryNoteSchedule or WithPromissoryNoteCount.

func (*DirectMethodPaymentRequest) WithPaymentChannel added in v1.3.0

func (r *DirectMethodPaymentRequest) WithPaymentChannel(value string) *DirectMethodPaymentRequest

WithPaymentChannel sets paymentChannel.

func (*DirectMethodPaymentRequest) WithPaymentGroup added in v1.3.0

func (r *DirectMethodPaymentRequest) WithPaymentGroup(value string) *DirectMethodPaymentRequest

WithPaymentGroup sets paymentGroup.

func (*DirectMethodPaymentRequest) WithPreauth added in v1.3.0

WithPreauth true holds the amount (AUTHORIZED); take it with Capture or release it with Void. A method that does not support it is refused with 422 payment.preauth.unsupported_for_method.

func (*DirectMethodPaymentRequest) WithPromissoryNoteCount added in v1.3.0

func (r *DirectMethodPaymentRequest) WithPromissoryNoteCount(count int) *DirectMethodPaymentRequest

WithPromissoryNoteCount sets the promissory-note plan as a number of notes (1–24, within your provider connection limits); it is sent as text. The amount is split evenly and due dates follow your connection settings. It replaces a schedule.

func (*DirectMethodPaymentRequest) WithPromissoryNoteSchedule added in v1.3.0

WithPromissoryNoteSchedule sets the promissory-note plan as one note per row. Amounts are positive minor-unit text adding up to the payment amount; due dates are YYYY-MM-DD in ascending order, at most 24 rows. That a due date is in the future is checked by the gateway. It replaces a note count.

func (*DirectMethodPaymentRequest) WithShippingAddress added in v1.3.0

func (r *DirectMethodPaymentRequest) WithShippingAddress(value Address) *DirectMethodPaymentRequest

WithShippingAddress sets the shipping address.

type FraudClient

type FraudClient struct {
	// contains filtered or unexported fields
}

FraudClient exposes transaction evaluation and event ingestion. Results remain gateway decisions; callers must enforce their own business policy.

func (*FraudClient) Decision

func (f *FraudClient) Decision(ctx context.Context, traceID string) (*Response, error)

Decision reads one fraud decision by trace ID.

func (*FraudClient) Decisions

func (f *FraudClient) Decisions(ctx context.Context, filters url.Values) (*Response, error)

Decisions lists fraud decisions without discarding sibling pageInfo.

func (*FraudClient) Evaluate

func (f *FraudClient) Evaluate(ctx context.Context, body map[string]any) (*Response, error)

Evaluate rejects unknown top-level fields, including tenantId, before authentication. Tenant identity always comes from the merchant credential.

func (*FraudClient) LatestForPayment added in v1.3.0

func (f *FraudClient) LatestForPayment(ctx context.Context, paymentID string) (json.RawMessage, error)

LatestForPayment returns the most recent fraud decision of a payment, or nil when the payment has none. It reads the decision list with paymentId and limit 1.

func (*FraudClient) RecordBatch added in v1.3.0

func (f *FraudClient) RecordBatch(ctx context.Context, events []map[string]any, key string) (*Response, error)

RecordBatch ingests 1–FraudEventBatchLimit transaction events in one request (POST /fraud/events/transactions/batch, sent as a JSON array). Every event needs eventId, subjectType, eventType and occurredAt; a stable caller key is required, as for RecordEvent. Data reports the accepted and rejected events.

func (*FraudClient) RecordEvent

func (f *FraudClient) RecordEvent(ctx context.Context, event map[string]any, key string) (*Response, error)

RecordEvent ingests one transaction event. A stable eventId and caller key are required by this helper for durable application-level idempotency.

type IdentityClient added in v1.3.0

type IdentityClient struct {
	// contains filtered or unexported fields
}

IdentityClient — identity signals (/api/v1/identity/*), reached as Client.Identity.

The calls carry the access token, without the per-request signature. The browser fingerprint SDK produces a traceId; your server reads the linked accounts of that trace and flags or blocks when the device is shared ("one person, many accounts", IsIdentityDeviceShared).

This is a signal surface: it carries risk flags, reason codes, similarity probabilities and the identity snapshot, not an allow / review / block verdict (that is the fraud decision). Calls return the envelope's data; ListSessions returns CursorPage.

func (i *IdentityClient) AccountLinks(ctx context.Context, traceID string) (json.RawMessage, error)

AccountLinks reads the other accounts seen on this device, fingerprint or IP (account keys hashed).

func (*IdentityClient) Analyze added in v1.3.0

func (i *IdentityClient) Analyze(ctx context.Context, request map[string]any) (json.RawMessage, error)

Analyze queues the analysis and returns the traceId at once; the same body as AnalyzeSync.

func (*IdentityClient) AnalyzeSync added in v1.3.0

func (i *IdentityClient) AnalyzeSync(ctx context.Context, request map[string]any) (json.RawMessage, error)

AnalyzeSync analyses a session synchronously: subjectType, subjectId, productContext, integrationMode, customer, device, session, source, account, metadata, paymentId (all optional; subjectType and subjectId go together). Returns {traceId, analysisStatus, riskFlags, reasonCodes, identitySnapshot, …}.

func (*IdentityClient) GetSession added in v1.3.0

func (i *IdentityClient) GetSession(ctx context.Context, traceID string) (json.RawMessage, error)

GetSession reads one identity session.

func (*IdentityClient) ListSessions added in v1.3.0

func (i *IdentityClient) ListSessions(ctx context.Context, filters map[string]any) (*CursorPage, error)

ListSessions lists identity sessions. Filters: fingerprintId, deviceId, paymentId, limit.

func (*IdentityClient) RelatedSessions added in v1.3.0

func (i *IdentityClient) RelatedSessions(ctx context.Context, traceID string, limit int) (json.RawMessage, error)

RelatedSessions reads the recent sessions of the same device-identity cluster; limit 0 sends none.

func (*IdentityClient) Timeline added in v1.3.0

func (i *IdentityClient) Timeline(ctx context.Context, traceID string) (json.RawMessage, error)

Timeline reads the session summary and its recorded lifecycle events.

func (*IdentityClient) TopSources added in v1.3.0

func (i *IdentityClient) TopSources(ctx context.Context, filters map[string]any) (json.RawMessage, error)

TopSources ranks source domains by repeated risky activity. Filters: days, limit.

type InstallmentOptionsRequest added in v1.3.0

type InstallmentOptionsRequest struct {
	Amount        string `json:"amount,omitempty"`
	Currency      string `json:"currency,omitempty"`
	IntentID      string `json:"intentId,omitempty"`
	BinOrPan      string `json:"binOrPan,omitempty"`
	Installment   int    `json:"installment,omitempty"`
	CardBrand     string `json:"cardBrand,omitempty"`
	PaymentMethod string `json:"paymentMethod,omitempty"`
	// EnabledInstallments limits the table to these counts, e.g. []int{1, 2, 3}
	// for a product page that allows at most 3. Same rules as
	// IntentRequest.EnabledInstallments: integers 1–36, no duplicates, 1
	// included; nil means no restriction. Sent in ascending order.
	EnabledInstallments []int `json:"enabledInstallments,omitempty"`
}

InstallmentOptionsRequest is the body of InstallmentOptions (POST /bin/installments). Give Amount (positive minor units, the basket total) with Currency, or IntentID to quote against an existing intent. Installment greater than 1 together with BinOrPan returns the binding quoteToken to send as the installmentQuoteToken of a card payment.

type InsuranceClient added in v1.3.0

type InsuranceClient struct {
	// contains filtered or unexported fields
}

InsuranceClient — offer, sell and service insurance for your basket items, and submit leads for the types sold by request only (/api/v1/insurance, product INSURANCE_SERVICE).

Every call is signed, reads included; a key without the product is 403 PRODUCT_NOT_ENABLED. The key decides the environment (TEST or LIVE).

Request fields and query filters are checked before anything is sent (the gateway rejects an unknown field with 400): an unknown field or filter, a missing required value, a basket sent both as paymentIntentId and as context.items, or a malformed Idempotency-Key returns ErrConfiguration. The field rules of an insurance type's own object (insured, tickets …) are not repeated here — a violation comes back as 422 insurance.validation.invalid with every details.errors[{field, reason}] at once. Amounts are canonical minor-unit text.

Idempotency-Key (8–200 printable ASCII characters, no spaces) is required by CreateOrder, ConfirmPayment, IssuePolicy, CancelOrder, RefundPremium and CreateLead, and optional ("" sends none) for CreateQuote and BindPayment.

Single records are the envelope's data; lists return CursorPage; policy documents and the reconciliation export are bytes.

func (*InsuranceClient) BindPayment added in v1.3.0

func (i *InsuranceClient) BindPayment(ctx context.Context, orderID, paymentIntentID, idempotencyKey string) (json.RawMessage, error)

BindPayment binds an order to the Lunixi payment that collects its premium. When you collect it (premiumCollectedBy MERCHANT) the payment basket must hold the premium item (PremiumBasketItem); when the provider collects it, it must not. Binding the same payment again returns the order. The key is optional ("" sends none).

func (*InsuranceClient) CancelOrder added in v1.3.0

func (i *InsuranceClient) CancelOrder(ctx context.Context, orderID, idempotencyKey string) (json.RawMessage, error)

CancelOrder opens a cancellation at the provider for every issued policy of the order (policyStatus CANCEL_PENDING; insurance.policy.cancelled confirms it). Cancelling does not refund the premium: call RefundPremium after it. The key is required.

func (*InsuranceClient) ConfirmPayment added in v1.3.0

func (i *InsuranceClient) ConfirmPayment(ctx context.Context, orderID string, payment map[string]any, idempotencyKey string) (json.RawMessage, error)

ConfirmPayment records a premium you collected outside Lunixi: {externalPaymentId, paidAmount, paidCurrency, paidAt, paymentProvider?}. paidAmount and paidCurrency must equal the order's premium. The key is required; repeating the same externalPaymentId returns the order.

func (*InsuranceClient) ConsentFromQuote added in v1.3.0

func (i *InsuranceClient) ConsentFromQuote(option any, acceptedAt time.Time) (map[string]any, error)

ConsentFromQuote builds CreateOrder's consent from a quote option (the data of GetQuote, or one of CreateQuote's options): the option's terms unchanged and the moment the buyer accepted them (not in the future).

func (*InsuranceClient) CreateLead added in v1.3.0

func (i *InsuranceClient) CreateLead(ctx context.Context, request map[string]any, idempotencyKey string) (json.RawMessage, error)

CreateLead submits a lead (HTTP 201) for an insurance type sold by request only: the provider gives no quote, so there is no premium, order, policy or document. policyholder, the type object and an optional note (sent as given, at most 1000 characters) follow the type's lead schema. The answer's status is SUBMITTED (followed by insurance.lead.submitted) or UNKNOWN (the lead is not sent again). A provider refusal is 422 insurance.lead.rejected; a type or connection without leads is 412 insurance.type.not_available. The key is required: the same key with the same body returns the same lead, with another body 409 insurance.idempotency.conflict.

func (*InsuranceClient) CreateOrder added in v1.3.0

func (i *InsuranceClient) CreateOrder(ctx context.Context, request map[string]any, idempotencyKey string) (json.RawMessage, error)

CreateOrder turns a quote option into an order (HTTP 201) and records the buyer's consent: quoteId, optional merchantOrderId, consent {termsVersion, termsSha256, acceptedAt} — the option's terms back unchanged plus the moment the buyer accepted them (ConsentFromQuote builds it). No provider call and no money movement. The key is required: the same key with the same body returns the recorded order, with another body 409 insurance.idempotency.conflict.

func (*InsuranceClient) CreateQuote added in v1.3.0

func (i *InsuranceClient) CreateQuote(ctx context.Context, request map[string]any, idempotencyKey string) (json.RawMessage, error)

CreateQuote prices an insurance type (HTTP 201). The basket is either a payment's recorded basket (paymentIntentId) or the items you will send in the payment (context.items), not both; send neither for an insurance type sold without a basket item (the insured value is then in the type object). Every option of the answer has its own quoteId, terms and expiresAt; a company the request could not be priced with is in excludedOptions.

The Idempotency-Key is optional ("" sends none) and only correlates traces: every call is a new, time-limited price.

func (*InsuranceClient) ExportReconciliation added in v1.3.0

func (i *InsuranceClient) ExportReconciliation(ctx context.Context, filters map[string]any) (*InsuranceReconciliationExport, error)

ExportReconciliation downloads the reconciliation report for the GetReconciliationSummary filters (plus cursor).

func (*InsuranceClient) GetLead added in v1.3.0

func (i *InsuranceClient) GetLead(ctx context.Context, leadID string) (json.RawMessage, error)

GetLead reads one lead; 404 insurance.lead.not_found for an unknown or another merchant's lead.

func (*InsuranceClient) GetOrder added in v1.3.0

func (i *InsuranceClient) GetOrder(ctx context.Context, orderID string) (json.RawMessage, error)

GetOrder reads one order; 404 insurance.order.not_found for an unknown or another merchant's order.

func (*InsuranceClient) GetPolicyCertificate added in v1.3.0

func (i *InsuranceClient) GetPolicyCertificate(ctx context.Context, policyID string) (*Response, error)

GetPolicyCertificate returns the provider's certificate of the policy (for example the Green Card of a motor policy; a PDF in Response.Bytes). Only for products that issue one; otherwise 412 insurance.document.not_supported. Same availability as GetPolicyDocument.

func (*InsuranceClient) GetPolicyDocument added in v1.3.0

func (i *InsuranceClient) GetPolicyDocument(ctx context.Context, policyID string) (*Response, error)

GetPolicyDocument returns the policy PDF in Response.Bytes. It is read from the provider on every call and is available while the policy is in force (ISSUED, CANCEL_PENDING); 503 insurance.document.unavailable is temporary — retry later. Error answers are read as the JSON envelope.

func (*InsuranceClient) GetPolicyReceipt added in v1.3.0

func (i *InsuranceClient) GetPolicyReceipt(ctx context.Context, policyID string) (*Response, error)

GetPolicyReceipt returns the provider's receipt for the policy premium (a PDF in Response.Bytes). Only for products that issue one; otherwise 412 insurance.document.not_supported. Same availability as GetPolicyDocument.

func (*InsuranceClient) GetQuote added in v1.3.0

func (i *InsuranceClient) GetQuote(ctx context.Context, quoteID string) (json.RawMessage, error)

GetQuote reads one quote option; 404 insurance.quote.not_found for an unknown or another merchant's quote.

func (*InsuranceClient) GetReconciliationSummary added in v1.3.0

func (i *InsuranceClient) GetReconciliationSummary(ctx context.Context, filters map[string]any) (json.RawMessage, error)

GetReconciliationSummary returns reconciliation totals grouped by provider connection, currency and premiumCollectedBy. Filters: from (inclusive) and to (exclusive), required, on the order creation time — a time.Time or ISO-8601 text with a time zone, at most 366 days apart; also connectionId, insuranceType, currency.

func (*InsuranceClient) IssuePolicy added in v1.3.0

func (i *InsuranceClient) IssuePolicy(ctx context.Context, orderID, idempotencyKey string) (json.RawMessage, error)

IssuePolicy requests the policy of an order whose premium you collected outside Lunixi (policyStatus PENDING; the result arrives by webhook). With a Lunixi payment the policy is requested on its own once the premium is collected. 412 insurance.premium.not_captured before the premium is collected. The key is required.

func (*InsuranceClient) IterateLeads added in v1.3.0

func (i *InsuranceClient) IterateLeads(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateLeads yields every lead matching the filters, page by page.

func (*InsuranceClient) IterateOrders added in v1.3.0

func (i *InsuranceClient) IterateOrders(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateOrders yields every order matching the filters, page by page.

func (*InsuranceClient) IterateReconciliationOrders added in v1.3.0

func (i *InsuranceClient) IterateReconciliationOrders(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateReconciliationOrders yields every reconciliation order, page by page.

func (*InsuranceClient) IterateReferenceValues added in v1.3.0

func (i *InsuranceClient) IterateReferenceValues(ctx context.Context, kind string, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateReferenceValues yields every reference code of one kind.

func (*InsuranceClient) ListLeads added in v1.3.0

func (i *InsuranceClient) ListLeads(ctx context.Context, filters map[string]any) (*CursorPage, error)

ListLeads lists your leads, newest first; personal data is masked in requestMasked. Filters: limit, cursor, insuranceType, status (InsuranceLeadStatus*).

func (*InsuranceClient) ListOrders added in v1.3.0

func (i *InsuranceClient) ListOrders(ctx context.Context, filters map[string]any) (*CursorPage, error)

ListOrders lists your insurance orders, newest first. Filters: limit, cursor, paymentIntentId, merchantOrderId.

func (*InsuranceClient) ListProducts added in v1.3.0

func (i *InsuranceClient) ListProducts(ctx context.Context, filters map[string]any) (json.RawMessage, error)

ListProducts lists the insurance types offered for a payment's basket, read from the items sent when the payment was created (GET /products). Filters: currency (required), paymentIntentId, insuranceType. Without paymentIntentId it lists the insurance types sold without a basket item. An empty list means insurance is not offered; it is not an error.

func (*InsuranceClient) ListReconciliationOrders added in v1.3.0

func (i *InsuranceClient) ListReconciliationOrders(ctx context.Context, filters map[string]any) (*CursorPage, error)

ListReconciliationOrders lists the orders and policies behind the summary for the same filters, newest first (plus limit, cursor).

func (*InsuranceClient) ListReferenceValues added in v1.3.0

func (i *InsuranceClient) ListReferenceValues(ctx context.Context, kind string, filters map[string]any) (*CursorPage, error)

ListReferenceValues lists the Lunixi reference codes of one kind (InsuranceReferenceKind*), for the type fields that take a code. Filters: parentCode, limit, cursor.

func (*InsuranceClient) PremiumBasketItem added in v1.3.0

func (i *InsuranceClient) PremiumBasketItem(order any, name, category1, category2 string) (BasketItem, error)

PremiumBasketItem is the premium basket item for a payment that collects the premium of an order (premiumCollectedBy MERCHANT; the data of GetOrder or CreateOrder): ID = orderId, ItemType VIRTUAL, Price = premiumAmount. Add it to the payment's basket next to the insured items and add the premium to the payment amount; for insurance sold without a basket item it can be the only item. It carries no insurance field. A PROVIDER order must not have one. category2 "" leaves it out.

func (*InsuranceClient) RefundPremium added in v1.3.0

func (i *InsuranceClient) RefundPremium(ctx context.Context, orderID string, externalRefund map[string]any, idempotencyKey string) (json.RawMessage, error)

RefundPremium refunds the premium. With a Lunixi payment pass nil: the premium is refunded from that payment (refundStatus PENDING, then insurance.refund.completed). For a premium collected outside Lunixi pass the refund you made: {externalRefundId, refundedAt}. An in-force policy must be cancelled first (409, policy_active). The key is required.

func (*InsuranceClient) SearchProducts added in v1.3.0

func (i *InsuranceClient) SearchProducts(ctx context.Context, request map[string]any) (json.RawMessage, error)

SearchProducts lists the insurance types offered for basket items before the payment exists (POST /products, read-only): {currency, insuranceType?, context: {items}} with the items you will send in the payment.

type InsuranceLeadWebhookData added in v1.3.0

type InsuranceLeadWebhookData struct {
	// EventID is the same as the envelope's id; dedupe on it.
	EventID    string               `json:"eventId"`
	EventType  string               `json:"eventType"`
	MerchantID string               `json:"merchantId"`
	Lead       InsuranceWebhookLead `json:"lead"`
	CreatedAt  string               `json:"createdAt"`
}

InsuranceLeadWebhookData is the data of an insurance.lead.* webhook (all InsuranceLeadEventTypes). No other key is delivered.

func ParseInsuranceLeadWebhook added in v1.3.0

func ParseInsuranceLeadWebhook(event *WebhookEvent) (*InsuranceLeadWebhookData, error)

ParseInsuranceLeadWebhook reads a verified insurance.lead.* event.

type InsuranceProvider added in v1.3.0

type InsuranceProvider struct {
	Code         string  `json:"code"`
	Name         string  `json:"name"`
	LogoURL      *string `json:"logoUrl"`
	ConnectionID string  `json:"connectionId"`
}

InsuranceProvider is the provider behind an insurance quote or order (for information; Code is the Lunixi catalogue code).

type InsuranceReconciliationExport added in v1.3.0

type InsuranceReconciliationExport struct {
	ContentType string
	Bytes       []byte
	Truncated   bool
	NextCursor  string
	Aborted     bool
	RequestID   string
}

InsuranceReconciliationExport is the reconciliation report: CSV (UTF-8 with BOM, one line per policy, amounts in minor units). A file holds at most InsuranceExportOrderCap orders; when it was cut, Truncated is true and NextCursor continues it (pass it as the cursor filter). Aborted is true when the file ends with the gateway's abort line: it is incomplete, request it again.

type InsuranceWebhookData added in v1.3.0

type InsuranceWebhookData struct {
	// EventID is the same as the envelope's id; dedupe on it.
	EventID            string            `json:"eventId"`
	EventType          string            `json:"eventType"`
	MerchantID         string            `json:"merchantId"`
	InsuranceOrderID   string            `json:"insuranceOrderId"`
	PaymentIntentID    *string           `json:"paymentIntentId"`
	MerchantOrderID    *string           `json:"merchantOrderId"`
	InsuranceType      string            `json:"insuranceType"`
	PremiumCollectedBy string            `json:"premiumCollectedBy"`
	Provider           InsuranceProvider `json:"provider"`
	Status             string            `json:"status"`
	CollectionStatus   string            `json:"collectionStatus"`
	PolicyStatus       string            `json:"policyStatus"`
	RefundStatus       string            `json:"refundStatus"`
	DocumentStatus     string            `json:"documentStatus"`
	// PremiumAmount is minor-unit text.
	PremiumAmount string                   `json:"premiumAmount"`
	Currency      string                   `json:"currency"`
	Policies      []InsuranceWebhookPolicy `json:"policies"`
	// ErrorCode is set only on insurance.policy.failed and
	// insurance.refund.required.
	ErrorCode *string `json:"errorCode"`
	CreatedAt string  `json:"createdAt"`
}

InsuranceWebhookData is the data of every order insurance.* webhook (all InsuranceOrderEventTypes). No other key is delivered; no personal data.

func ParseInsuranceWebhook added in v1.3.0

func ParseInsuranceWebhook(event *WebhookEvent) (*InsuranceWebhookData, error)

ParseInsuranceWebhook reads a verified order insurance.* event (every InsuranceOrderEventTypes type). A lead event is read with ParseInsuranceLeadWebhook.

type InsuranceWebhookLead added in v1.3.0

type InsuranceWebhookLead struct {
	LeadID        string  `json:"leadId"`
	InsuranceType string  `json:"insuranceType"`
	SchemaVersion int     `json:"schemaVersion"`
	Status        string  `json:"status"`
	SubmittedAt   *string `json:"submittedAt"`
	CreatedAt     string  `json:"createdAt"`
}

InsuranceWebhookLead is the lead in an insurance.lead.* webhook. No personal data, no note, no provider reference.

type InsuranceWebhookPolicy added in v1.3.0

type InsuranceWebhookPolicy struct {
	PolicyID       string  `json:"policyId"`
	BasketItemID   string  `json:"basketItemId"`
	PolicyNumber   *string `json:"policyNumber"`
	PolicyStatus   string  `json:"policyStatus"`
	DocumentStatus string  `json:"documentStatus"`
	// DocumentURL is the GetPolicyDocument address while the policy is in
	// force, otherwise "". Downloading it is a signed API call.
	DocumentURL string `json:"documentUrl"`
}

InsuranceWebhookPolicy is a policy in an insurance webhook's data.

type IntentRequest

type IntentRequest struct {
	Amount          string         `json:"amount"`
	Currency        string         `json:"currency"`
	OrderID         string         `json:"orderId"`
	CallbackURL     string         `json:"callbackUrl"`
	Buyer           *Buyer         `json:"buyer,omitempty"`
	BillingAddress  *Address       `json:"billingAddress,omitempty"`
	ShippingAddress *Address       `json:"shippingAddress,omitempty"`
	BasketItems     []BasketItem   `json:"basketItems,omitempty"`
	Metadata        map[string]any `json:"metadata,omitempty"`
	Preauth         bool           `json:"preauth,omitempty"`
	Locale          string         `json:"locale,omitempty"`
	Description     string         `json:"description,omitempty"`
	CustomerID      string         `json:"customerId,omitempty"`
	CardUserKey     string         `json:"cardUserKey,omitempty"`
	PaymentMethod   string         `json:"paymentMethod,omitempty"`
	WalletProvider  string         `json:"walletProvider,omitempty"`
	PaymentChannel  string         `json:"paymentChannel,omitempty"`
	PaymentGroup    string         `json:"paymentGroup,omitempty"`
	Force3D         *bool          `json:"force3D,omitempty"`
	Settings        map[string]any `json:"settings,omitempty"`
	// EnabledInstallments lists the installment counts the hosted form may
	// offer for this payment, e.g. []int{1, 2, 3}; []int{1} allows a single
	// payment only. The form shows only the counts also allowed by the panel
	// settings, the card and the platform maximum. Nil means no restriction.
	// Integers 1–36, no duplicates, 1 included; sent in ascending order.
	EnabledInstallments []int `json:"enabledInstallments,omitempty"`
}

IntentRequest creates a checkout form token. Amount is the basket total before a provider-calculated installment fee. The buyer selects the installment in the shared form; EnabledInstallments can only narrow the counts the form offers.

type KycClient added in v1.3.0

type KycClient struct {
	// contains filtered or unexported fields
}

KycClient — KYC, KYB and evidence sessions (/api/v1/kyc/*), reached as Client.Kyc.

The calls carry the access token, without the per-request signature. Your server creates the session (externalCustomerId = your own user id, echoed on every webhook); the browser SDK then runs the capture with the publishable key. The kyc.* webhook is the authority for the result.

Requests and filters are maps checked against KycRoutes before anything is sent; the error names the field, never its value (document images included). Session calls return the envelope's data ({session, capturePolicy, …}: no personal data comes back, only status, decision, risk and the achieved assurance). Lists return CursorPage.

func (*KycClient) CreateSession added in v1.3.0

func (k *KycClient) CreateSession(ctx context.Context, request map[string]any, idempotencyKey string) (json.RawMessage, error)

CreateSession creates a session: subjectId, sessionType (KycSessionType*, case-insensitive), optional externalCustomerId, customerMode, person | company | customer, jurisdiction, requiredDocumentTypes, primaryDocumentType, evidencePurpose, ttlMinutes (1–KycSessionTTLMaxMinutes), metadata. person and company are sent as customer with customerType PERSON or COMPANY; metadata is sent as evidenceContextJson. An Idempotency-Key (the argument or the request's idempotencyKey) goes in the header and the body; "" sends none.

func (*KycClient) ErasureRequests added in v1.3.0

func (k *KycClient) ErasureRequests(ctx context.Context, filters map[string]any) (*CursorPage, error)

ErasureRequests lists the data erasure requests. Filters: limit, status.

func (*KycClient) EvidenceRequest added in v1.3.0

func (k *KycClient) EvidenceRequest(ctx context.Context, request map[string]any, idempotencyKey string) (json.RawMessage, error)

EvidenceRequest creates an EVIDENCE session (proof-of-X), optionally linked to a payment or order; the same body and key rule as CreateSession.

func (*KycClient) GetSession added in v1.3.0

func (k *KycClient) GetSession(ctx context.Context, sessionID string) (json.RawMessage, error)

GetSession reads one session.

func (*KycClient) IterateSessions added in v1.3.0

func (k *KycClient) IterateSessions(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateSessions yields every session, page by page.

func (*KycClient) ListSessions added in v1.3.0

func (k *KycClient) ListSessions(ctx context.Context, filters map[string]any) (*CursorPage, error)

ListSessions lists sessions. Filters: limit, cursor (pageSize and pageToken are read as the same). Anything else is refused: the merchant list has no status or customer filter, and dropping one would return every session.

func (*KycClient) ManualReview added in v1.3.0

func (k *KycClient) ManualReview(ctx context.Context, sessionID, reasonCode, reasonDetail string) (json.RawMessage, error)

ManualReview sends a session to manual review; reasonCode and reasonDetail "" are left out (no body when both are).

func (*KycClient) MerchantPolicy added in v1.3.0

func (k *KycClient) MerchantPolicy(ctx context.Context) (json.RawMessage, error)

MerchantPolicy reads your KYC policy (required assurance, providers …).

func (*KycClient) RetryWebhookEvent added in v1.3.0

func (k *KycClient) RetryWebhookEvent(ctx context.Context, eventID string) (json.RawMessage, error)

RetryWebhookEvent retries one KYC webhook delivery.

func (*KycClient) RotateWebhookSecret added in v1.3.0

func (k *KycClient) RotateWebhookSecret(ctx context.Context) (json.RawMessage, error)

RotateWebhookSecret rotates the KYC webhook signing secret.

func (*KycClient) SetJurisdiction added in v1.3.0

func (k *KycClient) SetJurisdiction(ctx context.Context, sessionID, jurisdiction string) (json.RawMessage, error)

SetJurisdiction sets the applicant jurisdiction (ISO country) on a server-created session.

func (*KycClient) SetPrimaryDocument added in v1.3.0

func (k *KycClient) SetPrimaryDocument(ctx context.Context, sessionID, documentType string) (json.RawMessage, error)

SetPrimaryDocument sets the primary document type: PASSPORT, NATIONAL_ID, DRIVERS_LICENSE or RESIDENCE_PERMIT.

func (*KycClient) Submit added in v1.3.0

func (k *KycClient) Submit(ctx context.Context, sessionID string) (json.RawMessage, error)

Submit submits a session for processing.

func (*KycClient) Timeline added in v1.3.0

func (k *KycClient) Timeline(ctx context.Context, sessionID string) (json.RawMessage, error)

Timeline reads the event timeline of a session (audit).

func (*KycClient) UpdateMerchantPolicy added in v1.3.0

func (k *KycClient) UpdateMerchantPolicy(ctx context.Context, policy map[string]any) (json.RawMessage, error)

UpdateMerchantPolicy writes your KYC policy.

func (*KycClient) UploadDocument added in v1.3.0

func (k *KycClient) UploadDocument(ctx context.Context, sessionID string, document map[string]any) (json.RawMessage, error)

UploadDocument uploads a document from your server (most flows use the browser SDK): documentType, fileBase64, mimeType, optional side, jurisdiction, metadataJson, idempotencyKey. The image never appears in an error message.

func (*KycClient) WebhookOutbox added in v1.3.0

func (k *KycClient) WebhookOutbox(ctx context.Context, filters map[string]any) (*CursorPage, error)

WebhookOutbox lists the KYC webhook deliveries. Filters: limit, status.

type MarketplaceClient added in v1.3.0

type MarketplaceClient struct {
	// contains filtered or unexported fields
}

MarketplaceClient — split charges across sub-dealers, the sub-dealer lifecycle, commissions, payouts and the audit log, reached as Client.Marketplace.

Split charges (/api/v1/payments/marketplace/*) are signed per request and take an optional Idempotency-Key (16–128 printable ASCII characters, as every payment write). A split is aggregate per seller: group the basket by vendor and pass one leg per sub-dealer (MarketplaceSeller); the legs must add up to amount. Dealer, commission, payout and audit routes (/api/v1/marketplace/*) are bearer-only and take no key.

Card data (card number, expiry, security code) is sent as given and never logged or put in an error message; a direct card charge is PCI DSS SAQ-D scope, so most marketplaces use CreateCheckoutIntent (hosted form).

Amounts are canonical minor-unit strings. Entity calls return the envelope's data; the charges return the whole Response; lists return CursorPage.

func (*MarketplaceClient) ActivateDealer added in v1.3.0

func (m *MarketplaceClient) ActivateDealer(ctx context.Context, dealerID string) (json.RawMessage, error)

ActivateDealer activates a sub-dealer.

func (*MarketplaceClient) AuditLog added in v1.3.0

func (m *MarketplaceClient) AuditLog(ctx context.Context, filters map[string]any) (*CursorPage, error)

AuditLog lists the audit log. Filters: limit, type.

func (*MarketplaceClient) BulkCreateDealers added in v1.3.0

func (m *MarketplaceClient) BulkCreateDealers(ctx context.Context, dealers []map[string]any) (json.RawMessage, error)

BulkCreateDealers creates several dealers at once (an import); each row as in CreateDealer.

func (*MarketplaceClient) BulkMarkPayoutsPaid added in v1.3.0

func (m *MarketplaceClient) BulkMarkPayoutsPaid(ctx context.Context, payoutIDs []string, extra map[string]any) (json.RawMessage, error)

BulkMarkPayoutsPaid marks several payouts paid; extra (paidAt, reference …) goes into the same body, nil for none.

func (*MarketplaceClient) ChargeMarketplaceCard added in v1.3.0

func (m *MarketplaceClient) ChargeMarketplaceCard(ctx context.Context, payload map[string]any, threeDS bool, idempotencyKey string) (*Response, error)

ChargeMarketplaceCard sends a direct split card charge from a raw body (amount, currency, orderId, card, buyer, billingAddress, basketItems, sellers, multiSellerPolicy, preauth? …): POST /payments/marketplace/3d when threeDS is true, /2d otherwise. amount is positive minor-unit text, price and paidPrice are refused, preauth is a boolean. Prefer ChargeMarketplaceCard2d / ChargeMarketplaceCard3d, which also check the commercial context and the legs.

func (*MarketplaceClient) ChargeMarketplaceCard2d added in v1.3.0

func (m *MarketplaceClient) ChargeMarketplaceCard2d(ctx context.Context, request map[string]any, sellers []MarketplaceSeller, multiSellerPolicy, idempotencyKey string) (*Response, error)

ChargeMarketplaceCard2d charges a card without 3-D Secure: the card payment body (MarketplaceChargeRequiredFields at least: amount, currency, orderId, card, buyer, billingAddress and a non-empty basketItems) plus the seller legs. multiSellerPolicy "" is ALL_OR_NOTHING.

func (*MarketplaceClient) ChargeMarketplaceCard3d added in v1.3.0

func (m *MarketplaceClient) ChargeMarketplaceCard3d(ctx context.Context, request map[string]any, sellers []MarketplaceSeller, multiSellerPolicy, idempotencyKey string) (*Response, error)

ChargeMarketplaceCard3d charges a card with 3-D Secure; the same body as ChargeMarketplaceCard2d (with your callbackUrl).

func (*MarketplaceClient) CommissionRules added in v1.3.0

func (m *MarketplaceClient) CommissionRules(ctx context.Context, filters map[string]any) (*CursorPage, error)

CommissionRules lists the commission rules. Filter: limit.

func (*MarketplaceClient) CreateCheckoutIntent added in v1.3.0

func (m *MarketplaceClient) CreateCheckoutIntent(ctx context.Context, request IntentRequest, sellers []MarketplaceSeller, multiSellerPolicy, idempotencyKey string) (*Response, error)

CreateCheckoutIntent creates a hosted-form split checkout (POST /payments/marketplace/intents, the route of Payments.CreateMarketplaceIntent): the intent plus the seller legs. multiSellerPolicy "" is MarketplaceMultiSellerPolicyAllOrNothing; idempotencyKey "" sends none. An answer without a token or form (a seller not eligible under ALL_OR_NOTHING) is an *APIError instead of leaving the buyer on an empty page.

func (*MarketplaceClient) CreateDealer added in v1.3.0

func (m *MarketplaceClient) CreateDealer(ctx context.Context, request map[string]any) (json.RawMessage, error)

CreateDealer creates a sub-dealer: legalName, optional taxId, dealerType (MarketplaceDealerType*), categoryCode, email, externalRef. The dealer then onboards itself (KYC, IBAN, contract) before it is ACTIVE.

func (*MarketplaceClient) CreatePayout added in v1.3.0

func (m *MarketplaceClient) CreatePayout(ctx context.Context, payload map[string]any) (json.RawMessage, error)

CreatePayout creates a manual payout: subDealerId, amountMinor (positive minor-unit string), currency, reference? …

func (*MarketplaceClient) DealerApplication added in v1.3.0

func (m *MarketplaceClient) DealerApplication(ctx context.Context, dealerID string) (json.RawMessage, error)

DealerApplication reads the onboarding / application status.

func (*MarketplaceClient) GetDealer added in v1.3.0

func (m *MarketplaceClient) GetDealer(ctx context.Context, dealerID string) (json.RawMessage, error)

GetDealer reads one sub-dealer.

func (*MarketplaceClient) ListDealers added in v1.3.0

func (m *MarketplaceClient) ListDealers(ctx context.Context, filters map[string]any) (*CursorPage, error)

ListDealers lists sub-dealers. Filters: status, search, limit, offset.

func (*MarketplaceClient) MarkPayoutPaid added in v1.3.0

func (m *MarketplaceClient) MarkPayoutPaid(ctx context.Context, payoutID string, payload map[string]any) (json.RawMessage, error)

MarkPayoutPaid marks a payout paid: paidAt?, reference? …; payload nil sends {}.

func (*MarketplaceClient) OnboardingToken added in v1.3.0

func (m *MarketplaceClient) OnboardingToken(ctx context.Context, dealerID string) (json.RawMessage, error)

OnboardingToken creates a self-onboarding link: {token, url, …} (token also starts the embedded onboarding SDK), the envelope root and data merged. MarketplaceOnboardingURL gives the URL.

func (*MarketplaceClient) PayoutLedger added in v1.3.0

func (m *MarketplaceClient) PayoutLedger(ctx context.Context, filters map[string]any) (*CursorPage, error)

PayoutLedger lists the payout ledger. Filters: status, subDealerId, days, limit.

func (*MarketplaceClient) PreviewCommissionRule added in v1.3.0

func (m *MarketplaceClient) PreviewCommissionRule(ctx context.Context, rule map[string]any) (json.RawMessage, error)

PreviewCommissionRule dry-runs a rule's effect.

func (*MarketplaceClient) RecordDealerKycResult added in v1.3.0

func (m *MarketplaceClient) RecordDealerKycResult(ctx context.Context, dealerID string, payload map[string]any) (json.RawMessage, error)

RecordDealerKycResult records a KYC outcome, when you run the dealer's KYC yourself.

func (*MarketplaceClient) ResolveCommission added in v1.3.0

func (m *MarketplaceClient) ResolveCommission(ctx context.Context, subDealerID, categoryCode, mtdVolumeMinor string) (json.RawMessage, error)

ResolveCommission reads the effective commission of a dealer (and category, "" for none) at a month-to-date volume (mtdVolumeMinor, a minor-unit string, "" for none).

func (*MarketplaceClient) SetDealerTerms added in v1.3.0

func (m *MarketplaceClient) SetDealerTerms(ctx context.Context, dealerID string, payload map[string]any) (json.RawMessage, error)

SetDealerTerms sets the commission / terms definition of a dealer.

func (*MarketplaceClient) SignDealerContract added in v1.3.0

func (m *MarketplaceClient) SignDealerContract(ctx context.Context, dealerID string, payload map[string]any) (json.RawMessage, error)

SignDealerContract records the signature / contract acceptance; payload nil sends {}.

func (*MarketplaceClient) SubmitDealerApplication added in v1.3.0

func (m *MarketplaceClient) SubmitDealerApplication(ctx context.Context, dealerID string, payload map[string]any) (json.RawMessage, error)

SubmitDealerApplication submits the dealer's application; payload nil sends {}.

func (*MarketplaceClient) Transactions added in v1.3.0

func (m *MarketplaceClient) Transactions(ctx context.Context, filters map[string]any) (*CursorPage, error)

Transactions lists split transactions. Filters: status, subDealerId, limit.

func (*MarketplaceClient) UpdateDealerStatus added in v1.3.0

func (m *MarketplaceClient) UpdateDealerStatus(ctx context.Context, dealerID, status string) (json.RawMessage, error)

UpdateDealerStatus moves a sub-dealer to a MarketplaceDealerStatus*.

func (*MarketplaceClient) UpsertCommissionRule added in v1.3.0

func (m *MarketplaceClient) UpsertCommissionRule(ctx context.Context, rule map[string]any) (json.RawMessage, error)

UpsertCommissionRule creates or updates a commission rule.

func (*MarketplaceClient) VerifyAuditLog added in v1.3.0

func (m *MarketplaceClient) VerifyAuditLog(ctx context.Context) (json.RawMessage, error)

VerifyAuditLog verifies the integrity of the hash chain.

type MarketplaceIntentRequest added in v1.3.0

type MarketplaceIntentRequest struct {
	IntentRequest
	Sellers           []MarketplaceSeller `json:"sellers"`
	MultiSellerPolicy string              `json:"multiSellerPolicy,omitempty"`
}

MarketplaceIntentRequest is the body of CreateMarketplaceIntent (POST /payments/marketplace/intents): the checkout intent fields plus the sellers and their shares.

type MarketplaceSeller added in v1.3.0

type MarketplaceSeller struct {
	SubDealerID string         `json:"subDealerId"`
	AmountMinor string         `json:"amountMinor"`
	Scenario    map[string]any `json:"scenario,omitempty"`
}

MarketplaceSeller is one seller leg of a marketplace split: the aggregate amount of one sub-dealer (group the basket by vendor and add up). AmountMinor is positive minor-unit text; the legs add up to the payment amount. Scenario is an optional per-request commission scenario override (for example {"type": "DYNAMIC_RATE", "ratePercent": "5"}).

type NestedFields added in v1.3.0

type NestedFields struct {
	Required []string
	Optional []string
}

NestedFields are the fields of the rows of a list field (wallet rows and payout items, sanction identifiers, parties and accounts).

type PaymentActionBankTransfer added in v1.3.0

type PaymentActionBankTransfer struct {
	// BankCode is the 4-digit bank code of the merchant's bank.
	BankCode string `json:"bankCode"`
	BankName string `json:"bankName"`
	// HolderName is the account holder; the buyer enters it as the recipient.
	HolderName string `json:"holderName"`
	// IBAN without spaces.
	IBAN string `json:"iban"`
	// AmountMinor is the amount to send, in minor units.
	AmountMinor string `json:"amountMinor"`
	Currency    string `json:"currency"`
	// PaymentCode is written by the buyer in the transfer description; it
	// matches the transfer to the payment.
	PaymentCode string `json:"paymentCode"`
	ExpiresAt   string `json:"expiresAt"`
	// OtherBank is true when the buyer chose other banks
	// (BankTransferOtherBanksCode); the instruction is for EFT/FAST.
	OtherBank bool `json:"otherBank"`
}

PaymentActionBankTransfer is the transfer instruction of a BANK_TRANSFER payment's DISPLAY action: the merchant's own bank account the buyer sends the money to.

type PaymentActionConfirmRequest added in v1.3.0

type PaymentActionConfirmRequest struct {
	OTP             string         `json:"otp,omitempty"`
	ConsentAccepted *bool          `json:"consentAccepted,omitempty"`
	Fields          map[string]any `json:"fields,omitempty"`
}

PaymentActionConfirmRequest is the body of ConfirmPaymentAction: the buyer's one-time code (digits), the agreement consent when action.consent.required is true, or the values an INPUT action asks for. At least one is required. Checkout token fields are never sent.

type PaymentClient

type PaymentClient struct {
	// contains filtered or unexported fields
}

PaymentClient implements checkout forms, payment lifecycle and split payment merchant endpoints. It never determines an order's paid state.

func (*PaymentClient) AcceptBankTransferException added in v1.3.0

func (p *PaymentClient) AcceptBankTransferException(ctx context.Context, exceptionID string) (*Response, error)

AcceptBankTransferException accepts an exception (POST /payments/bank-transfer/exceptions/{id}/accept, no body; the key needs payment:refund). LATE opens a new captured payment for the same order (acceptedPaymentId); UNDERPAID captures the payment with the amount received. OVERPAID cannot be accepted (409 payment.bank_transfer.decision_not_supported). Data is the exception or null.

func (*PaymentClient) BinInfo added in v1.3.0

func (p *PaymentClient) BinInfo(ctx context.Context, binOrPan string) (*Response, error)

BinInfo reads the card type, bank and installment eligibility of a 6 or 8 digit BIN or a card number prefix (POST /bin/info). Prefer sending the BIN only; a full card number is never logged or echoed by this SDK.

func (*PaymentClient) CancelPromissoryNotes added in v1.3.0

func (p *PaymentClient) CancelPromissoryNotes(ctx context.Context, paymentID string, serialNumbers []string, key string) (*Response, error)

CancelPromissoryNotes cancels notes (POST /payments/{paymentId}/promissory-notes/cancel). A nil serialNumbers cancels every open note and sends no body; otherwise 1–24 serial numbers from GetPromissoryNotes. The answer adds cancelResults[] per note (PromissoryNoteCancelResult*, errorCode PromissoryNoteCancelError*). The payment stays CAPTURED. key is optional; when given it makes retries safe.

func (*PaymentClient) Capture

func (p *PaymentClient) Capture(ctx context.Context, id string, amount *string, key string) (*Response, error)

Capture captures the full authorization when amount is nil, or a specified positive integer amount. It must reference the original payment account.

func (*PaymentClient) CardTaxonomy added in v1.3.0

func (p *PaymentClient) CardTaxonomy(ctx context.Context) (*Response, error)

CardTaxonomy lists the card brand, family and bank reference values (GET /bin/card-taxonomy).

func (*PaymentClient) ConfirmPaymentAction added in v1.3.0

func (p *PaymentClient) ConfirmPaymentAction(ctx context.Context, paymentID, actionID string, input PaymentActionConfirmRequest) (*Response, error)

ConfirmPaymentAction completes the open action of a payment (POST /payments/{paymentId}/actions/{actionId}/confirm). It does not start a new charge; repeating the same confirm returns the recorded result. A rejected code is a 422 with details.attemptsRemaining and the action stays open.

func (*PaymentClient) CreateIntent

func (p *PaymentClient) CreateIntent(ctx context.Context, r IntentRequest, key string) (*Response, error)

CreateIntent creates a hosted checkout session. Persist key per payment attempt before calling; reuse it after a timeout instead of charging again.

func (*PaymentClient) CreateMarketplaceIntent added in v1.3.0

func (p *PaymentClient) CreateMarketplaceIntent(ctx context.Context, r MarketplaceIntentRequest, key string) (*Response, error)

CreateMarketplaceIntent creates a hosted checkout session split between sellers. The sellers' AmountMinor values must add up to Amount; any other total is refused before sending (the gateway refuses it with 400 and charges nothing). key is optional: pass a stable key per payment attempt to make retries safe, or "" to send none.

func (*PaymentClient) DeactivateStoredCard added in v1.3.0

func (p *PaymentClient) DeactivateStoredCard(ctx context.Context, storedCardToken, key string) (*Response, error)

DeactivateStoredCard deactivates a stored card (DELETE /payments/cards/{token}). key is required.

func (*PaymentClient) DirectMethodPayment added in v1.3.0

func (p *PaymentClient) DirectMethodPayment(ctx context.Context, request *DirectMethodPaymentRequest, key string) (*Response, error)

DirectMethodPayment starts a payment with any method from the merchant server (POST /payments/direct/payment). key is required: persist it per payment attempt and reuse it when retrying the same payment. This is also the only server-side card charge (WithCard, plus WithForce3D(true) for 3D Secure).

The gateway envelope comes back as it is: Data holds paymentId, orderId, status, paymentMethod, providerCode and, when the buyer must act, action (HTTP 202; see PaymentActionType*). A declined payment is an APIError. With providerSelectionMode PLATFORM and no providerCode the platform picks the provider; 422 payment.provider.none_eligible means nothing was charged.

func (*PaymentClient) DownloadPromissoryNoteDocument added in v1.3.0

func (p *PaymentClient) DownloadPromissoryNoteDocument(ctx context.Context, paymentID, locale string) (*Response, error)

DownloadPromissoryNoteDocument returns the printable notes as a PDF, one note per page (GET /payments/{paymentId}/promissory-notes/document). The PDF is in Response.Bytes with Response.ContentType; an error answer is read as the JSON envelope and returned as APIError (503 payment.promissory_note.document_unavailable: try again later). locale is "" (gateway default) or a PromissoryNoteDocumentLocale* value. The document is not stored; download it when you need it.

func (*PaymentClient) FailoverRecoveryAnalytics added in v1.3.0

func (p *PaymentClient) FailoverRecoveryAnalytics(ctx context.Context, filters url.Values) (*Response, error)

FailoverRecoveryAnalytics reports the volume and count of payments rescued by provider failover retries (GET /payments/analytics/failover-recovery). filters are the documented reporting filters (for example from, to, range); nil sends none.

func (*PaymentClient) Get

func (p *PaymentClient) Get(ctx context.Context, id string) (*Response, error)

Get reads the authoritative gateway payment state.

func (*PaymentClient) GetPromissoryNotes added in v1.3.0

func (p *PaymentClient) GetPromissoryNotes(ctx context.Context, paymentID string) (*Response, error)

GetPromissoryNotes reads the notes of a promissory-note payment (GET /payments/{paymentId}/promissory-notes): documentType, rowSerialNumber, totalAmount and per note serialNumber, sequence, amount (minor units), dueDate and status (PromissoryNoteStatus*). A payment without notes is a 404 payment.promissory_note.not_found.

func (*PaymentClient) GetSplit

func (p *PaymentClient) GetSplit(ctx context.Context, id string) (*Response, error)

GetSplit returns all legs and aggregate amounts; COMPLETED alone should not replace amount/currency/balancing/reconciliation checks in the order adapter.

func (*PaymentClient) GetStoredCard added in v1.3.0

func (p *PaymentClient) GetStoredCard(ctx context.Context, storedCardToken string) (*Response, error)

GetStoredCard reads one stored card by its token (GET /payments/cards/{token}).

func (*PaymentClient) InstallmentOptions added in v1.3.0

func (p *PaymentClient) InstallmentOptions(ctx context.Context, request InstallmentOptionsRequest) (*Response, error)

InstallmentOptions returns the installment table for an amount and card (POST /bin/installments). The provider's installment fee is quoted here; the merchant never adds it to amount.

func (*PaymentClient) List

func (p *PaymentClient) List(ctx context.Context, filters url.Values) (*Response, error)

List returns the original gateway envelope including pagination metadata.

func (*PaymentClient) ListBankTransferExceptions added in v1.3.0

func (p *PaymentClient) ListBankTransferExceptions(ctx context.Context, filters BankTransferExceptionFilters) (*Response, error)

ListBankTransferExceptions lists late (LATE), short (UNDERPAID) and excess (OVERPAID) transfers of BANK_TRANSFER payments (GET /payments/bank-transfer/exceptions). Data is { items: [{ id, paymentId, kind, status, environment, amountMinor, currency, expectedMinor, receivedMinor, counterpartyNameMasked, acceptedPaymentId, refundSource, decidedAt, refundedAt, createdAt }] }; the sender name is masked.

func (*PaymentClient) ListPaymentMethods added in v1.3.0

func (p *PaymentClient) ListPaymentMethods(ctx context.Context, paymentMethod string) (*Response, error)

ListPaymentMethods reads the payment methods open for the account (GET /payments/methods): per method its blockName, providerSelection, providerSelectionMode, preauth support, limits, split behaviour and the providers with the inputFields to send in the method block. paymentMethod "" lists every method; a code lists that method only ("QR" is sent as QR_CODE) and gives an empty list when it is not open for the account.

func (*PaymentClient) ListSplits added in v1.3.0

func (p *PaymentClient) ListSplits(ctx context.Context, filters SplitListFilters) (*Response, error)

ListSplits lists split payments, newest first (GET /payments/split), with a forward cursor in PageInfo.

func (*PaymentClient) ListStoredCards added in v1.3.0

func (p *PaymentClient) ListStoredCards(ctx context.Context, cardUserKey string) (*Response, error)

ListStoredCards lists the stored cards of a buyer (GET /payments/cards).

func (*PaymentClient) MarkBankTransferExceptionRefunded added in v1.3.0

func (p *PaymentClient) MarkBankTransferExceptionRefunded(ctx context.Context, exceptionID string) (*Response, error)

MarkBankTransferExceptionRefunded reports that you refunded the money of an exception to the sender from your own bank (POST /payments/bank-transfer/exceptions/{id}/refunded, no body; the key needs payment:refund). Lunixi does not send the refund. For UNDERPAID the waiting payment closes as failed. Data is the exception or null.

func (*PaymentClient) Methods

func (p *PaymentClient) Methods(ctx context.Context) (*Response, error)

Methods reads the merchant's enabled method/provider capabilities.

func (*PaymentClient) ProviderCredentialAnalytics added in v1.3.0

func (p *PaymentClient) ProviderCredentialAnalytics(ctx context.Context, credentialID string, filters url.Values) (*Response, error)

ProviderCredentialAnalytics reports the performance of one provider credential (GET /payments/analytics/provider-credentials/{credentialId}).

func (*PaymentClient) Refund

func (p *PaymentClient) Refund(ctx context.Context, id string, amount *string, reason, key string) (*Response, error)

Refund refunds the full refundable payment when amount is nil, or a partial amount. Unknown outcomes must be reconciled with the same key.

func (*PaymentClient) RefundSplit

func (p *PaymentClient) RefundSplit(ctx context.Context, id string, amount string, reason, key string) (*Response, error)

RefundSplit asks the gateway to distribute a refund across refundable legs. Partial or failed allocations return an APIError and require review.

func (*PaymentClient) ResendPaymentAction added in v1.3.0

func (p *PaymentClient) ResendPaymentAction(ctx context.Context, paymentID, actionID string) (*Response, error)

ResendPaymentAction sends a new one-time code (POST /payments/{paymentId}/actions/{actionId}/resend, no body). The previous action is closed; confirm with the new data.action.id.

func (*PaymentClient) Split

func (p *PaymentClient) Split(ctx context.Context, body map[string]any, key string) (*Response, error)

Split validates the documented split amount/leg contract and starts or continues it. Supply the same body and key for every continuation. Pending split states can be returned on HTTP 400 and remain explicitly unpaid.

A card leg (paymentMethod empty or CARD) carries no method block. A non-card leg is a mobileBilling, wallet or promissoryNote method (SplitLegBlockFields) with exactly its own block, including providerCode, and no card fields; MEAL_CARD, OPEN_BANKING, SHOPPING_LOAN and BANK_TRANSFER cannot be legs. A promissory-note leg gives noteCount, not a schedule.

func (*PaymentClient) StoreCard added in v1.3.0

func (p *PaymentClient) StoreCard(ctx context.Context, request StoreCardRequest, key string) (*Response, error)

StoreCard verifies and stores a card (POST /payments/cards). key is required; reuse it when retrying the same request.

func (*PaymentClient) Void

func (p *PaymentClient) Void(ctx context.Context, id, key string) (*Response, error)

Void releases an authorization; it does not refund a captured payment.

type PaymentLinkActionOptions added in v1.3.0

type PaymentLinkActionOptions struct {
	ExpectedRowVersion *int64 `json:"expectedRowVersion,omitempty"`
	Reason             string `json:"reason,omitempty"`
}

PaymentLinkActionOptions are the optional fields of Pause, Resume and Deactivate. ExpectedRowVersion nil skips the version check; a value fails with 409 payment_link.link.version_conflict if the link changed meanwhile.

type PaymentLinkAttemptFilters added in v1.3.0

type PaymentLinkAttemptFilters struct {
	PaymentLinkPage
	State []string
}

PaymentLinkAttemptFilters filters PaymentLinks.ListAttempts; State takes PaymentLinkAttemptState* values.

type PaymentLinkBuyerFields added in v1.3.0

type PaymentLinkBuyerFields struct {
	Name           string `json:"name,omitempty"`
	Email          string `json:"email,omitempty"`
	Phone          string `json:"phone,omitempty"`
	Address        string `json:"address,omitempty"`
	IdentityNumber string `json:"identityNumber,omitempty"`
}

PaymentLinkBuyerFields sets each buyer field to a BuyerFieldRequirement* value; empty leaves the gateway default.

type PaymentLinkCheckout added in v1.3.0

type PaymentLinkCheckout struct {
	RequireThreeDs      bool     `json:"requireThreeDs"`
	PaymentMethods      []string `json:"paymentMethods"`
	EnabledInstallments []int    `json:"enabledInstallments,omitempty"`
}

PaymentLinkCheckout narrows the checkout: RequireThreeDs can only tighten, PaymentMethods is a subset of your form settings (empty = your form settings) and EnabledInstallments follows IntentRequest.EnabledInstallments (nil or empty = no restriction).

type PaymentLinkClient added in v1.3.0

type PaymentLinkClient struct {
	// contains filtered or unexported fields
}

PaymentLinkClient manages payment links (/api/v1/payments/links). Every gateway call is signed with the client key, reads included; the merchant and the environment come from that key, so a TEST key sees and changes only TEST links. The key needs the matching scope (payment-link:create, :view, :manage, :send); a missing scope is 403 API_INSUFFICIENT_SCOPE.

The only request that is not sent through the signed transport is the image PUT of UploadImage: it goes to the storage host behind a presigned URL and carries only the upload headers, never the access token or signature.

func (*PaymentLinkClient) Action added in v1.3.0

func (l *PaymentLinkClient) Action(ctx context.Context, linkID, action string, options PaymentLinkActionOptions, key string) (*Response, error)

Action runs "pause", "resume" or "deactivate" on a link. key is optional.

func (*PaymentLinkClient) ConfirmImageUpload added in v1.3.0

func (l *PaymentLinkClient) ConfirmImageUpload(ctx context.Context, assetID string) (*PaymentLinkImage, error)

ConfirmImageUpload is step 3 of 3: it publishes an uploaded image (POST /payments/links/images/{assetId}/confirm). The gateway checks the stored bytes (declared type, at most 2 MiB and 4096×4096 px); a file that fails is deleted and must be uploaded again from CreateImageUpload. Confirming before the PUT has landed is 400 media.confirm.object_missing and can be retried.

func (*PaymentLinkClient) Create added in v1.3.0

func (l *PaymentLinkClient) Create(ctx context.Context, request PaymentLinkRequest, key string) (*Response, error)

Create creates a payment link. key is required: repeating the same key with the same body returns the stored link with replayed true (HTTP 200) instead of a second link; the same key with another body is 409 payment_link.idempotency.conflict.

func (*PaymentLinkClient) CreateImageUpload added in v1.3.0

func (l *PaymentLinkClient) CreateImageUpload(ctx context.Context, fileName, contentType string, sizeBytes int64) (*PaymentLinkImageUpload, error)

CreateImageUpload is step 1 of 3 of a link image: an upload target for a PNG, JPEG or WebP image (POST /payments/links/images). fileName (1–255 characters) is recorded only; a declared sizeBytes over the 2 MiB image limit is refused by the gateway before anything is uploaded. Step 2 is a PUT of the bytes to UploadURL with exactly UploadHeaders; step 3 is ConfirmImageUpload. UploadImage runs all three.

func (*PaymentLinkClient) Deactivate added in v1.3.0

func (l *PaymentLinkClient) Deactivate(ctx context.Context, linkID string, options PaymentLinkActionOptions, key string) (*Response, error)

Deactivate closes the link permanently; it cannot be reopened.

func (*PaymentLinkClient) Get added in v1.3.0

func (l *PaymentLinkClient) Get(ctx context.Context, linkID string) (*Response, error)

Get reads one link.

func (*PaymentLinkClient) List added in v1.3.0

List returns one page of links, newest first; Data.items holds the rows and PageInfo the paging.

func (*PaymentLinkClient) ListAttempts added in v1.3.0

func (l *PaymentLinkClient) ListAttempts(ctx context.Context, linkID string, filters PaymentLinkAttemptFilters) (*Response, error)

ListAttempts lists the payment attempts on a link, newest first.

func (*PaymentLinkClient) ListPayments added in v1.3.0

func (l *PaymentLinkClient) ListPayments(ctx context.Context, linkID string, page PaymentLinkPage) (*Response, error)

ListPayments lists the successful payments on a link, with refund totals.

func (*PaymentLinkClient) Pause added in v1.3.0

func (l *PaymentLinkClient) Pause(ctx context.Context, linkID string, options PaymentLinkActionOptions, key string) (*Response, error)

Pause stops accepting payments until Resume.

func (*PaymentLinkClient) QR added in v1.3.0

func (l *PaymentLinkClient) QR(ctx context.Context, linkID, format string, size int) (*Response, error)

QR returns the link's QR code image in Response.Bytes (Response.ContentType image/svg+xml or image/png). format is PaymentLinkQRFormatSVG (also for "") or PaymentLinkQRFormatPNG; size 0 uses the default (512), otherwise 128–2048 pixels.

func (*PaymentLinkClient) Resume added in v1.3.0

func (l *PaymentLinkClient) Resume(ctx context.Context, linkID string, options PaymentLinkActionOptions, key string) (*Response, error)

Resume accepts payments again after Pause.

func (*PaymentLinkClient) Send added in v1.3.0

func (l *PaymentLinkClient) Send(ctx context.Context, linkID string, request PaymentLinkSendRequest, key string) (*Response, error)

Send delivers the link by e-mail or SMS. key is required so a retried call cannot send twice. An accepted delivery can still fail: check data.delivery.state and data.delivery.failureReason (with a TEST key only your organisation's own verified addresses receive messages).

func (*PaymentLinkClient) Update added in v1.3.0

func (l *PaymentLinkClient) Update(ctx context.Context, linkID string, expectedRowVersion int64, changes map[string]any, key string) (*Response, error)

Update changes a link and creates a new version of it (PATCH). Only the keys in changes are updated (PaymentLinkSpecFields names); a nil value clears a field and a nested object is replaced as a whole. Usage, amountMode and currency cannot change. expectedRowVersion is the link's current rowVersion; a concurrent change answers 409 payment_link.link.version_conflict. Amount fields are locked (409 payment_link.link.amount_locked) while a payment is in progress or once the link has been paid. key is optional ("" sends none).

func (*PaymentLinkClient) UploadImage added in v1.3.0

func (l *PaymentLinkClient) UploadImage(ctx context.Context, fileName, contentType string, content []byte) (*PaymentLinkImage, error)

UploadImage uploads a link image in one call: CreateImageUpload, the PUT of content to the returned UploadURL, then ConfirmImageUpload. The PUT goes straight to the storage host with only the upload headers, through the configured HTTP client but not the signed transport, so the access token and the request signature are never sent there. A failed PUT is not retried: it returns an APIError with the storage host's HTTP status and error code (for example AccessDenied once the URL has expired); call UploadImage again for a new upload URL.

type PaymentLinkCustomField added in v1.3.0

type PaymentLinkCustomField struct {
	Key       string   `json:"key"`
	Label     string   `json:"label"`
	FieldType string   `json:"fieldType"`
	Required  bool     `json:"required,omitempty"`
	Options   []string `json:"options,omitempty"`
	MaxLength int      `json:"maxLength,omitempty"`
	HelpText  string   `json:"helpText,omitempty"`
}

PaymentLinkCustomField is a typed question the buyer answers on the payment page. Options are the choices of a SELECT field.

type PaymentLinkImage added in v1.3.0

type PaymentLinkImage struct {
	AssetID string `json:"assetId"`
	URL     string `json:"url"`
	State   string `json:"state"`
}

PaymentLinkImage is a published payment link image. Use AssetID as the ImageAssetID of a link or an item. URL is empty when the public image host is not configured.

type PaymentLinkImageUpload added in v1.3.0

type PaymentLinkImageUpload struct {
	AssetID       string            `json:"assetId"`
	UploadURL     string            `json:"uploadUrl"`
	UploadMethod  string            `json:"uploadMethod"`
	UploadHeaders map[string]string `json:"uploadHeaders"`
	ExpiresAt     string            `json:"expiresAt"`
}

PaymentLinkImageUpload is the upload target of CreateImageUpload: PUT the file's bytes to UploadURL with exactly UploadHeaders before ExpiresAt, then call ConfirmImageUpload(AssetID). UploadURL is the storage host, not the gateway: send it no access token and no signature.

type PaymentLinkItem added in v1.3.0

type PaymentLinkItem struct {
	Name           string `json:"name"`
	UnitPriceMinor string `json:"unitPriceMinor"`
	ItemKey        string `json:"itemKey,omitempty"`
	Description    string `json:"description,omitempty"`
	MinQuantity    *int   `json:"minQuantity,omitempty"`
	MaxQuantity    *int   `json:"maxQuantity,omitempty"`
	// Capacity is the units available for this line across all payments;
	// nil is unlimited.
	Capacity     *int   `json:"capacity,omitempty"`
	ImageAssetID string `json:"imageAssetId,omitempty"`
	// ProductCategory is a ProductCategory* code; not checked locally.
	ProductCategory string `json:"productCategory,omitempty"`
}

PaymentLinkItem is one line of an ITEMIZED link. ItemKey is the line's permanent identity (stock counters hang off it); empty lets the gateway assign one. A MinQuantity of 0 makes the line optional.

type PaymentLinkListFilters added in v1.3.0

type PaymentLinkListFilters struct {
	PaymentLinkPage
	State       []string
	Usage       []string
	AmountMode  []string
	Environment string
	Tag         string
	BranchCode  string
	CreatedByID string
	Query       string
	CreatedFrom string
	CreatedTo   string
}

PaymentLinkListFilters filters PaymentLinks.List. State, Usage and AmountMode accept several values (sent as a comma list). CreatedFrom and CreatedTo (RFC 3339) bound a half-open window [from, to). Query matches a short code exactly, or a title or reference prefix.

type PaymentLinkPage added in v1.3.0

type PaymentLinkPage struct {
	Limit        int
	Cursor       string
	IncludeTotal bool
}

PaymentLinkPage holds the paging filters of the list calls. Limit 0 and an empty Cursor are left out; pass the previous page's pageInfo.nextCursor as Cursor. IncludeTotal asks for pageInfo.totalCount.

type PaymentLinkPrefill added in v1.3.0

type PaymentLinkPrefill struct {
	Name           string `json:"name,omitempty"`
	Surname        string `json:"surname,omitempty"`
	Email          string `json:"email,omitempty"`
	Phone          string `json:"phone,omitempty"`
	IdentityNumber string `json:"identityNumber,omitempty"`
	Address        string `json:"address,omitempty"`
	City           string `json:"city,omitempty"`
	Country        string `json:"country,omitempty"`
	ZipCode        string `json:"zipCode,omitempty"`
}

PaymentLinkPrefill holds buyer details filled in on the server side (Country is ISO 3166-1 alpha-2).

type PaymentLinkRecipient added in v1.3.0

type PaymentLinkRecipient struct {
	Name  string `json:"name,omitempty"`
	Email string `json:"email,omitempty"`
	Phone string `json:"phone,omitempty"`
}

PaymentLinkRecipient is who the link is for (Phone in E.164).

type PaymentLinkReminders added in v1.3.0

type PaymentLinkReminders struct {
	Enabled       bool `json:"enabled"`
	IntervalHours int  `json:"intervalHours"`
	MaxCount      int  `json:"maxCount"`
}

PaymentLinkReminders sends reminder e-mails every 24–168 hours, at most 1–3 times.

type PaymentLinkRequest added in v1.3.0

type PaymentLinkRequest struct {
	// Environment is optional: the signing key decides it, and an explicit
	// value must match the key (403 payment_link.environment.mismatch).
	Environment string `json:"environment,omitempty"`
	// Usage is PaymentLinkUsageSingleUse or PaymentLinkUsageMultiUse.
	Usage string `json:"usage"`
	// AmountMode is PaymentLinkAmountModeFixed, Open or Itemized.
	AmountMode string `json:"amountMode"`
	Currency   string `json:"currency"`
	// AmountMinor is the amount of a FIXED link.
	AmountMinor string `json:"amountMinor,omitempty"`
	// MinAmountMinor (required) and MaxAmountMinor bound an OPEN link.
	MinAmountMinor string `json:"minAmountMinor,omitempty"`
	MaxAmountMinor string `json:"maxAmountMinor,omitempty"`
	// SuggestedAmountsMinor offers up to six ascending amounts on an OPEN link.
	SuggestedAmountsMinor []string `json:"suggestedAmountsMinor,omitempty"`
	// QuantityEnabled lets the buyer choose a quantity (FIXED + MULTI_USE
	// only) between MinQuantity and MaxQuantity (1–999).
	QuantityEnabled bool `json:"quantityEnabled,omitempty"`
	MinQuantity     *int `json:"minQuantity,omitempty"`
	MaxQuantity     *int `json:"maxQuantity,omitempty"`
	// Items are the lines of an ITEMIZED link (1–50).
	Items []PaymentLinkItem `json:"items,omitempty"`
	// Capacity is the total units the link can sell (MULTI_USE only); nil is
	// unlimited.
	Capacity *int   `json:"capacity,omitempty"`
	Title    string `json:"title"`
	// Description is plain text (no HTML or Markdown).
	Description string `json:"description,omitempty"`
	// ImageAssetID is a published image from UploadImage or ConfirmImageUpload.
	ImageAssetID   string `json:"imageAssetId,omitempty"`
	SuccessMessage string `json:"successMessage,omitempty"`
	// SuccessRedirectURL must use https://.
	SuccessRedirectURL string `json:"successRedirectUrl,omitempty"`
	TaxNote            string `json:"taxNote,omitempty"`
	// Locale is the payment page language, PaymentLinkLocaleTR or EN.
	Locale string `json:"locale,omitempty"`
	// StartsAt, ExpiresAt and EventAt are RFC 3339 times; EventAt is display
	// only (for example the date of an event ticket).
	StartsAt  string `json:"startsAt,omitempty"`
	ExpiresAt string `json:"expiresAt,omitempty"`
	EventAt   string `json:"eventAt,omitempty"`
	// ButtonLabelKey is a PaymentLinkButtonLabel* value; empty uses your
	// organisation's default.
	ButtonLabelKey         string                   `json:"buttonLabelKey,omitempty"`
	RequireTermsAcceptance bool                     `json:"requireTermsAcceptance,omitempty"`
	BuyerFields            *PaymentLinkBuyerFields  `json:"buyerFields,omitempty"`
	CustomFields           []PaymentLinkCustomField `json:"customFields,omitempty"`
	// Recipient is who the link is for; stored encrypted.
	Recipient *PaymentLinkRecipient `json:"recipient,omitempty"`
	// Prefill holds buyer details filled in on the server side; never sent to
	// the browser.
	Prefill *PaymentLinkPrefill `json:"prefill,omitempty"`
	// Verification asks the buyer to confirm a one-time code sent to the
	// recipient e-mail before paying.
	Verification *PaymentLinkVerification `json:"verification,omitempty"`
	// Reminders are reminder e-mails of a SINGLE_USE link with a recipient.
	Reminders *PaymentLinkReminders `json:"reminders,omitempty"`
	// Checkout narrows the checkout of the link.
	Checkout             *PaymentLinkCheckout `json:"checkout,omitempty"`
	Reference            string               `json:"reference,omitempty"`
	Tags                 []string             `json:"tags,omitempty"`
	BranchCode           string               `json:"branchCode,omitempty"`
	SalesChannel         string               `json:"salesChannel,omitempty"`
	Campaign             string               `json:"campaign,omitempty"`
	AgentCode            string               `json:"agentCode,omitempty"`
	MerchantNotifyEmails []string             `json:"merchantNotifyEmails,omitempty"`
	// Metadata is up to 20 string pairs returned to you in webhooks.
	Metadata map[string]string `json:"metadata,omitempty"`
}

PaymentLinkRequest is the body of PaymentLinks.Create (POST /payments/links). Fields follow the gateway's order; empty values are left out. Amounts are minor-unit text: "150000" is 1,500.00 TRY. Usage, AmountMode and Currency are fixed at creation. The SDK checks types and value sets; business rules (title length, amount ranges, which fields a mode allows) are enforced by the gateway, which answers 422 payment_link.validation.invalid with details.errors.

type PaymentLinkSendRequest added in v1.3.0

type PaymentLinkSendRequest struct {
	Channel        string `json:"channel"`
	RecipientEmail string `json:"recipientEmail,omitempty"`
	RecipientPhone string `json:"recipientPhone,omitempty"`
	Locale         string `json:"locale,omitempty"`
}

PaymentLinkSendRequest is the body of PaymentLinks.Send. Without RecipientEmail and RecipientPhone the link's recipient is used.

type PaymentLinkVerification added in v1.3.0

type PaymentLinkVerification struct {
	Required bool   `json:"required"`
	Channel  string `json:"channel"`
}

PaymentLinkVerification requires a one-time code before paying. Channel empty means PaymentLinkDeliveryChannelEmail, the only available channel.

type PhysicalPosCardDataRejectedError added in v1.3.0

type PhysicalPosCardDataRejectedError struct {
	Field          string
	StatusCode     int
	Code           string
	RequestID      string
	IdempotencyKey string
	// contains filtered or unexported fields
}

PhysicalPosCardDataRejectedError: a physical POS request carried card data. The card is read on the device; the API never takes a card number, expiry date, security code, track or PIN. Raised before anything is sent for a card-data field name in a body or filter set, or a card number in merchantReference, an item name or tax group code, or the merchantReference / q filters (StatusCode 0; errors.Is(err, ErrConfiguration) is true). The gateway's own refusal (physical_pos.payment.card_data_rejected) maps to the same type and unwraps to its *APIError. Field is the path of the offending field (items[1].cvv), never its value; empty when the gateway gave none.

func (*PhysicalPosCardDataRejectedError) Error added in v1.3.0

func (*PhysicalPosCardDataRejectedError) Unwrap added in v1.3.0

type PhysicalPosCashier added in v1.3.0

type PhysicalPosCashier struct {
	CashierID   string
	CashierCode string
}

PhysicalPosCashier is data.cashier of a payment event.

type PhysicalPosClient added in v1.3.0

type PhysicalPosClient struct {
	// contains filtered or unexported fields
}

PhysicalPosClient — payments on your card terminals, transactions, reports, end-of-day runs and results (/api/v1/physical-pos, product PHYSICAL_POS).

Every call is signed with your API key; the key decides the environment (a TEST key can read but every payment write is 403 physical_pos.environment.test_key_read_only). Payment writes need the scope physical_pos:payments; reads need physical_pos:view or physical_pos:payments.

Requests and filters are maps with the gateway's field names (PhysicalPosRequestFields, PhysicalPosFilters). Card data is never sent: the card is read on the device. A field that looks like card data (pan, cardNumber, cvv, expiry …) or a card number in merchantReference, an item name or tax group code, or a free-text filter returns *PhysicalPosCardDataRejectedError before anything is sent; any other unknown field returns ErrConfiguration. Amounts are canonical minor-unit text ("4500"); counts, line numbers and quantities are integers.

A payment write is asynchronous: the answer means "accepted", not "paid". Follow the outcome with the physical_pos.payment.* webhooks or GetPayment. Resolving a payment under manual review is done in the panel only.

Idempotency — store the key first, then call:

key := lunixi.NewPhysicalPosIdempotencyKey()
orders.SavePosKey(orderID, key) // your storage
result, err := client.PhysicalPos.CreatePayment(ctx, request, key)
var unknown *lunixi.PhysicalPosOutcomeUnknownError
if errors.As(err, &unknown) {
	// the payment may exist: call again later with the SAME key
}

A new key for the same payment can charge the card twice. For a SALE, also send merchantReference with allowDuplicateReference false: the gateway then refuses a second sale while one with that reference is unresolved (physical_pos.payment.previous_outcome_unknown).

func (*PhysicalPosClient) CancelPayment added in v1.3.0

func (p *PhysicalPosClient) CancelPayment(ctx context.Context, paymentID, idempotencyKey string) (*PhysicalPosWriteResult, error)

CancelPayment cancels a payment before its start command reaches the device (POST /payments/{paymentId}/cancel, 200). Read payment.paymentStatus: only EXPIRED with statusReason MERCHANT_CANCELLED_BEFORE_DISPATCH means it was cancelled; a payment already in a final state comes back unchanged with Replayed true. To undo an approved sale use a reversal. Cancelling is idempotent, so the key is optional ("" sends a new UUID, returned as IdempotencyKey).

func (*PhysicalPosClient) CreatePayment added in v1.3.0

func (p *PhysicalPosClient) CreatePayment(ctx context.Context, request map[string]any, idempotencyKey string) (*PhysicalPosWriteResult, error)

CreatePayment starts a payment on a device: SALE, PREAUTH_OPEN or REFUND_UNMATCHED (POST /payments). target is exactly one of {deviceId}, {vendorCode, serialNumber} or {externalRef}; items (SALE only) are {lineNo, name, quantityMilli, unitCode, unitPriceMinor, taxGroupCode, lineTotalMinor, barcode?}.

instrument is CARD (default) or a provider-collected card such as MEAL_CARD; for those send interaction (INSTRUMENT_READ: the device reads the card, CODE_DISPLAY: the device shows the provider's QR / short code) and, when the terminal has several provider rows, terminalProviderId (a ListTerminalProviders row id). Leave both out for CARD.

idempotencyKey is required and sent exactly as given. The result is 202 with paymentStatus NOT_STARTED for a new payment, 200 with Replayed true when the same key and body were sent before (the payment's current view). When the outcome is unknown the error is *PhysicalPosOutcomeUnknownError.

func (*PhysicalPosClient) CreateReversal added in v1.3.0

func (p *PhysicalPosClient) CreateReversal(ctx context.Context, paymentID string, request map[string]any, idempotencyKey string) (*PhysicalPosWriteResult, error)

CreateReversal reverses an approved payment (POST /payments/{paymentId}/reversals): VOID, REFUND (by amountMinor or by items [{lineNo, quantityMilli, amountMinor?}]), PREAUTH_CLOSE or PREAUTH_CANCEL. The reversal is a new child payment (originalPaymentId = paymentID) followed like any payment. idempotencyKey is required; same result and errors as CreatePayment. A void after the device's end-of-day is *PhysicalPosVoidAfterSettlementError: refund it instead.

func (*PhysicalPosClient) GetPayment added in v1.3.0

func (p *PhysicalPosClient) GetPayment(ctx context.Context, paymentID string) (json.RawMessage, error)

GetPayment reads one payment with its items and refund items (GET /payments/{paymentId}).

func (*PhysicalPosClient) GetSalesSummary added in v1.3.0

func (p *PhysicalPosClient) GetSalesSummary(ctx context.Context, filters map[string]any) (json.RawMessage, error)

GetSalesSummary returns sale / refund / void counts and amounts with the net per currency (GET /reports/sales-summary). dateFrom / dateTo are business days (YYYY-MM-DD, Europe/Istanbul; a time.Time is sent as its own calendar day); groupBy DAY, STORE, DEVICE or INSTRUMENT; also deviceId, storeId.

func (*PhysicalPosClient) GetSettlementRun added in v1.3.0

func (p *PhysicalPosClient) GetSettlementRun(ctx context.Context, runID string) (json.RawMessage, error)

GetSettlementRun reads one end-of-day run with its command status and result state (GET /settlement-runs/{runId}).

func (*PhysicalPosClient) GetTaxSummary added in v1.3.0

func (p *PhysicalPosClient) GetTaxSummary(ctx context.Context, filters map[string]any) (json.RawMessage, error)

GetTaxSummary returns the tax breakdown with refunds and voids deducted (GET /reports/tax-summary). Filters: dateFrom, dateTo, deviceId, storeId.

func (*PhysicalPosClient) GetTransaction added in v1.3.0

func (p *PhysicalPosClient) GetTransaction(ctx context.Context, paymentID string) (json.RawMessage, error)

GetTransaction reads the tree of a root or child payment with its timeline (GET /transactions/{paymentId}).

func (*PhysicalPosClient) IterateAmbiguousPayments added in v1.3.0

func (p *PhysicalPosClient) IterateAmbiguousPayments(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateAmbiguousPayments yields every ambiguous payment, page by page.

func (*PhysicalPosClient) IteratePayments added in v1.3.0

func (p *PhysicalPosClient) IteratePayments(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IteratePayments yields every payment matching the filters, page by page.

func (*PhysicalPosClient) IterateSettlementRuns added in v1.3.0

func (p *PhysicalPosClient) IterateSettlementRuns(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateSettlementRuns yields every end-of-day run matching the filters.

func (*PhysicalPosClient) IterateSettlements added in v1.3.0

func (p *PhysicalPosClient) IterateSettlements(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateSettlements yields every settlement line, page by page.

func (*PhysicalPosClient) IterateTransactions added in v1.3.0

func (p *PhysicalPosClient) IterateTransactions(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateTransactions yields every transaction tree matching the filters.

func (*PhysicalPosClient) ListAmbiguousPayments added in v1.3.0

func (p *PhysicalPosClient) ListAmbiguousPayments(ctx context.Context, filters map[string]any) (*PhysicalPosPage, error)

ListAmbiguousPayments lists payments with an unknown outcome or under manual review (GET /transactions/ambiguous). Filters: limit, cursor, deviceId, paymentStatus (UNKNOWN or MANUAL_REVIEW).

func (*PhysicalPosClient) ListPayments added in v1.3.0

func (p *PhysicalPosClient) ListPayments(ctx context.Context, filters map[string]any) (*PhysicalPosPage, error)

ListPayments lists payments, newest first (GET /payments). Roots and reversals are in one list; items and refundItems are empty here (read one payment for them). Filters: limit, cursor, deviceId, paymentStatus, createdFrom, createdTo, merchantReference (finds a payment after an unknown outcome).

func (*PhysicalPosClient) ListSettlementRuns added in v1.3.0

func (p *PhysicalPosClient) ListSettlementRuns(ctx context.Context, filters map[string]any) (*PhysicalPosPage, error)

ListSettlementRuns lists the end-of-day runs started by Lunixi (manual and scheduled), newest first (GET /settlement-runs). Filters: limit, cursor, includeTotal, deviceId, source (MANUAL_API, MANUAL_PANEL, SCHEDULED), runStatus (PENDING, STARTED, SKIPPED, FAILED), createdFrom, createdTo.

func (*PhysicalPosClient) ListSettlements added in v1.3.0

func (p *PhysicalPosClient) ListSettlements(ctx context.Context, filters map[string]any) (*PhysicalPosPage, error)

ListSettlements lists end-of-day results per bank line, with the reported / system / difference totals (GET /settlements). Filters: limit, cursor, deviceId, lineStatus (MATCHED, MISMATCH, UNMAPPED), createdFrom, createdTo.

func (*PhysicalPosClient) ListTransactions added in v1.3.0

func (p *PhysicalPosClient) ListTransactions(ctx context.Context, filters map[string]any) (*PhysicalPosPage, error)

ListTransactions lists transaction trees (root payment + its reversals), newest first (GET /transactions). Filters: limit, cursor, deviceId, storeId, registerId, paymentStatus, createdFrom, createdTo, merchantReference, amountFromMinor, amountToMinor, origin, operation.

func (*PhysicalPosClient) StartSettlement added in v1.3.0

func (p *PhysicalPosClient) StartSettlement(ctx context.Context, deviceID, idempotencyKey string) (*PhysicalPosWriteResult, error)

StartSettlement starts end-of-day (batch close) on a device (POST /devices/{deviceId}/settlement, physical_pos:payments). End-of-day cannot be undone. The answer means "accepted": the device reports the result later — follow it with GetSettlementRun or ListSettlements. The result holds data.run (Record("run")), Replayed, StatusCode (202 new / 200 replay) and IdempotencyKey. Pass the key you stored, or "" for a new UUID; after an unknown outcome call again with the same key. A TEST key is refused with 403 physical_pos.environment.test_key_read_only.

type PhysicalPosManagementClient added in v1.3.0

type PhysicalPosManagementClient struct {
	// contains filtered or unexported fields
}

PhysicalPosManagementClient — stores, registers, logical terminals with their bank rows, payment-provider rows and device links, devices with their identity keys, the end-of-day policy, the catalog and the overview (/api/v1/physical-pos). Reads need physical_pos:view, writes physical_pos:manage, device identity writes (key revocation, enrollment revert, activation-code revocation) physical_pos:identity; a TEST key can only read. Activation codes are issued in the panel only.

Updates and status changes take the rowVersion you last read (409 physical_pos.version_conflict when the record changed). Reason codes are closed sets checked by the gateway (400 physical_pos.input.reason_code_invalid). Routes that require an Idempotency-Key get a new UUID when you pass ""; a key you pass is sent exactly as given (never trimmed). The key sent comes back as IdempotencyKey. A key belongs to one operation: reusing it for another body or route is 409 physical_pos.idempotency_mismatch.

Records come back as JSON (the record of data, or the whole data object where it has several parts); pages as PhysicalPosPage, whose TotalCount is set only with includeTotal true on entity lists.

func (*PhysicalPosManagementClient) AddTerminalAcquirer added in v1.3.0

func (m *PhysicalPosManagementClient) AddTerminalAcquirer(ctx context.Context, terminalID string, request map[string]any, idempotencyKey string) (*PhysicalPosWriteResult, error)

AddTerminalAcquirer adds a bank row: {vendorAcquirerRef, merchantNumber, terminalNumber, label?, currencies}. The result holds data.acquirer, Replayed, StatusCode and IdempotencyKey.

func (*PhysicalPosManagementClient) AddTerminalProvider added in v1.3.0

func (m *PhysicalPosManagementClient) AddTerminalProvider(ctx context.Context, terminalID string, request map[string]any, idempotencyKey string) (*PhysicalPosWriteResult, error)

AddTerminalProvider adds a provider row: {vendorAccountId, merchantCode, terminalCode, productCode?, label?}; the provider comes from the vendor account. The result holds data.provider, Replayed, StatusCode (201 new / 200 replay) and IdempotencyKey.

func (*PhysicalPosManagementClient) ArchiveRegister added in v1.3.0

func (m *PhysicalPosManagementClient) ArchiveRegister(ctx context.Context, registerID string, request map[string]any) (json.RawMessage, error)

ArchiveRegister archives a register: {rowVersion, reasonCode}.

func (*PhysicalPosManagementClient) ArchiveStore added in v1.3.0

func (m *PhysicalPosManagementClient) ArchiveStore(ctx context.Context, storeID string, request map[string]any) (json.RawMessage, error)

ArchiveStore archives a store with its active registers: {rowVersion, reasonCode}. Returns {store, archivedRegisterCount}.

func (*PhysicalPosManagementClient) AssignDevice added in v1.3.0

func (m *PhysicalPosManagementClient) AssignDevice(ctx context.Context, deviceID string, request map[string]any) (json.RawMessage, error)

AssignDevice assigns the device to a store (and register): {rowVersion, storeId, registerId?, reasonCode}. Returns {device, assignment, previousAssignmentId}.

func (*PhysicalPosManagementClient) ChangeDeviceLifecycle added in v1.3.0

func (m *PhysicalPosManagementClient) ChangeDeviceLifecycle(ctx context.Context, deviceID string, request map[string]any) (json.RawMessage, error)

ChangeDeviceLifecycle moves the device to target ACTIVE, SUSPENDED or MAINTENANCE: {rowVersion, target, reasonCode}.

func (*PhysicalPosManagementClient) ChangeTerminalDevice added in v1.3.0

func (m *PhysicalPosManagementClient) ChangeTerminalDevice(ctx context.Context, terminalID string, request map[string]any) (json.RawMessage, error)

ChangeTerminalDevice links the terminal to a device, closing the previous link: {rowVersion, deviceId, reasonCode}. Returns {terminal, link}.

func (*PhysicalPosManagementClient) ClearAccountSettlementPolicy added in v1.3.0

func (m *PhysicalPosManagementClient) ClearAccountSettlementPolicy(ctx context.Context, expectedRowVersion int64) (json.RawMessage, error)

ClearAccountSettlementPolicy resets the account's policy to MANUAL.

func (*PhysicalPosManagementClient) ClearDeviceSettlementPolicy added in v1.3.0

func (m *PhysicalPosManagementClient) ClearDeviceSettlementPolicy(ctx context.Context, deviceID string, expectedRowVersion int64) (json.RawMessage, error)

ClearDeviceSettlementPolicy removes a device's override; the device then inherits its store's or the account's policy.

func (*PhysicalPosManagementClient) ClearStoreSettlementPolicy added in v1.3.0

func (m *PhysicalPosManagementClient) ClearStoreSettlementPolicy(ctx context.Context, storeID string, expectedRowVersion int64) (json.RawMessage, error)

ClearStoreSettlementPolicy removes a store's override; the store then inherits the account's policy.

func (*PhysicalPosManagementClient) CloseDeviceAssignment added in v1.3.0

func (m *PhysicalPosManagementClient) CloseDeviceAssignment(ctx context.Context, deviceID string, request map[string]any, idempotencyKey string) (*PhysicalPosWriteResult, error)

CloseDeviceAssignment moves the device to storage: {rowVersion, reasonCode}. The result holds data.device and data.closedAssignment, Replayed and IdempotencyKey.

func (*PhysicalPosManagementClient) CloseTerminal added in v1.3.0

func (m *PhysicalPosManagementClient) CloseTerminal(ctx context.Context, terminalID string, request map[string]any) (json.RawMessage, error)

CloseTerminal closes a terminal: {rowVersion, reasonCode}.

func (m *PhysicalPosManagementClient) CloseTerminalDeviceLink(ctx context.Context, terminalID string, request map[string]any, idempotencyKey string) (*PhysicalPosWriteResult, error)

CloseTerminalDeviceLink closes the terminal's device link: {rowVersion, reasonCode}. The result holds data.terminal and data.link (the closed link or null), Replayed, StatusCode and IdempotencyKey.

func (*PhysicalPosManagementClient) CreateDevice added in v1.3.0

func (m *PhysicalPosManagementClient) CreateDevice(ctx context.Context, request map[string]any, idempotencyKey string) (*PhysicalPosWriteResult, error)

CreateDevice registers a device: {vendorCode, deviceModelId, serialNumber, displayName?, externalRef?, storeId?, registerId?, integrationChannel, channelVariant?, appMode?}. The result holds data.device, Replayed, StatusCode and IdempotencyKey.

func (*PhysicalPosManagementClient) CreateRegister added in v1.3.0

func (m *PhysicalPosManagementClient) CreateRegister(ctx context.Context, storeID string, request map[string]any, idempotencyKey string) (*PhysicalPosWriteResult, error)

CreateRegister creates a register in a store: {code, name}. The result holds data.register, Replayed, StatusCode and IdempotencyKey.

func (*PhysicalPosManagementClient) CreateStore added in v1.3.0

func (m *PhysicalPosManagementClient) CreateStore(ctx context.Context, request map[string]any, idempotencyKey string) (*PhysicalPosWriteResult, error)

CreateStore creates a store: {code, name, city?, district?, addressLine?, timezone?, externalRef?}. The result holds data.store, Replayed, StatusCode (201 new / 200 replay) and IdempotencyKey.

func (*PhysicalPosManagementClient) CreateTerminal added in v1.3.0

func (m *PhysicalPosManagementClient) CreateTerminal(ctx context.Context, request map[string]any, idempotencyKey string) (*PhysicalPosWriteResult, error)

CreateTerminal creates a logical terminal: {code, displayName, vendorCode?, virtualSerial?, vendorTerminalRef?}. The result holds data.terminal, Replayed, StatusCode and IdempotencyKey.

func (*PhysicalPosManagementClient) GetAccountSettlementPolicy added in v1.3.0

func (m *PhysicalPosManagementClient) GetAccountSettlementPolicy(ctx context.Context) (json.RawMessage, error)

GetAccountSettlementPolicy reads the account's end-of-day policy.

func (*PhysicalPosManagementClient) GetDevice added in v1.3.0

func (m *PhysicalPosManagementClient) GetDevice(ctx context.Context, deviceID string) (json.RawMessage, error)

GetDevice reads one device (GET /devices/{deviceId}).

func (*PhysicalPosManagementClient) GetDeviceSettlementPolicy added in v1.3.0

func (m *PhysicalPosManagementClient) GetDeviceSettlementPolicy(ctx context.Context, deviceID string) (json.RawMessage, error)

GetDeviceSettlementPolicy reads a device's end-of-day policy override.

func (*PhysicalPosManagementClient) GetEffectiveSettlementPolicy added in v1.3.0

func (m *PhysicalPosManagementClient) GetEffectiveSettlementPolicy(ctx context.Context, deviceID string) (json.RawMessage, error)

GetEffectiveSettlementPolicy returns the policy a device follows (GET /devices/{deviceId}/settlement-policy/effective): {deviceId, sourceScopeType (ACCOUNT, STORE, DEVICE), policy, serverSettlementSupported, deviceAutoSupported, nextScheduledAt, lastSettlementAt, overdue, scheduleWarning}.

func (*PhysicalPosManagementClient) GetOverview added in v1.3.0

GetOverview returns the store, register, terminal and device counts (GET /overview).

func (*PhysicalPosManagementClient) GetStore added in v1.3.0

func (m *PhysicalPosManagementClient) GetStore(ctx context.Context, storeID string) (json.RawMessage, error)

GetStore returns {store, registerSummary: {activeCount, archivedCount}, assignedDeviceCount}.

func (*PhysicalPosManagementClient) GetStoreSettlementPolicy added in v1.3.0

func (m *PhysicalPosManagementClient) GetStoreSettlementPolicy(ctx context.Context, storeID string) (json.RawMessage, error)

GetStoreSettlementPolicy reads a store's end-of-day policy override.

func (*PhysicalPosManagementClient) GetTerminal added in v1.3.0

func (m *PhysicalPosManagementClient) GetTerminal(ctx context.Context, terminalID string) (json.RawMessage, error)

GetTerminal returns {terminal, acquirers: {items, pageInfo}}.

func (*PhysicalPosManagementClient) IterateDeviceAssignments added in v1.3.0

func (m *PhysicalPosManagementClient) IterateDeviceAssignments(ctx context.Context, deviceID string, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateDeviceAssignments yields every assignment of a device.

func (*PhysicalPosManagementClient) IterateDeviceAudit added in v1.3.0

func (m *PhysicalPosManagementClient) IterateDeviceAudit(ctx context.Context, deviceID string, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateDeviceAudit yields every audit entry of a device.

func (*PhysicalPosManagementClient) IterateDeviceKeys added in v1.3.0

func (m *PhysicalPosManagementClient) IterateDeviceKeys(ctx context.Context, deviceID string, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateDeviceKeys yields every identity key of a device.

func (*PhysicalPosManagementClient) IterateDevices added in v1.3.0

func (m *PhysicalPosManagementClient) IterateDevices(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateDevices yields every device matching the filters.

func (*PhysicalPosManagementClient) IterateRegisterAudit added in v1.3.0

func (m *PhysicalPosManagementClient) IterateRegisterAudit(ctx context.Context, registerID string, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateRegisterAudit yields every audit entry of a register.

func (*PhysicalPosManagementClient) IterateRegisters added in v1.3.0

func (m *PhysicalPosManagementClient) IterateRegisters(ctx context.Context, storeID string, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateRegisters yields every register of a store.

func (*PhysicalPosManagementClient) IterateStoreAudit added in v1.3.0

func (m *PhysicalPosManagementClient) IterateStoreAudit(ctx context.Context, storeID string, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateStoreAudit yields every audit entry of a store.

func (*PhysicalPosManagementClient) IterateStores added in v1.3.0

func (m *PhysicalPosManagementClient) IterateStores(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateStores yields every store matching the filters.

func (*PhysicalPosManagementClient) IterateTerminalAcquirers added in v1.3.0

func (m *PhysicalPosManagementClient) IterateTerminalAcquirers(ctx context.Context, terminalID string, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateTerminalAcquirers yields every bank row of a terminal.

func (*PhysicalPosManagementClient) IterateTerminalAudit added in v1.3.0

func (m *PhysicalPosManagementClient) IterateTerminalAudit(ctx context.Context, terminalID string, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateTerminalAudit yields every audit entry of a terminal.

func (m *PhysicalPosManagementClient) IterateTerminalLinks(ctx context.Context, terminalID string, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateTerminalLinks yields every device link of a terminal.

func (*PhysicalPosManagementClient) IterateTerminalProviders added in v1.3.0

func (m *PhysicalPosManagementClient) IterateTerminalProviders(ctx context.Context, terminalID string, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateTerminalProviders yields every provider row of a terminal.

func (*PhysicalPosManagementClient) IterateTerminals added in v1.3.0

func (m *PhysicalPosManagementClient) IterateTerminals(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateTerminals yields every terminal matching the filters.

func (*PhysicalPosManagementClient) ListAcquirers added in v1.3.0

ListAcquirers lists the banks a terminal row can belong to (GET /catalog/acquirers).

func (*PhysicalPosManagementClient) ListDeviceAssignments added in v1.3.0

func (m *PhysicalPosManagementClient) ListDeviceAssignments(ctx context.Context, deviceID string, filters map[string]any) (*PhysicalPosPage, error)

ListDeviceAssignments lists a device's store assignments; filters limit, cursor.

func (*PhysicalPosManagementClient) ListDeviceAudit added in v1.3.0

func (m *PhysicalPosManagementClient) ListDeviceAudit(ctx context.Context, deviceID string, filters map[string]any) (*PhysicalPosPage, error)

ListDeviceAudit lists a device's audit entries; filters limit, cursor.

func (*PhysicalPosManagementClient) ListDeviceKeys added in v1.3.0

func (m *PhysicalPosManagementClient) ListDeviceKeys(ctx context.Context, deviceID string, filters map[string]any) (*PhysicalPosPage, error)

ListDeviceKeys lists the device's identity keys, fingerprints only (GET /devices/{deviceId}/keys). Each key: keyId, algorithm, keyStatus (ACTIVE, SUPERSEDED, REVOKED), enrolledVia (PAIRING, ACTIVATION_CODE, ROTATION), fingerprint, lineageRootKeyId, rotatedFromKeyId, activatedAt, supersededAt, revokedAt, revokeReason, rowVersion. Filters limit, cursor.

func (*PhysicalPosManagementClient) ListDeviceModels added in v1.3.0

func (m *PhysicalPosManagementClient) ListDeviceModels(ctx context.Context, filters map[string]any) (json.RawMessage, error)

ListDeviceModels lists the device models; filters vendorCode, deviceType, status (GET /catalog/device-models).

func (*PhysicalPosManagementClient) ListDevices added in v1.3.0

func (m *PhysicalPosManagementClient) ListDevices(ctx context.Context, filters map[string]any) (*PhysicalPosPage, error)

ListDevices lists devices; filters limit, cursor, includeTotal, storeId, registerId, vendorCode, deviceModelId, deviceType, lifecycleStatus, ownershipStatus, integrationChannel, q.

func (*PhysicalPosManagementClient) ListRegisterAudit added in v1.3.0

func (m *PhysicalPosManagementClient) ListRegisterAudit(ctx context.Context, registerID string, filters map[string]any) (*PhysicalPosPage, error)

ListRegisterAudit lists a register's audit entries; filters limit, cursor.

func (*PhysicalPosManagementClient) ListRegisters added in v1.3.0

func (m *PhysicalPosManagementClient) ListRegisters(ctx context.Context, storeID string, filters map[string]any) (*PhysicalPosPage, error)

ListRegisters lists a store's registers; filters limit, cursor, includeTotal, status.

func (*PhysicalPosManagementClient) ListStoreAudit added in v1.3.0

func (m *PhysicalPosManagementClient) ListStoreAudit(ctx context.Context, storeID string, filters map[string]any) (*PhysicalPosPage, error)

ListStoreAudit lists a store's audit entries; filters limit, cursor.

func (*PhysicalPosManagementClient) ListStores added in v1.3.0

func (m *PhysicalPosManagementClient) ListStores(ctx context.Context, filters map[string]any) (*PhysicalPosPage, error)

ListStores lists stores; filters limit, cursor, includeTotal, status, q.

func (*PhysicalPosManagementClient) ListTerminalAcquirers added in v1.3.0

func (m *PhysicalPosManagementClient) ListTerminalAcquirers(ctx context.Context, terminalID string, filters map[string]any) (*PhysicalPosPage, error)

ListTerminalAcquirers lists the bank rows of a terminal; a row's id is the payment's terminalAcquirerId. Filters limit, cursor, includeTotal.

func (*PhysicalPosManagementClient) ListTerminalAudit added in v1.3.0

func (m *PhysicalPosManagementClient) ListTerminalAudit(ctx context.Context, terminalID string, filters map[string]any) (*PhysicalPosPage, error)

ListTerminalAudit lists a terminal's audit entries; filters limit, cursor.

func (m *PhysicalPosManagementClient) ListTerminalLinks(ctx context.Context, terminalID string, filters map[string]any) (*PhysicalPosPage, error)

ListTerminalLinks lists a terminal's device links; filters limit, cursor.

func (*PhysicalPosManagementClient) ListTerminalProviders added in v1.3.0

func (m *PhysicalPosManagementClient) ListTerminalProviders(ctx context.Context, terminalID string, filters map[string]any) (*PhysicalPosPage, error)

ListTerminalProviders lists the payment-provider rows of a terminal (a provider's merchant / terminal / product code, for example of a meal card provider). A row's id is the payment's terminalProviderId. Filters limit, cursor, includeTotal.

func (*PhysicalPosManagementClient) ListTerminals added in v1.3.0

func (m *PhysicalPosManagementClient) ListTerminals(ctx context.Context, filters map[string]any) (*PhysicalPosPage, error)

ListTerminals lists logical terminals; filters limit, cursor, includeTotal, status, q.

func (*PhysicalPosManagementClient) ListVendors added in v1.3.0

ListVendors lists the device vendors (GET /catalog/vendors).

func (*PhysicalPosManagementClient) RestoreRegister added in v1.3.0

func (m *PhysicalPosManagementClient) RestoreRegister(ctx context.Context, registerID string, request map[string]any) (json.RawMessage, error)

RestoreRegister restores an archived register: {rowVersion, reasonCode}.

func (*PhysicalPosManagementClient) RestoreStore added in v1.3.0

func (m *PhysicalPosManagementClient) RestoreStore(ctx context.Context, storeID string, request map[string]any) (json.RawMessage, error)

RestoreStore restores an archived store: {rowVersion, reasonCode}.

func (*PhysicalPosManagementClient) RetireDevice added in v1.3.0

func (m *PhysicalPosManagementClient) RetireDevice(ctx context.Context, deviceID string, request map[string]any, idempotencyKey string) (*PhysicalPosWriteResult, error)

RetireDevice retires the device for good: {rowVersion, reasonCode}. The result holds data.device, Replayed and IdempotencyKey.

func (*PhysicalPosManagementClient) RevertDeviceEnrollment added in v1.3.0

func (m *PhysicalPosManagementClient) RevertDeviceEnrollment(ctx context.Context, deviceID, keyID string, request map[string]any) (json.RawMessage, error)

RevertDeviceEnrollment reverts an activation-code enrollment (revokes the key, suspends the device): {reasonCode}; NOT_MY_DEVICE, SUSPECTED_PHISHING, WRONG_DEVICE or OTHER. Returns {key, lifecycleStatus, replayed}.

func (*PhysicalPosManagementClient) RevokeActivationCode added in v1.3.0

func (m *PhysicalPosManagementClient) RevokeActivationCode(ctx context.Context, deviceID string, request map[string]any) (json.RawMessage, error)

RevokeActivationCode revokes the device's open activation code: {reasonCode}; MERCHANT_REVOKED, DEVICE_LOST, DEVICE_STOLEN or OTHER. Returns {deviceId, revokedAt, revokeReason}.

func (*PhysicalPosManagementClient) RevokeDeviceKey added in v1.3.0

func (m *PhysicalPosManagementClient) RevokeDeviceKey(ctx context.Context, deviceID, keyID string, request map[string]any) (json.RawMessage, error)

RevokeDeviceKey revokes a device key: {rowVersion (the key's), reasonCode}; reasonCode DEVICE_LOST, DEVICE_STOLEN, KEY_COMPROMISED, DEVICE_REPLACED, MERCHANT_REQUEST or OTHER. Returns {key, lifecycleStatus, replayed}.

func (*PhysicalPosManagementClient) SetAccountSettlementPolicy added in v1.3.0

func (m *PhysicalPosManagementClient) SetAccountSettlementPolicy(ctx context.Context, request map[string]any) (json.RawMessage, error)

SetAccountSettlementPolicy replaces the account's end-of-day policy.

func (*PhysicalPosManagementClient) SetDeviceSettlementPolicy added in v1.3.0

func (m *PhysicalPosManagementClient) SetDeviceSettlementPolicy(ctx context.Context, deviceID string, request map[string]any) (json.RawMessage, error)

SetDeviceSettlementPolicy replaces a device's end-of-day policy override. DEVICE_AUTO only on devices that report their end-of-day results.

func (*PhysicalPosManagementClient) SetStoreSettlementPolicy added in v1.3.0

func (m *PhysicalPosManagementClient) SetStoreSettlementPolicy(ctx context.Context, storeID string, request map[string]any) (json.RawMessage, error)

SetStoreSettlementPolicy replaces a store's end-of-day policy override.

func (*PhysicalPosManagementClient) UpdateDevice added in v1.3.0

func (m *PhysicalPosManagementClient) UpdateDevice(ctx context.Context, deviceID string, request map[string]any) (json.RawMessage, error)

UpdateDevice changes a device: {rowVersion, displayName?, externalRef?, integrationChannel?, channelVariant?, appMode?}; nil clears displayName, externalRef, channelVariant and appMode.

func (*PhysicalPosManagementClient) UpdateRegister added in v1.3.0

func (m *PhysicalPosManagementClient) UpdateRegister(ctx context.Context, registerID string, request map[string]any) (json.RawMessage, error)

UpdateRegister changes a register: {rowVersion, name?}.

func (*PhysicalPosManagementClient) UpdateStore added in v1.3.0

func (m *PhysicalPosManagementClient) UpdateStore(ctx context.Context, storeID string, request map[string]any) (json.RawMessage, error)

UpdateStore changes a store: {rowVersion, name?, city?, district?, addressLine?, timezone?, externalRef?}. nil clears city, district, addressLine and externalRef; a field left out is unchanged.

func (*PhysicalPosManagementClient) UpdateTerminal added in v1.3.0

func (m *PhysicalPosManagementClient) UpdateTerminal(ctx context.Context, terminalID string, request map[string]any) (json.RawMessage, error)

UpdateTerminal changes a terminal: {rowVersion, displayName?, vendorCode?}.

func (*PhysicalPosManagementClient) UpdateTerminalAcquirer added in v1.3.0

func (m *PhysicalPosManagementClient) UpdateTerminalAcquirer(ctx context.Context, terminalAcquirerID string, request map[string]any) (json.RawMessage, error)

UpdateTerminalAcquirer changes a bank row: {rowVersion, label?, currencies?, status?}; nil label clears it.

func (*PhysicalPosManagementClient) UpdateTerminalProvider added in v1.3.0

func (m *PhysicalPosManagementClient) UpdateTerminalProvider(ctx context.Context, terminalProviderID string, request map[string]any) (json.RawMessage, error)

UpdateTerminalProvider changes a provider row: {rowVersion, label?, status?}; nil label clears it, status ACTIVE or DISABLED.

type PhysicalPosOriginalPayment added in v1.3.0

type PhysicalPosOriginalPayment struct {
	PaymentID string
	Origin    string
}

PhysicalPosOriginalPayment is data.original of a reversal event; Origin is API or DEVICE_DIRECT.

type PhysicalPosOutcomeUnknownError added in v1.3.0

type PhysicalPosOutcomeUnknownError struct {
	IdempotencyKey string
	Attempts       int
	StatusCode     int
	Code           string
	RequestID      string
	RetryAfter     time.Duration
	// contains filtered or unexported fields
}

PhysicalPosOutcomeUnknownError: the outcome of a payment write (start, reversal, cancel) is unknown; the payment may or may not exist. Raised when an attempt got no HTTP answer (also while the body was read, or when the context ended), a 2xx without a readable payment, or a 5xx that does not say "not started" — and then for the whole call, whatever a later attempt answered (a 429 or 409 included).

Call again with the same IdempotencyKey (safe: an existing payment comes back with Replayed true), or look it up with ListPayments and the merchantReference filter. A new key can start a second payment. StatusCode, Code and RequestID are the last HTTP answer's (0 / transport code when there was none); Attempts is the number of attempts made; the error unwraps to the last attempt's error.

func (*PhysicalPosOutcomeUnknownError) Error added in v1.3.0

func (*PhysicalPosOutcomeUnknownError) Unwrap added in v1.3.0

type PhysicalPosPage added in v1.3.0

type PhysicalPosPage struct {
	Items      []json.RawMessage
	HasMore    bool
	NextCursor string
	TotalCount *int64
	RequestID  string
}

PhysicalPosPage is one page of a physical POS list. Items are the rows of data.items in wire order; the paging comes from the envelope's pageInfo (a copy inside data is read as a fallback). Send NextCursor back verbatim as the cursor filter; HasMore is true only with a non-empty cursor. TotalCount is set only when includeTotal was asked for on an entity list.

type PhysicalPosRateLimitError added in v1.3.0

type PhysicalPosRateLimitError struct {
	RetryAfter     time.Duration
	StatusCode     int
	Code           string
	RequestID      string
	IdempotencyKey string
	// contains filtered or unexported fields
}

PhysicalPosRateLimitError: 429 RATE_LIMITED (payment writes are limited per API key). RetryAfter is the Retry-After header, or details.retryAfterSeconds when the header is missing; 0 when neither was given.

func (*PhysicalPosRateLimitError) Error added in v1.3.0

func (e *PhysicalPosRateLimitError) Error() string

func (*PhysicalPosRateLimitError) Unwrap added in v1.3.0

func (e *PhysicalPosRateLimitError) Unwrap() error

type PhysicalPosVoidAfterSettlementError added in v1.3.0

type PhysicalPosVoidAfterSettlementError struct {
	AllowedOperation string
	StatusCode       int
	Code             string
	RequestID        string
	IdempotencyKey   string
	// contains filtered or unexported fields
}

PhysicalPosVoidAfterSettlementError: 409 physical_pos.payment.void_after_settlement. The payment is already in a device end-of-day, so it can no longer be voided; return the amount with a REFUND reversal on the same payment (with a new Idempotency-Key). AllowedOperation is details.allowedOperation (REFUND).

func (*PhysicalPosVoidAfterSettlementError) Error added in v1.3.0

func (*PhysicalPosVoidAfterSettlementError) Unwrap added in v1.3.0

type PhysicalPosWebhookEvent added in v1.3.0

type PhysicalPosWebhookEvent struct {
	ID          string
	Type        string
	Category    string
	Environment string
	CreatedAt   string
	// HistorySeq is data.historySeq, nil when absent (settlement events).
	HistorySeq *int64
	// Original is the reversal's original payment, nil on a root payment.
	Original *PhysicalPosOriginalPayment
	// Cashier is set for a payment started from a device cashier session
	// (register mode), nil otherwise (the payload then has no cashier key).
	Cashier *PhysicalPosCashier
	// IsDeviceSale is true for physical_pos.payment.device_sale, a sale made
	// directly on the device (data.origin, data.deviceOccurredAt).
	IsDeviceSale bool
	Data         json.RawMessage
	// Raw is the signed envelope. It can contain customer data: do not log
	// it or persist it outside your data-retention policy.
	Raw json.RawMessage
}

PhysicalPosWebhookEvent is a verified physical_pos.* webhook.

Data is the envelope's data (or its payloadJson, as an object or JSON text). Amounts in it are minor-unit text ("4500"), as in the HTTP API; they are checked after the signature. Delivery order is not guaranteed and an event can arrive more than once: deduplicate by ID and ignore an event whose HistorySeq is not greater than the last one you applied for the same data.paymentId. End-of-day events (Category settlement) carry no HistorySeq; deduplicate them by ID.

func ParsePhysicalPosWebhookEvent added in v1.3.0

func ParsePhysicalPosWebhookEvent(event *WebhookEvent) (*PhysicalPosWebhookEvent, error)

ParsePhysicalPosWebhookEvent reads an event already verified by WebhookVerifier as a physical POS event. A WebhookEvent can only be built by the verifier, so an unverified body cannot be read here. The event type comes from the signed body; a type outside physical_pos.*, an envelope without data, or an amount that is not minor-unit text is ErrWebhook.

func (*PhysicalPosWebhookEvent) DecodeData added in v1.3.0

func (e *PhysicalPosWebhookEvent) DecodeData(target any) error

DecodeData decodes Data using json.Number for interface values.

type PhysicalPosWriteError added in v1.3.0

type PhysicalPosWriteError struct {
	IdempotencyKey string
	Err            error
}

PhysicalPosWriteError carries the Idempotency-Key a physical POS write sent (yours, or the one the SDK generated for an empty key) together with the error of that write, so the same key can be used again. It unwraps to the underlying error (*APIError, a context error …). The typed physical POS errors carry the key themselves and are not wrapped.

func (*PhysicalPosWriteError) Error added in v1.3.0

func (e *PhysicalPosWriteError) Error() string

func (*PhysicalPosWriteError) Unwrap added in v1.3.0

func (e *PhysicalPosWriteError) Unwrap() error

type PhysicalPosWriteResult added in v1.3.0

type PhysicalPosWriteResult struct {
	// Data is the whole data object (payment, run, store, terminal, device
	// … and sibling fields such as link or closedAssignment).
	Data           json.RawMessage
	Replayed       bool
	StatusCode     int
	IdempotencyKey string
	RequestID      string
}

PhysicalPosWriteResult is the answer of a physical POS write that carries an Idempotency-Key.

Payment writes (CreatePayment, CreateReversal) answer 202 for a new payment — accepted, not paid: follow the outcome by webhook or GetPayment — and 200 with Replayed true when the same key and body were sent again (the payment's current view). CancelPayment answers 200. StartSettlement answers 202 new / 200 replay, management creates 201 new / 200 replay. IdempotencyKey is the key that was sent (yours, or the generated one); keep it while the outcome is not known.

func (*PhysicalPosWriteResult) Accepted added in v1.3.0

func (r *PhysicalPosWriteResult) Accepted() bool

Accepted reports a 202 answer: a new payment, reversal or end-of-day run was queued to the device.

func (*PhysicalPosWriteResult) DecodeData added in v1.3.0

func (r *PhysicalPosWriteResult) DecodeData(target any) error

DecodeData decodes Data using json.Number for interface values.

func (*PhysicalPosWriteResult) Payment added in v1.3.0

func (r *PhysicalPosWriteResult) Payment() json.RawMessage

Payment returns data.payment of a payment write.

func (*PhysicalPosWriteResult) Record added in v1.3.0

func (r *PhysicalPosWriteResult) Record(name string) json.RawMessage

Record returns one field of Data (payment, run, store, register, terminal, acquirer, provider, device …), nil when absent.

type PromissoryNoteScheduleRow added in v1.3.0

type PromissoryNoteScheduleRow struct {
	Amount  string `json:"amount"`
	DueDate string `json:"dueDate"`
}

PromissoryNoteScheduleRow is one note of a promissory-note schedule. Amount is positive minor-unit text; DueDate is a YYYY-MM-DD calendar date.

type ReferenceClient added in v1.3.0

type ReferenceClient struct {
	// contains filtered or unexported fields
}

ReferenceClient reads the Lunixi address dictionary for Türkiye (province, district, neighborhood). The codes fill an ADDRESS input field, for example the debtor address of a promissory-note payment: { provinceCode, districtCode, neighborhoodCode, line }. Data is { items: [{ code, name }] }; an empty list means the data for that level is not published yet.

func (*ReferenceClient) ListDistricts added in v1.3.0

func (r *ReferenceClient) ListDistricts(ctx context.Context, provinceCode string) (*Response, error)

ListDistricts lists the districts of a province (provinceCode 01–81).

func (*ReferenceClient) ListNeighborhoods added in v1.3.0

func (r *ReferenceClient) ListNeighborhoods(ctx context.Context, districtCode string) (*Response, error)

ListNeighborhoods lists the neighborhoods of a district (districtCode from ListDistricts).

func (*ReferenceClient) ListProvinces added in v1.3.0

func (r *ReferenceClient) ListProvinces(ctx context.Context) (*Response, error)

ListProvinces lists provinces with their code (01–81).

type ReplayStore

type ReplayStore interface {
	Process(context.Context, *WebhookEvent, func(*sql.Tx) error) (bool, error)
}

ReplayStore applies a verified event and its event-ID marker in the SAME transaction. The callback must use the supplied transaction for business state. Network requests and other nontransactional effects belong in a durable application outbox, not inside this callback.

type Request

type Request struct {
	Method         string
	Path           string
	Query          url.Values
	Body           any
	IdempotencyKey string
}

Request is a signed merchant API request. Path must be an unescaped path under /api/v1/ (or under /api/panel/v1/subscriptions/portal/, the customer portal links of subscriptions); use Query for query parameters. A stable IdempotencyKey is required by financial mutation helpers and controls safe automatic retries.

type Response

type Response struct {
	StatusCode  int
	RequestID   string
	Envelope    json.RawMessage
	Data        json.RawMessage
	PageInfo    json.RawMessage
	ContentType string
	Bytes       []byte
	// contains filtered or unexported fields
}

Response preserves the gateway envelope, including pageInfo and pending financial states. Inspect verified amount, currency and status before order fulfillment. A successful HTTP response alone is not proof of payment.

func (*Response) BankTransferInstruction added in v1.3.0

func (r *Response) BankTransferInstruction() *PaymentActionBankTransfer

BankTransferInstruction reads data.action.bankTransfer of a payment response. It returns nil when there is no action, the action type is not DISPLAY or the instruction is missing. The instruction is display data only; the payment's paid state still comes from the gateway result.

func (*Response) DecodeData

func (r *Response) DecodeData(target any) error

DecodeData decodes data without converting integer amounts to float64. A map/interface target receives json.Number values.

type Route added in v1.3.0

type Route struct {
	Method                 string
	Path                   string
	IdempotencyKey         bool
	Required               []string
	Optional               []string
	AnyOf                  []string
	Query                  []string
	Binary                 bool
	Screening              bool
	StepUp                 bool
	OptionalIdempotencyKey bool
	Free                   bool
	OptionalBody           bool
	AnyQuery               bool
}

Route is one gateway route of a table-driven client (WalletRoutes, SanctionRoutes, BankTransferRoutes, SubscriptionRoutes, KycRoutes, IdentityRoutes, MarketplaceRoutes). Path is the template; ":name" segments are filled from the method arguments. IdempotencyKey reports that the gateway refuses the call without an Idempotency-Key. Required and Optional are the body fields the gateway accepts (any other is refused before sending); AnyOf names fields of which at least one must be present; Query lists the accepted query parameters. Binary: a 2xx answer is a file (an image), not the JSON envelope. Screening: the answer is read only when the envelope's status is "success" (sanction screening).

The remaining fields are read by the subscription, KYC, identity and marketplace clients. StepUp: the call carries the per-request Ed25519 signature; their other routes are sent with the access token only (every other client signs every call). OptionalIdempotencyKey: an Idempotency-Key may be sent (IdempotencyKey: it must be). Free: the body is an object the gateway validates, without a field list. OptionalBody: an empty body is sent as no body. AnyQuery: any scalar filter is accepted.

func (Route) Fields added in v1.3.0

func (r Route) Fields() []string

Fields returns Required followed by Optional.

func (Route) KeyRule added in v1.3.0

func (r Route) KeyRule() string

KeyRule is the route's Idempotency-Key rule: "required", "optional" or "none".

type SQLInbox

type SQLInbox struct {
	// contains filtered or unexported fields
}

SQLInbox is a durable ReplayStore for PostgreSQL and SQLite. Database drivers are supplied by the application; the SDK has no runtime dependency. Its table stores IDs, timestamp and a payload hash, never webhook raw data.

func NewSQLInbox

func NewSQLInbox(db *sql.DB, table, scope string) (*SQLInbox, error)

NewSQLInbox validates a separate deduplication scope for each merchant or integration. table must be a trusted migration-time SQL identifier.

func (*SQLInbox) EnsureSchema

func (s *SQLInbox) EnsureSchema(ctx context.Context) error

EnsureSchema explicitly creates the inbox table. Production applications can apply the equivalent DDL in their normal migration process instead.

func (*SQLInbox) Process

func (s *SQLInbox) Process(ctx context.Context, event *WebhookEvent, apply func(*sql.Tx) error) (bool, error)

Process returns true only when the callback and event marker are committed. A duplicate returns false without running callback. An event-ID collision with different signed content fails closed. Callback failure rolls back its marker so the provider can safely retry after an application crash/error.

type SanctionClient added in v1.3.0

type SanctionClient struct {
	// contains filtered or unexported fields
}

SanctionClient — sanctions screening (/api/v1/sanction/*, product SANCTION_SERVICE). The key needs the sanction:view_results permission (403 otherwise).

Screening returns matches, not verdicts: the decision is yours. Read a result with IsClearScreening: an empty match list is clear only when coverageStatus is COMPLETE. When the screening cannot run (no list publication can be pinned) the gateway answers 503 and the call returns an *APIError; a 2xx answer whose status is not "success" is an *APIError too, so a screening that did not run never comes back as an empty result.

Requests and filters are maps checked against SanctionRoutes before anything is sent: an unknown field, a missing required field, an empty AnyOf group, a nested row field outside SanctionNestedFields or a value outside SanctionValueSets returns ErrConfiguration (the service would drop an unknown field silently). Results are the envelope's data; the envelope's requestId is the HTTP request's id, the screening's own id is screeningRequestId (name screening). Lists return CursorPage.

func (*SanctionClient) EvaluateBehavioralAlert added in v1.3.0

func (s *SanctionClient) EvaluateBehavioralAlert(ctx context.Context, request map[string]any) (json.RawMessage, error)

EvaluateBehavioralAlert evaluates a behavioural risk signal.

func (*SanctionClient) GetDatasetFreshness added in v1.3.0

func (s *SanctionClient) GetDatasetFreshness(ctx context.Context) (json.RawMessage, error)

GetDatasetFreshness reads the freshness of the source lists: {manifest}. A manifest that could not be produced comes back as status "failure" and is an *APIError.

func (*SanctionClient) GetEntityGraph added in v1.3.0

func (s *SanctionClient) GetEntityGraph(ctx context.Context, entityID string, filters map[string]any) (json.RawMessage, error)

GetEntityGraph reads an entity's relationship graph. Filter: depth (1–3).

func (*SanctionClient) GetEntityProfile added in v1.3.0

func (s *SanctionClient) GetEntityProfile(ctx context.Context, entityID string, filters map[string]any) (json.RawMessage, error)

GetEntityProfile reads an entity's risk profile. Filter: screeningRequestId (read it on that screening's publication).

func (*SanctionClient) GetIndirectExposure added in v1.3.0

func (s *SanctionClient) GetIndirectExposure(ctx context.Context, entityID string, filters map[string]any) (json.RawMessage, error)

GetIndirectExposure reads an entity's indirect exposure paths. Filters: maxDepth, entityIds (the records of a merged match: a list or one id, sent comma-separated).

func (*SanctionClient) GetOwnershipAggregation added in v1.3.0

func (s *SanctionClient) GetOwnershipAggregation(ctx context.Context, entityID string, filters map[string]any) (json.RawMessage, error)

GetOwnershipAggregation reads an entity's ownership aggregation (50% rule). Filters: depth, entityIds (as in GetIndirectExposure).

func (*SanctionClient) IterateBlacklistEntries added in v1.3.0

func (s *SanctionClient) IterateBlacklistEntries(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateBlacklistEntries yields every deny-list entry, page by page.

func (*SanctionClient) IterateMonitoredEntities added in v1.3.0

func (s *SanctionClient) IterateMonitoredEntities(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateMonitoredEntities yields every monitored subject, page by page.

func (*SanctionClient) IterateMonitoringAlerts added in v1.3.0

func (s *SanctionClient) IterateMonitoringAlerts(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateMonitoringAlerts yields every monitoring alert, page by page.

func (*SanctionClient) IterateMonitoringMatches added in v1.3.0

func (s *SanctionClient) IterateMonitoringMatches(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateMonitoringMatches yields every monitoring match, page by page.

func (*SanctionClient) IterateScreeningHistory added in v1.3.0

func (s *SanctionClient) IterateScreeningHistory(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

IterateScreeningHistory yields every earlier screening, page by page.

func (*SanctionClient) ListBlacklistEntries added in v1.3.0

func (s *SanctionClient) ListBlacklistEntries(ctx context.Context, filters map[string]any) (*CursorPage, error)

ListBlacklistEntries lists your own deny-list entries (read only with an API key). Filters: limit, cursor.

func (*SanctionClient) ListMonitoredEntities added in v1.3.0

func (s *SanctionClient) ListMonitoredEntities(ctx context.Context, filters map[string]any) (*CursorPage, error)

ListMonitoredEntities lists the monitored subjects. Filters: activeOnly (true by default on the gateway), limit, cursor, includeTotal.

func (*SanctionClient) ListMonitoringAlerts added in v1.3.0

func (s *SanctionClient) ListMonitoringAlerts(ctx context.Context, filters map[string]any) (*CursorPage, error)

ListMonitoringAlerts lists the new-match alerts raised by monitoring. Filters: status (e.g. open), limit, cursor, includeTotal.

func (*SanctionClient) ListMonitoringMatches added in v1.3.0

func (s *SanctionClient) ListMonitoringMatches(ctx context.Context, filters map[string]any) (*CursorPage, error)

ListMonitoringMatches lists the matches raised by monitoring. Filters: status, limit, cursor.

func (*SanctionClient) ListScreeningHistory added in v1.3.0

func (s *SanctionClient) ListScreeningHistory(ctx context.Context, filters map[string]any) (*CursorPage, error)

ListScreeningHistory lists earlier screenings (audit trail), newest first. Filters: limit, cursor. Raw also carries runsToday, reviewDecisions, blockedCount and avgLatencyMs.

func (*SanctionClient) RegisterMonitoring added in v1.3.0

func (s *SanctionClient) RegisterMonitoring(ctx context.Context, request map[string]any) (json.RawMessage, error)

RegisterMonitoring registers a subject for ongoing monitoring and returns {monitoredEntityId}: externalCustomerId, optional subjectType, profileJson, frequency, riskDomainScope. A "profile" member (an object: name, dateOfBirth, country, identifiers …) is sent as profileJson text; pass one of the two.

func (*SanctionClient) ScreenAccount added in v1.3.0

func (s *SanctionClient) ScreenAccount(ctx context.Context, request map[string]any) (json.RawMessage, error)

ScreenAccount screens a bank account / IBAN against your own deny list and account risk data (no list publication): accountValue, accountScheme, optional providerCode, productChannel, customerReference.

func (*SanctionClient) ScreenAdverseMedia added in v1.3.0

func (s *SanctionClient) ScreenAdverseMedia(ctx context.Context, request map[string]any) (json.RawMessage, error)

ScreenAdverseMedia screens adverse media. It runs only when your adverse-media policy is enabled.

func (*SanctionClient) ScreenName added in v1.3.0

func (s *SanctionClient) ScreenName(ctx context.Context, request map[string]any) (json.RawMessage, error)

ScreenName screens a person or organization: name, optional subjectType, country, dateOfBirth, identifiers [{type, value}], riskDomains, mode, threshold, customerReference.

func (*SanctionClient) ScreenPublicProcurementBan added in v1.3.0

func (s *SanctionClient) ScreenPublicProcurementBan(ctx context.Context, request map[string]any) (json.RawMessage, error)

ScreenPublicProcurementBan screens public procurement debarment lists by entityName, tckn or vkn (at least one). The Turkish procurement list is not published, so coverageStatus is PARTIAL and uncoveredSources names it: no match is not a clean result for it.

func (*SanctionClient) ScreenTransaction added in v1.3.0

func (s *SanctionClient) ScreenTransaction(ctx context.Context, request map[string]any) (json.RawMessage, error)

ScreenTransaction screens every party and account of a transaction against one list publication; parties [{name, …}] or accounts [{accountType, value, …}] (at least one of them).

func (*SanctionClient) ScreenWallet added in v1.3.0

func (s *SanctionClient) ScreenWallet(ctx context.Context, request map[string]any) (json.RawMessage, error)

ScreenWallet screens a crypto wallet address (exact match against the listed addresses): walletAddress, optional chain, mode, customerReference.

func (*SanctionClient) SearchEntities added in v1.3.0

func (s *SanctionClient) SearchEntities(ctx context.Context, filters map[string]any) (json.RawMessage, error)

SearchEntities searches entities by name. Filters: q, limit.

type SplitListFilters added in v1.3.0

type SplitListFilters struct {
	Status      []string
	Currency    []string
	CreatedFrom string
	CreatedTo   string
	OrderID     string
	OwnerRef    string
	Limit       *int
	After       string
}

SplitListFilters narrows ListSplits. Empty fields are not sent. Status (SplitPaymentStatus* values) and Currency take 1–20 values each and are sent as repeated parameters; CreatedFrom/CreatedTo are ISO 8601 date-times; Limit, when set, is 1–100; After is the pageInfo.endCursor of the previous page.

type StoreCardRequest added in v1.3.0

type StoreCardRequest struct {
	Card        map[string]any `json:"card"`
	CardUserKey string         `json:"cardUserKey"`
	CallbackURL string         `json:"callbackUrl"`
	Currency    string         `json:"currency,omitempty"`
}

StoreCardRequest is the body of StoreCard (POST /payments/cards): the card is verified and stored under CardUserKey, your stable identifier of the buyer. Card holds the gateway card fields (cardHolderName, cardNumber, expireMonth, expireYear, cvcNumber, ...). Card values are sent to Lunixi only; never log the request. CallbackURL receives the buyer after a 3D Secure verification.

type SubscriptionAddons added in v1.3.0

type SubscriptionAddons struct {
	// contains filtered or unexported fields
}

SubscriptionAddons — add-ons.

func (*SubscriptionAddons) Create added in v1.3.0

func (a *SubscriptionAddons) Create(ctx context.Context, addon map[string]any) (json.RawMessage, error)

Create creates an add-on.

func (*SubscriptionAddons) Deactivate added in v1.3.0

func (a *SubscriptionAddons) Deactivate(ctx context.Context, addonID string) (json.RawMessage, error)

Deactivate deactivates an add-on.

func (*SubscriptionAddons) List added in v1.3.0

func (a *SubscriptionAddons) List(ctx context.Context, filters map[string]any) (*CursorPage, error)

List lists add-ons; any text, integer or boolean filter is passed on.

func (*SubscriptionAddons) Update added in v1.3.0

func (a *SubscriptionAddons) Update(ctx context.Context, addonID string, changes map[string]any) (json.RawMessage, error)

Update changes an add-on.

type SubscriptionCards added in v1.3.0

type SubscriptionCards struct {
	// contains filtered or unexported fields
}

SubscriptionCards — saved cards for automatic charges. A card is added from the checkout SDK's paymentMethodToken; a card number or security code is never sent (those fields are refused, and the refusal names only the field).

func (*SubscriptionCards) Add added in v1.3.0

func (c *SubscriptionCards) Add(ctx context.Context, request map[string]any, idempotencyKey string) (json.RawMessage, error)

Add saves a card: customerId, paymentMethodToken, optional brand, last4, bin, expireMonth, expireYear, cardholderName, isDefault, nickname, verificationMode (SubscriptionCardVerificationMode*), supportedCurrencies. idempotencyKey "" sends none.

func (*SubscriptionCards) Deactivate added in v1.3.0

func (c *SubscriptionCards) Deactivate(ctx context.Context, cardID, reason string) (json.RawMessage, error)

Deactivate deactivates a card; reason "" sends no body.

func (*SubscriptionCards) Get added in v1.3.0

func (c *SubscriptionCards) Get(ctx context.Context, cardID string) (json.RawMessage, error)

Get reads one saved card.

func (*SubscriptionCards) Iterate added in v1.3.0

func (c *SubscriptionCards) Iterate(ctx context.Context, customerID string, filters map[string]any) iter.Seq2[json.RawMessage, error]

Iterate yields every card of a customer.

func (*SubscriptionCards) List added in v1.3.0

func (c *SubscriptionCards) List(ctx context.Context, customerID string, filters map[string]any) (*CursorPage, error)

List lists a customer's cards. Filters: includeInactive (false when left out), pageSize, pageToken.

func (*SubscriptionCards) SetDefault added in v1.3.0

func (c *SubscriptionCards) SetDefault(ctx context.Context, cardID string) (json.RawMessage, error)

SetDefault makes a card the customer's default card.

func (*SubscriptionCards) Update added in v1.3.0

func (c *SubscriptionCards) Update(ctx context.Context, cardID string, changes map[string]any) (json.RawMessage, error)

Update changes card metadata (label, expiry, billing …); never a card number.

func (*SubscriptionCards) Verify added in v1.3.0

func (c *SubscriptionCards) Verify(ctx context.Context, cardID string, options map[string]any) (json.RawMessage, error)

Verify verifies a saved card (a small authorisation or a 3-D check); options as the gateway documents them, nil for none.

type SubscriptionCustomers added in v1.3.0

type SubscriptionCustomers struct {
	// contains filtered or unexported fields
}

SubscriptionCustomers — customers, upserted by your own externalId (one stable customer per user).

func (*SubscriptionCustomers) AdjustCredit added in v1.3.0

func (c *SubscriptionCustomers) AdjustCredit(ctx context.Context, customerID string, adjustment map[string]any) (json.RawMessage, error)

AdjustCredit grants or deducts credit: amountMinor (minor-unit string), currency, reason, type …

func (*SubscriptionCustomers) Archive added in v1.3.0

func (c *SubscriptionCustomers) Archive(ctx context.Context, customerID string) (json.RawMessage, error)

Archive archives a customer.

func (*SubscriptionCustomers) CreditBalance added in v1.3.0

func (c *SubscriptionCustomers) CreditBalance(ctx context.Context, customerID string) (json.RawMessage, error)

CreditBalance reads the credit balance of a customer.

func (*SubscriptionCustomers) Get added in v1.3.0

func (c *SubscriptionCustomers) Get(ctx context.Context, customerID string) (json.RawMessage, error)

Get reads one customer.

func (*SubscriptionCustomers) GetByExternalID added in v1.3.0

func (c *SubscriptionCustomers) GetByExternalID(ctx context.Context, externalID string) (json.RawMessage, error)

GetByExternalID finds a customer by your own externalId (letters, digits and _ . : - only).

func (*SubscriptionCustomers) Iterate added in v1.3.0

func (c *SubscriptionCustomers) Iterate(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

Iterate yields every customer matching the filters.

func (*SubscriptionCustomers) List added in v1.3.0

func (c *SubscriptionCustomers) List(ctx context.Context, filters map[string]any) (*CursorPage, error)

List lists customers. Filters: search, includeArchived, pageSize, pageToken.

func (*SubscriptionCustomers) Upsert added in v1.3.0

func (c *SubscriptionCustomers) Upsert(ctx context.Context, request map[string]any, idempotencyKey string) (json.RawMessage, error)

Upsert creates or updates a customer: externalId, optional email, name, phone, locale, metadata. idempotencyKey "" sends none.

type SubscriptionFeatures added in v1.3.0

type SubscriptionFeatures struct {
	// contains filtered or unexported fields
}

SubscriptionFeatures — entitlement features.

func (*SubscriptionFeatures) Create added in v1.3.0

func (f *SubscriptionFeatures) Create(ctx context.Context, feature map[string]any) (json.RawMessage, error)

Create creates a feature.

func (*SubscriptionFeatures) Delete added in v1.3.0

func (f *SubscriptionFeatures) Delete(ctx context.Context, featureID string) (json.RawMessage, error)

Delete deletes a feature.

func (*SubscriptionFeatures) Get added in v1.3.0

func (f *SubscriptionFeatures) Get(ctx context.Context, featureID string) (json.RawMessage, error)

Get reads one feature.

func (*SubscriptionFeatures) List added in v1.3.0

func (f *SubscriptionFeatures) List(ctx context.Context, filters map[string]any) (*CursorPage, error)

List lists features; any text, integer or boolean filter is passed on.

func (*SubscriptionFeatures) Translations added in v1.3.0

func (f *SubscriptionFeatures) Translations(ctx context.Context, featureID string) (json.RawMessage, error)

Translations reads the translations of a feature.

func (*SubscriptionFeatures) Update added in v1.3.0

func (f *SubscriptionFeatures) Update(ctx context.Context, featureID string, changes map[string]any) (json.RawMessage, error)

Update changes a feature.

func (*SubscriptionFeatures) UpsertTranslation added in v1.3.0

func (f *SubscriptionFeatures) UpsertTranslation(ctx context.Context, featureID, locale string, translation map[string]any) (json.RawMessage, error)

UpsertTranslation writes the translation of a feature for one locale.

type SubscriptionInvoices added in v1.3.0

type SubscriptionInvoices struct {
	// contains filtered or unexported fields
}

SubscriptionInvoices — invoices: billing history, void and charge retry.

func (*SubscriptionInvoices) Get added in v1.3.0

func (i *SubscriptionInvoices) Get(ctx context.Context, invoiceID string) (json.RawMessage, error)

Get reads one invoice.

func (*SubscriptionInvoices) Iterate added in v1.3.0

func (i *SubscriptionInvoices) Iterate(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

Iterate yields every invoice matching the filters.

func (*SubscriptionInvoices) List added in v1.3.0

func (i *SubscriptionInvoices) List(ctx context.Context, filters map[string]any) (*CursorPage, error)

List lists invoices. Filters: subscriptionId, status, pageSize, pageToken.

func (*SubscriptionInvoices) RetryCharge added in v1.3.0

func (i *SubscriptionInvoices) RetryCharge(ctx context.Context, invoiceID, idempotencyKey string) (json.RawMessage, error)

RetryCharge retries the charge of an open invoice; idempotencyKey "" sends none.

func (*SubscriptionInvoices) Void added in v1.3.0

func (i *SubscriptionInvoices) Void(ctx context.Context, invoiceID, reason string) (json.RawMessage, error)

Void voids an invoice; reason "" sends no body.

type SubscriptionPlans added in v1.3.0

type SubscriptionPlans struct {
	// contains filtered or unexported fields
}

SubscriptionPlans — plans, the templates a subscription is created against.

func (*SubscriptionPlans) Archive added in v1.3.0

func (p *SubscriptionPlans) Archive(ctx context.Context, planID string) (json.RawMessage, error)

Archive archives a plan.

func (*SubscriptionPlans) Create added in v1.3.0

func (p *SubscriptionPlans) Create(ctx context.Context, request map[string]any, idempotencyKey string) (json.RawMessage, error)

Create creates a plan: productId, code, name, price (minor-unit string, "0" for a free plan), currency, billing {frequency, interval?, byMonthDay?, byWeekDay?, timezone?, lastDayOfMonthFix?, count?} (interval defaults to 1), optional description, trialPeriodDays, maxDunningAttempts, dunningScheduleDays, gracePeriodDays, metadata. idempotencyKey "" sends none.

func (*SubscriptionPlans) Get added in v1.3.0

func (p *SubscriptionPlans) Get(ctx context.Context, planID string) (json.RawMessage, error)

Get reads one plan.

func (*SubscriptionPlans) Iterate added in v1.3.0

func (p *SubscriptionPlans) Iterate(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

Iterate yields every plan matching the filters.

func (*SubscriptionPlans) List added in v1.3.0

func (p *SubscriptionPlans) List(ctx context.Context, filters map[string]any) (*CursorPage, error)

List lists plans. Filters: productId, includeArchived, pageSize, pageToken.

func (*SubscriptionPlans) Translations added in v1.3.0

func (p *SubscriptionPlans) Translations(ctx context.Context, planID string) (json.RawMessage, error)

Translations reads the translations of a plan.

func (*SubscriptionPlans) Update added in v1.3.0

func (p *SubscriptionPlans) Update(ctx context.Context, planID string, changes map[string]any) (json.RawMessage, error)

Update changes a plan (price, billing, metadata …); a price is a minor-unit string.

func (*SubscriptionPlans) UpsertTranslation added in v1.3.0

func (p *SubscriptionPlans) UpsertTranslation(ctx context.Context, planID, locale string, translation map[string]any) (json.RawMessage, error)

UpsertTranslation writes the translation of a plan for one locale.

type SubscriptionPortal added in v1.3.0

type SubscriptionPortal struct {
	// contains filtered or unexported fields
}

SubscriptionPortal — the customer portal. Embedded: CreateSdkSession mints an origin-bound session for the browser portal SDK (origin must be allow-listed). Hosted: CreatePortalLink returns a link whose token opens the hosted portal (SubscriptionPortalURL); the customer verifies with a one-time code.

func (p *SubscriptionPortal) CreatePortalLink(ctx context.Context, customerID string, options map[string]any) (json.RawMessage, error)

CreatePortalLink creates a hosted portal link for a customer. options: allowedPlanIds, defaultPlanId, permissions, sessionDurationMinutes, expiresAt, requireEmailVerification …

func (*SubscriptionPortal) CreateSdkSession added in v1.3.0

func (p *SubscriptionPortal) CreateSdkSession(ctx context.Context, customerID, origin string, options SubscriptionPortalSessionOptions) (json.RawMessage, error)

CreateSdkSession mints a portal SDK session. The gateway answers at the envelope root; the result merges the root and data ({portalToken, sessionProof, proofNonce, proofExpiresAt, …}, proofNonce and proofExpiresAt read from nonce and expiresAt when only those are sent). Hand those four to the browser.

func (p *SubscriptionPortal) GetLink(ctx context.Context, linkID string) (json.RawMessage, error)

GetLink reads one portal link.

func (*SubscriptionPortal) GetSettings added in v1.3.0

func (p *SubscriptionPortal) GetSettings(ctx context.Context) (json.RawMessage, error)

GetSettings reads the portal settings (branding, allowed origins).

func (*SubscriptionPortal) LinkActivity added in v1.3.0

func (p *SubscriptionPortal) LinkActivity(ctx context.Context, linkID string) (json.RawMessage, error)

LinkActivity reads the activity of a portal link.

func (p *SubscriptionPortal) ListLinks(ctx context.Context, filters map[string]any) (*CursorPage, error)

ListLinks lists portal links. Filters: customerId, status, limit.

func (p *SubscriptionPortal) RevokeLink(ctx context.Context, linkID, reason string) (json.RawMessage, error)

RevokeLink revokes a portal link; reason "" sends no body.

func (*SubscriptionPortal) SendInvite added in v1.3.0

func (p *SubscriptionPortal) SendInvite(ctx context.Context, invite map[string]any) (json.RawMessage, error)

SendInvite emails a portal invite: customerId, optional email, allowedPlanIds …

func (p *SubscriptionPortal) UpdateLink(ctx context.Context, linkID string, changes map[string]any) (json.RawMessage, error)

UpdateLink changes a portal link.

func (*SubscriptionPortal) UpdateSettings added in v1.3.0

func (p *SubscriptionPortal) UpdateSettings(ctx context.Context, settings map[string]any) (json.RawMessage, error)

UpdateSettings writes the portal settings.

type SubscriptionPortalSessionOptions added in v1.3.0

type SubscriptionPortalSessionOptions struct {
	// SdkMode is a SubscriptionPortalSdkMode* value; "" sends none.
	SdkMode string
	// PortalLinkID binds the session to a portal link; "" sends none.
	PortalLinkID string
}

SubscriptionPortalSessionOptions are the optional fields of a portal SDK session.

type SubscriptionProducts added in v1.3.0

type SubscriptionProducts struct {
	// contains filtered or unexported fields
}

SubscriptionProducts — catalog products (groups of plans).

func (*SubscriptionProducts) Archive added in v1.3.0

func (p *SubscriptionProducts) Archive(ctx context.Context, productID string) (json.RawMessage, error)

Archive archives a catalog product.

func (*SubscriptionProducts) Create added in v1.3.0

func (p *SubscriptionProducts) Create(ctx context.Context, product map[string]any) (json.RawMessage, error)

Create creates a catalog product.

func (*SubscriptionProducts) Get added in v1.3.0

func (p *SubscriptionProducts) Get(ctx context.Context, productID string) (json.RawMessage, error)

Get reads one catalog product.

func (*SubscriptionProducts) Iterate added in v1.3.0

func (p *SubscriptionProducts) Iterate(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

Iterate yields every catalog product matching the filters.

func (*SubscriptionProducts) List added in v1.3.0

func (p *SubscriptionProducts) List(ctx context.Context, filters map[string]any) (*CursorPage, error)

List lists catalog products. Filters: limit, cursor, active.

func (*SubscriptionProducts) Translations added in v1.3.0

func (p *SubscriptionProducts) Translations(ctx context.Context, productID string) (json.RawMessage, error)

Translations reads the translations of a catalog product.

func (*SubscriptionProducts) Update added in v1.3.0

func (p *SubscriptionProducts) Update(ctx context.Context, productID string, changes map[string]any) (json.RawMessage, error)

Update changes a catalog product.

func (*SubscriptionProducts) UpsertTranslation added in v1.3.0

func (p *SubscriptionProducts) UpsertTranslation(ctx context.Context, productID, locale string, translation map[string]any) (json.RawMessage, error)

UpsertTranslation writes the translation of a catalog product for one locale.

type SubscriptionUsage added in v1.3.0

type SubscriptionUsage struct {
	// contains filtered or unexported fields
}

SubscriptionUsage — metered usage and entitlement checks.

func (*SubscriptionUsage) CheckEntitlement added in v1.3.0

func (u *SubscriptionUsage) CheckEntitlement(ctx context.Context, check map[string]any) (json.RawMessage, error)

CheckEntitlement reports whether the customer is entitled or has quota left: customerId or subscriptionId, featureKey, optional requested …

func (*SubscriptionUsage) Record added in v1.3.0

func (u *SubscriptionUsage) Record(ctx context.Context, usage map[string]any) (json.RawMessage, error)

Record records a metered-usage event: customerId or subscriptionId, featureKey, quantity, optional timestamp, idempotencyKey …

type SubscriptionsClient added in v1.3.0

type SubscriptionsClient struct {
	Plans     *SubscriptionPlans
	Customers *SubscriptionCustomers
	Cards     *SubscriptionCards
	Invoices  *SubscriptionInvoices
	Portal    *SubscriptionPortal
	Products  *SubscriptionProducts
	Features  *SubscriptionFeatures
	Addons    *SubscriptionAddons
	Usage     *SubscriptionUsage
	// contains filtered or unexported fields
}

SubscriptionsClient — subscriptions (/api/v1/subscriptions/*), reached as Client.Subscriptions. The related resources hang off Plans, Customers, Cards, Invoices, Portal, Products, Features, Addons and Usage.

The calls carry the access token minted from your key, without the per-request signature. Creating a subscription requires an Idempotency-Key (reuse it when retrying the same subscription; it is sent in the body too); plan, customer, card, plan-change and charge-retry writes accept one. Keys are 1–200 printable ASCII characters.

Requests and filters are maps with the gateway's field names, checked against SubscriptionRoutes before anything is sent: an unknown field or filter, a missing required field, a value outside its set or a missing key returns ErrConfiguration, which names the field and never its value. Amounts are canonical minor-unit strings ("9900" is 99.00 TRY; "0" is a free plan), checked in bodies, filters and answers.

Single records are returned as the envelope's data. The subscription, plan, customer, card, invoice and audit-log lists return CursorPage with the nextPageToken in NextCursor (send it back as pageToken) and PageSize; the other lists return CursorPage with the cursor of the answer.

func (*SubscriptionsClient) AuditLogs added in v1.3.0

func (s *SubscriptionsClient) AuditLogs(ctx context.Context, subscriptionID string, filters map[string]any) (*CursorPage, error)

AuditLogs lists the audit trail of a subscription. Filters: limit, pageToken.

func (*SubscriptionsClient) Cancel added in v1.3.0

func (s *SubscriptionsClient) Cancel(ctx context.Context, subscriptionID string, atPeriodEnd bool, reason string) (json.RawMessage, error)

Cancel cancels a subscription now, or at the period end with atPeriodEnd; reason "" sends none.

func (*SubscriptionsClient) ChangePlan added in v1.3.0

func (s *SubscriptionsClient) ChangePlan(ctx context.Context, subscriptionID string, request map[string]any, idempotencyKey string) (json.RawMessage, error)

ChangePlan moves a subscription to another plan: newPlanId, optional behavior (SubscriptionPlanChangeBehavior*, case-insensitive), reason. An Idempotency-Key (the argument or the request's idempotencyKey) is sent in the header and the body.

func (*SubscriptionsClient) Create added in v1.3.0

func (s *SubscriptionsClient) Create(ctx context.Context, request map[string]any, idempotencyKey string) (json.RawMessage, error)

Create creates a subscription: customerId, planId, optional paymentCardId, paymentMethodId, collectionMethod, priceUpdatePolicy, entitlementPolicy, billingTimezone, startsAt, chargeOnCreate, billingCycleAnchorOverride, skipTrial, metadata. The Idempotency-Key is required (the argument or the request's idempotencyKey; both given, they must agree) and is sent in the header and the body.

func (*SubscriptionsClient) Get added in v1.3.0

func (s *SubscriptionsClient) Get(ctx context.Context, subscriptionID string) (json.RawMessage, error)

Get reads one subscription.

func (*SubscriptionsClient) Iterate added in v1.3.0

func (s *SubscriptionsClient) Iterate(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

Iterate yields every subscription matching the filters, page by page.

func (*SubscriptionsClient) List added in v1.3.0

func (s *SubscriptionsClient) List(ctx context.Context, filters map[string]any) (*CursorPage, error)

List lists subscriptions. Filters: customerId, status, pageSize, pageToken.

func (*SubscriptionsClient) Pause added in v1.3.0

func (s *SubscriptionsClient) Pause(ctx context.Context, subscriptionID, resumeAt string) (json.RawMessage, error)

Pause pauses billing; resumeAt (ISO-8601) resumes it automatically, "" sends no body.

func (*SubscriptionsClient) Resume added in v1.3.0

func (s *SubscriptionsClient) Resume(ctx context.Context, subscriptionID string) (json.RawMessage, error)

Resume resumes a paused subscription.

type WalletAccounts added in v1.3.0

type WalletAccounts struct {
	// contains filtered or unexported fields
}

WalletAccounts — wallets and their currency accounts.

func (*WalletAccounts) CreateAccount added in v1.3.0

func (a *WalletAccounts) CreateAccount(ctx context.Context, walletID, currency, idempotencyKey string) (json.RawMessage, error)

CreateAccount adds a currency account to a wallet. The key is required.

func (*WalletAccounts) Lookup added in v1.3.0

func (a *WalletAccounts) Lookup(ctx context.Context, request map[string]any) (json.RawMessage, error)

Lookup resolves a wallet number or phone (programId, phone, walletNo) to {exists, walletNo, maskedName} before a transfer.

type WalletBulkPayouts added in v1.3.0

type WalletBulkPayouts struct {
	// contains filtered or unexported fields
}

WalletBulkPayouts — bulk payouts, maker-checker: the approver must be a DIFFERENT key than the creator (the principal is the signing key id). Creating needs wallet:bulk:create; submit, approve, process and retry-failed need wallet:bulk:approve — so the maker key holds both, the checker key holds wallet:bulk:approve.

func (*WalletBulkPayouts) Approve added in v1.3.0

func (b *WalletBulkPayouts) Approve(ctx context.Context, batchID string, approve bool, reason string) (json.RawMessage, error)

Approve approves a bulk payout; approve false declines it with reason. reason "" sends none.

func (*WalletBulkPayouts) Create added in v1.3.0

func (b *WalletBulkPayouts) Create(ctx context.Context, request map[string]any, idempotencyKey string) (json.RawMessage, error)

Create creates a bulk payout (programId, sourceWalletAccountId, currency, items [{targetType, targetRef, amount, beneficiaryName?}], optional reason). The key is required.

func (*WalletBulkPayouts) Get added in v1.3.0

func (b *WalletBulkPayouts) Get(ctx context.Context, batchID string) (json.RawMessage, error)

Get reads one bulk payout.

func (*WalletBulkPayouts) List added in v1.3.0

func (b *WalletBulkPayouts) List(ctx context.Context, filters map[string]any) (*CursorPage, error)

List lists bulk payouts. Filters: programId, status, limit.

func (*WalletBulkPayouts) ListItems added in v1.3.0

func (b *WalletBulkPayouts) ListItems(ctx context.Context, batchID string, filters map[string]any) (*CursorPage, error)

ListItems lists the items of a bulk payout. Filters: status, limit.

func (*WalletBulkPayouts) Process added in v1.3.0

func (b *WalletBulkPayouts) Process(ctx context.Context, batchID string) (json.RawMessage, error)

Process starts paying out an approved bulk payout.

func (*WalletBulkPayouts) Reject added in v1.3.0

func (b *WalletBulkPayouts) Reject(ctx context.Context, batchID, reason string) (json.RawMessage, error)

Reject rejects a bulk payout; reason "" sends none.

func (*WalletBulkPayouts) RetryFailed added in v1.3.0

func (b *WalletBulkPayouts) RetryFailed(ctx context.Context, batchID string) (json.RawMessage, error)

RetryFailed retries the failed items of a bulk payout.

func (*WalletBulkPayouts) Submit added in v1.3.0

func (b *WalletBulkPayouts) Submit(ctx context.Context, batchID string) (json.RawMessage, error)

Submit submits a bulk payout for approval.

type WalletClient added in v1.3.0

type WalletClient struct {
	Programs    *WalletPrograms
	EndUsers    *WalletEndUsers
	Wallets     *WalletAccounts
	Deposits    *WalletDeposits
	Corporate   *WalletCorporate
	Fees        *WalletFees
	Transfers   *WalletTransfers
	Withdrawals *WalletWithdrawals
	Operations  *WalletOperations
	Topups      *WalletTopups
	Payments    *WalletPayments
	QR          *WalletQR
	BulkPayouts *WalletBulkPayouts
	// contains filtered or unexported fields
}

WalletClient — the merchant server-to-server surface of the closed-loop wallet (/api/v1/wallet/*, product WALLET_SERVICE).

Every call is signed; the merchant, its programs and its end users come from the signing key. The key also needs the wallet permission behind the route (otherwise 403 WALLET_INSUFFICIENT_SCOPE): wallet:*:read for reads, wallet:program|enduser|limit|fee:manage for set-up, wallet:operation:intervene for moving money inside the wallet, wallet:bank-payout:operate for IBAN transfers and bank withdrawals, wallet:qr:manage, wallet:bulk:create, wallet:bulk:approve and wallet:enduser:kyc-override for the KYC level.

Requests and filters are maps with the gateway's field names; they are checked against WalletRoutes before anything is sent: an unknown field, a missing required field, an amount that is not minor-unit digit text, or a missing Idempotency-Key returns ErrConfiguration. Amounts are minor units as text ("12550" is 125.50 TRY). A call that moves money for an end user names that end user (endUserId, buyerEndUserId); the source account must belong to them or the answer is 404 WALLET_NOT_FOUND.

Single records are returned as the envelope's data; lists as CursorPage.

func (*WalletClient) Ping added in v1.3.0

func (w *WalletClient) Ping(ctx context.Context) (json.RawMessage, error)

Ping checks that the key reaches the wallet (signature, product and a wallet:*:manage permission).

type WalletCorporate added in v1.3.0

type WalletCorporate struct {
	// contains filtered or unexported fields
}

WalletCorporate — corporate accounts and their employees.

func (*WalletCorporate) Create added in v1.3.0

func (c *WalletCorporate) Create(ctx context.Context, request map[string]any, idempotencyKey string) (json.RawMessage, error)

Create creates a corporate account (programId, code, name, ownerEndUserId, optional fundingCurrency). The key is required.

func (*WalletCorporate) ImportEmployees added in v1.3.0

func (c *WalletCorporate) ImportEmployees(ctx context.Context, corporateAccountID string, rows []map[string]any, idempotencyKey string) (json.RawMessage, error)

ImportEmployees imports up to 1000 employees at once ({phone, displayName, externalCustomerId, kycRef} rows); all or nothing (a 422 writes nothing). The key is required.

func (*WalletCorporate) Iterate added in v1.3.0

func (c *WalletCorporate) Iterate(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

Iterate yields every corporate account matching the filters.

func (*WalletCorporate) List added in v1.3.0

func (c *WalletCorporate) List(ctx context.Context, filters map[string]any) (*CursorPage, error)

List lists corporate accounts. Filters: programId, status, limit, cursor.

func (*WalletCorporate) OffboardEmployees added in v1.3.0

func (c *WalletCorporate) OffboardEmployees(ctx context.Context, corporateAccountID string, rows []map[string]any, reason, idempotencyKey string) (json.RawMessage, error)

OffboardEmployees offboards employees ({endUserId} or {externalCustomerId} rows); reason "" sends none. The key is required.

type WalletDeposits added in v1.3.0

type WalletDeposits struct {
	// contains filtered or unexported fields
}

WalletDeposits — bank transfer details the end user pays into to top up.

func (*WalletDeposits) CreateInstruction added in v1.3.0

func (d *WalletDeposits) CreateInstruction(ctx context.Context, endUserID string, request map[string]any) (json.RawMessage, error)

CreateInstruction creates a deposit instruction (walletAccountId, optional currency).

func (*WalletDeposits) ListInstructions added in v1.3.0

func (d *WalletDeposits) ListInstructions(ctx context.Context, endUserID string) (json.RawMessage, error)

ListInstructions lists the end user's deposit instructions.

func (*WalletDeposits) SimulateInboundCredit added in v1.3.0

func (d *WalletDeposits) SimulateInboundCredit(ctx context.Context, request map[string]any) (json.RawMessage, error)

SimulateInboundCredit books an incoming bank transfer as the bank rail would. Test environment only.

type WalletEndUsers added in v1.3.0

type WalletEndUsers struct {
	// contains filtered or unexported fields
}

WalletEndUsers — end users and their wallets, balances, limits and KYC level.

func (*WalletEndUsers) Create added in v1.3.0

func (e *WalletEndUsers) Create(ctx context.Context, request map[string]any, idempotencyKey string) (json.RawMessage, error)

Create creates an end user and their default wallet (programId, accountType, phone, optional externalCustomerId, kycRef, kycLevelCache, displayName, corporateAccountId, defaultCurrency). The key is required.

func (*WalletEndUsers) CreateWallet added in v1.3.0

func (e *WalletEndUsers) CreateWallet(ctx context.Context, endUserID string, request map[string]any, idempotencyKey string) (json.RawMessage, error)

CreateWallet adds a wallet to an end user (optional name, currencies). The key is required.

func (*WalletEndUsers) Freeze added in v1.3.0

func (e *WalletEndUsers) Freeze(ctx context.Context, endUserID, reason, idempotencyKey string) (json.RawMessage, error)

Freeze freezes an end user; reason "" sends none. The key is required.

func (*WalletEndUsers) Get added in v1.3.0

func (e *WalletEndUsers) Get(ctx context.Context, endUserID string) (json.RawMessage, error)

Get reads one end user.

func (*WalletEndUsers) GetBalances added in v1.3.0

func (e *WalletEndUsers) GetBalances(ctx context.Context, endUserID string) (json.RawMessage, error)

GetBalances reads the balances of an end user's accounts.

func (*WalletEndUsers) GetByExternalID added in v1.3.0

func (e *WalletEndUsers) GetByExternalID(ctx context.Context, externalCustomerID, programID string) (json.RawMessage, error)

GetByExternalID finds an end user by your own customer id; programID "" searches every program.

func (*WalletEndUsers) GetKycLevel added in v1.3.0

func (e *WalletEndUsers) GetKycLevel(ctx context.Context, endUserID string) (json.RawMessage, error)

GetKycLevel reads the end user's KYC level.

func (*WalletEndUsers) GetLimits added in v1.3.0

func (e *WalletEndUsers) GetLimits(ctx context.Context, endUserID string, filters map[string]any) (json.RawMessage, error)

GetLimits reads limit usage per operation type; the operationType and currency filters narrow the answer.

func (*WalletEndUsers) Iterate added in v1.3.0

func (e *WalletEndUsers) Iterate(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

Iterate yields every end user matching the filters, page by page.

func (*WalletEndUsers) List added in v1.3.0

func (e *WalletEndUsers) List(ctx context.Context, filters map[string]any) (*CursorPage, error)

List lists end users. Filters: programId, accountType, status, corporateAccountId, merchantCategoryState, limit, cursor.

func (*WalletEndUsers) UpdateKycLevel added in v1.3.0

func (e *WalletEndUsers) UpdateKycLevel(ctx context.Context, endUserID string, request map[string]any, idempotencyKey string) (json.RawMessage, error)

UpdateKycLevel records the KYC level from your own verification (kycLevel, sourceRef = your KYC session id, optional externalCustomerId, programId, reason, effectiveAt, expectedCurrentLevel). The key is required.

type WalletFees added in v1.3.0

type WalletFees struct {
	// contains filtered or unexported fields
}

WalletFees — fee quotes.

func (*WalletFees) Quote added in v1.3.0

func (f *WalletFees) Quote(ctx context.Context, request map[string]any) (json.RawMessage, error)

Quote returns the fee, tax and total charge an operation would cost (programId, operationType, currency, amount, optional at).

type WalletOperations added in v1.3.0

type WalletOperations struct {
	// contains filtered or unexported fields
}

WalletOperations — every money movement of the wallet.

func (*WalletOperations) Get added in v1.3.0

func (o *WalletOperations) Get(ctx context.Context, operationID string) (json.RawMessage, error)

Get reads an operation: {operation, history}.

func (*WalletOperations) GetReceipt added in v1.3.0

func (o *WalletOperations) GetReceipt(ctx context.Context, operationID string) (json.RawMessage, error)

GetReceipt reads the receipt of an operation.

func (*WalletOperations) Iterate added in v1.3.0

func (o *WalletOperations) Iterate(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

Iterate yields every operation matching the filters.

func (*WalletOperations) List added in v1.3.0

func (o *WalletOperations) List(ctx context.Context, filters map[string]any) (*CursorPage, error)

List lists operations. Filters: endUserId, walletAccountId, status, operationType, destinationWalletAccountId, limit, cursor.

type WalletPayments added in v1.3.0

type WalletPayments struct {
	// contains filtered or unexported fields
}

WalletPayments — the end user pays the merchant. The creditor is the wallet terminal bound to the signing key (WALLET_TERMINAL_* 403 without one); a businessAccountId in the body is refused.

func (*WalletPayments) Approve added in v1.3.0

func (p *WalletPayments) Approve(ctx context.Context, operationID string, request map[string]any, idempotencyKey string) (json.RawMessage, error)

Approve approves a payment request (buyerEndUserId, integrityHash, nonce, optional otpCode, trustedActionToken). The key is required.

func (*WalletPayments) Collect added in v1.3.0

func (p *WalletPayments) Collect(ctx context.Context, request map[string]any, idempotencyKey string) (json.RawMessage, error)

Collect collects with the payment code the buyer shows (code, amount, currency, optional orderRef, paymentPurpose, locale). The key is required.

func (*WalletPayments) Get added in v1.3.0

func (p *WalletPayments) Get(ctx context.Context, operationID string) (json.RawMessage, error)

Get reads a payment: {operation, history}.

func (*WalletPayments) GetCommission added in v1.3.0

func (p *WalletPayments) GetCommission(ctx context.Context, businessAccountID string) (json.RawMessage, error)

GetCommission reads the commission of a business account.

func (*WalletPayments) Request added in v1.3.0

func (p *WalletPayments) Request(ctx context.Context, request map[string]any, idempotencyKey string) (json.RawMessage, error)

Request asks the buyer (by wallet number or phone) to pay; approve it with Approve. The key is required.

type WalletPrograms added in v1.3.0

type WalletPrograms struct {
	// contains filtered or unexported fields
}

WalletPrograms — the wallet programs of the signing merchant.

func (*WalletPrograms) ListMine added in v1.3.0

func (p *WalletPrograms) ListMine(ctx context.Context) (*CursorPage, error)

ListMine lists the wallet programs of the signing merchant.

func (*WalletPrograms) SetCollectionAnchor added in v1.3.0

func (p *WalletPrograms) SetCollectionAnchor(ctx context.Context, programID string, request map[string]any) (json.RawMessage, error)

SetCollectionAnchor sets the end user whose wallet collects the program's merchant payments (collectionEndUserId, reason, expectedVersion). Leaving collectionEndUserId out clears the anchor.

type WalletQR added in v1.3.0

type WalletQR struct {
	// contains filtered or unexported fields
}

WalletQR — wallet QR codes.

func (*WalletQR) Create added in v1.3.0

func (q *WalletQR) Create(ctx context.Context, request map[string]any, idempotencyKey string) (json.RawMessage, error)

Create creates a QR code (qrType, currency, optional targetEndUserId, targetExternalCustomerId, programId, amount, expiresInSeconds, metadata). Static codes carry no amount; dynamic ones require it. The key is required.

func (*WalletQR) Get added in v1.3.0

func (q *WalletQR) Get(ctx context.Context, qrID string) (json.RawMessage, error)

Get reads one QR code.

func (*WalletQR) Image added in v1.3.0

func (q *WalletQR) Image(ctx context.Context, qrID, format string, scale int) (*Response, error)

Image returns the QR code as an image in Response.Bytes (Response.ContentType says which). format is WalletQRImageFormatSVG (the gateway's default) or WalletQRImageFormatPNG, "" for the default; scale is 1–20, 0 for the default. Error answers are still read as the JSON envelope.

func (*WalletQR) Iterate added in v1.3.0

func (q *WalletQR) Iterate(ctx context.Context, filters map[string]any) iter.Seq2[json.RawMessage, error]

Iterate yields every QR code matching the filters.

func (*WalletQR) List added in v1.3.0

func (q *WalletQR) List(ctx context.Context, filters map[string]any) (*CursorPage, error)

List lists QR codes. Filters: programId, qrType, status, targetEndUserId, limit, cursor.

func (*WalletQR) Parse added in v1.3.0

func (q *WalletQR) Parse(ctx context.Context, payload string) (json.RawMessage, error)

Parse decodes a scanned QR payload.

func (*WalletQR) Revoke added in v1.3.0

func (q *WalletQR) Revoke(ctx context.Context, qrID string) (json.RawMessage, error)

Revoke revokes a QR code.

type WalletTopups added in v1.3.0

type WalletTopups struct {
	// contains filtered or unexported fields
}

WalletTopups — card and agent top-ups.

func (*WalletTopups) Agent added in v1.3.0

func (t *WalletTopups) Agent(ctx context.Context, request map[string]any, idempotencyKey string) (json.RawMessage, error)

Agent books a cash top-up through an agent of the program (agentId, creditWalletAccountId, amount, currency). The key is required.

func (*WalletTopups) Get added in v1.3.0

func (t *WalletTopups) Get(ctx context.Context, operationID string) (json.RawMessage, error)

Get reads a top-up: {operation, history}.

func (*WalletTopups) Refund added in v1.3.0

func (t *WalletTopups) Refund(ctx context.Context, operationID string, request map[string]any) (json.RawMessage, error)

Refund refunds a card top-up to the card (reason, requesterPrincipal, approverPrincipal). Four eyes: approverPrincipal is required and must differ from requesterPrincipal; binding them to two real people is your approval flow's job.

func (*WalletTopups) StartCard added in v1.3.0

func (t *WalletTopups) StartCard(ctx context.Context, request map[string]any, idempotencyKey string) (json.RawMessage, error)

StartCard starts a card top-up. Render checkoutFormContent (or follow redirectUrl / threeDsHtml); the wallet is credited when the payment completes (wallet.topup.completed). The key is required.

type WalletTransfers added in v1.3.0

type WalletTransfers struct {
	// contains filtered or unexported fields
}

WalletTransfers — wallet-to-wallet transfers and transfers to an IBAN.

Money moves in two steps: Initiate… reserves the limit and returns {operationId, integrityHash, nonce, otpRequired, …}; Complete… with the same integrityHash and nonce (and otpCode when otpRequired) commits it. Quote first to show the fee; pass its scheduleVersionId to Initiate… to hold that fee. Complete… puts operationId into the body itself.

func (*WalletTransfers) CompleteW2Iban added in v1.3.0

func (t *WalletTransfers) CompleteW2Iban(ctx context.Context, operationID string, request map[string]any, idempotencyKey string) (json.RawMessage, error)

CompleteW2Iban commits a transfer to an IBAN. The key is required.

func (*WalletTransfers) CompleteW2W added in v1.3.0

func (t *WalletTransfers) CompleteW2W(ctx context.Context, operationID string, request map[string]any, idempotencyKey string) (json.RawMessage, error)

CompleteW2W commits a wallet-to-wallet transfer (endUserId, integrityHash, nonce, optional otpCode, trustedActionToken). The key is required.

func (*WalletTransfers) InitiateW2Iban added in v1.3.0

func (t *WalletTransfers) InitiateW2Iban(ctx context.Context, request map[string]any, idempotencyKey string) (json.RawMessage, error)

InitiateW2Iban starts a transfer to an IBAN. The key is required.

func (*WalletTransfers) InitiateW2W added in v1.3.0

func (t *WalletTransfers) InitiateW2W(ctx context.Context, request map[string]any, idempotencyKey string) (json.RawMessage, error)

InitiateW2W starts a wallet-to-wallet transfer. The key is required.

func (*WalletTransfers) QuoteW2Iban added in v1.3.0

func (t *WalletTransfers) QuoteW2Iban(ctx context.Context, request map[string]any) (json.RawMessage, error)

QuoteW2Iban quotes a transfer to an IBAN.

func (*WalletTransfers) QuoteW2W added in v1.3.0

func (t *WalletTransfers) QuoteW2W(ctx context.Context, request map[string]any) (json.RawMessage, error)

QuoteW2W quotes a wallet-to-wallet transfer.

type WalletWithdrawals added in v1.3.0

type WalletWithdrawals struct {
	// contains filtered or unexported fields
}

WalletWithdrawals — withdrawals to the end user's own bank account (the same two steps as transfers).

func (*WalletWithdrawals) Complete added in v1.3.0

func (w *WalletWithdrawals) Complete(ctx context.Context, operationID string, request map[string]any, idempotencyKey string) (json.RawMessage, error)

Complete commits a bank withdrawal. The key is required.

func (*WalletWithdrawals) Get added in v1.3.0

func (w *WalletWithdrawals) Get(ctx context.Context, operationID string) (json.RawMessage, error)

Get reads a withdrawal: {operation, history}.

func (*WalletWithdrawals) Initiate added in v1.3.0

func (w *WalletWithdrawals) Initiate(ctx context.Context, request map[string]any, idempotencyKey string) (json.RawMessage, error)

Initiate starts a bank withdrawal. The key is required.

func (*WalletWithdrawals) Quote added in v1.3.0

func (w *WalletWithdrawals) Quote(ctx context.Context, request map[string]any) (json.RawMessage, error)

Quote quotes a bank withdrawal.

type WebhookConfig

type WebhookConfig struct {
	Secrets   []string
	Tolerance time.Duration
	Now       func() time.Time
}

WebhookConfig verifies current and previous rotation secrets. Tolerance defaults to five minutes and cannot be disabled in production verification.

type WebhookEvent

type WebhookEvent struct {
	// contains filtered or unexported fields
}

WebhookEvent is an authenticated immutable event. Accessors return copies; unverified events cannot be constructed through exported fields.

func (*WebhookEvent) Data

func (e *WebhookEvent) Data() json.RawMessage

Data returns an independent copy of the signed data object.

func (*WebhookEvent) DecodeData

func (e *WebhookEvent) DecodeData(target any) error

DecodeData decodes the signed data using json.Number for interface values.

func (*WebhookEvent) ID

func (e *WebhookEvent) ID() string

ID is the event ID bound to the raw-body signature.

func (*WebhookEvent) Raw

func (e *WebhookEvent) Raw() []byte

Raw returns an independent copy of the signed body. It can contain customer data: do not log it or persist it outside your data-retention policy.

func (*WebhookEvent) Timestamp

func (e *WebhookEvent) Timestamp() time.Time

Timestamp is the verified signature timestamp.

func (*WebhookEvent) Type

func (e *WebhookEvent) Type() string

Type is read from the signed JSON body, never an unsigned header fallback.

type WebhookVerifier

type WebhookVerifier struct {
	// contains filtered or unexported fields
}

WebhookVerifier authenticates raw request bytes. Verification does not consume an event ID: use a durable transactional ReplayStore before applying financial state, so a crash cannot lose a previously claimed event.

func NewWebhookVerifier

func NewWebhookVerifier(config WebhookConfig) (*WebhookVerifier, error)

NewWebhookVerifier validates webhook configuration without handling data.

func (*WebhookVerifier) Verify

func (v *WebhookVerifier) Verify(raw []byte, headers http.Header) (*WebhookEvent, error)

Verify checks the exact raw bytes, event ID, ISO timestamp, body/header ID agreement, type and rotated v2 signatures. Unknown schemes do not authorize a request. Read the body with an application-level size limit before calling.

func (*WebhookVerifier) VerifyPhysicalPos added in v1.3.0

func (v *WebhookVerifier) VerifyPhysicalPos(raw []byte, headers http.Header) (*PhysicalPosWebhookEvent, error)

VerifyPhysicalPos verifies a webhook (signature, event id, timestamp) with the configured secrets and reads it as a physical POS event. There is no way in without the signature: pass the exact raw body and the request headers. Any failure is ErrWebhook.

func (*WebhookVerifier) VerifyRequest

func (v *WebhookVerifier) VerifyRequest(ctx context.Context, request *http.Request) (*WebhookEvent, error)

VerifyRequest reads an HTTP request with a fixed limit before verification. The caller remains responsible for applying ReplayStore transactionally.

Directories

Path Synopsis
examples
checkout command
This example creates a TEST checkout intent from trusted merchant values.
This example creates a TEST checkout intent from trusted merchant values.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL