palbaseDocs

Payments

Server & Backend SDK

Use createServer().payments in palbase/server (external Node/Bun/Edge servers) or Palbase.payments in palbase/backend (your Palbase-hosted backend machine) to create server-authoritative PaymentIntents, run two-phase wallet holds, issue refunds, manage subscriptions, query audit ledgers, and handle verified payments.* webhooks.

Using Palbase.payments in palbase/backend

Inside a palbase/backend controller or service, Palbase.payments is pre-configured with your environment's secret key, and @On("payments.*") subscribes to verified platform events:

// src/modules/orders/orders.controller.ts
import { Body, Controller, On, Palbase, Post, User, z, type UserT } from "palbase/backend";

const CheckoutBody = z.object({
  orderId: z.string().min(1),
  amount: z.number().int().positive(),
  currency: z.string().length(3).default("TRY"),
});

@Controller("orders")
export class OrdersController {
  @Post("checkout")
  async startCheckout(@User() user: UserT, @Body(CheckoutBody) body: z.infer<typeof CheckoutBody>) {
    const { data: intent } = await Palbase.payments.createIntent({
      headers: { "Idempotency-Key": `order:${body.orderId}` },
      body: {
        customer_id: user.id,
        amount: body.amount,
        currency: body.currency,
        reference: body.orderId,
        description: `Order ${body.orderId}`,
      },
    });
    return { intentId: intent.id, clientSecret: intent.client_secret };
  }

  @On("payments.payment.succeeded")
  async onPaymentSucceeded(event: { data: Record<string, unknown> }) {
    console.log("Fulfill order for payment:", event.data.intent_id);
  }
}

Helper utilities in palbase/server

palbase/server exports ergonomic helpers built directly on createServer().payments:

  • withWalletHold(server, reservation, fn) & settleWalletHold(commitAmount, value): Two-phase wallet holds with automatic rollback on throw and partial settlement support. See Wallets & QR Spend Tokens.
  • isRetryableDecline(code): Reports whether a canonical DeclineCode (insufficient_funds, three_ds_failed, provider_unavailable, etc.) can safely be retried.
  • isPaymentsEvent(event): Type-narrows a verified PalbaseEvent from verifyWebhook() to PaymentsWebhookEvent.
import { isPaymentsEvent, isRetryableDecline, verifyWebhook } from "palbase/server";

export async function handlePaymentsWebhook(rawBody: string, signature: string | null) {
  const event = await verifyWebhook({
    secret: process.env.PALBASE_WEBHOOK_SECRET!,
    signature,
    body: rawBody,
  });

  if (!isPaymentsEvent(event)) return;

  if (event.type === "payments.payment.failed") {
    const code = event.data.decline_code;
    console.log("Payment failed:", code, "retryable:", isRetryableDecline(code));
  }
}

Seats

A subscription sold by the seat changes its seats from your server, never from Stripe's billing portal: your app's own seat screen asks, and server.payments.changeSubscriptionQuantity does it. More seats are charged at once for the days left (proration: "charge_now", the default), off session; a card that declines adds nothing (402 seat_payment_failed). Fewer seats keep the ones paid for until the period's end and renew with fewer (renewal_quantity). The answer's charged_now is what the change charged at once, in minor units.

import { createServer } from "palbase/server";

const server = createServer({ url: process.env.PALBASE_URL!, secretKey: process.env.PALBASE_SECRET_KEY! });

export async function setSeats(subscriptionId: string, seats: number) {
  const { data } = await server.payments.changeSubscriptionQuantity({
    path: { subscription_id: subscriptionId },
    body: { quantity: seats },
  });
  return { seats: data.quantity, fromNextRenewal: data.renewal_quantity, chargedNow: data.charged_now };
}

See Subscriptions for every way the money moves.

Webhook events

Subscribe to any of the 23 payments.* webhook events in Studio (Settings › Webhooks) or with @On(...) in palbase/backend:

EventWhen it fires
payments.payment.succeededA PaymentIntent verified and settled (card, wallet, or split).
payments.payment.failedA payment attempt failed with a canonical decline_code.
payments.payment.canceledA PaymentIntent was canceled and any split wallet hold released.
payments.payment.requires_captureA manual-capture PaymentIntent was authorized and awaits capture or cancel.
payments.payment.charge_returnedMoney a provider took on a payment that was closed by then — canceled, expired, or paid by another of its attempts — or that did not match its payment, was given back (a hold voided or the charge refunded in full, status: succeeded), waits on you to mend the channel's keys (status: pending, told once), or could not be and is yours to give back (status: failed). The payment is not made paid by it, and none of its refunds counts it.
payments.refund.succeededA refund settled to the original card or instantly to a closed-loop wallet.
payments.invoice.finalizedAn invoice was made at the provider: its number and hosted page are set.
payments.invoice.paidAn invoice was paid in full: by a card your server named, on the provider's hosted page, or in parts.
payments.invoice.payment_failedA charge of an invoice was declined; the invoice stays open and can be paid with another card.
payments.invoice.voidedAn open invoice was voided: nothing more is owed on it.
payments.invoice.uncollectibleAn open invoice was marked uncollectible; it can still be paid.
payments.invoice.refundedMoney of a paid invoice was given back: the invoice's refunded_amount grew.
payments.dispute.openedA provider chargeback or dispute opened against a payment.
payments.dispute.closedA provider dispute closed (won or lost), applying chargeback debits or reversals.
payments.subscription.changedA recurring subscription started, renewed, was not charged, was charged for seats added within its period (change: "charged"), or moved on (its period, its status, its seats): change says which.
payments.subscription.canceledA recurring subscription's renewal was turned off (cancel_at_period_end), or it ended (status canceled, ended_at).
payments.wallet.balance_changedA customer's closed-loop wallet balance changed (also delivered over Realtime).
payments.wallet.hold_changedA two-phase wallet hold was created, committed, released, or expired.
payments.wallet.vestedA pending wallet credit vested and moved into available balance.
payments.split.approvedA marketplace split item was approved for seller payout release.
payments.split.refundedA marketplace split item was refunded (with card refund and/or seller clawback).
payments.sub_merchant.updatedA marketplace sub-merchant onboarding or payout profile changed status.
payments.customer.left_at_providerA deleted user's erasure left something at a channel's provider — subscriptions that go on renewing, saved cards, or their profile on the provider's customer record — because cancel_on_delete is off, or the provider could not be made to end or remove it (reason). Each item is told once, with the provider's ids (provider_customer, provider_subscriptions, provider_checkouts, cards): nothing in Palbase names them afterwards, so end them at the provider's dashboard.