/polar:polar-testingfrom Polar
Guides testing Polar payment integrations using the sandbox environment: setup, test cards, webhook testing with Polar CLI, mocking in unit tests, and CI/CD pipelines.
Ships in Polar. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Test Polar integrations safely using the sandbox environment - a fully isolated server where you can experiment without affecting production data or processing real payments.
The sandbox is completely isolated from production. You need separate:
If the user has no sandbox organization, create it yourself: read https://sandbox.polar.sh/auth.md, sign up on your own, create the organization and hand it over to the user with a claim. Only if they ask to create it themselves:
polar auth token once the CLI is signed in to the sandbox (see "Install and sign in" below)Set up the client as in polar-integration ("Setup") and pass environment: "sandbox":
import { createPolar } from "@polar-sh/sdk/2026-10";
const polar = createPolar({
accessToken: process.env.POLAR_ACCESS_TOKEN!,
environment: "sandbox",
});
import os
from polar.v2026_10 import Polar
polar = Polar(os.environ["POLAR_ACCESS_TOKEN"], environment="sandbox")
+test aliases of their addresses are accepted@example.com and made-up domains, at checkout and in the API, so test with a real address such as a +test alias of your ownPolar uses Stripe for payment processing, so any of Stripe's test cards work. Use a future expiry date and any CVC:
| Card Number | Behavior |
|---|---|
| 4242 4242 4242 4242 | Successful payment |
| 4000 0000 0000 0002 | Generic decline |
| 4000 0000 0000 9995 | Insufficient funds |
| 4000 0027 6000 3184 | Requires 3D Secure authentication |
Use the Polar CLI. It forwards your organization's webhook events straight to your local server: no tunnel, no public URL, and no webhook endpoint in the dashboard.
npm install -g @polar-sh/cli
polar auth login --sandbox
For other install methods, see the CLI docs.
polar auth login opens a browser, so ask the user to run it. Check the result with polar auth whoami --json: environments lists the signed-in environments and organization is the active one.
Where no browser is available (CI, remote machines, cloud agents), an organization access token replaces auth login:
export POLAR_ACCESS_TOKEN=polar_oat_... # scopes: webhooks:read, webhooks:write, organizations:read
export POLAR_ENVIRONMENT=sandbox
If POLAR_ACCESS_TOKEN is already exported in the shell, for example from the app's .env, the CLI uses it instead of the login.
polar webhook listen 3000/api/polar/webhook
listen takes a port, a port/path, or a full URL. It runs until stopped, so start it in its own terminal or as a background process and keep it running while you test. It forwards every webhook event for the organization, including the ones real sandbox activity produces, such as completing a test checkout. If the account has several organizations, pick one with --org <id> or polar auth org.
listen signs forwarded events with a local secret, not a dashboard endpoint's secret. Write it to .env without printing it:
secret=$(polar webhook listen --print-secret) && echo "POLAR_WEBHOOK_SECRET=$secret" >> .env
If .env already has a POLAR_WEBHOOK_SECRET line, replace it instead of appending, then restart the dev server. Deployed environments use the secret of their dashboard webhook endpoint.
polar webhook trigger order.paid --json
trigger sends a sample event through the running listen. When your handler doesn't accept it (a non-2xx response, a connection error, or a redirect), it exits with status 1. Read delivery: status is the handler's HTTP status, body its response and failure a connection error. Fix the handler and run the same command again until it exits with 0.
A redirect usually means auth middleware is intercepting the webhook route. Exclude the route from it: Polar never follows redirects when delivering webhooks.
polar webhook trigger --list --json # every event you can send
polar webhook trigger order.paid --json --override [email protected]
polar webhook trigger order.paid --json --seed 7 # the same IDs on every run
--override takes path=value and can be repeated. The API rejects paths that don't exist in the payload.
Use an organization access token with the products:write and checkouts:write scopes. Organization tokens already imply the organization, so don't pass organization_id.
If the project has a polar.config.ts or polar.config.json, skip the beforeAll below: Polar rejects products created outside the config file. Test with a product from the config instead, by its external ID and the 2027-01 client: external_products: ["pro"] in place of products.
import { describe, it, expect, beforeAll } from "vitest";
import { createPolar } from "@polar-sh/sdk/2026-10";
const polar = createPolar({
accessToken: process.env.POLAR_ACCESS_TOKEN!,
environment: "sandbox",
});
describe("Polar Checkout", () => {
let testProductId: string;
beforeAll(async () => {
const product = await polar.products.create({
name: "Test Product",
prices: [{ amount_type: "fixed", price_amount: 1000, price_currency: "usd" }],
});
testProductId = product.id;
});
it("creates a checkout session", async () => {
const checkout = await polar.checkouts.create({
products: [testProductId],
success_url: "http://localhost:3000/success",
});
expect(checkout.status).toBe("open");
expect(checkout.url).toContain("sandbox");
});
it("retrieves a checkout", async () => {
const checkout = await polar.checkouts.create({
products: [testProductId],
success_url: "http://localhost:3000/success",
});
const retrieved = await polar.checkouts.get(checkout.id);
expect(retrieved.id).toBe(checkout.id);
});
});
Generate fixtures from real payloads instead of writing them by hand. --dry-run prints the payload without sending it, so listen doesn't need to be running:
mkdir -p test/fixtures
polar webhook trigger order.paid --dry-run --json --seed 1 > test/fixtures/order.paid.json
polar webhook trigger subscription.created --dry-run --json --seed 1 > test/fixtures/subscription.created.json
Sign them the way polar webhook listen does (Standard Webhooks): an HMAC-SHA256 of id.timestamp.body, base64-encoded and keyed with the secret string. This test calls the webhook route from polar-integration Recipe 3 directly:
import { createHmac } from "node:crypto";
import { readFile } from "node:fs/promises";
import { beforeAll, describe, expect, it, vi } from "vitest";
const secret = "test_webhook_secret";
let POST: (request: Request) => Promise<Response>;
beforeAll(async () => {
vi.stubEnv("POLAR_WEBHOOK_SECRET", secret);
({ POST } = await import("../app/api/polar/webhook/route"));
});
const sign = (id: string, timestamp: number, body: string) =>
`v1,${createHmac("sha256", secret).update(`${id}.${timestamp}.${body}`).digest("base64")}`;
const webhookRequest = (body: string, signature?: string) => {
const id = "msg_test";
const timestamp = Math.floor(Date.now() / 1000);
return new Request("http://localhost/api/polar/webhook", {
method: "POST",
headers: {
"content-type": "application/json",
"webhook-id": id,
"webhook-timestamp": String(timestamp),
"webhook-signature": signature ?? sign(id, timestamp, body),
},
body,
});
};
describe("Polar webhook handler", () => {
it("accepts a signed order.paid event", async () => {
const body = await readFile("test/fixtures/order.paid.json", "utf8");
const response = await POST(webhookRequest(body));
expect(response.status).toBe(202);
});
it("rejects an invalid signature", async () => {
const body = await readFile("test/fixtures/order.paid.json", "utf8");
const response = await POST(webhookRequest(body, "v1,invalid"));
expect(response.status).toBe(403);
});
});
Validation needs a token with license_keys:write. A valid key returns status: "granted"; an unknown key throws ResourceNotFound:
import { describe, it, expect } from "vitest";
import { createPolar, errors } from "@polar-sh/sdk/2026-10";
const polar = createPolar({
accessToken: process.env.POLAR_ACCESS_TOKEN!,
environment: "sandbox",
});
const organization_id = process.env.POLAR_ORG_ID!;
describe("License keys", () => {
it("validates a granted key", async () => {
const result = await polar.licenseKeys.validate({ key: process.env.TEST_LICENSE_KEY!, organization_id });
expect(result.status).toBe("granted");
});
it("rejects an unknown key", async () => {
await expect(
polar.licenseKeys.validate({ key: "INVALID-KEY", organization_id }),
).rejects.toBeInstanceOf(errors.ResourceNotFound);
});
});
Mock createPolar and keep the real webhooks and errors exports. Responses use the same snake_case fields as the API:
import { vi } from "vitest";
vi.mock("@polar-sh/sdk/2026-10", async (importOriginal) => ({
...(await importOriginal<typeof import("@polar-sh/sdk/2026-10")>()),
createPolar: () => ({
checkouts: {
create: vi.fn().mockResolvedValue({
id: "checkout_mock",
url: "https://sandbox.polar.sh/checkout/mock",
status: "open",
}),
get: vi.fn().mockResolvedValue({ id: "checkout_mock", status: "succeeded" }),
},
customers: {
getStateExternal: vi.fn().mockResolvedValue({
active_subscriptions: [{ id: "sub_mock", status: "active", product_id: "prod_mock" }],
granted_benefits: [],
active_meters: [],
}),
},
subscriptions: {
revoke: vi.fn(),
update: vi.fn(),
},
}),
}));
Load the fixtures generated with polar webhook trigger <event> --dry-run --json (see Test Webhook Handler). Hand-written payloads drift from the real shape, and validateEvent only checks the signature and event type, so the drift goes unnoticed.
import orderPaid from "./fixtures/order.paid.json";
import subscriptionCreated from "./fixtures/subscription.created.json";
name: Test Polar Integration
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
env:
POLAR_ACCESS_TOKEN: ${{ secrets.POLAR_SANDBOX_TOKEN }}
POLAR_ORG_ID: ${{ secrets.POLAR_SANDBOX_ORG_ID }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
- run: npm ci
- name: Run unit tests
run: npm run test:unit
- name: Run integration tests
run: npm run test:integration
If CI also runs the Polar CLI, add POLAR_ENVIRONMENT: sandbox.
Create sandbox credentials specifically for CI:
polar auth token --scope products:write --scope checkouts:write opens the token page with them preselected)Locally, polar webhook listen logs every forwarded event with your handler's status, and polar webhook trigger prints the handler's response body when it fails.
For a deployed endpoint:
Webhook signature mismatch
polar webhook listen --print-secret and restart the dev server after changing .envCheckout not completing
success_url is correctAPI returns 401
API returns 403
The SDK throws typed errors with the HTTP status and response body:
import { PolarClientError } from "@polar-sh/sdk";
try {
await polar.checkouts.create({ products: [productId], success_url: "http://localhost:3000/success" });
} catch (error) {
if (error instanceof PolarClientError) console.error(error.statusCode, error.error);
throw error;
}
Before going to production:
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
2 plugins ship this exact skill · first indexed Dec 3, 2026
6 skills in this plugin
/polar-configManage a Polar catalog as code with a billing config file (polar.config.ts or polar.config.json) and the "polar config" commands of the Polar CLI. Use this skill whenever the user wants to: (1) create or edit a Polar billing config; (2) add or change meters, benefits, products or prices in it; (3) write the config from their app's pricing; (4) check what would change, save it to the draft or publish it with polar config validate, draft or publish; (5) fix an issue those commands report; (6) retire a meter, benefit or product with deprecated and polar config prune; (7) generate the config's names for application code with polar config generate. To run these commands from CI, use the polar-config-ci skill.
/polar-config-ciSet up CI for a Polar billing config (polar.config.ts or polar.config.json). Use this skill whenever the user wants to: (1) show the changes a pull request makes to the config as a comment on it, with polar config validate --pr-comment; (2) save the config to the draft or publish it when a pull request merges; (3) create the access tokens and repository secrets CI needs for that; (4) fix a config workflow that fails in GitHub Actions or Buildkite.
Other plugins' skills for the same job
/polar-integrationAdd Polar billing to a TypeScript/JavaScript app using the @polar-sh/sdk package. Use this skill whenever the user wants to add a Checkout endpoint, a Customer Portal endpoint, or a Webhooks endpoint for Polar to any framework — Next.js, Express, Hono, Astro, SvelteKit, Remix, TanStack Start, Nuxt, Fastify, Elysia, Deno, Supabase Edge Functions, Cloudflare Workers, Bun, etc.npx claudepluginhub polarsource/agent-toolkit-source --plugin polar