polar-sh / sdk
Requires
- php: ^8.2
- brick/date-time: ^0.7.0
- brick/math: ^0.12.1
- galbar/jsonpath: ^3.0
- guzzlehttp/guzzle: ^7.0
- phpdocumentor/type-resolver: ^1.8
- speakeasy/serializer: ^4.0.3
Requires (Dev)
- laravel/pint: ^1.21.2
- orchestra/testbench: ^9.6
- phpstan/phpstan: ^2.1.0
- phpunit/phpunit: ^10
- roave/security-advisories: dev-latest
This package is auto-updated.
Last update: 2025-06-05 16:20:04 UTC
README
Developer-friendly & type-safe Php SDK specifically catered to leverage polar-sh/sdk API.
Important
This SDK is not yet ready for production use. To complete setup please follow the steps outlined in your workspace. Delete this section before > publishing to a package manager.
Summary
Polar API: Polar HTTP and Webhooks API
Read the docs at https://docs.polar.sh/api-reference
Table of Contents
SDK Installation
The SDK relies on Composer to manage its dependencies.
To install the SDK and add it as a dependency to an existing composer.json
file:
composer require "polar-sh/sdk"
SDK Example Usage
Example
declare(strict_types=1); require 'vendor/autoload.php'; use Polar; use Polar\Models\Components; use Polar\Utils; $sdk = Polar\Polar::builder()->build(); $request = new Components\WebhookCheckoutCreatedPayload( data: new Components\Checkout( createdAt: Utils\Utils::parseDateTime('2023-02-15T15:44:21.478Z'), modifiedAt: Utils\Utils::parseDateTime('2025-09-12T19:48:15.814Z'), id: '<value>', paymentProcessor: Components\PaymentProcessor::Stripe, status: Components\CheckoutStatus::Expired, clientSecret: '<value>', url: 'https://fair-veto.com/', expiresAt: Utils\Utils::parseDateTime('2025-03-15T14:26:53.109Z'), successUrl: 'https://junior-linseed.net/', embedOrigin: '<value>', amount: 631188, discountAmount: 968968, netAmount: 929514, taxAmount: 323773, totalAmount: 115799, currency: 'Som', productId: '<value>', productPriceId: '<value>', discountId: '<value>', allowDiscountCodes: false, requireBillingAddress: false, isDiscountApplicable: false, isFreeProductPrice: false, isPaymentRequired: false, isPaymentSetupRequired: false, isPaymentFormRequired: false, customerId: '<value>', isBusinessCustomer: false, customerName: '<value>', customerEmail: '<value>', customerIpAddress: '<value>', customerBillingName: '<value>', customerBillingAddress: new Components\Address( country: 'US', ), customerTaxId: '<id>', paymentProcessorMetadata: [ 'key' => '<value>', ], metadata: [ 'key' => false, ], customerExternalId: '<id>', products: [ new Components\CheckoutProduct( createdAt: Utils\Utils::parseDateTime('2023-10-30T00:08:39.161Z'), modifiedAt: Utils\Utils::parseDateTime('2023-01-11T22:31:47.320Z'), id: '<value>', name: '<value>', description: 'commodity woefully thick scarper replacement', recurringInterval: Components\SubscriptionRecurringInterval::Month, isRecurring: false, isArchived: false, organizationId: '<value>', prices: [ new Components\ProductPriceFree( createdAt: Utils\Utils::parseDateTime('2025-04-06T21:19:53.791Z'), modifiedAt: Utils\Utils::parseDateTime('2025-11-01T17:42:17.316Z'), id: '<value>', isArchived: false, productId: '<value>', type: Components\ProductPriceType::OneTime, recurringInterval: Components\SubscriptionRecurringInterval::Month, ), ], benefits: [ new Components\BenefitPublic( id: '<value>', createdAt: Utils\Utils::parseDateTime('2023-06-01T15:28:54.615Z'), modifiedAt: Utils\Utils::parseDateTime('2024-08-02T17:12:30.950Z'), type: Components\BenefitType::Custom, description: 'graceful structure tenderly dirty colon though faithfully how next accomplished', selectable: false, deletable: false, organizationId: '<value>', ), ], medias: [ new Components\ProductMediaFileRead( id: '<value>', organizationId: '<value>', name: '<value>', path: '/Applications', mimeType: '<value>', size: 572714, storageVersion: '<value>', checksumEtag: '<value>', checksumSha256Base64: '<value>', checksumSha256Hex: '<value>', lastModifiedAt: Utils\Utils::parseDateTime('2023-10-22T16:07:40.109Z'), version: '<value>', isUploaded: false, createdAt: Utils\Utils::parseDateTime('2025-01-26T05:36:04.109Z'), sizeReadable: '<value>', publicUrl: 'https://joyous-midwife.org/', ), ], ), ], product: new Components\CheckoutProduct( createdAt: Utils\Utils::parseDateTime('2025-09-23T14:09:57.086Z'), modifiedAt: Utils\Utils::parseDateTime('2023-11-12T23:35:10.131Z'), id: '<value>', name: '<value>', description: 'glaring home indolent', recurringInterval: Components\SubscriptionRecurringInterval::Year, isRecurring: false, isArchived: false, organizationId: '<value>', prices: [ new Components\ProductPriceMeteredUnit( createdAt: Utils\Utils::parseDateTime('2023-12-27T05:27:05.016Z'), modifiedAt: Utils\Utils::parseDateTime('2024-08-27T14:04:32.879Z'), id: '<value>', isArchived: false, productId: '<value>', type: Components\ProductPriceType::Recurring, recurringInterval: Components\SubscriptionRecurringInterval::Month, priceCurrency: '<value>', unitAmount: '<value>', capAmount: 503783, meterId: '<value>', meter: new Components\ProductPriceMeter( id: '<value>', name: '<value>', ), ), ], benefits: [ new Components\BenefitPublic( id: '<value>', createdAt: Utils\Utils::parseDateTime('2025-09-17T18:38:51.288Z'), modifiedAt: Utils\Utils::parseDateTime('2023-07-11T10:52:20.563Z'), type: Components\BenefitType::Custom, description: 'tenement whose discontinue duh limp', selectable: false, deletable: false, organizationId: '<value>', ), ], medias: [ new Components\ProductMediaFileRead( id: '<value>', organizationId: '<value>', name: '<value>', path: '/etc/periodic', mimeType: '<value>', size: 567071, storageVersion: '<value>', checksumEtag: '<value>', checksumSha256Base64: '<value>', checksumSha256Hex: '<value>', lastModifiedAt: Utils\Utils::parseDateTime('2024-03-23T13:16:28.157Z'), version: '<value>', isUploaded: false, createdAt: Utils\Utils::parseDateTime('2025-07-11T07:27:27.079Z'), sizeReadable: '<value>', publicUrl: 'https://nautical-formation.name', ), ], ), productPrice: new Components\LegacyRecurringProductPriceFixed( createdAt: Utils\Utils::parseDateTime('2024-01-27T18:07:00.005Z'), modifiedAt: Utils\Utils::parseDateTime('2025-07-02T13:05:31.034Z'), id: '<value>', isArchived: false, productId: '<value>', recurringInterval: Components\SubscriptionRecurringInterval::Year, priceCurrency: '<value>', priceAmount: 721380, ), discount: new Components\CheckoutDiscountPercentageRepeatDuration( duration: Components\DiscountDuration::Repeating, durationInMonths: 232529, type: Components\DiscountType::Fixed, basisPoints: 874811, id: '<value>', name: '<value>', code: '<value>', ), subscriptionId: '<value>', attachedCustomFields: [ new Components\AttachedCustomField( customFieldId: '<value>', customField: new Components\CustomFieldSelect( createdAt: Utils\Utils::parseDateTime('2023-04-26T15:28:45.523Z'), modifiedAt: Utils\Utils::parseDateTime('2023-01-04T08:21:13.484Z'), id: '<value>', metadata: [ 'key' => false, ], slug: '<value>', name: '<value>', organizationId: '1dbfc517-0bbf-4301-9ba8-555ca42b9737', properties: new Components\CustomFieldSelectProperties( options: [ new Components\CustomFieldSelectOption( value: '<value>', label: '<value>', ), ], ), ), order: 800933, required: false, ), ], customerMetadata: [ 'key' => false, ], customerBillingAddressFields: new Components\CheckoutCustomerBillingAddressFields( country: false, state: false, city: false, postalCode: false, line1: false, line2: false, ), ), ); $response = $sdk->endpointcheckoutCreatedPost( request: $request ); if ($response->any !== null) { // handle response }
Authentication
Per-Client Security Schemes
This SDK supports the following security scheme globally:
Name | Type | Scheme |
---|---|---|
accessToken |
http | HTTP Bearer |
To authenticate with the API the accessToken
parameter must be set when initializing the SDK. For example:
declare(strict_types=1); require 'vendor/autoload.php'; use Polar; use Polar\Models\Components; $sdk = Polar\Polar::builder() ->setSecurity( '<YOUR_BEARER_TOKEN_HERE>' ) ->build(); $responses = $sdk->organizations->list( slug: '<value>', page: 1, limit: 10, sorting: [ Components\OrganizationSortProperty::CreatedAt, ] ); foreach ($responses as $response) { if ($response->statusCode === 200) { // handle response } }
Per-Operation Security Schemes
Some operations in this SDK require the security scheme to be specified at the request level. For example:
declare(strict_types=1); require 'vendor/autoload.php'; use Polar; use Polar\Models\Operations; $sdk = Polar\Polar::builder()->build(); $request = new Operations\CustomerPortalBenefitGrantsListRequest( organizationId: '1dbfc517-0bbf-4301-9ba8-555ca42b9737', ); $requestSecurity = new Operations\CustomerPortalBenefitGrantsListSecurity( customerSession: '<YOUR_BEARER_TOKEN_HERE>', ); $responses = $sdk->customerPortal->benefitGrants->list( request: $request, security: $requestSecurity ); foreach ($responses as $response) { if ($response->statusCode === 200) { // handle response } }
Available Resources and Operations
Available methods
benefits
- list - List Benefits
- create - Create Benefit
- get - Get Benefit
- update - Update Benefit
- delete - Delete Benefit
- grants - List Benefit Grants
checkoutLinks
- list - List Checkout Links
- create - Create Checkout Link
- get - Get Checkout Link
- update - Update Checkout Link
- delete - Delete Checkout Link
checkouts
- list - List Checkout Sessions
- create - Create Checkout Session
- get - Get Checkout Session
- update - Update Checkout Session
- clientGet - Get Checkout Session from Client
- clientUpdate - Update Checkout Session from Client
- clientConfirm - Confirm Checkout Session from Client
customerMeters
customerPortal
customerPortal->benefitGrants
customerPortal->customerMeters
customerPortal->customers
- get - Get Customer
- update - Update Customer
- getPaymentMethods - Get Customer Payment Methods
- addPaymentMethod - Add Customer Payment Method
- deletePaymentMethod - Delete Customer Payment Method
customerPortal->downloadables
customerPortal->licenseKeys
- list - List License Keys
- get - Get License Key
- validate - Validate License Key
- activate - Activate License Key
- deactivate - Deactivate License Key
customerPortal->orders
- list - List Orders
- get - Get Order
- update - Update Order
- generateInvoice - Generate Order Invoice
- invoice - Get Order Invoice
customerPortal->organizations
- get - Get Organization
customerPortal->subscriptions
- list - List Subscriptions
- get - Get Subscription
- update - Update Subscription
- cancel - Cancel Subscription
customers
- list - List Customers
- create - Create Customer
- get - Get Customer
- update - Update Customer
- delete - Delete Customer
- getExternal - Get Customer by External ID
- updateExternal - Update Customer by External ID
- deleteExternal - Delete Customer by External ID
- getState - Get Customer State
- getStateExternal - Get Customer State by External ID
customerSessions
- create - Create Customer Session
customFields
- list - List Custom Fields
- create - Create Custom Field
- get - Get Custom Field
- update - Update Custom Field
- delete - Delete Custom Field
discounts
- list - List Discounts
- create - Create Discount
- get - Get Discount
- update - Update Discount
- delete - Delete Discount
events
files
- list - List Files
- create - Create File
- uploaded - Complete File Upload
- update - Update File
- delete - Delete File
licenseKeys
- list - List License Keys
- get - Get License Key
- update - Update License Key
- getActivation - Get Activation
meters
- list - List Meters
- create - Create Meter
- get - Get Meter
- update - Update Meter
- quantities - Get Meter Quantities
metrics
oauth2
- authorize - Authorize
- token - Request Token
- revoke - Revoke Token
- introspect - Introspect Token
- userinfo - Get User Info
oauth2->clients
- list - List Clients
- create - Create Client
- get - Get Client
- update - Update Client
- delete - Delete Client
orders
- list - List Orders
- get - Get Order
- update - Update Order
- generateInvoice - Generate Order Invoice
- invoice - Get Order Invoice
organizations
- list - List Organizations
- create - Create Organization
- get - Get Organization
- update - Update Organization
payments
products
- list - List Products
- create - Create Product
- get - Get Product
- update - Update Product
- updateBenefits - Update Product Benefits
refunds
subscriptions
Pagination
Some of the endpoints in this SDK support pagination. To use pagination, you make your SDK calls as usual, but the
returned object will be a Generator
instead of an individual response.
Working with generators is as simple as iterating over the responses in a foreach
loop, and you can see an example below:
declare(strict_types=1); require 'vendor/autoload.php'; use Polar; use Polar\Models\Components; $sdk = Polar\Polar::builder() ->setSecurity( '<YOUR_BEARER_TOKEN_HERE>' ) ->build(); $responses = $sdk->organizations->list( slug: '<value>', page: 1, limit: 10, sorting: [ Components\OrganizationSortProperty::CreatedAt, ] ); foreach ($responses as $response) { if ($response->statusCode === 200) { // handle response } }
Error Handling
Handling errors in this SDK should largely match your expectations. All operations return a response object or throw an exception.
By default an API error will raise a Errors\APIException
exception, which has the following properties:
Property | Type | Description |
---|---|---|
$message |
string | The error message |
$statusCode |
int | The HTTP status code |
$rawResponse |
?\Psr\Http\Message\ResponseInterface | The raw HTTP response |
$body |
string | The response content |
When custom error responses are specified for an operation, the SDK may also throw their associated exception. You can refer to respective Errors tables in SDK docs for more details on possible exception types for each operation. For example, the list
method throws the following exceptions:
Error Type | Status Code | Content Type |
---|---|---|
Errors\HTTPValidationError | 422 | application/json |
Errors\APIException | 4XX, 5XX | */* |
Example
declare(strict_types=1); require 'vendor/autoload.php'; use Polar; use Polar\Models\Components; use Polar\Models\Errors; $sdk = Polar\Polar::builder() ->setSecurity( '<YOUR_BEARER_TOKEN_HERE>' ) ->build(); try { $responses = $sdk->organizations->list( slug: '<value>', page: 1, limit: 10, sorting: [ Components\OrganizationSortProperty::CreatedAt, ] ); foreach ($responses as $response) { if ($response->statusCode === 200) { // handle response } } } catch (Errors\HTTPValidationErrorThrowable $e) { // handle $e->$container data throw $e; } catch (Errors\APIException $e) { // handle default exception throw $e; }
Server Selection
Select Server by Name
You can override the default server globally using the setServer(string $serverName)
builder method when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers:
Name | Server | Description |
---|---|---|
production |
https://api.polar.sh |
Production environment |
sandbox |
https://sandbox-api.polar.sh |
Sandbox environment |
Example
declare(strict_types=1); require 'vendor/autoload.php'; use Polar; use Polar\Models\Components; $sdk = Polar\Polar::builder() ->setServer('sandbox') ->setSecurity( '<YOUR_BEARER_TOKEN_HERE>' ) ->build(); $responses = $sdk->organizations->list( slug: '<value>', page: 1, limit: 10, sorting: [ Components\OrganizationSortProperty::CreatedAt, ] ); foreach ($responses as $response) { if ($response->statusCode === 200) { // handle response } }
Override Server URL Per-Client
The default server can also be overridden globally using the setServerUrl(string $serverUrl)
builder method when initializing the SDK client instance. For example:
declare(strict_types=1); require 'vendor/autoload.php'; use Polar; use Polar\Models\Components; $sdk = Polar\Polar::builder() ->setServerURL('https://api.polar.sh') ->setSecurity( '<YOUR_BEARER_TOKEN_HERE>' ) ->build(); $responses = $sdk->organizations->list( slug: '<value>', page: 1, limit: 10, sorting: [ Components\OrganizationSortProperty::CreatedAt, ] ); foreach ($responses as $response) { if ($response->statusCode === 200) { // handle response } }
Development
Maturity
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
Contributions
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.