Originally published on opencals.com. The original stays updated; check it for the latest version.
Adding booking to an app looks like a weekend project until you start. Real-time availability across staff and locations, cart state that survives a page refresh, a payment flow that fails gracefully, booking statuses that move through their lifecycle — every piece is more nested and more stateful than it looks from the outside.
A booking SDK is what turns that from raw HTTP plumbing into typed method calls. This is a look at what a booking SDK does, when it's worth using over the raw API, and how the Opencals storefront SDK is structured — with code you can actually run.
Why a booking flow earns an SDK
Plenty of APIs don't need an SDK. A booking API does, and the reason is the shape of the data. A single booking flow touches:
- Availability: nested slots computed across staff, hours, duration, capacity
- Cart state: line items, quantities, selected times, held across steps
- Payment intents: Stripe client secrets, confirmation, idempotency
- Booking status: pending (held, awaiting payment or approval), scheduled, completed, canceled
Wire that up with hand-rolled fetch calls and you're maintaining a private, untyped copy of the API's mental model — one that silently drifts every time the backend adds a field. A typed SDK gives you autocomplete for every request, compile-time errors when a shape changes, and schemas for validating responses at the boundary. In a domain this nested, that's the difference between a booking flow you trust and one you babysit.
Key takeaway
Use a booking SDK when the flow is stateful and the types are nested — availability, carts, and payments. Reach for the raw REST API for one-off scripts, server-to-server jobs, or non-JavaScript stacks.
Install and set up
The Opencals storefront SDK is a TypeScript package:
npm install @opencals/storefront-sdk
Initialize it once with your store API key. Keys are scoped to a single store. For server code use a private storefront key: it starts with spk_ and comes from the dashboard under Users → your user → API Keys. Keep it server-side, and forward each visitor's IP with the buyerIp option so rate limits count per visitor, not per server.
// lib/opencals.ts — import it from server code
import { setupOpencals } from "@opencals/storefront-sdk";
import { nextBuyerIp } from "@opencals/storefront-sdk/next"; // Next.js; elsewhere pass your own function
setupOpencals({
apiKey: process.env.OPENCALS_API_KEY, // spk_...
buyerIp: nextBuyerIp,
throwOnError: true, // failed calls throw OpencalsApiError instead of returning { error }
});
That's the whole setup. setupOpencals configures one shared client, so the service classes below don't take a client argument: every call takes a single options object with path, query, body and headers as needed. The base URL (https://api.opencals.com) is the default, and every route is typed. The full endpoint reference is at api.opencals.com/docs/storefront if you want to see the raw HTTP underneath.
The five things every booking flow does
Almost every custom booking flow is the same five steps. Here's each one through the SDK (version 0.3.20, checked November 2026; the examples assume throwOnError: true).
1. Load the service catalog
Your services page is populated from the product catalog. It rarely changes, so cache it.
import { ProductService } from "@opencals/storefront-sdk";
const { data: page } = await ProductService.list({
query: { status: ["active"], take: 50 },
});
const services = page.data;
// each service is typed: title, price, duration (seconds), variants, staff and locations
2. Fetch real-time availability
This is the endpoint that earns the platform. You ask for a service on a date, optionally narrowed to a staff member and a location; you get back the slots that are bookable right now — after existing bookings, working hours, buffers, and capacity are all accounted for.
import { ProductService } from "@opencals/storefront-sdk";
const { data: slots } = await ProductService.getCurrentAvailabilities({
path: { productId },
query: {
date: "2026-07-20", // one day per call
staffMemberId, // optional — omit for "any available"
locationId, // optional
timezone: "Europe/Warsaw",
},
});
// slots: [{ productId, fromDate, fromTime, toDate, toTime, staffMemberIds, attendees, maxAttendees }]
You render slots straight into a calendar. You are not reconstructing availability logic on the client — the hard part stays on the server where it belongs. For "next free slot" buttons there's ProductService.getNearestAvailability.
3. Create a cart and hold the slot
A cart holds the selected slot while the customer finishes checkout. Every cart and checkout call names its cart in the X-Cart-Id header; store the cart ID (an httpOnly cookie works) so the cart survives a page refresh.
import { AppointmentService, CartService } from "@opencals/storefront-sdk";
const { data: cart } = await CartService.createOrGet({
headers: { "X-Cart-Id": savedCartId ?? "" },
});
await AppointmentService.create({
body: {
slot: {
productId: slot.productId,
fromDate: slot.fromDate,
fromTime: slot.fromTime,
toDate: slot.toDate,
toTime: slot.toTime,
}, // times are UTC
numberOfAttendees: 1,
cartId: cart.id,
},
});
If two people try to hold the same slot at the same moment, one gets it and the other gets a clear error that the slot is being booked, so show that and let them pick another time.
4. Start checkout, pay, submit
CheckoutService.start attaches the customer and creates the payment. For card payments it returns a Stripe client secret, the publishable key and the connected account ID, so your app never stores a Stripe key. The browser confirms the payment with Stripe.js, then your server submits.
import { CheckoutService } from "@opencals/storefront-sdk";
const cartHeaders = { "X-Cart-Id": cart.id };
const { data: checkout } = await CheckoutService.start({
headers: cartHeaders,
body: {
provider: "stripe",
customer: { kind: "new", email, firstName, lastName },
},
});
// browser: loadStripe(checkout.publishableKey, { stripeAccount: checkout.stripeAccountId })
// → mount a Payment Element with checkout.clientSecret → stripe.confirmPayment(...)
const { data: result } = await CheckoutService.submit({
headers: cartHeaders,
body: { stripePaymentIntentId: paymentIntent.id },
});
The failure cases are named, so a retry doesn't have to guess. Submitting a card payment that isn't authorised returns 402 PAYMENT_NOT_AUTHORIZED: no order is placed and the cart is untouched, so the customer can try again. A second start or submit while one is still running returns 409 CHECKOUT_IN_PROGRESS, and starting a cart that already became an order returns 409 CART_ALREADY_CHECKED_OUT with that order's ID. Not every booking is confirmed on submit: a pending appointment with pendingReason set is awaiting payment or the store's approval, so label it that way rather than "Confirmed".
5. Customer self-service
Viewing, rescheduling, and cancelling a customer's own bookings uses a second credential: a customer access token from Opencals' customer accounts (AuthService.signIn, or signUp for new customers), sent as a Bearer header. The store key stays on the server while a signed-in customer acts only on their own bookings.
import { AppointmentService, AuthService } from "@opencals/storefront-sdk";
const { data: session } = await AuthService.signIn({ body: { email, password } });
const asCustomer = { Authorization: `Bearer ${session.accessToken}` };
const { data: upcoming } = await AppointmentService.list({
headers: asCustomer,
query: { status: ["scheduled", "pending"], orderBy: "from", order: "ASC" },
});
await AppointmentService.reschedule({
headers: asCustomer,
path: { appointmentId },
body: { slot: newSlot }, // from getCurrentAvailabilities with excludeAppointmentId
});
await AppointmentService.cancel({
headers: asCustomer,
path: { appointmentId },
body: { notifyCustomer: true },
});
The five steps at a glance:
- 1. Catalog: ProductService.list() — populate services from page.data. Cache it.
- 2. Availability: ProductService.getCurrentAvailabilities({ path: { productId }, query: { date } }) — render the calendar from real bookable slots, one day per call.
- 3. Cart: CartService.createOrGet() with the X-Cart-Id header, then AppointmentService.create() with the slot and cartId to hold it.
- 4. Checkout: CheckoutService.start() for the Stripe client secret, stripe.confirmPayment() in the browser, then CheckoutService.submit().
- 5. Self-service: AuthService.signIn() for a customer token, then AppointmentService.list(), reschedule() and cancel() with it.
Type safety and runtime validation
Static types catch shape mismatches at compile time. But data crossing a network boundary can still surprise you at runtime, so the SDK also exports a Zod schema for every response type. Run the ones you care about with safeParse at the boundary, and a malformed or unexpected payload fails loudly at the edge instead of leaking an undefined three components deep into your UI.
import { zProductListResponse } from "@opencals/storefront-sdk";
const parsed = zProductListResponse.safeParse(raw);
if (!parsed.success) console.error(parsed.error);
It also includes the small formatting helpers you'd otherwise rewrite on every project:
import { formatPrice, formatDuration } from "@opencals/storefront-sdk";
formatPrice(45, "USD"); // "$45.00"
formatPrice(0, "USD"); // "Free"
formatDuration(5400); // "1 hour 30 minutes"
Durations come back in seconds and prices as plain amounts in the store's currency (45 is $45.00, not cents), which is what the helpers expect. Check the output in your own locale before you ship; formatPrice takes a locale as its third argument.
Using it with Next.js and React
The SDK is framework-agnostic; it runs wherever JavaScript runs. The only real rule is credential placement.
Keep the store API key on the server — route handlers, server actions, or server components. Fetch there, then pass typed data (or a customer token) down to the client. Never ship the private spk_ key to the browser. The Next.js booking tutorial walks through the whole flow this way, from services to checkout.
// app/api/availability/route.ts (Next.js route handler)
import "@/lib/opencals"; // the setupOpencals module from above
import { ProductService } from "@opencals/storefront-sdk";
export async function GET(req: Request) {
const { searchParams } = new URL(req.url);
const { data: slots } = await ProductService.getCurrentAvailabilities({
path: { productId: searchParams.get("productId")! },
query: {
date: searchParams.get("date")!, // YYYY-MM-DD
staffMemberId: searchParams.get("staffMemberId") ?? undefined,
},
});
return Response.json(slots);
}
The client calls your route, not Opencals directly. That's the whole headless booking pattern: your frontend, your framework, your domain — the booking engine and payments handled underneath.
SDK or raw REST — which to reach for
Both are supported; they're not competitors.
SDK pros
- SDK: typed methods, autocomplete, and compile-time safety across the whole flow
- SDK: Zod runtime validation and money/duration helpers included
- SDK: less boilerplate for the stateful cart-and-checkout sequence
Raw REST pros
- Raw REST: better for non-JavaScript stacks (Python, Go, PHP) — no SDK to depend on
- Raw REST: leaner for server-to-server jobs or one-off scripts
- Raw REST: nothing to update when you just need a single endpoint
If you're building a production booking experience in TypeScript, the SDK is the shorter path. If you're integrating from another language or writing a quick automation, the REST API is right there with the same guarantees.
Note
The SDK and the website templates are open source and free; the Opencals platform underneath is a managed cloud service. You get open, inspectable client code running against an API you don't have to operate.
Related reading
- Booking API guide: The endpoint-level reference: auth model, core routes, and the full flow in raw REST.
- Headless booking system: The architecture for building a custom booking frontend on any stack.
- Add booking to a Next.js app: The full flow in a Next.js App Router project: services, slots, cart and checkout over the REST API.
- Opencals for developers: API docs, the OpenAPI spec, and how to get a storefront key.
- Build a booking website: Deploy a free open-source template on your own domain in an afternoon.
- Open-source booking system: What's open (SDK + templates) and what's managed (the platform), and why.
Frequently asked questions
What is a booking SDK?
A booking SDK is a client library that wraps a booking platform's API in typed methods, so you can build a custom appointment flow — loading services, checking availability, adding to a cart, taking payment — without writing raw HTTP calls or guessing at request and response shapes. The Opencals storefront SDK is a TypeScript package (@opencals/storefront-sdk) that covers the full booking flow with type safety and runtime validation built in.
Why use an SDK instead of calling the REST API directly?
You can call the REST API directly — the SDK is optional. But a booking flow has a lot of nested, stateful objects: availability slots, cart line items, payment intents, booking statuses. A typed SDK gives you autocomplete, compile-time errors when a shape changes, and runtime validation, which removes a whole class of bugs. For quick scripts or non-JS stacks, raw REST is fine; for a production TypeScript app, the SDK saves real time.
Does the booking SDK work with Next.js and React?
Yes. The SDK is framework-agnostic — it runs anywhere JavaScript runs. In Next.js, keep the store API key server-side (route handlers, server actions, or server components) and pass only the data or a customer token to the client. In React, fetch on the server or in a data-loading hook and render from typed results. The SDK doesn't force a framework or a state library on you.
Is the Opencals booking SDK open source?
The SDK and the website templates are open source and free to use; the Opencals platform itself (the booking engine, dashboard, and hosted infrastructure) is a managed cloud service, not open source. So you get open, inspectable client code and templates you own, running against a managed API you don't have to operate. The distinction matters if you're evaluating self-hosting versus a managed backend.
How do I authenticate with the booking SDK?
There are two credentials. A private storefront key (prefix spk_, from the dashboard under Users → your user → API Keys) scopes all storefront calls to one store and must stay server-side. A customer access token, from Opencals' customer accounts via AuthService.signIn, is required for customer self-service endpoints like viewing, rescheduling, or cancelling their own bookings; send it as an Authorization: Bearer header on those calls. You initialize the SDK with the store key once; you attach the customer token per call.
Can the SDK handle payments?
The SDK drives the checkout flow, and card payment is collected through Stripe. CheckoutService.start returns a Stripe client secret plus the publishable key and connected account ID, so your app stores no Stripe key; you confirm the payment with Stripe.js in the browser, then call CheckoutService.submit to place the order. An unauthorised card returns 402 PAYMENT_NOT_AUTHORIZED with the cart untouched, and a concurrent start or submit on the same cart returns 409 CHECKOUT_IN_PROGRESS, so retries are safe to handle. Manual methods such as bank transfer skip the Stripe step.
Top comments (0)