### Install TanStack Start Packages (bun) Source: https://polar.sh/docs/integrate/sdk/adapters/tanstack-start Installs the necessary Polar packages for TanStack Start using bun. This includes zod and the main tanstack-start library. ```bash bun add zod @polar-sh/tanstack-start ``` -------------------------------- ### Quickstart: Initialize Polar SDK and List User Benefits in TypeScript Source: https://polar.sh/docs/integrate/sdk/typescript A quickstart example demonstrating how to initialize the Polar SDK with an access token and server configuration. It then shows how to asynchronously fetch and iterate over a list of user benefits. ```typescript import { Polar } from '@polar-sh/sdk' const polar = new Polar({ accessToken: process.env.POLAR_ACCESS_TOKEN, server: process.env.POLAR_MODE || 'sandbox' // sandbox or production }) async function run() { const result = await polar.users.benefits.list({}) for await (const page of result) { // Handle the page console.log(page) } } run() ``` -------------------------------- ### Install TanStack Start Packages (yarn) Source: https://polar.sh/docs/integrate/sdk/adapters/tanstack-start Installs the necessary Polar packages for TanStack Start using yarn. This includes zod and the main tanstack-start library. ```bash yarn add zod @polar-sh/tanstack-start ``` -------------------------------- ### Install Polar Go SDK Source: https://polar.sh/docs/integrate/sdk/golang Installs the Polar Go SDK using the go get command. This is the first step to integrating Polar functionality into your Go applications. ```bash go get github.com/polarsource/polar-go ``` -------------------------------- ### Install TanStack Start Packages (npm) Source: https://polar.sh/docs/integrate/sdk/adapters/tanstack-start Installs the necessary Polar packages for TanStack Start using npm. This includes zod and the main tanstack-start library. ```bash npm install zod @polar-sh/tanstack-start ``` -------------------------------- ### Install TanStack Start Packages (pnpm) Source: https://polar.sh/docs/integrate/sdk/adapters/tanstack-start Installs the necessary Polar packages for TanStack Start using pnpm. This includes zod and the main tanstack-start library. ```bash pnpm add zod @polar-sh/tanstack-start ``` -------------------------------- ### Integration Guides Source: https://context7_llms Guides for integrating Polar with various frameworks and platforms. ```APIDOC ## Integrate Polar with Laravel ### Description In this guide, we'll show you how to integrate Polar with Laravel. ### Method N/A (Guide) ### Endpoint N/A (Guide) ## Integrate Polar with Next.js ### Description In this guide, we'll show you how to integrate Polar with Next.js. ### Method N/A (Guide) ### Endpoint N/A (Guide) ``` -------------------------------- ### Integrate Polar with Deno SDK Source: https://context7_llms This guide covers integrating Polar with Deno applications. It simplifies the process of adding payment and checkout functionalities. The example shows how to initialize the Polar client and create a checkout session using Deno's fetch API. ```typescript import { PolarClient } from '@polar-finance/sdk'; const polar = new PolarClient(Deno.env.get('POLAR_API_KEY')); async function createCheckout(email: string, productId: string): Promise { const checkout = await polar.createCheckout({ customer_email: email, products: [{ id: productId, quantity: 1 }], }); return checkout.url; } // Example usage: // const checkoutUrl = await createCheckout('test@example.com', 'prod_abc'); // console.log(checkoutUrl); ``` -------------------------------- ### Create Customer Portal with TanStack Start Source: https://polar.sh/docs/integrate/sdk/adapters/tanstack-start Implements a Customer Portal handler using TanStack Start. This allows customers to view orders and subscriptions, requiring an access token and a function to resolve customer IDs. ```typescript import { CustomerPortal } from "@polar-sh/tanstack-start"; import { createFileRoute } from "@tanstack/react-start"; import { getSupabaseServerClient } from "~/servers/supabase-server"; export const Route = createFileRoute("/api/portal")({ server: { handlers: { GET: CustomerPortal({ accessToken: POLAR_ACCESS_TOKEN, getCustomerId: async (request: Request) => "", // Function to resolve a Polar Customer ID returnUrl: "https://myapp.com", // An optional URL which renders a back-button in the Checkout server: "sandbox", // Use sandbox if you're testing Polar - omit the parameter or pass 'production' otherwise }), }, }, }); ``` -------------------------------- ### Quick Examples Source: https://polar.sh/docs/api-reference/introduction Provides quick cURL examples for interacting with the Core API (Production and Sandbox) and the Customer Portal API. ```APIDOC ## Quick Examples ### Production - Core API Example **Method:** GET **Endpoint:** `https://api.polar.sh/v1/products/` **Description:** Fetches a list of products from the production environment using an Organization Access Token. **Request Example:** ```bash curl https://api.polar.sh/v1/products/ \ -H "Authorization: Bearer $POLAR_OAT" \ -H "Accept: application/json" ``` ``` ```APIDOC ### Sandbox - Core API Example **Method:** GET **Endpoint:** `https://sandbox-api.polar.sh/v1/products/` **Description:** Fetches a list of products from the sandbox environment using a sandbox Organization Access Token. **Request Example:** ```bash curl https://sandbox-api.polar.sh/v1/products/ \ -H "Authorization: Bearer $POLAR_OAT_SANDBOX" \ -H "Accept: application/json" ``` ``` ```APIDOC ### Customer Portal API Example **Method:** GET **Endpoint:** `https://api.polar.sh/v1/customer-portal/orders/` **Description:** Fetches a list of orders for the authenticated customer using a Customer Access Token. **Request Example:** ```bash curl https://api.polar.sh/v1/customer-portal/orders/ \ -H "Authorization: Bearer $POLAR_CUSTOMER_TOKEN" \ -H "Accept: application/json" ``` ``` -------------------------------- ### Install Python SDK Source: https://polar.sh/docs/features/usage-based-billing/ingestion-strategies/llm-strategy Installs the Polar SDK for Python, which includes helpers for event ingestion and various strategies for common use cases. ```bash pip install polar-sdk ``` ```bash uv add polar-sdk ``` -------------------------------- ### Create Checkout Handler with TanStack Start Source: https://polar.sh/docs/integrate/sdk/adapters/tanstack-start Sets up a Checkout handler for API routes using TanStack Start. It configures access tokens, URLs, and server environment for Polar payments. ```typescript import { Checkout } from "@polar-sh/tanstack-start"; import { createFileRoute } from "@tanstack/react-start"; export const Route = createFileRoute("/api/checkout")({ server: { handlers: { GET: Checkout({ accessToken: process.env.POLAR_ACCESS_TOKEN, successUrl: process.env.SUCCESS_URL, returnUrl: "https://myapp.com", // An optional URL which renders a back-button in the Checkout server: "sandbox", // Use sandbox if you're testing Polar - omit the parameter or pass 'production' otherwise theme: "dark", // Enforces the theme - System-preferred theme will be set if left omitted }), }, }, }); ``` -------------------------------- ### Integrate Polar with Fastify SDK Source: https://context7_llms This guide details the integration of Polar with a Fastify application using the Polar SDK. It streamlines the implementation of payment and checkout functionalities. The example shows how to initialize the Polar client and create a checkout session within a Fastify route. ```javascript const fastify = require('fastify')(); const { PolarClient } = require('@polar-finance/sdk'); const polar = new PolarClient(process.env.POLAR_API_KEY); fastify.post('/create-checkout', async (request, reply) => { try { const checkout = await polar.createCheckout({ customer_email: request.body.email, products: request.body.products, }); reply.send({ url: checkout.url }); } catch (error) { reply.code(500).send({ error: error.message }); } }); const start = async () => { try { await fastify.listen(3000); console.log(`Server listening on port 3000`); } catch (err) { fastify.log.error(err); process.exit(1); } }; start(); ``` -------------------------------- ### Integrate Polar with Elysia SDK Source: https://context7_llms This guide details how to integrate Polar with Elysia, a fast and minimalist web framework. It simplifies adding payment and checkout functionalities. The example shows initializing the Polar client and creating a checkout session within an Elysia route. ```typescript import { Elysia, t } from 'elysia'; import { PolarClient } from '@polar-finance/sdk'; const app = new Elysia(); const polar = new PolarClient(process.env.POLAR_API_KEY); app.post('/create-checkout', async ({ body, set }) => { try { const checkout = await polar.createCheckout({ customer_email: body.email, products: body.products, }); return { url: checkout.url }; } catch (error) { set.status = 500; return { error: error.message }; } }, { body: t.Object({ email: t.String(), products: t.Array(t.Object({ id: t.String(), quantity: t.Number() })) }) } ) app.listen(3000); console.log('Elysia server running on port 3000'); ``` -------------------------------- ### Create Deno Customer Portal Handler Source: https://polar.sh/docs/integrate/sdk/adapters/deno Creates a Deno server endpoint for a customer portal. This allows customers to view their orders and subscriptions. It requires an access token, a function to get the customer ID, a return URL, and the server environment (e.g., 'sandbox'). ```typescript import { CustomerPortal } from "jsr:@polar-sh/deno"; Deno.serve( CustomerPortal({ accessToken: "xxx", getCustomerId: (req) => "", returnUrl: "https://myapp.com", // An optional URL which renders a back-button in the Customer Portal server: "sandbox", }) ); ``` -------------------------------- ### Quickstart: List Organizations with Go SDK Source: https://polar.sh/docs/integrate/sdk/golang Demonstrates how to initialize the Polar Go SDK and list organizations. It shows how to handle pagination and potential errors during the API call. Requires a POLAR_ACCESS_TOKEN environment variable for authentication. ```go package main import ( "context" polargo "github.com/polarsource/polar-go" "log" "os" ) func main() { ctx := context.Background() s := polargo.New( polargo.WithSecurity(os.Getenv("POLAR_ACCESS_TOKEN")), ) res, err := s.Organizations.List(ctx, nil, polargo.Pointer[int64](1), polargo.Pointer[int64](10), nil) if err != nil { log.Fatal(err) } if res.ListResourceOrganization != nil { for { // handle items res, err = res.Next() if err != nil { // handle error } if res == nil { break } } } } ``` -------------------------------- ### TanStack Start Adapter for Polar Payments Source: https://context7_llms Integrate Polar payments and checkouts with TanStack Start. This adapter simplifies the setup and management of transactions within the TanStack Start framework. ```typescript import { polar } from "@polar-sh/sdk"; // Initialize Polar SDK polar.init({ apiKey: "YOUR_POLAR_API_KEY", }); // Example usage in a TanStack Start route handler export async function POST({ request }) { const payload = await request.json(); // Handle payment events await polar.webhooks.handleEvent(payload); return new Response(null, { status: 200 }); } ``` -------------------------------- ### Create an OAuth 2.0 Client for Polar Integration Source: https://context7_llms This guide details the process of creating an OAuth 2.0 client to integrate with Polar. It covers the necessary steps for setting up the client credentials and understanding the OAuth flow for authorization. This is essential for third-party applications interacting with Polar. ```bash # Example using curl to initiate the OAuth flow (conceptual) CLIENT_ID="your_client_id" REDIRECT_URI="your_redirect_uri" curl -G https://polar.sh/oauth/authorize \ --data-urlencode "response_type=code" \ --data-urlencode "client_id=$CLIENT_ID" \ --data-urlencode "redirect_uri=$REDIRECT_URI" \ --data-urlencode "scope=read write" ``` -------------------------------- ### Create Basic Checkout Session (Python) Source: https://polar.sh/docs/features/checkout/session Illustrates how to create a basic checkout session with the Polar Python SDK. This example focuses on initiating a checkout for a product. ```Python from polar_sdk import Polar with Polar( access_token="", ) as polar: checkout = polar.checkouts.create(request={ "allow_discount_codes": True, "product_id": "", }) print(checkout.url) ``` -------------------------------- ### Make Authenticated API Request Source: https://polar.sh/docs/integrate/oauth2/connect Example of how to make an authenticated request to the Polar API using an access token. ```APIDOC ## Authenticated API Request ### Description Once you have obtained an access token (either from a Personal Access Token or the OAuth2 flow), you can use it to authenticate requests to the Polar API. ### Method GET ### Endpoint `https://api.polar.sh/v1/oauth2/userinfo` ### Parameters #### Headers - **Authorization** (string) - Required - The access token prefixed with `Bearer `. ### Request Example ```bash curl -X GET https://api.polar.sh/v1/oauth2/userinfo \ -H 'Authorization: Bearer polar_at_XXX' ``` ### Response #### Success Response (200) - **userinfo** (object) - Contains information about the authenticated user or organization. ``` -------------------------------- ### Integrate Polar with Next.js Source: https://context7_llms This guide explains how to integrate Polar into a Next.js application. It provides examples for setting up Polar payments and checkouts within a Next.js environment. Dependencies include Next.js and the Polar SDK. ```javascript import { PolarClient } from '@polar-finance/sdk'; const polar = new PolarClient(process.env.POLAR_API_KEY); async function createCheckout(email, productId) { const checkout = await polar.createCheckout({ customer_email: email, products: [{ id: productId, quantity: 1 }], }); return checkout.url; } ``` -------------------------------- ### Integrate Polar with BetterAuth SDK Source: https://context7_llms This guide explains how to integrate Polar with BetterAuth, simplifying payments and checkouts. The code snippet shows the basic setup for initializing the Polar client, assuming BetterAuth handles the underlying authentication and request context. ```javascript import { PolarClient } from '@polar-finance/sdk'; // Assuming BetterAuth provides access to API keys or configuration const polar = new PolarClient(process.env.POLAR_API_KEY); async function createCheckout(email, productId) { // This function would be called within a BetterAuth protected route or handler const checkout = await polar.createCheckout({ customer_email: email, products: [{ id: productId, quantity: 1 }], }); return checkout.url; } ``` -------------------------------- ### Initialize Polar SDK with Sandbox Server Source: https://polar.sh/docs/api-reference/introduction Demonstrates how to initialize the Polar SDK for sandbox usage across multiple programming languages. This ensures that API calls are directed to a testing environment rather than the live production server. The `server` parameter is crucial for this configuration. ```typescript import { Polar } from "@polar-sh/sdk"; const polar = new Polar({ accessToken: process.env.POLAR_ACCESS_TOKEN!, server: "sandbox", // omit or use 'production' for live }); ``` ```python from polar import Polar client = Polar( access_token=os.environ["POLAR_ACCESS_TOKEN"], server="sandbox", ) ``` ```go s := polargo.New( polargo.WithServer("sandbox"), polargo.WithSecurity(os.Getenv("POLAR_ACCESS_TOKEN")), ) ``` ```php $sdk = Polar\Polar::builder() ->setServer('sandbox') ->setSecurity(getenv('POLAR_ACCESS_TOKEN')) ->build(); ``` -------------------------------- ### Define Route for Products in Laravel Source: https://polar.sh/docs/guides/laravel This PHP code snippet defines a GET route for '/products' in Laravel's web.php file, which will be handled by the 'handle' method of the ProductsController. It's a basic routing setup for fetching and displaying products. ```php // routes/web.php Route::get('/products', [ProductsController::class, 'handle']); ``` -------------------------------- ### POST /v1/subscriptions/ Source: https://polar.sh/docs/api-reference/subscriptions/create Create a subscription programmatically for free products. This endpoint does not create an initial order or send a confirmation email. Requires 'subscriptions:write' scope. ```APIDOC ## POST /v1/subscriptions/ ### Description Create a subscription programmatically. This endpoint only allows to create subscription on free products. For paid products, use the checkout flow. No initial order will be created and no confirmation email will be sent. **Scopes**: `subscriptions:write` ### Method POST ### Endpoint /v1/subscriptions/ ### Parameters #### Request Body - **metadata** (object) - Optional - Key-value object allowing you to store additional information. The key must be a string with a maximum length of 40 characters. The value must be a string (max 500 chars), integer, float, or boolean. Up to 50 key-value pairs. - **product_id** (string) - Required - The ID of the recurring product to subscribe to. Must be a free product. - **customer_id** (string) - Required - The ID of the customer to create the subscription for. ### Request Example ```json { "metadata": { "internal_ref": "abc-123" }, "product_id": "d8dd2de1-21b7-4a41-8bc3-ce909c0cfe23", "customer_id": "992fae2a-2a17-4b7a-8d9e-e287cf90131b" } ``` ### Response #### Success Response (201) - **Subscription** (object) - Details of the created subscription. #### Response Example ```json { "id": "sub_12345", "customer_id": "cust_67890", "product_id": "prod_abcde", "status": "active", "created_at": "2023-10-27T10:00:00Z", "current_period_end": "2023-11-27T10:00:00Z" } ``` #### Error Response (422) - **HTTPValidationError** (object) - Details of the validation error. ``` -------------------------------- ### Exchange Authorization Code for Access Token using cURL Source: https://polar.sh/docs/integrate/oauth2/connect This example shows how to exchange an authorization code for an access token using a cURL POST request. It requires the `grant_type`, `code`, `client_id`, `client_secret`, and `redirect_uri`. The response contains `access_token`, `refresh_token`, and `id_token`. ```bash curl -X POST https://api.polar.sh/v1/oauth2/token \ -H 'Content-Type: application/x-www-form-urlencoded' \ -d 'grant_type=authorization_code&code=AUTHORIZATION_CODE&client_id=CLIENT_ID&client_secret=CLIENT_SECRET&redirect_uri=https://example.com/callback' ``` -------------------------------- ### POST /products Source: https://polar.sh/docs/api-reference/products/create Creates a new product. This endpoint requires the `products:write` scope. ```APIDOC ## POST /products ### Description Creates a new product. This endpoint requires the `products:write` scope. ### Method POST ### Endpoint /products ### Parameters #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the product. - **description** (string) - Optional - A detailed description of the product. - **price** (number) - Required - The price of the product. ### Request Example ```json { "name": "Example Product", "description": "This is a sample product.", "price": 99.99 } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier of the created product. - **name** (string) - The name of the product. - **description** (string) - The description of the product. - **price** (number) - The price of the product. #### Response Example ```json { "id": "prod_12345", "name": "Example Product", "description": "This is a sample product.", "price": 99.99 } ``` ``` -------------------------------- ### Make Authenticated API Request with cURL Source: https://polar.sh/docs/integrate/oauth2/connect This cURL command demonstrates how to make an authenticated GET request to the Polar API's user info endpoint. It requires an Authorization header with a Bearer token, which can be obtained from a Personal Access Token or the OpenID Connect flow. ```bash curl -X GET https://api.polar.sh/v1/oauth2/userinfo \ -H 'Authorization: Bearer polar_at_XXX' ``` -------------------------------- ### SDK Adapters Source: https://context7_llms Guides for integrating Polar using various SDK adapters for different frameworks. ```APIDOC ## Astro SDK Adapter ### Description Payments and Checkouts made dead simple with Astro. ### Method N/A (Guide) ### Endpoint N/A (Guide) ## BetterAuth SDK Adapter ### Description Payments and Checkouts made dead simple with BetterAuth. ### Method N/A (Guide) ### Endpoint N/A (Guide) ## Deno SDK Adapter ### Description Payments and Checkouts made dead simple with Deno. ### Method N/A (Guide) ### Endpoint N/A (Guide) ## Elysia SDK Adapter ### Description Payments and Checkouts made dead simple with Elysia. ### Method N/A (Guide) ### Endpoint N/A (Guide) ## Express SDK Adapter ### Description Payments and Checkouts made dead simple with Express. ### Method N/A (Guide) ### Endpoint N/A (Guide) ## Fastify SDK Adapter ### Description Payments and Checkouts made dead simple with Fastify. ### Method N/A (Guide) ### Endpoint N/A (Guide) ## Hono SDK Adapter ### Description Payments and Checkouts made dead simple with Hono. ### Method N/A (Guide) ### Endpoint N/A (Guide) ## Laravel SDK Adapter ### Description Payments and Checkouts made dead simple with Laravel. ### Method N/A (Guide) ### Endpoint N/A (Guide) ## Next.js SDK Adapter ### Description Payments and Checkouts made dead simple with Next.js. ### Method N/A (Guide) ### Endpoint N/A (Guide) ## Nuxt SDK Adapter ### Description Payments and Checkouts made dead simple with Nuxt. ### Method N/A (Guide) ### Endpoint N/A (Guide) ``` -------------------------------- ### Customer Portal API Source: https://polar.sh/docs/integrate/sdk/adapters/tanstack-start Creates a customer portal where customers can view their orders and subscriptions. ```APIDOC ## GET /api/portal ### Description Creates a customer portal where customers can view their orders and subscriptions. ### Method GET ### Endpoint /api/portal ### Parameters #### Request Body - **accessToken** (string) - Required - Your Polar API access token. - **getCustomerId** (function) - Required - A function that resolves the Polar Customer ID. - **returnUrl** (string) - Optional - The URL to redirect to after actions in the portal. - **server** (string) - Optional - Specifies the server environment ('sandbox' or 'production'). Defaults to 'production'. ### Request Example ```json { "accessToken": "YOUR_POLAR_ACCESS_TOKEN", "getCustomerId": "async (request: Request) => \"customer_id\"", "returnUrl": "https://myapp.com/portal/return", "server": "sandbox" } ``` ### Response #### Success Response (200) This endpoint renders the customer portal interface. #### Response Example (Customer portal interface) ``` -------------------------------- ### Create Basic Checkout Session (TypeScript) Source: https://polar.sh/docs/features/checkout/session A simple example of creating a checkout session using the Polar TypeScript SDK without specifying ad-hoc prices. This is for standard product checkouts. ```TypeScript import { Polar } from "@polar-sh/sdk"; const polar = new Polar({ accessToken: process.env["POLAR_ACCESS_TOKEN"] ?? "", }); async function run() { const checkout = await polar.checkouts.create({ products: ["productId"] }); console.log(checkout.url) } run(); ``` -------------------------------- ### POST /v1/customers/ Source: https://polar.sh/docs/api-reference/customers/create Create a new customer with the provided details. This endpoint allows for the creation of customers, including their contact information, billing address, and tax ID. ```APIDOC ## POST /v1/customers/ ### Description Create a customer. ### Method POST ### Endpoint /v1/customers/ ### Parameters #### Request Body - **metadata** (object) - Optional - Key-value object allowing you to store additional information. The key must be a string with a maximum length of 40 characters. The value must be either a string (max 500 chars), an integer, a floating-point number, or a boolean. You can store up to 50 key-value pairs. - **external_id** (string | null) - Optional - The ID of the customer in your system. This must be unique within the organization. Once set, it can't be updated. - **email** (string) - Required - The email address of the customer. This must be unique within the organization. - **name** (string | null) - Optional - The name of the customer. - **billing_address** (object | null) - Optional - The billing address of the customer. See AddressInput schema for details. - **tax_id** (array | null) - Optional - The tax ID of the customer. Expects an array of two strings: the tax ID and its format (e.g., ['911144442', 'us_ein']). - **type** (string | null) - Optional - The type of customer. Defaults to 'individual'. Set to 'team' for customers that can have multiple members. - **organization_id** (string | null) - Optional - The ID of the organization owning the customer. Required unless you use an organization token. - **owner** (object | null) - Optional - Information about the owner of the customer. ### Request Example ```json { "email": "customer@example.com", "name": "John Doe", "external_id": "usr_1337", "metadata": { "internal_ref": "ref_abc" }, "billing_address": { "address1": "123 Main St", "city": "Anytown", "state": "CA", "postal_code": "90210", "country": "US" }, "tax_id": [ "911144442", "us_ein" ], "type": "individual" } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier for the customer. - **created_at** (string) - The timestamp when the customer was created. - **customer_polar_url** (string) - A URL to the customer's page in Polar. - **email** (string) - The email address of the customer. - **name** (string) - The name of the customer. - **balance** (integer) - The current balance of the customer. - **has_strong_authentication** (boolean) - Indicates if the customer has strong authentication enabled. - **is_delinquent** (boolean) - Indicates if the customer is delinquent. - **organization_id** (string) - The ID of the organization owning the customer. - **tax_form** (string) - The tax form associated with the customer. - **tax_withholding** (number) - The tax withholding amount for the customer. - **address** (object) - The billing address of the customer. - **tax_id** (array) - The tax ID of the customer. - **type** (string) - The type of customer. - **external_id** (string) - The external ID of the customer. - **metadata** (object) - Additional metadata for the customer. - **created_by** (object) - Information about the user who created the customer. - **payment_provider_id** (string) - The ID of the customer in the payment provider. - **default_currency** (string) - The default currency for the customer. - **automatic_payment_failed_count** (integer) - The number of failed automatic payments for the customer. - **next_invoice_sequence** (integer) - The next invoice sequence number for the customer. - **due_since** (string) - The date since the customer is due. - **feature_flags** (array) - A list of feature flags enabled for the customer. - **is_legacy** (boolean) - Indicates if the customer is a legacy customer. - **id_str** (string) - The string representation of the customer ID. - **created_at_ts** (integer) - The timestamp when the customer was created (in seconds). - **updated_at** (string) - The timestamp when the customer was last updated. - **updated_at_ts** (integer) - The timestamp when the customer was last updated (in seconds). - **deleted_at** (string) - The timestamp when the customer was deleted. - **deleted_at_ts** (integer) - The timestamp when the customer was deleted (in seconds). - **owner** (object) - Information about the owner of the customer. - **members** (array) - A list of members associated with the customer. #### Response Example ```json { "id": "cus_abc123", "created_at": "2023-10-27T10:00:00.000Z", "customer_polar_url": "https://polar.sh/customers/cus_abc123", "email": "customer@example.com", "name": "John Doe", "balance": 0, "has_strong_authentication": false, "is_delinquent": false, "organization_id": "org_xyz789", "tax_form": null, "tax_withholding": 0, "address": { "address1": "123 Main St", "city": "Anytown", "state": "CA", "postal_code": "90210", "country": "US" }, "tax_id": [ "911144442", "us_ein" ], "type": "individual", "external_id": "usr_1337", "metadata": { "internal_ref": "ref_abc" }, "created_by": { "id": "use_def456", "email": "user@example.com" }, "payment_provider_id": null, "default_currency": "USD", "automatic_payment_failed_count": 0, "next_invoice_sequence": 1, "due_since": null, "feature_flags": [], "is_legacy": false, "id_str": "cus_abc123", "created_at_ts": 1698397200, "updated_at": "2023-10-27T10:00:00.000Z", "updated_at_ts": 1698397200, "deleted_at": null, "deleted_at_ts": null, "owner": { "name": "John Doe", "email": "customer@example.com" }, "members": [] } ``` #### Error Response (422) - **detail** (array) - An array of validation errors. #### Response Example ```json { "detail": [ { "loc": [ "body", "email" ], "msg": "field required", "type": "value_error.missing" } ] } ``` ``` -------------------------------- ### Install Polar.sh Packages for Next.js Source: https://polar.sh/docs/integrate/sdk/adapters/nextjs Installs the required Polar.sh packages for Next.js applications using various package managers. Ensure zod is also installed as it's a dependency. ```bash npm install zod @polar-sh/nextjs ``` ```bash yarn add zod @polar-sh/nextjs ``` ```bash pnpm add zod @polar-sh/nextjs ``` ```bash bun add zod @polar-sh/nextjs ``` -------------------------------- ### Install Polar.sh SvelteKit Packages Source: https://polar.sh/docs/integrate/sdk/adapters/sveltekit Installs the required Polar.sh packages for SvelteKit using various package managers (npm, yarn, pnpm, bun). Ensure zod is also installed as a dependency. ```bash npm install zod @polar-sh/sveltekit ``` ```bash yarn add zod @polar-sh/sveltekit ``` ```bash pnpm add zod @polar-sh/sveltekit ``` ```bash bun add zod @polar-sh/sveltekit ``` -------------------------------- ### Example Usage Flow for Credits with TypeScript Source: https://polar.sh/docs/guides/grant-meter-credits-before-purchase Illustrates a typical flow for managing customer credits using the Polar.sh SDK. It shows how granting credits, customer usage, and subsequent balance updates are handled by ingesting 'api_usage' events. This example demonstrates the state changes of a customer's credit balance over time. ```typescript // Initial state: Customer created, 0 balance // Grant 10 credits: balance = 10 // Customer uses 3 units await polar.events.ingest({ events: [{ name: "api_usage", customerId: "cus_abc123", metadata: { units: 3 } // Positive value for usage }] }); // Balance is now 7 (7 credits remaining) // Customer uses 8 more units await polar.events.ingest({ events: [{ name: "api_usage", customerId: "cus_abc123", metadata: { units: 8 } }] }); // Balance is now -1 (used 1 unit beyond credits) ``` -------------------------------- ### POST /v1/checkout-links/ Source: https://polar.sh/docs/guides/customize-products-order-in-checkouts Create a checkout link with a specified order of products. The order of product IDs in the 'products' array determines their display order in the checkout. ```APIDOC ## POST /v1/checkout-links/ ### Description Creates a checkout link with products in a specified order. ### Method POST ### Endpoint /v1/checkout-links/ ### Parameters #### Request Body - **products** (array[string]) - Required - An array of product IDs in the desired display order. ### Request Example ```json { "products": [ "", "" ] } ``` ### Response #### Success Response (200) - **url** (string) - The URL of the created checkout link. #### Response Example ```json { "url": "https://buy.polar.sh/polar_cl_..." } ``` ``` -------------------------------- ### Install Polar Packages with npm, yarn, pnpm, or bun Source: https://polar.sh/docs/integrate/sdk/adapters/elysia Installs the necessary Polar packages for Elysia integration using various package managers. Ensure you have Node.js and a package manager installed. ```bash npm install zod @polar-sh/elysia ``` ```bash yarn add zod @polar-sh/elysia ``` ```bash pnpm add zod @polar-sh/elysia ``` ```bash bun add zod @polar-sh/elysia ``` -------------------------------- ### Install Polar Express Packages (npm, yarn, pnpm, bun) Source: https://polar.sh/docs/integrate/sdk/adapters/express Installs the necessary Polar packages for Express.js integration using various package managers. Ensure zod is also installed as a dependency. ```bash npm install zod @polar-sh/express ``` ```bash yarn add zod @polar-sh/express ``` ```bash pnpm add zod @polar-sh/express ``` ```bash bun add zod @polar-sh/express ``` -------------------------------- ### Checkout Link JSON Response Example Source: https://polar.sh/docs/guides/customize-products-order-in-checkouts This is an example of the JSON response received after creating a checkout link. The 'url' key contains the link to the checkout page where products will be displayed in the order specified. ```json { "...": "...", "...": "...", "url": "https://buy.polar.sh/polar_cl_..." // [!code ++] } ``` -------------------------------- ### Handle Webhooks with TanStack Start Source: https://polar.sh/docs/integrate/sdk/adapters/tanstack-start Provides a utility to resolve incoming webhook payloads by verifying the webhook secret. It includes a callback function to handle the payload data. ```typescript import { Webhooks } from "@polar-sh/tanstack-start"; import { createFileRoute } from "@tanstack/react-router"; export const Route = createFileRoute("/api/webhook/polar")({ server: { handlers: { POST: Webhooks({ webhookSecret: process.env.POLAR_WEBHOOK_SECRET!, onPayload: async (payload) => { // Handle the payload // No need to return an acknowledge response }, }), }, }, }); ```