Polar TypeScript SDK

repository·main·Indexed 41 days ago

https://github.com/polarsource/polar-js

A type-safe TypeScript SDK (@polar-sh/sdk version 0.49.0) for interacting with the Polar HTTP and Webhooks API. It provides tools to manage benefits, benefit grants, and checkout links, offering both a main Polar class and standalone functions via PolarCore for optimized tree-shaking in production applications.

Tokens
334.3K
Snippets
721
Records
911
Agent score
49%

What's inside Polar

  1. Overview of CustomerSeats operations

    main

    The CustomerSeats namespace in the Polar SDK provides methods to manage seat assignments and invitations.

    Available operations include:

    • listSeats: List all seats.
    • assignSeat: Assign a seat to a user.
    • revokeSeat: Revoke an existing seat.
    • resendInvitation: Resend a seat invitation.
    • getClaimInfo: Retrieve information about claiming a seat.
    • claimSeat: Claim a seat.
  2. Explore available SDK resources and operations

    main

    The @polar-sh/sdk provides a comprehensive set of resources for managing monetization, customers, and subscriptions. The SDK is organized into logical groups, including:

    • Core Monetization: Products, Subscriptions, Orders, Discounts, Refunds, and Payments.
    • Customer Management: Customers, CustomerPortal (for managing customer-facing sessions, orders, and profiles), and Members.
    • Checkout & Links: Checkouts (session management) and CheckoutLinks.
    • Licensing & Access: LicenseKeys, Seats, and BenefitGrants.
    • Infrastructure & Events: Webhooks, Events, Meters (for usage-based billing), and Oauth2.

    Each resource provides standard CRUD operations (list, get, create, update, delete) along with specialized methods (e.g., validate for LicenseKeys or invoice for Orders).

  3. Available operations in CustomerPortal.Customers

    main

    The CustomerPortal.Customers namespace provides the following operations:

    • get: Get authenticated customer
    • update: Update Customer
    • listPaymentMethods: List Customer Payment Methods
    • addPaymentMethod: Add Customer Payment Method
    • confirmPaymentMethod: Confirm Customer Payment Method
    • deletePaymentMethod: Delete Customer Payment Method
    • requestEmailUpdate: Request Email Change
    • checkEmailUpdate: Check Email Change Token
    • verifyEmailUpdate: Verify Email Change
  4. Available Webhook Operations in the Polar SDK

    main

    The Polar SDK provides several operations to manage webhooks and monitor event deliveries. The available operations are:

    • listWebhookEndpoints: List all configured webhook endpoints.
    • createWebhookEndpoint: Create a new webhook endpoint.
    • getWebhookEndpoint: Retrieve details for a specific webhook endpoint.
    • deleteWebhookEndpoint: Remove a webhook endpoint.
    • updateWebhookEndpoint: Modify an existing webhook endpoint.
    • resetWebhookEndpointSecret: Regenerate the secret used to sign webhook payloads.
    • listWebhookDeliveries: List the history of webhook event deliveries.
    • redeliverWebhookEvent: Manually trigger a redelivery of a specific webhook event.
  5. Handle subscription updates via WebhookSubscriptionUpdatedPayload

    main

    The WebhookSubscriptionUpdatedPayload is sent whenever a subscription is updated. This event is a catch-all for all changes to a subscription, including renewals.

    Choosing the right event

    Depending on your use case, you may want to listen to more specific events instead of the general update event:

    • Specific status changes: Listen to subscription.active, subscription.canceled, subscription.past_due, or subscription.revoked.
    • Renewals: To specifically track renewals, listen to order.created events and inspect the billing_reason field.

    Integrations

    • Discord & Slack: These integrations support cancellation, past due, and revocation events. Note that renewals are skipped for these integrations.
    import { WebhookSubscriptionUpdatedPayload } from "@polar-sh/sdk/models/components/webhooksubscriptionupdatedpayload.js";
    
    let value: WebhookSubscriptionUpdatedPayload = {
      type: "subscription.updated",
      timestamp: new Date("2025-09-20T20:10:21.776Z"),
      data: {
        // ... subscription data
      }
    };
  6. Understand the BalanceRefundEvent model

    main

    A BalanceRefundEvent is an event generated by Polar whenever an order is refunded. It contains details about the refund, the associated customer, and the organization that owns the event. This model is useful for synchronizing refund states in your own system or triggering post-refund workflows.

    import { BalanceRefundEvent } from "@polar-sh/sdk/models/components/balancerefundevent.js";
    
    // Example of a BalanceRefundEvent object structure
    let value: BalanceRefundEvent = {
      id: "<value>",
      timestamp: new Date("2024-02-22T00:39:19.003Z"),
      organizationId: "1dbfc517-0bbf-4301-9ba8-555ca42b9737",
      customerId: "<value>",
      customer: {
        id: "992fae2a-2a17-4b7a-8d9e-e287cf90131b",
        // ... other customer fields
      },
      externalCustomerId: null,
      label: "<value>",
      source: "system",
      name: "balance.refund",
      metadata: {
        transactionId: "<id>",
        refundId: "<id>",
        amount: 231482,
        currency: "Denar",
        // ... other metadata fields
      },
    };
  7. Understand the ListResourceSubscription component

    main

    The ListResourceSubscription component is a paginated collection of subscription objects. It is used when retrieving lists of subscriptions from the Polar API. It consists of two primary fields:

    • items: An array of Subscription objects.
    • pagination: A Pagination object containing metadata for navigating through the result set.

    This component is typically returned by list-based API endpoints related to subscriptions.

  8. Understand the BenefitGrantLicenseKeysWebhook object

    main

    The BenefitGrantLicenseKeysWebhook is a data structure used in webhooks to notify systems when license keys are granted or revoked as a benefit. It contains details about the grant status, the associated customer, the member involved, and the specific benefit being provided.

    Key properties include:

    • isGranted and isRevoked: Boolean flags indicating the current state of the benefit.
    • subscriptionId and orderId: Identifiers for the transaction that triggered the grant.
    • benefit: Details about the license key benefit being issued.
    • customer and member: Information about the entities receiving the benefit.
    import { BenefitGrantLicenseKeysWebhook } from "@polar-sh/sdk/models/components/benefitgrantlicensekeyswebhook.js";
    
    let value: BenefitGrantLicenseKeysWebhook = {
      createdAt: new Date("2024-03-27T04:10:14.057Z"),
      modifiedAt: new Date("2026-11-09T06:34:32.498Z"),
      id: "<value>",
      isGranted: true,
      isRevoked: false,
      subscriptionId: null,
      orderId: "<value>",
      customerId: "<value>",
      benefitId: "<value>",
      customer: {
        id: "992fae2a-2a17-4b7a-8d9e-e287cf90131b",
        // ... other customer fields
      },
      member: {
        id: "<value>",
        // ... other member fields
      },
      benefit: {
        id: "<value>",
        type: "license_keys",
        // ... other benefit fields
      },
      properties: {},
    };
  9. Use BenefitFeatureFlag to grant feature flags

    main

    A BenefitFeatureFlag is a specific type of benefit used to grant feature flags accompanied by key-value metadata. These flags can be queried via the Polar API and through webhooks, allowing you to control feature access dynamically based on user benefits.

    import { BenefitFeatureFlag } from "@polar-sh/sdk/models/components/benefitfeatureflag.js";
    
    let value: BenefitFeatureFlag = {
      id: "<value>",
      createdAt: new Date("2026-01-23T21:17:09.985Z"),
      modifiedAt: new Date("2026-03-18T19:56:22.426Z"),
      type: "feature_flag",
      description: "while dreary bestride revoke continually hm so terrible",
      selectable: true,
      deletable: true,
      isDeleted: true,
      organizationId: "<value>",
      metadata: {},
      visibility: "public",
      properties: {},
      visibilityConfigurable: false,
    };
  10. Use standalone functions for better tree-shaking

    main

    For optimal bundle size and tree-shaking performance, use the standalone function versions of API methods instead of the main Polar class. This requires using PolarCore instead of Polar.

    Example: Standalone checkEmailUpdate

    import { PolarCore } from "@polar-sh/sdk/core.js";
    import { customerPortalCustomersCheckEmailUpdate } from "@polar-sh/sdk/funcs/customerPortalCustomersCheckEmailUpdate.js";
    
    const polar = new PolarCore();
    
    async function run() {
      const res = await customerPortalCustomersCheckEmailUpdate(polar, {
        token: "<value>",
      });
      if (res.ok) {
        const { value: result } = res;
      } else {
        console.log("customerPortalCustomersCheckEmailUpdate failed:", res.error);
      }
    }
    
    run();

    Example: Standalone verifyEmailUpdate

    import { PolarCore } from "@polar-sh/sdk/core.js";
    import { customerPortalCustomersVerifyEmailUpdate } from "@polar-sh/sdk/funcs/customerPortalCustomersVerifyEmailUpdate.js";
    
    const polar = new PolarCore();
    
    async function run() {
      const res = await customerPortalCustomersVerifyEmailUpdate(polar, {
        token: "<value>",
      });
      if (res.ok) {
        const { value: result } = res;
        console.log(result);
      } else {
        console.log("customerPortalCustomersVerifyEmailUpdate failed:", res.error);
      }
    }
    
    run();