# TopPay integration brief

Use this brief with my own Chrome extension or web app. Inspect my existing source first, preserve its features and design, and implement checkout plus plan-specific paid-access checks. Report what you changed, what you verified, and what remains untested.

## Start with the right integration

- Docs: https://toppayext.com/docs
- Chrome guide: https://toppayext.com/docs/extension
- Web/backend guide: https://toppayext.com/docs/web
- API reference: https://toppayext.com/docs/api
- Testing: https://toppayext.com/docs/testing
- Troubleshooting: https://toppayext.com/docs/troubleshooting
- API origin: https://toppayext.com
- Local Chrome SDK: https://toppayext.com/toppay-sdk.js

For a first Chrome test, use **My apps → app → Setup → choose an active pricing plan → Download ready-to-test extension**. It contains the selected app ID, plan ID, API origin, and public tracking key. Customers must never be asked for these values.

The public download at https://toppayext.com/toppay-chrome-starter.zip is a **manual developer template**. It needs configuration before use. Do not confuse it with the dashboard-generated package or describe the test demo as my finished product.

## Product inputs

I will provide my source project, the paid features to gate, and either a configured demo or these public values:

- TopPay app ID: `YOUR_TOPPAY_APP_ID`
- Pricing plan ID (the API calls this `profileId`): `YOUR_PAYMENT_PROFILE_ID`
- App type: Chrome extension or web app
- Public tracking key (needed for analytics): `YOUR_PUBLIC_TRACKING_KEY`

If a backend is needed, its per-app server API key belongs in the deployment secret manager as `TOPPAY_API_KEY`. Never ask me to paste secrets into chat or include one in frontend code, an extension, logs, screenshots, or source control.

## Chrome extension

Bundle the SDK locally, typically as `payframe.js`. Do not execute remotely hosted JavaScript. Initialize:

```js
const topPay = TopPay(appId, {
  profileId,
  apiBaseUrl: "https://toppayext.com/api"
});
```

The configured demo uses `globalThis.TOPPAY_CONFIG` with `appId`, `profileId`, `origin`, and `publicKey`. The manual template uses `globalThis.PAYFRAME_CONFIG` with `apiBaseUrl`, `appId`, and `profileId`. Match the package I provide; do not mix its configuration names.

- Load configuration, SDK, then product logic from local script files.
- Add `storage` and `https://toppayext.com/*` host permissions. Preserve permissions required by my own product.
- For analytics, merge `alarms` and an existing/new service worker. Call `startBackground()` and `startAnalytics()` synchronously at worker top level. startBackground handles managed checkout return and periodic access checks; startAnalytics handles usage events.
- Display the selected plan's price, currency, interval, and trial before opening checkout.
- On a buyer action, call `openPaymentPage({ profileId })`. Stripe collects the receipt email; you may optionally supply `email` to prefill it. Email is not authentication.
- Before each premium action, call `getUser({ profileId })` and permit it only on `active === true`. Handle API/network errors with a locked state and retry message.
- Checkout opens in a compact Stripe window. With startBackground, the worker checks the same identity/plan after the return, waits for verified access, and reopens the action popup where supported (Chrome 127+). Leave a manual toolbar/retry fallback. Never unlock based on the redirect.
- Use `openBillingPortal()` for billing management when a Stripe customer is linked to the current installation. Handle errors and provide a visible seller support route.

### Identity limitation

The SDK stores a random installation token in Chrome local storage. Do not regenerate it per request or treat the receipt email as ownership proof. Reinstalling, clearing extension data, or changing browser/profile can lose purchase access. There is no built-in cross-device restore flow.

If cross-device customer access is required, design around my authenticated backend and a stable customer ID from the beginning. Server customer records and Chrome installation records are not automatically merged by email. Do not promise migration or restoration that has not been implemented.

Browser code can be modified by its owner. Enforce access on my server for valuable backend features.

## Web app / authenticated backend

Keep my existing login. Derive `customerId` from a verified server session, not a request-body value that the browser controls. Keep the ID stable, 1–160 characters. Use the server key belonging to the selected app.

Send `Content-Type: application/json` and `Authorization: Bearer <server key>`:

- `POST /api/v1/server/customers` with `{appId, customerId, email}` after signup/login to register users before purchase. This does not grant access.
- `POST /api/v1/server/checkout` with `{appId, profileId, customerId, email}`. Call only on a checkout action; redirect to `checkoutUrl`.
- `POST /api/v1/server/access` with `{appId, profileId, customerId}`. Run the protected operation only when `active === true`.

Treat errors as no access until successfully verified. The current implementation has no public server-customer billing-portal endpoint; provide a seller support route for web customer billing instead of calling the Chrome-token endpoint with a customer ID.

## Usage tracking

Use the background SDK for Chrome installation analytics (see Advanced Chrome extension analytics below). The pixel instructions here are for aggregate web tracking or legacy integrations; they do not create an installation/customer record. Do not combine both for the same action.

Prefer the dashboard's generated snippet. The configured demo includes installation analytics and sends `app_open` and `feature_used` through its background worker; avoid duplicate handlers. Earlier aggregate pixels remain separate.

Tracking uses `GET /api/v1/pixel.gif?key=PUBLIC_KEY&event=EVENT&source=SOURCE` on the API origin. Use a cache-busting timestamp for JavaScript events, no credentials, and no referrer. Events and sources accept 1–40 letters, digits, underscores, or hyphens and become lowercase. Do not include personal information.

Call events when the action happens, not on every render. Counts are aggregated by UTC day; they are not unique users or sessions. `tracking_test` is reserved for diagnostics and excluded from usage totals. A GIF response alone is not proof of recording; verify the report.

## Payment mode and access behavior

- The platform deployment controls payment mode. There is no per-app test-mode toggle in the seller dashboard.
- A demo extension or plan named “test” can still use LIVE payments. A live recurring plan can create a real subscription.
- No-money end-to-end tests require a platform environment with matching Stripe test credentials, test seller data, and webhook configuration.
- Do not complete a real charge without explicit authorization for that payment.
- Current access checks accept valid active or trialing entitlements; they reject past-due, cancelled, or expired access.
- A cancellation scheduled for period end can leave access active until its period expires.
- Full refunds and open disputes block related access after processing. Partial refunds do not automatically revoke access under the current rule.
- Do not blindly retry checkout creation. The public API does not expose a caller-provided idempotency key; repeated attempts may create more sessions.

## Acceptance checks

1. New customer: premium is locked.
2. Offer: correct app, seller, selected plan, price, currency, interval, trial, and mode.
3. Cancelled checkout: no new access.
4. Completed payment/eligible trial: access only after server-confirmed entitlement; real feature runs.
5. Plan separation: access to one plan does not unlock another.
6. Renewal failure, cancellation, full refund: expected access changes after event processing.
7. Network failure: locked state and useful retry UI.
8. Billing: portal works for a linked Chrome customer, or a clear seller support route is available.
9. Tracking: actual product events appear, without duplicate counts or personal information.
10. Secrets: absent from browser bundles, extension ZIPs, source, logs, and screenshots.

Keep compilation, checkout-session creation, completed payment, webhook processing, and feature unlock as separate verification checkpoints. Never call the entire flow tested if only some of these succeeded.

## Optional pricing experiences

Templates are optional editable starters; TopPay can also be integrated directly through the SDK/API with a custom interface. The Templates tab can export Monthly + Lifetime, a subscription trial, Monthly + Annual, or a single offer. Owners select real active plans; a lifetime option is a one-time plan and a trial requires trial days on a recurring plan. The offer options unlock the same listed premium features. Generated clients route each selection to its own Stripe checkout and accept access from any included plan. Web backend examples allowlist these plans and always derive customer identity from the app's verified server session. Downloaded templates do not update automatically when the dashboard design changes.

## Advanced Chrome extension analytics

Use the dashboard’s configured integration kit (Setup → Connect usage tracking) or a newly downloaded extension starter. App IDs/public keys are included. Keep the SDK local.

- Merge storage/alarms permissions and TopPay host access. In the background service worker, create TopPay(appId, {publicKey, apiBaseUrl}) and call startAnalytics() synchronously at top level. Merge with the existing worker; do not remove app features.
- In the popup use topPay.track('app_open'); at a feature action use topPay.track('feature_export'). The names of custom feature events must begin with feature_. Lifecycle events are registered by the worker.
- Call topPay.identifyEmail(email, {consent: true}) only when the user intentionally provides it. This is not a verified identity or a permission to grant access. Chrome/Google account emails are not collected. Checkout emails are associated automatically when the same SDK identity purchases.
- Recorded installs count Chrome install events; upgrades/reloads count as updates. Existing installations first receiving the SDK are observed, with unknown original install date. Developer-mode data has its own filter.
- The worker registers Chrome’s one uninstall URL. Merge an existing uninstall survey before enabling this worker. Reports can be missed offline or when blocked, cannot identify the removal screen, and do not include dependable disable/profile-deletion signals. Uninstalling does not cancel subscriptions.
- Activity is counted as distinct browser installations, not people. Retention is exact UTC day 1/day 7, with completed return days only. Reinstalling or clearing storage can create a new installation. There is no historical backfill.
- The local retry queue is capped at 100 records and event dates are server receipt dates. Do not send browsing history, page contents, or personal data in event names. Disclose the collection in the extension’s privacy notice.

## Email flow, customer controls, and custom integrations

Buy opens Stripe's hosted email and payment form. No separate pre-checkout email field is required. TopPay receives and saves checkout email from a signed completed-checkout event (including a trial signup), not a live feed of abandoned form input. For earlier email capture, use a voluntary form and identifyEmail; web apps can register signed-in users from their backend. Never use a matching email as authentication or silently merge identities.

Implement tracking in MY actual source even if I use no template. Setup → Connect usage tracking offers configured manifest, worker, popup snippets and a template-free kit. Existing installed extensions need a published update to run it. Verify real app-open and feature events in Setup and Usage & traffic; Stripe connected is not a tracking installation check. Web pixels are aggregate event counts, not per-user retention or extension lifecycle analytics.

Owners manage Customers & access → Manage: app-wide block/restore, plan-specific complimentary grants, start/restart/extend TopPay free access, and remove grants. These never alter Stripe billing dates, cancel subscriptions, refund charges, or count as sales. An owner block overrides both billing and manual grants. Check effective active === true before EVERY protected action; do not cache access indefinitely. A block is not remote Chrome logout/uninstall. Add tests for each owner action, expiry, and restore with the same customer identity.

## Automatic access UI (required for lock/unlock behavior)

Call `topPay.watchAccess(listener, {profileId})` from the UI and render premium only when `user.active === true`. For multiple alternative offers, use `{profileIds: [monthlyPlan, lifetimePlan]}`. Render a paywall and billing information when inactive. Show Manage billing when `user.billingAvailable` is true, even after paid access ends. Use `user.status` for blocked/past_due/canceled/expired/refunded/disputed/unpaid/unavailable messages. Keep the identity token; do not sign out of my own auth system without a separate explicit product decision. Unsubscribe on pagehide.

The watcher refreshes immediately, every 15 seconds while visible, on focus/online, at known expiry, and on background signals (which trigger a fresh server read). The worker checks about every 5 minutes; alarms may be delayed. Call getUser again before each premium action. Server-hosted operations must check on the backend. Network failures lock access. A cancellation scheduled for period end keeps valid paid time; canceling an unfinished checkout does not remove earlier purchases. A trial/complimentary grant counts as access, not as a sale.

Card fields remain on Stripe's HTTPS checkout in a compact window, not inside the extension popup. Managed return requires the updated local SDK + top-level startBackground + action popup in the manifest. Pending checkout is persisted across worker restarts for up to 30 minutes. Existing extensions require a shipped update to receive this flow. Test worker restart, delayed webhook, canceled checkout, popup reopening fallback, expiry, owner blocks, and offline behavior.

## Optional self-custody crypto
Read /docs/crypto. USDC on Base only, 5% to TopPay and 95% to the owner-level developer wallet. Requires platform activation and per-plan opt-in. Add getCryptoPaymentOption({profileId}) and openCryptoPaymentPage({profileId}) with the current SDK, or create web checkout from your authenticated server through POST /api/v1/crypto/checkout. Do not alter identity or access checks. Wallet checkout opens a TopPay browser tab. Monthly/weekly/yearly mean 30/7/365 days with manual renewals; one_time means lifetime. No auto debit or Stripe trial on crypto. Only server verification of finalized native USDC transfers to both recipients grants access. Customer signature binds the paying wallet to an order; transaction hashes are single-use. Keep pending checkout URLs for recovery. Never put private keys or server/RPC credentials in client code. Crypto is not live until the platform fee wallet and RPC are configured.


## Seats and device/session controls
Read https://toppayext.com/docs/seats. Plans default to one seat per unit and unrestricted devices/sessions. The developer configures limits in Seats & devices. Purchasers occupy seat 1; invitation codes reserve remaining seats and are bearer secrets valid for seven days. Use SDK getSeats/createSeatInvite/acceptSeatInvite/removeSeat or the authenticated /api/v1/server/seats endpoint; never accept another acting customer ID from browser input. No invitation email is sent automatically. Checkout quantity is optional and capped by the plan. Prices and fees multiply by quantity; verified payments establish seat capacity.
The updated extension SDK supplies device/session IDs automatically (one active installation session per Chrome profile). Web server access checks must include stable deviceId and current authenticated sessionId when limits are enabled. Leases expire after two minutes without access checks. On every protected action require active === true. Missing IDs and exhausted/revoked devices or sessions fail closed. Show these errors rather than inviting the customer to buy again. Downloaded templates need your customer-facing team UI and web authentication wiring.
