palbaseDocs

In-App Purchases

Web

The catalog's web products are sold through your environment's connected Payments channels (Stripe or iyzico): Payments collects the card payment or recurring subscription using your deterministic routing rules and keeps the IAP entitlement ledger current on renewals, cancellations, refunds, and disputes. Connect a channel first under Payments › Channels (Stripe or iyzico).

In a browser, pb.iap — the palbase/web client's In-App Purchases module — reads the offerings, opens web checkout and the customer portal, and keeps what the signed-in customer has current. Every call here takes the publishable key; what is the customer's takes their session too.

Quick example

A pricing page: the web's plans with their prices, a button that buys one, and the page kept in step with what the customer has.

// app/pricing.ts
import { createClient } from "palbase/web";
import { formatPrice } from "palbase/web/paywall";

const pb = createClient({ url: "https://<ref>.palbase.studio", publishableKey: "pb_<ref>_c…" });

/** Every plan the web sells, priced in the catalog's currency. */
export async function plans(locale: string): Promise<{ product: string; plan: string; label: string }[]> {
  const { products } = await pb.iap.offerings("web");
  return products.flatMap((p) =>
    (p.channels.web?.plans ?? []).map((plan) => ({
      product: p.key,
      plan: plan.key,
      label: `${p.channels.web?.locales[locale]?.name ?? p.key} — ${formatPrice(plan.price.amount, plan.price.currency, locale)}`,
    })),
  );
}

export async function buy(product: string, plan: string): Promise<void> {
  const url = await pb.iap.checkout({
    product,
    plan,
    successUrl: "https://app.example.com/thanks",
    cancelUrl: "https://app.example.com/pricing",
  });
  location.assign(url);
}

// Told what the customer has once it is read, then whenever it changes; null while no one is signed in.
export const stop = pb.iap.onCustomerInfo((info) => {
  document.body.dataset.pro = String(info?.entitlements["pro"]?.active === true);
});

The offerings

pb.iap.offerings(channel) is the catalog as a paywall shows it — each product's text in every language, its plans and their prices on a channel (the web's unless another is named), and the id each store sells a plan by. Nobody's purchases are in it: the publishable key reads it with no one signed in. Amounts are in the currency's minor units (999 is 9.99); formatPrice(amount, currency, locale) from palbase/web/paywall writes one as the language writes it.

Buying

pb.iap.checkout({ product, plan, successUrl, cancelUrl }) opens a hosted web checkout session for one of the catalog's web plans through your active Payments channel (Stripe or iyzico, selected by your routing rules) and answers its URL: send the buyer there. The payment provider sends them back to successUrl once they paid, or to cancelUrl.

Both addresses go back to one of the project's registered apps — a web app's origin (palbase apps:env:set <app> --origin https://app.example.com), or a native app's own scheme — and nowhere else.

With a customer signed in — a guest too — the purchase is theirs once the payment settles, and onCustomerInfo hears it then: the success page shows the change when it arrives, not before.

RefusalWhy
409 already_entitledThe customer already has the product, or a subscription of its group, from any store. Nothing is charged twice; the error's body names the store it is managed in — and, for a web subscription, its payments_subscription_id. Credits can always be bought again.
429 too_many_checkoutsCheckouts are limited per address and per project with the publishable key alone, per customer and per address with a session.

A free trial is given once per customer, across every channel — and on the web not to a guest, nor to a buyer with no account.

A buyer with no account

With no one signed in, the buyer is no one yet: Checkout asks their email, and what they buy waits for the app user who redeems it. Put {CHECKOUT_SESSION_ID} in successUrl — Stripe writes the session's id there — and the success page asks for the purchase's redemption link:

// app/thanks.ts
import { createClient } from "palbase/web";

const pb = createClient({ url: "https://<ref>.palbase.studio", publishableKey: "pb_<ref>_c…" });

// successUrl was "https://app.example.com/thanks?session={CHECKOUT_SESSION_ID}".
const session = new URLSearchParams(location.search).get("session");
if (session) {
  // Stripe may not have told of the payment yet: it is asked again for up to 20 seconds.
  const link = await pb.iap.redemptionLink(session);
  document.querySelector("#redeem")!.setAttribute("href", link.url);
}

The link works once, within an hour; the buyer is emailed one too. Opened on a phone, its page hands it to the app (<scheme>://palbase/redeem?token=…); opened on a computer, it shows a QR code to scan with the phone. The app — signed in, or a guest — redeems it, and the purchase is that customer's:

// app/redeem.ts
import { createClient, PalbaseError } from "palbase/web";

const pb = createClient({ url: "https://<ref>.palbase.studio", publishableKey: "pb_<ref>_c…" });

export async function redeem(link: string): Promise<string> {
  try {
    const info = await pb.iap.redeem(link);
    return info.entitlements["pro"]?.active ? "Pro is yours" : "Redeemed";
  } catch (e) {
    if (e instanceof PalbaseError && e.code === "redemption_expired") {
      // Past its hour: a new link goes to the buyer's email, once.
      const resent = (e.body as { resent?: boolean } | undefined)?.resent === true;
      return resent ? "That link expired: a new one is on its way to your email" : "That link expired";
    }
    if (e instanceof PalbaseError && e.code === "already_redeemed") return "That link was used already";
    throw e;
  }
}

redemptionLink keeps the key it needs in the tab's sessionStorage from the checkout on; the redirect to Stripe and back keeps it. Each call makes a new link, ten at most within an hour of the payment; past it, the email's is the one. Your server can make one for a buyer whose email went astray, with the secret key (createCheckoutRedemption, any time).

Selling by the seat

A plan can be sold by the seat — a team's plan, a company's. Its catalog entry says how many seats one subscription may be of, and its price is one seat's:

{ "key": "monthly", "period": "P1M", "max_quantity": 500, "price": { "currency": "USD", "amount": 2000 } }

A plan of several seats is sold on the web alone: the App Store and Google Play sell a subscription as one, and validate says so on their channel (quantity_web_only). It needs a payment channel whose capabilities say subscription_quantity (Stripe); on another, a checkout of more than one seat is refused with 422 quantity_not_supported. So is an offer's discount where the channel's capabilities do not say subscription_discount: 422 discount_not_supported — the buyer is never charged the full price of a plan shown at a discount. At a discount Stripe takes the percentage of the whole — five seats of 9.99 at 33 % off are 33.47, not five of 6.69 (33.45) — so show a total of seats as the percentage of their sum.

Your server opens the checkout, with its secret key, for the customer the seats are for — the team, not the person who clicked:

POST /iap/checkout

{
  "product": "team",
  "plan": "monthly",
  "customer_id": "team_42",
  "quantity": 5,
  "success_url": "https://app.example.com/billing?paid=1",
  "cancel_url": "https://app.example.com/billing"
}
FieldWhat it is
quantityHow many seats: 1 when left out, at most the plan's max_quantity (400 invalid_quantity). The subscription is charged the plan's price times the seats, each period.
customer_idThe customer the purchase is for. They become a customer if they were not one, and the purchase is theirs once paid: there is nothing to redeem. Only your secret key may name one (403 customer_id_not_allowed otherwise): a signed-in customer buys for themselves.

Once paid, the customer has the plan's entitlement — one, however many seats: who sits on a seat is your app's own rule — and their subscription says its seats (What a customer has):

{
  "product": "team", "plan": "monthly", "store": "web", "state": "active",
  "quantity": 5, "unit_amount": 2000, "currency": "USD", "interval": "month", "interval_count": 1,
  "payments_subscription_id": "8d3a…"
}

More or fewer seats are a change of that subscription, not another purchase: POST /payments/subscriptions/{payments_subscription_id}/quantity. Seats added are charged for the days left of the period; fewer stay until the period's end, and renewal_quantity says how many the next renewal bills. A second checkout of the plan is refused with 409 already_entitled, whose body carries the same payments_subscription_id.

The team's billing page is the provider's portal, opened by your server for the customer it names:

POST /iap/portal

{ "customer_id": "team_42", "return_url": "https://app.example.com/billing" }

It answers the portal's url: send whoever manages the team's billing there. Whoever holds that link manages the customer's subscriptions and cards at the provider, so it is your secret key's to ask for — never an environment token's (403 token_out_of_scope). Seats are not changed there: leave quantity changes off in the provider's portal settings (Stripe's are off unless you turn them on), and change them with the quantity call.

Tax

By default Checkout charges a plan's price as it is and works out no tax: collecting and filing VAT or sales tax is yours. Set the environment's web_tax to managed and it sells through Stripe Managed Payments: Stripe is the merchant of record — it works out, collects, files and remits the tax of the buyer's country, sends them the invoice, and takes their refunds, disputes and fraud. Stripe charges 3.5% for it on top of its payment fees.

  1. Connect Stripe with a restricted key. Managed Payments does not work through Stripe Connect, which is what the Stripe App connects with: the channel web checkouts go to is one connected with palbase payments:stripe:grant. While web checkouts go to the App's channel, or to one not Stripe's — the default, or the first routing rule that takes them — web_tax managed is refused, and while it is managed a write that would send them to one is too: the default, the routing rules, a channel connected; all 409 managed_payments_needs_key. A project that takes its other payments elsewhere keeps doing so: a rule of payment_kind iap_web and no currency to the key's channel, before the rest, sends every web checkout there.
  2. Turn it on at Stripe. In the Stripe Dashboard, Settings › Managed Payments. Stripe reviews a live account before it sells this way; try it in a sandbox first. Stripe's API does not say whether it is on: palbase iap:doctor reminds you of it.
  3. Give every web product a tax code. The catalog's channels.web.tax_code: one of Stripe's tax codes that Managed Payments takes — txcd_10103000 is software as a service for personal use. It goes with every checkout of the product.
  4. Set it. palbase iap:settings:set --web-tax managed, Studio's IAP › Settings › Tax on web sales, or PUT /iap/settings with the secret key and {"web_tax": "managed"}. While a product sold on the web has no tax code it is refused, 409 tax_code_missing, naming them.

From then on every Checkout session sells through Managed Payments. A checkout that meets a channel that cannot is refused before Stripe is asked (409 managed_payments_needs_key); one Stripe refuses — Managed Payments not on for the account, a product without an eligible tax code — answers with Stripe's reason. What a buyer paid in tax is in the ledger, a credit pack's as well as a subscription's, so the charts take it off the revenue; add Managed Payments' 3.5% to Stripe's fee in the charts' settings for their proceeds.

Whether a price holds the tax

A web price says whether its amount holds the tax (inclusive: the buyer pays the amount) or the tax is added to it (exclusive: the buyer pays the amount and the tax) — for every currency of the price with tax_behavior, or one currency at a time with tax_behaviors. Studio's product sheet asks it of each plan sold on the web (Tax on the web); in the catalog:

"price": { "currency": "USD", "amount": 2900, "overrides": { "TRY": 83250 },
           "tax_behavior": "exclusive", "tax_behaviors": { "TRY": "exclusive" } }

A price that says neither is taxed as the Stripe account's Include tax in prices says — its default, Automatic, adds tax to USD and CAD prices and includes it in every other currency: a TRY 832.50 price is then 832.50 with the VAT inside, not 832.50 plus VAT. The offerings carry both fields, so an app shows the total a buyer will pay, and palbase iap:catalog:plan lists the web's prices, each currency apart, with their tax behavior. With web_tax none no tax is worked out, and the amount is charged as it is whatever the price says.

palbase iap:doctor checks the web too — the channels web checkouts go to, asked at Stripe now, web_tax against them, the tax codes, Stripe's events — and says an App Store that the catalog does not sell in as not applicable.

What the customer has

pb.iap.me() reads everything the signed-in customer has now — entitlements, subscriptions, one-time purchases, credits, quota use — whatever store they bought in. The first read makes the user a customer.

pb.iap.onCustomerInfo(listener) tells the listener once it is read, then each time it changes — a purchase in any store, a renewal or its end, a refund, credits spent — and null while no one is signed in; it answers the function that stops it. The first listener joins the customer's own realtime channel, the last one's stop leaves it. A new user signing in is read anew.

What a page shows from it is for the page. The content a purchase opens is served by your server, which checks the entitlement itself: Entitlements, Credits & Limits.

Managing what was bought

// app/account.ts
import { createClient } from "palbase/web";

const pb = createClient({ url: "https://<ref>.palbase.studio", publishableKey: "pb_<ref>_c…" });

export async function manage(): Promise<void> {
  const info = await pb.iap.me();
  const pro = info.entitlements["pro"];
  if (pro?.manage?.store === "web") {
    location.assign(await pb.iap.portal("https://app.example.com/account"));
  } else if (pro?.manage?.url) {
    location.assign(pro.manage.url); // the App Store's or Google Play's own page
  }
}

portal(returnUrl) opens the customer billing portal for the signed-in customer on their web payment provider (when supported by the channel, such as Stripe's Customer Portal), where they change, cancel or renew what they bought on the web and how they pay. A subscription bought in the App Store or on Google Play is managed there: its manage.url is the store's page.

A paywall on the web

pb.iap.paywall(placement) is the paywall the project published at a placement — designed in Studio, drawn by the SDK — and render() puts it in the page:

// app/upgrade.ts
import { createClient } from "palbase/web";

const pb = createClient({ url: "https://<ref>.palbase.studio", publishableKey: "pb_<ref>_c…" });

export async function showPaywall(container: HTMLElement): Promise<void> {
  const paywall = await pb.iap.paywall("settings", { attributes: { plan: "free" } });
  if (!paywall) return; // the web sells nothing
  const view = paywall.render(container, {
    successUrl: "https://app.example.com/thanks",
    cancelUrl: "https://app.example.com/settings",
    links: { terms: "https://example.com/terms", privacy: "https://example.com/privacy" },
    onClose: () => view.destroy(),
  });
}

Its purchase button opens Checkout for the package selected. The web has no restore button: a web purchase is the account's, wherever it signs in. See Paywalls.

Offers and coupons

pb.iap.offers() lists the catalog's offers the signed-in customer may take now. A discount or a free trial is bought with checkout({ …, offer: key }); a grant is taken with claimOffer(key); a code the customer typed is redeemCoupon(code); offerShown(key) counts an offer seen. See Offers & Coupons.

Guests

A guest — a user signed in with no account yet — buys like anyone else, and what it buys goes with it:

  • A guest that becomes an account keeps its id, and its purchases with it: nothing to do.
  • A guest that signs in to an existing account hands its purchases over. Before signing in, ask for the proof (pb.iap.mergeGrant(), good for 5 minutes); once signed in, spend it (pb.iap.merge(grant)): everything the guest bought goes to the account, for good.

See Customers › Guests.

From a native app

On iOS and the Mac, an app may link out to buy on the web beside In-App Purchase in the App Store's United States storefront (App Review Guideline 3.1.1(a)). PalbaseIAP checks the storefront and opens Checkout in the system browser for the signed-in customer; back in the app, what they have is read again:

import PalbaseIAP

// Show the web button only where Apple lets the app link out.
if await pb.iap.canOpenWebCheckout() {
    try await pb.iap.openWebCheckout(product: "pro", plan: "yearly")
}

Elsewhere openWebCheckout throws web_checkout_not_allowed and asks nothing. Checkout sends the customer back to the app's own scheme, its bundle id. The checkout records where it was opened — the app's platform (ios, or macos in a Mac app) and the storefront — so the charts count the purchase on that platform and can take off what the App Store may charge on one from an iOS app (nothing today).

A redemption link opens the app with <scheme>://palbase/redeem?token=…: hand it to pb.iap.redeem(_:) on iOS, pb.iap.redeem(link) on Android, and the web purchase is the app user's.