# Browser client

```ts
import { createMayarinBrowser } from "@mayarin/sdk/browser";

const mayarin = createMayarinBrowser({
  baseUrl: "https://api.mayarin.xyz",
  publishableKey: "pk_…",
});

const products = await mayarin.commerce.products.list("merchant_123");
```

`@mayarin/sdk/browser` is the entry point for code that ships to a device. Its config has no `secretKey` field, so a leaked secret is a compile error rather than a production incident.

## What a publishable key reaches

| Available                 | Not available                        | Where the rest lives                                               |
| ------------------------- | ------------------------------------ | ------------------------------------------------------------------ |
| `commerce.products.list`  | `products.create`, `products.update` | [Commerce → Products](/sdk/typescript/commerce#products)           |
| `commerce.products.get`   | `paymentLinks.*`                     | [Commerce → Payment links](/sdk/typescript/commerce#payment-links) |
| `commerce.carts.checkout` | `invoices.*`                         | [Commerce → Invoices](/sdk/typescript/commerce#invoices)           |
|                           | the whole `payment` module           | [Payments module](/sdk/typescript/payments)                        |

`PublishableCommerceModule` is a narrowed `CommerceModule`, so the missing methods do not exist on the type — the browser bundle refuses a catalog write the same way the API's key check would.

```ts
mayarin.commerce.products.create; // ✗ type error, property does not exist
```

Nothing in the right-hand column is missing from the SDK; it is missing from *this entry point*. Creating a product, minting a payment link, issuing an invoice, or reading a payment all run on the [server client](/sdk/typescript/server) with an `sk_` key — a publishable key reaches none of them, and shipping a secret key to the browser to get around that is the one thing the split exists to prevent. See [authentication and key safety](/guides/authentication).

A browser that needs one of those results calls your own backend, which does the work with the secret key and returns only what the page needs. That is the shape [`mayarin-demo`](https\://github.com/playriglabs/mayarin-demo) takes — its page holds no key at all, and the build fails if a secret ever reaches the bundle ([`verify-bundle.ts`](https\://github.com/playriglabs/mayarin-demo/blob/main/verify-bundle.ts))\:

```ts
// Browser: no Mayarin key involved.
const { url } = await fetch("/api/checkout", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ lines }),
}).then((response) => response.json());

window.location.assign(url);
```

`publishableKey` is optional\: without one, the client still reaches the keyless buyer routes, and no `Authorization` header is sent.

For a livestream overlay the browser client also takes an `alertKey` (`ak_…`), which opens the read-only [live feed](/sdk/typescript/feed) of finished payments and reaches nothing else. A secret key in either field is refused.

## Check out a cart from the browser

```ts
const intent = await mayarin.commerce.carts.checkout({
  currency: "USD",
  lines: cart.map((line) => ({
    productId: line.productId,
    quantity: line.quantity,
  })),
  merchantReference: orderId,
});

window.location.assign(intent.url);
```

No `merchant` is needed\: the publishable key names its merchant, and the intent always carries that merchant's own name, city and country from the dashboard settings, whatever the browser sends. In React, [`PayButton`](/sdk/typescript/react) wraps this call.

The hosted checkout owns asset selection, the wallet connection or deposit instructions, and live payment status — so a storefront hands the payer over and waits for a [webhook](/sdk/typescript/webhooks) rather than tracking clearing itself.

A payment link is the alternative hand-off\: mint it on the server and redirect to `link.url`, which needs no publishable key in the page at all.

## Open the checkout in a modal

`openCheckout(url, options)` shows the hosted checkout in a modal over your page, with plain DOM and no framework. React, Vue, Svelte, Angular and a script tag all call it the same way\:

```ts
import { openCheckout } from "@mayarin/sdk/browser";

const { url } = await fetch("/api/pay", { method: "POST" }).then((r) =>
  r.json(),
);

const modal = openCheckout(url, {
  onSuccess: ({ intentId }) => showThanks(intentId),
  onFailed: ({ status }) => showRetry(status), // "FAILED" | "EXPIRED"
  onClose: () => {},
});

modal.close(); // closes it from your side
```

It shows a loader until the checkout reports it is ready, closes on Escape or a click on the backdrop, and locks the page's scroll while open. Styles are set through the DOM, not a stylesheet or a `style` attribute, so a page with a strict `style-src` still gets the modal. Your CSP needs `frame-src` for the checkout's origin.

The modal only believes messages that come from its own iframe and the checkout's origin. A `success` event is a signal for your UI; confirm the payment in your [webhook](/sdk/typescript/webhooks) before you ship anything.

Without `onSuccess`, a payment minted with a `successUrl` sends the page there when it settles. The checkout never navigates its own frame.

An invoice, or a subscription cycle, opens the same way\: pass its `url`. The modal shows the price (with `/ mo` for a cycle), the invoice number, who it is billed to and when it is due, then the same rail choice as any payment. An invoice that is already paid opens a short "Paid" sheet instead, and still sends `success`.

### Let the buyer type the amount

`openCheckout` takes any checkout URL, not only one for an intent you minted. A [payment link](/sdk/typescript/commerce#payment-links) of kind `open` has no price\: the modal opens on an amount field, the buyer types it, and the checkout works out the total in the asset they pick. Use it for tips, donations and pay-what-you-want.

```ts
// Once, on your server: an open link in the currency you price in.
const link = await mayarin.commerce.paymentLinks.create({
  kind: "open",
  merchant,
  currency: "IDR",
  title: "Tip the team",
});

// In the browser: link.url opens straight on the amount field.
openCheckout(link.url, { onSuccess: ({ intentId }) => showThanks(intentId) });
```

The link is reusable\: every open creates a new payment, so the same URL serves every donor. In React, the same URL goes to `openCheckout` from a click handler; in [React Native](/sdk/typescript/react-native) it goes to `MayarinCheckoutModal`'s `url`.

The buyer fixes the price here, so treat `onSuccess` as you would for any tip\: confirm the amount in the [webhook](/sdk/typescript/webhooks) before you credit anything.

The same events are available without the modal, for a WebView or a frame you manage yourself, from `@mayarin/sdk/embed`\: `parseCheckoutEvent` reads what the checkout posts, and `embedUrl` adds the flag that lays the page out for a modal.

## QR helpers

Both entry points re-export the QR utilities, which are pure functions with no network access\:

```ts
import { qr } from "@mayarin/sdk/browser";

const parsed = qr.parseQr(scannedPayload); // EMVCo/QRIS → normalized merchant + amount
const uri = qr.encodeAddressUri({
  recipient: deposit.address,
  chainId: 8453n,
  amount: { amount: 18_500_000n, asset: "USDC" },
  token: usdcAddress, // omit for a chain's native asset
});
```

`parseQr` verifies the CRC and throws on a malformed payload. `encodeAddressUri` builds the EIP-681 URI a wallet scans; the deposit DTO already carries a ready `uri`, so encode one yourself only when you are constructing the request from parts.

Omitting `token` produces the **native** form. A token amount sent through the native form transfers the chain's native asset to a token contract, which is unrecoverable — pass the contract address whenever the asset is not native.

## Errors

Failures use the same [`MayarinApiError`](/errors) contract as the server client, re-exported here\:

```ts
import { isMayarinApiError } from "@mayarin/sdk/browser";

try {
  await mayarin.commerce.carts.checkout(body);
} catch (error) {
  if (isMayarinApiError(error)) {
    showMessage(error.status === 0 ? "Network unavailable" : error.message);
    return;
  }
  throw error;
}
```

`status: 0` with code `NETWORK_ERROR` means the request never reached the API — the usual case on a flaky mobile connection, and worth retrying.
