Skip to content

polarsource/polar-php

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

polar-sh/sdk

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

Table of Contents

SDK Installation

The SDK relies on Composer to manage its dependencies.

To install the SDK first add the below to your composer.json file:

{
    "repositories": [
        {
            "type": "github",
            "url": "<UNSET>.git"
        }
    ],
    "require": {
        "polar-sh/sdk": "*"
    }
}

Then run the following command:

composer update

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('2024-11-12T14:26:42.882Z'),
        id: '<value>',
        status: Components\CheckoutStatus::Confirmed,
        clientSecret: '<value>',
        url: 'https://fragrant-freezing.com',
        expiresAt: Utils\Utils::parseDateTime('2022-04-01T05:43:33.513Z'),
        successUrl: 'https://lined-privilege.biz/',
        productId: '<value>',
        productPriceId: '<value>',
        allowDiscountCodes: false,
        isDiscountApplicable: false,
        isFreeProductPrice: false,
        isPaymentRequired: false,
        isPaymentSetupRequired: false,
        isPaymentFormRequired: false,
        paymentProcessorMetadata: new Components\PaymentProcessorMetadata(),
        metadata: [
            'key' => 962818,
        ],
        product: new Components\CheckoutProduct(
            createdAt: Utils\Utils::parseDateTime('2022-01-08T00:22:16.025Z'),
            id: '<value>',
            name: '<value>',
            isRecurring: false,
            isArchived: false,
            organizationId: '<value>',
            prices: [
                new Components\ProductPriceRecurringCustom(
                    createdAt: Utils\Utils::parseDateTime('2022-08-19T22:18:44.316Z'),
                    id: '<value>',
                    isArchived: false,
                    productId: '<value>',
                    priceCurrency: '<value>',
                    recurringInterval: Components\SubscriptionRecurringInterval::Month,
                    modifiedAt: Utils\Utils::parseDateTime('2024-04-20T22:18:45.464Z'),
                    minimumAmount: 598949,
                    maximumAmount: 500372,
                    presetAmount: 688646,
                ),
            ],
            benefits: [
                new Components\BenefitBase(
                    createdAt: Utils\Utils::parseDateTime('2024-07-22T12:18:02.066Z'),
                    id: '<value>',
                    type: Components\BenefitType::Downloadables,
                    description: 'rotten relative for embarrassment untidy long-term near honestly separate',
                    selectable: false,
                    deletable: false,
                    organizationId: '<value>',
                    modifiedAt: Utils\Utils::parseDateTime('2024-01-10T13:42:03.592Z'),
                ),
            ],
            medias: [
                new Components\ProductMediaFileRead(
                    id: '<value>',
                    organizationId: '<value>',
                    name: '<value>',
                    path: '/etc/namedb',
                    mimeType: '<value>',
                    size: 879649,
                    isUploaded: false,
                    createdAt: Utils\Utils::parseDateTime('2024-09-12T19:41:14.261Z'),
                    sizeReadable: '<value>',
                    publicUrl: 'https://rectangular-worth.info/',
                    storageVersion: '<value>',
                    checksumEtag: '<value>',
                    checksumSha256Base64: '<value>',
                    checksumSha256Hex: '<value>',
                    lastModifiedAt: Utils\Utils::parseDateTime('2024-06-29T02:23:28.661Z'),
                    version: '<value>',
                ),
            ],
            modifiedAt: Utils\Utils::parseDateTime('2023-05-08T04:30:09.331Z'),
            description: 'provided publicize astride oof mockingly if opposite coagulate pro',
        ),
        productPrice: new Components\ProductPriceRecurringFree(
            createdAt: Utils\Utils::parseDateTime('2023-12-29T06:38:59.235Z'),
            id: '<value>',
            isArchived: false,
            productId: '<value>',
            recurringInterval: Components\SubscriptionRecurringInterval::Year,
            modifiedAt: Utils\Utils::parseDateTime('2022-03-21T13:22:46.065Z'),
        ),
        attachedCustomFields: [
            new Components\AttachedCustomField(
                customFieldId: '<value>',
                customField: new Components\CustomFieldNumber(
                    createdAt: Utils\Utils::parseDateTime('2024-09-13T23:13:23.872Z'),
                    id: '<value>',
                    metadata: [
                        'key' => false,
                    ],
                    slug: '<value>',
                    name: '<value>',
                    organizationId: '<value>',
                    properties: new Components\CustomFieldNumberProperties(),
                    modifiedAt: Utils\Utils::parseDateTime('2024-03-11T01:07:03.723Z'),
                ),
                order: 169862,
                required: false,
            ),
        ],
        customerMetadata: [
            'key' => '<value>',
        ],
        modifiedAt: Utils\Utils::parseDateTime('2022-09-27T02:51:25.666Z'),
        embedOrigin: '<value>',
        amount: 587344,
        taxAmount: 753909,
        currency: 'Leone',
        subtotalAmount: 299632,
        totalAmount: 617409,
        discountId: '<value>',
        customerId: '<value>',
        customerName: '<value>',
        customerEmail: '[email protected]',
        customerIpAddress: '<value>',
        customerBillingAddress: new Components\Address(
            country: 'Northern Mariana Islands',
        ),
        customerTaxId: '<id>',
        discount: new Components\CheckoutDiscountPercentageRepeatDuration(
            duration: Components\DiscountDuration::Forever,
            durationInMonths: 496211,
            type: Components\DiscountType::Percentage,
            basisPoints: 741459,
            id: '<value>',
            name: '<value>',
            code: '<value>',
        ),
        subscriptionId: '<value>',
    ),
);

$response = $sdk->endpointcheckoutCreatedPost(
    request: $request
);

if ($response->any !== null) {
    // handle response
}

Available Resources and Operations

Available methods
  • get - Get Campaign
  • list - List Campaigns
  • create - Create Checkout Link
  • delete - Delete Checkout Link
  • get - Get Checkout Link
  • list - List Checkout Links
  • update - Update Checkout Link
  • create - Create Checkout ⚠️ Deprecated Use create instead.
  • get - Get Checkout ⚠️ Deprecated
  • clientConfirm - Confirm Checkout Session from Client
  • clientGet - Get Checkout Session from Client
  • clientUpdate - Update Checkout Session from Client
  • create - Create Checkout Session
  • get - Get Checkout Session
  • list - List Checkout Sessions
  • update - Update Checkout Session
  • get - Get Benefit Grant
  • list - List Benefit Grants
  • update - Update Benefit Grant
  • get - Get Customer
  • get - Get Downloadable
  • list - List Downloadables
  • get - Get Organization
  • cancel - Cancel Subscription
  • get - Get Subscription
  • list - List Subscriptions
  • update - Update Subscription
  • create - Create Customer Session
  • create - Create Custom Field
  • delete - Delete Custom Field
  • get - Get Custom Field
  • list - List Custom Fields
  • update - Update Custom Field
  • list - List External Organizations
  • get - Get Metrics
  • limits - Get Metrics Limits
  • create - Create Organization
  • get - Get Organization
  • list - List Organizations
  • update - Update Organization
  • get - Get Repository
  • list - List Repositories
  • update - Update Repository
  • export - Export Subscriptions
  • list - List 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\Operations;

$security = '<YOUR_BEARER_TOKEN_HERE>';

$sdk = Polar\Polar::builder()->setSecurity($security)->build();

$request = new Operations\ExternalOrganizationsListRequest();

$responses = $sdk->externalOrganizations->list(
    request: $request
);


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\Operations;

$security = '<YOUR_BEARER_TOKEN_HERE>';

$sdk = Polar\Polar::builder()->setSecurity($security)->build();

try {
    $request = new Operations\ExternalOrganizationsListRequest();

    $responses = $sdk->externalOrganizations->list(
        request: $request
    );

    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
production https://api.polar.sh
sandbox https://sandbox-api.polar.sh

Example

declare(strict_types=1);

require 'vendor/autoload.php';

use Polar;
use Polar\Models\Operations;

$security = '<YOUR_BEARER_TOKEN_HERE>';

$sdk = Polar\Polar::builder()
    ->setServer("sandbox")
    ->setSecurity($security)->build();

$request = new Operations\ExternalOrganizationsListRequest();

$responses = $sdk->externalOrganizations->list(
    request: $request
);


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\Operations;

$security = '<YOUR_BEARER_TOKEN_HERE>';

$sdk = Polar\Polar::builder()
    ->setServerURL('https://api.polar.sh')
    ->setSecurity($security)->build();

$request = new Operations\ExternalOrganizationsListRequest();

$responses = $sdk->externalOrganizations->list(
    request: $request
);


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.

SDK Created by Speakeasy