PHP code example of danestves / laravel-polar

1. Go to this page and download the library: Download danestves/laravel-polar library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

danestves / laravel-polar example snippets




return [
    /*
    |--------------------------------------------------------------------------
    | Polar Access Token
    |--------------------------------------------------------------------------
    |
    | The Polar access token is used to authenticate with the Polar API.
    | You can find your access token in the Polar dashboard > Settings
    | under the "Developers" section.
    |
    */
    'access_token' => env('POLAR_ACCESS_TOKEN'),

    /*
    |--------------------------------------------------------------------------
    | Polar Organization ID
    |--------------------------------------------------------------------------
    |
    | Optional. Some Polar endpoints (notably the public license-key
    | validate / activate / deactivate routes) ('POLAR_SERVER', 'sandbox'),

    /*
    |--------------------------------------------------------------------------
    | Polar Webhook Secret
    |--------------------------------------------------------------------------
    |
    | The Polar webhook secret is used to verify that the webhook requests
    | are coming from Polar. You can find your webhook secret in the Polar
    | dashboard > Settings > Webhooks on each registered webhook.
    |
    | We (the developers) recommend using a single webhook for all your
    | integrations. This way you can use the same secret for all your
    | integrations and you don't have to manage multiple webhooks.
    |
    */
    'webhook_secret' => env('POLAR_WEBHOOK_SECRET'),

    /*
    |--------------------------------------------------------------------------
    | Polar Url Path
    |--------------------------------------------------------------------------
    |
    | This is the base URI where routes from Polar will be served
    | from. The URL built into Polar is used by default; however,
    | you can modify this path as you see fit for your application.
    |
    */
    'path' => env('POLAR_PATH', 'polar'),

    /*
    |--------------------------------------------------------------------------
    | Default Redirect URL
    |--------------------------------------------------------------------------
    |
    | This is the default redirect URL that will be used when a customer
    | is redirected back to your application after completing a purchase
    | from a checkout session in your Polar account.
    |
    */
    'redirect_url' => null,

    /*
    |--------------------------------------------------------------------------
    | Currency Locale
    |--------------------------------------------------------------------------
    |
    | This is the default locale in which your money values are formatted in
    | for display. To utilize other locales besides the default "en" locale
    | verify you have to have the "intl" PHP extension installed on the system.
    |
    */
    'currency_locale' => env('POLAR_CURRENCY_LOCALE', 'en'),
];

use Danestves\LaravelPolar\Billable;

class User extends Authenticatable
{
    use Billable;
}

->withMiddleware(function (Middleware $middleware) {
    $middleware->validateCsrfTokens(except: [
        'polar/*',
    ]);
})

use Illuminate\Http\Request;

Route::get('/subscribe', function (Request $request) {
    return $request->user()->checkout(['product_id_123']);
});

use Illuminate\Http\Request;

Route::get('/subscribe', function (Request $request) {
    return $request->user()->checkout(['product_id_123', 'product_id_456']);
});

use Illuminate\Http\Request;

Route::get('/subscribe', function (Request $request) {
    return $request->user()->charge(1000, ['product_id_123']);
});

use Illuminate\Http\Request;

Route::get('/billing', function (Request $request) {
    $checkout = $request->user()->checkout(['product_id_123'])
        ->withEmbedOrigin(config('app.url'));

    return view('billing', ['checkout' => $checkout]);
});

use Danestves\LaravelPolar\LaravelPolar;
use Polar\Models\Components;

// Create a checkout link for a single product:
$link = LaravelPolar::createCheckoutLink(new Components\CheckoutLinkCreateProduct(
    productId: 'product_id_123',
    paymentProcessor: 'stripe',
));

echo $link->url; // share this anywhere

// Or for multiple products (customer picks one):
LaravelPolar::createCheckoutLink(new Components\CheckoutLinkCreateProducts(/* ... */));

// Or pinned to a specific price:
LaravelPolar::createCheckoutLink(new Components\CheckoutLinkCreateProductPrice(/* ... */));

LaravelPolar::updateCheckoutLink('cl_xxx', new Components\CheckoutLinkUpdate(label: 'Black Friday'));
LaravelPolar::deleteCheckoutLink('cl_xxx');
LaravelPolar::listCheckoutLinks();           // optional CheckoutLinksListRequest
LaravelPolar::getCheckoutLink('cl_xxx');     // Components\CheckoutLink

public function polarName(): ?string; // default: $model->name
public function polarEmail(): ?string; // default: $model->email

$request->user()->checkout('variant-id')
    ->withSuccessUrl(url('/success'));

$request->user()->checkout('variant-id')
    ->withSuccessUrl(url('/success?checkout_id={CHECKOUT_ID}'));

$request->user()->checkout('variant-id')
    ->withMetadata(['key' => 'value']);

$request->user()->checkout('variant-id')
    ->withCustomerMetadata(['key' => 'value']);

use Danestves\LaravelPolar\LaravelPolar;
use Polar\Models\Components;

$field = LaravelPolar::createCustomField(new Components\CustomFieldCreateText(
    slug: 'company',
    name: 'Company name',
    properties: new Components\CustomFieldTextProperties(),
));

LaravelPolar::updateCustomField('cf_xxx', new Components\CustomFieldUpdateText(name: 'Org name'));
LaravelPolar::deleteCustomField('cf_xxx');
LaravelPolar::listCustomFields();
LaravelPolar::getCustomField('cf_xxx');

$user->checkout('product_id_123')
    ->withCustomFieldData([
        'company' => 'Acme, Inc.',
        'seats' => 10,
    ]);

$data = $order->customFieldData(); // array<string, string|int|bool|\DateTime|null>

use Danestves\LaravelPolar\LaravelPolar;
use Polar\Models\Components;

$discount = LaravelPolar::createDiscount(new Components\DiscountPercentageOnceForeverDurationCreate(
    name: 'Black Friday 50%',
    type: Components\DiscountType::Percentage,
    duration: Components\DiscountDuration::Once,
    basisPoints: 5000,
    organizationId: 'your-org-id',
));

LaravelPolar::updateDiscount('disc_xxx', new Components\DiscountUpdate(name: 'Black Friday extended'));
LaravelPolar::deleteDiscount('disc_xxx');
LaravelPolar::listDiscounts();
LaravelPolar::getDiscount('disc_xxx');

$user->checkout('product_id_123')
    ->withDiscountId('disc_xxx');

$user->checkout('product_id_123')
    ->withDiscountId('disc_xxx')
    ->withoutDiscountCodes();

$user->subscription()->applyDiscount('disc_xxx');
$user->subscription()->removeDiscount();

use Illuminate\Http\Request;

Route::get('/customer-portal', function (Request $request) {
    return $request->user()->redirectToCustomerPortal();
});

$url = $user->customerPortalUrl();

$methods = $user->paymentMethods(); // Collection<int, PaymentMethodCard|PaymentMethodGeneric>

foreach ($methods as $method) {
    // $method->type is the discriminator: 'card' for PaymentMethodCard, etc.
    // PaymentMethodCard exposes brand / last4 / expMonth / expYear etc.
}

$user->deletePaymentMethod('pm_xxx');

$order->status;

$order->paid();

if ($order->hasProduct('product_id_123')) {
    // ...
}

if ($user->hasPurchasedProduct('product_id_123')) {
    // ...
}

$order->refund();

$order->refund(amount: 2500);

use Polar\Models\Components\RefundReason;

$order->refund(
    amount: 2500,
    reason: RefundReason::Fraudulent,
    comment: 'flagged by risk team',
    metadata: ['ticket' => 'T-42'],
);

$refunds = $order->refunds(); // Illuminate\Support\Collection<int, \Polar\Models\Components\Refund>

use Danestves\LaravelPolar\LaravelPolar;
use Polar\Models\Components;
use Polar\Models\Operations;

LaravelPolar::createRefund(new Components\RefundCreate(
    orderId: 'ord_xxx',
    reason: Components\RefundReason::Duplicate,
    amount: 1000,
));

LaravelPolar::listRefunds(new Operations\RefundsListRequest(orderId: 'ord_xxx'));

// Get the URL (e.g. for an <a href> in a Blade view):
$url = $order->receiptUrl(); // ?string, memoized per Order instance

// Or redirect directly (for a controller route):
return $order->downloadInvoice(); // Illuminate\Http\RedirectResponse

Route::get('/orders/{order}/invoice', function (Order $order) {
    return $order->downloadInvoice(); // throws RuntimeException if no URL is available
});

use Illuminate\Http\Request;

Route::get('/subscribe', function (Request $request) {
    return $request->user()->subscribe('product_id_123');
});

$subscription = $user->subscription();

if ($user->subscribed()) {
    // ...
}

if ($user->subscription()->valid()) {
    // ...
}

if ($user->subscription()->hasProduct('product_id_123')) {
    // ...
}

if ($user->subscribedToProduct('product_id_123')) {
    // ...
}

if ($user->subscribed('swimming')) {
    // ...
}

if ($user->subscribedToProduct('product_id_123', 'swimming')) {
    // ...
}

if ($user->subscription()->cancelled()) {
    // ...
}

if ($user->subscription()->onGracePeriod()) {
    // ...
}

if ($user->subscription()->pastDue()) {
    // ...
}

// Get all active subscriptions...
$subscriptions = Subscription::query()->active()->get();

// Get all of the cancelled subscriptions for a specific user...
$subscriptions = $user->subscriptions()->cancelled()->get();

Subscription::query()->incomplete();
Subscription::query()->incompleteExpired();
Subscription::query()->onTrial();
Subscription::query()->active();
Subscription::query()->pastDue();
Subscription::query()->unpaid();
Subscription::query()->cancelled();

use App\Models\User;

$user = User::find(1);

$user->subscription()->swap('product_id_123');

$user = User::find(1);

$user->subscription()->swapAndInvoice('product_id_123');

$user = User::find(1);

$checkout = $user->subscribe('product_id_123', 'swimming');

$user = User::find(1);

// Retrieve the swimming subscription type...
$subscription = $user->subscription('swimming');

// Swap plans for the gym subscription type...
$user->subscription('gym')->swap('product_id_123');

// Cancel the swimming subscription...
$user->subscription('swimming')->cancel();

$user = User::find(1);

$user->subscription()->cancel();

if ($user->subscription()->onGracePeriod()) {
    // ...
}

$user->subscription()->resume();

if ($user->subscription()->onTrial()) {
    // ...
}

if ($user->onTrial()) {
    // ...
}

$trialEnd = $user->subscription()->trialEndsAt();

if ($user->subscription()->hasExpiredTrial()) {
    // ...
}

$user->subscription()->updateTrial(now()->addDays(30));

$seatsList = $user->subscription()->seats();

$seatsList->seats;          // array<Polar\Models\Components\CustomerSeat>
$seatsList->availableSeats; // int
$seatsList->totalSeats;     // int

$user->subscription()->assignSeat(email: '[email protected]');
$user->subscription()->assignSeat(customerId: 'cust_xxx');
$user->subscription()->assignSeat(
    email: '[email protected]',
    metadata: ['role' => 'admin'],
);

$user->subscription()->revokeSeat('seat_xxx');
$user->subscription()->resendSeatInvitation('seat_xxx');

use Danestves\LaravelPolar\LaravelPolar;
use Polar\Models\Components;

LaravelPolar::listSeats(subscriptionId: 'sub_xxx');
LaravelPolar::assignSeat(new Components\SeatAssign(
    subscriptionId: 'sub_xxx',
    email: '[email protected]',
));
LaravelPolar::revokeSeat('seat_xxx');
LaravelPolar::resendSeatInvitation('seat_xxx');

use Danestves\LaravelPolar\LaravelPolar;
use Polar\Models\Components;

$benefit = LaravelPolar::createBenefit(
    new Components\BenefitCustomCreate(
        description: 'Premium Support',
        organizationId: 'your-org-id',
        properties: new Components\BenefitCustomCreateProperties(),
    )
);

$benefits = $user->listBenefits('your-org-id');

$benefit = $user->getBenefit('benefit-id-123');

$grants = $user->listBenefitGrants('benefit-id-123');

use Danestves\LaravelPolar\LaravelPolar;
use Polar\Models\Components;

$benefit = LaravelPolar::updateBenefit(
    'benefit-id-123',
    new Components\BenefitCustomUpdate(
        description: 'Updated Premium Support',
        properties: new Components\BenefitCustomUpdateProperties(),
    )
);

LaravelPolar::deleteBenefit('benefit-id-123');

$user->ingestUsageEvent('api_request', [
    'endpoint' => '/api/v1/data',
    'method' => 'GET',
    'duration_ms' => 145,
]);

$user->ingestUsageEvents([
    [
        'eventName' => 'api_request',
        'properties' => [
            'endpoint' => '/api/v1/data',
            'method' => 'GET',
        ],
    ],
    [
        'eventName' => 'storage_used',
        'properties' => [
            'bytes' => 1048576,
        ],
        'timestamp' => time(),
    ],
]);

$meters = $user->listCustomerMeters();

use Danestves\LaravelPolar\LaravelPolar;

$meter = LaravelPolar::getCustomerMeter('meter-id-123');

use Danestves\LaravelPolar\LaravelPolar;
use Polar\Models\Components;

LaravelPolar::listLicenseKeys();                                  // optional filters
LaravelPolar::getLicenseKey('lk_xxx');                            // LicenseKeyWithActivations
LaravelPolar::updateLicenseKey('lk_xxx', new Components\LicenseKeyUpdate(
    limitActivations: 10,
));

// Validate a key (optionally bound to a specific activation):
LaravelPolar::validateLicenseKey(
    key: 'LIC-XXXX-XXXX-XXXX',
    activationId: 'act_xxx',
);

// Activate a license on a new device:
$activation = LaravelPolar::activateLicenseKey(
    key: 'LIC-XXXX-XXXX-XXXX',
    label: 'My MacBook Pro',
    meta: ['hostname' => 'macbook-pro', 'os' => 'darwin'],
);

// Deactivate an activation:
LaravelPolar::deactivateLicenseKey(
    key: 'LIC-XXXX-XXXX-XXXX',
    activationId: 'act_xxx',
);

LaravelPolar::validateLicenseKey('LIC-XXXX-XXXX-XXXX', organizationId: 'org_xxx');

$keys = $user->licenseKeys();                  // Collection<int, LicenseKeyRead>
$keys = $user->licenseKeys(benefitId: 'b_xx'); // scope to a single benefit

use Brick\DateTime\LocalDate;
use Danestves\LaravelPolar\LaravelPolar;
use Polar\Models\Components;
use Polar\Models\Operations;

$metrics = LaravelPolar::getMetrics(new Operations\MetricsGetRequest(
    startDate: LocalDate::of(2026, 1, 1),
    endDate:   LocalDate::of(2026, 1, 31),
    interval:  Components\TimeInterval::Day,
));

// $metrics->periods is an array of Components\MetricPeriod

$response = LaravelPolar::listFiles();
$items = $response->listResourceFileRead?->items ?? [];

$orgs = LaravelPolar::listOrganizations();
$org  = LaravelPolar::getOrganization('org_xxx'); // Components\Organization

use Danestves\LaravelPolar\LaravelPolar;

$sdk = LaravelPolar::sdk(); // returns Polar\Polar — the underlying SDK client

$sdk->customerPortal->wallets->list(...);
$sdk->files->create(...);
$sdk->organizations->update(...);
$sdk->oauth2->...;

// Events with convenience properties
public function handle(OrderCreated $event): void
{
    $order = $event->order; // Direct access
    $billable = $event->billable; // Direct access
}

// Events with only payload
public function handle(CheckoutCreated $event): void
{
    $checkout = $event->payload->checkout; // Access via payload
}



namespace App\Listeners;

use Danestves\LaravelPolar\Events\CheckoutCreated;

class HandleCheckoutCreated
{
    public function handle(CheckoutCreated $event): void
    {
        $checkout = $event->payload->checkout;
        // Handle checkout creation...
    }
}



namespace App\Listeners;

use Danestves\LaravelPolar\Events\SubscriptionUpdated;

class HandleSubscriptionUpdated
{
    public function handle(SubscriptionUpdated $event): void
    {
        $subscription = $event->subscription;
        // Handle subscription update...
    }
}



namespace App\Listeners;

use Danestves\LaravelPolar\Events\CheckoutCreated;
use Danestves\LaravelPolar\Events\SubscriptionUpdated;
use Danestves\LaravelPolar\Events\WebhookHandled;
use Illuminate\Events\Dispatcher;

class PolarEventListener
{
    /**
     * Handle received Polar webhooks.
     */
    public function handleWebhookHandled(WebhookHandled $event): void
    {
        if ($event->payload['type'] === 'subscription.updated') {
            // Handle the incoming event...
        }
    }

    /**
     * Handle checkout created events.
     */
    public function handleCheckoutCreated(CheckoutCreated $event): void
    {
        $checkout = $event->payload->checkout;
        // Handle checkout creation...
    }

    /**
     * Handle subscription updated events.
     */
    public function handleSubscriptionUpdated(SubscriptionUpdated $event): void
    {
        $subscription = $event->subscription;
        // Handle subscription update...
    }

    /**
     * Register the listeners for the subscriber.
     */
    public function subscribe(Dispatcher $events): void
    {
        $events->listen(
            WebhookHandled::class,
            [self::class, 'handleWebhookHandled']
        );

        $events->listen(
            CheckoutCreated::class,
            [self::class, 'handleCheckoutCreated']
        );

        $events->listen(
            SubscriptionUpdated::class,
            [self::class, 'handleSubscriptionUpdated']
        );
    }
}



namespace App\Providers;

use App\Listeners\HandleCheckoutCreated;
use App\Listeners\HandleSubscriptionUpdated;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Danestves\LaravelPolar\Events\CheckoutCreated;
use Danestves\LaravelPolar\Events\SubscriptionUpdated;
use Danestves\LaravelPolar\Events\WebhookHandled;

class EventServiceProvider extends ServiceProvider
{
    protected $listen = [
        WebhookHandled::class => [
            // Add your listeners here
        ],
        CheckoutCreated::class => [
            HandleCheckoutCreated::class,
        ],
        SubscriptionUpdated::class => [
            HandleSubscriptionUpdated::class,
        ],
    ];
}



namespace App\Providers;

use App\Listeners\PolarEventListener;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    protected $subscribe = [
        PolarEventListener::class,
    ];
}
bash
php artisan polar:install
bash
php artisan vendor:publish --tag="polar-migrations"
bash
php artisan vendor:publish --tag="polar-config"
bash
php artisan vendor:publish --tag="polar-views"
bash
php artisan migrate
jsx
// button.{jsx,tsx}

export function Button() {
  return (
    <a href="<CHECKOUT_LINK>" data-polar-checkout>Buy now</a>
  );
}
blade
<table>
    @foreach ($user->orders as $order)
        <td>{{ $order->ordered_at->toFormattedDateString() }}</td>
        <td>{{ $order->polar_id }}</td>
        <td>{{ $order->amount }}</td>
        <td>{{ $order->tax_amount }}</td>
        <td>{{ $order->refunded_amount }}</td>
        <td>{{ $order->refunded_tax_amount }}</td>
        <td>{{ $order->currency }}</td>
        <!-- Add more columns as needed -->
    @endforeach
</table>