Examples
Installation
npm install @polar-sh/sdk
Quickstart
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()
camelCase vs. snake_caseOur API (and docs) is designed with snake_case. However, our TS SDK currently
converts this to camelCase to follow JS/TS convention. You should automatically
see the camelCase parameters suggested in modern IDEs due to typing, but it’s
worth keeping in mind switching between code & docs.We aim to introduce the ability to toggle this in the future, i.e using
snake_case even in TypeScript to more easily map it to our documentation and
design of the API itself.
Authentication
The SDK requires an Organization Access Token for authentication. You can generate one from your organization’s settings in the Polar dashboard.
const polar = new Polar({
accessToken: process.env.POLAR_ACCESS_TOKEN
})
Common Operations
Create a Checkout Session
Create a checkout session to accept payments:
const checkout = await polar.checkouts.create({
products: ['prod_xxxxxxxxxxxxx'],
successUrl: 'https://myapp.com/success',
returnUrl: 'https://myapp.com'
})
// Redirect user to checkout.url
console.log(checkout.url)
Get Customer State
Retrieve a customer’s active subscriptions and benefits using their external ID:
const customerState = await polar.customers.getStateExternal({
externalCustomerId: 'user_123'
})
console.log(customerState.grantedBenefits)
console.log(customerState.subscriptions)
List Products
Get all products for an organization:
const products = await polar.products.list({
organizationId: 'org_xxxxxxxxxxxxx'
})
for await (const page of products) {
console.log(page)
}
Handle Pagination
The SDK automatically handles pagination for list endpoints:
const result = await polar.users.benefits.list({})
for await (const page of result) {
// Process each page of results
page.items.forEach(benefit => {
console.log(benefit.id)
})
}
Sandbox Environment
For testing, use the sandbox environment:
const polar = new Polar({
accessToken: process.env.POLAR_ACCESS_TOKEN,
server: 'sandbox'
})
Framework Adapters
Implement Checkout & Webhook handlers in few lines of code.