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 API Version
    |--------------------------------------------------------------------------
    |
    | Polar versions its API by date and sends the resolved version back in the
    | "polar-version" response header. This package's data objects are generated
    | from a specific version, which is pinned here and sent on every request so
    | a change to Polar's default cannot silently reshape your responses.
    |
    | Only change this if you have regenerated the data objects against another
    | version (see tools/generate-data.php).
    |
    */
    'version' => env('POLAR_API_VERSION', \Danestves\LaravelPolar\Http\PolarClient::API_VERSION),

    /*
    |--------------------------------------------------------------------------
    | Request Timeout
    |--------------------------------------------------------------------------
    |
    | Optional. Seconds to wait on a Polar API request before giving up. Leave
    | null to use the default timeout of Laravel's HTTP client.
    |
    */
    'timeout' => env('POLAR_TIMEOUT'),

    /*
    |--------------------------------------------------------------------------
    | Retry Policy
    |--------------------------------------------------------------------------
    |
    | Optional. Retry requests that Polar answers with 429 (rate limited) or a
    | 5xx server error. `sleep` is the delay between attempts in milliseconds.
    | Leave `times` at 0 to disable retries entirely.
    |
    */
    'retry' => [
        'times' => (int) env('POLAR_RETRY_TIMES', 0),
        'sleep' => (int) env('POLAR_RETRY_SLEEP', 100),
    ],

    /*
    |--------------------------------------------------------------------------
    | 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\Data;
use Danestves\LaravelPolar\Enums\SubscriptionStatus;

$subscription = LaravelPolar::updateSubscription('sub_xxx', ['product_id' => 'prod_xxx']);

$subscription->id;                 // string
$subscription->status;             // SubscriptionStatus enum
$subscription->currentPeriodEnd;   // Carbon\CarbonImmutable
$subscription->customer->email;    // nested objects are typed too

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 Danestves\LaravelPolar\Data;

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

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

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

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

LaravelPolar::updateCheckoutLink('cl_xxx', new Data\CheckoutLinkUpdate(label: 'Black Friday'));
LaravelPolar::deleteCheckoutLink('cl_xxx');
LaravelPolar::listCheckoutLinks();           // optional CheckoutLinksListRequest
LaravelPolar::getCheckoutLink('cl_xxx');     // Data\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 Danestves\LaravelPolar\Data;

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

LaravelPolar::updateCustomField('cf_xxx', new Data\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, mixed>

use Danestves\LaravelPolar\LaravelPolar;
use Danestves\LaravelPolar\Data;
use Danestves\LaravelPolar\Enums\DiscountDuration;

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

LaravelPolar::updateDiscount('disc_xxx', new Data\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();

$customer = $user->createAsPolarCustomer(); // Danestves\LaravelPolar\Data\Customer

$customer = $user->syncWithPolar();

$user->hasPolarCustomer();
$state = $user->customerState(); // active subscriptions and grants

use Danestves\LaravelPolar\LaravelPolar;

LaravelPolar::createCustomer(['email' => '[email protected]', 'name' => 'Jane']);
LaravelPolar::getCustomer('cust_xxx');
LaravelPolar::getCustomerByExternalId('123');
LaravelPolar::listCustomers(['limit' => 50]);       // Page<Data\Customer>
LaravelPolar::updateCustomer('cust_xxx', ['name' => 'Jane Doe']);
LaravelPolar::getCustomerState('cust_xxx');
LaravelPolar::deleteCustomer('cust_xxx');

$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');

use Danestves\LaravelPolar\LaravelPolar;

$orders = LaravelPolar::listOrders(['limit' => 50]); // Page<Data\Order>

$order->status;

$order->paid();

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

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

$order->refund();

$order->refund(amount: 2500);

use Danestves\LaravelPolar\Enums\RefundCreateReason;

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

$refunds = $order->refunds(); // Illuminate\Support\Collection<int, \Danestves\LaravelPolar\Data\Refund>

use Danestves\LaravelPolar\LaravelPolar;
use Danestves\LaravelPolar\Data;

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

LaravelPolar::listRefunds(['order_id' => 'ord_xxx']); // Page<Data\Refund>

// 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 Danestves\LaravelPolar\LaravelPolar;

$disputes = LaravelPolar::listDisputes(['status' => 'needs_response']); // Page<Data\Dispute>
$dispute  = LaravelPolar::getDispute('dsp_xxx');                        // Data\Dispute

// Acknowledge a dispute without submitting evidence:
LaravelPolar::acceptDispute('dsp_xxx');

use Illuminate\Http\Request;

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

$subscription = $user->subscription();

use Danestves\LaravelPolar\LaravelPolar;

$subscription = LaravelPolar::getSubscription('sub_xxx'); // Data\Subscription
$subscriptions = LaravelPolar::listSubscriptions(['limit' => 50]); // Page<Data\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();

use Danestves\LaravelPolar\Enums\CustomerCancellationReason;

$user->subscription()->cancelNow(
    reason: CustomerCancellationReason::TooExpensive,
    comment: 'Customer asked to stop immediately',
);

// Pause at period end and resume automatically in 30 days:
$user->subscription()->pause(now()->addDays(30));

// Pause at period end, resume manually later:
$user->subscription()->pause();

// Cancel a pause that has not taken effect yet:
$user->subscription()->unpause();

// Resume a subscription that is already paused (starts a new billing period and charges now):
$user->subscription()->resumePaused();

$user->subscription()->paused();            // status === paused
$user->subscription()->onPauseGracePeriod(); // pause scheduled, period not over yet
Subscription::query()->paused()->get();

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;          // list<Danestves\LaravelPolar\Data\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 Danestves\LaravelPolar\Data;

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

use Danestves\LaravelPolar\LaravelPolar;
use Danestves\LaravelPolar\Data;

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

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

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

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

use Danestves\LaravelPolar\LaravelPolar;
use Danestves\LaravelPolar\Data;

$benefit = LaravelPolar::updateBenefit(
    'benefit-id-123',
    new Data\BenefitCustomUpdate(
        description: 'Updated Premium Support',
        properties: new Data\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;

$meters = LaravelPolar::listMeters();               // Page<Data\Meter>
$meter  = LaravelPolar::getMeter('meter_xxx');       // Data\Meter

$meter = LaravelPolar::createMeter([
    'name' => 'API requests',
    'unit' => 'scalar',
    'organization_id' => 'org_xxx',
    'filter' => ['conjunction' => 'and', 'clauses' => []],
    'aggregation' => ['func' => 'count'],
]);

LaravelPolar::updateMeter('meter_xxx', ['name' => 'API calls']);

$wallets = $user->wallets();       // Collection<int, Data\CustomerWallet>
$wallet  = $user->wallet('wal_xxx');

echo $wallet->balance;             // in cents
echo $wallet->currency;

LaravelPolar::listCustomerWallets('cst_token');       // Page<Data\CustomerWallet>
LaravelPolar::getCustomerWallet('cst_token', 'wal_xxx');

use Danestves\LaravelPolar\LaravelPolar;
use Danestves\LaravelPolar\Data;

LaravelPolar::listLicenseKeys();                                  // optional filters
LaravelPolar::getLicenseKey('lk_xxx');                            // LicenseKeyWithActivations
LaravelPolar::updateLicenseKey('lk_xxx', new Data\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 Danestves\LaravelPolar\Enums\TimeInterval;
use Danestves\LaravelPolar\LaravelPolar;

$metrics = LaravelPolar::getMetrics([
    'start_date' => '2026-01-01',
    'end_date' => '2026-01-31',
    'interval' => TimeInterval::Day->value,
]);

// $metrics->periods is a list of Danestves\LaravelPolar\Data\MetricPeriod

$files = LaravelPolar::listFiles();   // Page<Data\FileRead>

foreach ($files as $file) {
    echo $file->name;
}

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

use Danestves\LaravelPolar\Data;
use Danestves\LaravelPolar\Enums\WebhookFormat;
use Danestves\LaravelPolar\LaravelPolar;

$endpoints = LaravelPolar::listWebhooks(); // Page<Data\WebhookEndpoint>

$endpoint = LaravelPolar::createWebhook(new Data\WebhookEndpointCreate(
    url: 'https://example.com/polar/webhook',
    format: WebhookFormat::Raw,
    events: ['order.created', 'subscription.created'],
));

LaravelPolar::updateWebhook($endpoint->id, new Data\WebhookEndpointUpdate(
    enabled: false,
));

$newSecret = LaravelPolar::rotateWebhookSecret($endpoint->id)->secret;

$deliveries = LaravelPolar::listWebhookDeliveries(['endpoint_id' => $endpoint->id]);
LaravelPolar::redeliverWebhookEvent('evt_xxx');
LaravelPolar::deleteWebhook($endpoint->id);

use Danestves\LaravelPolar\LaravelPolar;

$client = LaravelPolar::client();

// GET with query parameters (list filters may be arrays; they are repeated correctly):
$wallets = $client->get('/v1/customer-portal/wallets/', ['limit' => 20]);

// POST / PATCH / DELETE with a JSON body:
$file = $client->post('/v1/files/', ['name' => 'guide.pdf', 'organization_id' => 'org_xxx']);
$client->patch('/v1/organizations/org_xxx', ['name' => 'New name']);
$client->delete('/v1/files/file_xxx');

use Danestves\LaravelPolar\Data;

$organization = Data\Organization::from($client->get('/v1/organizations/org_xxx'));

// The orders list endpoint is not wrapped, but its shape is:
$page = $client->page('/v1/orders/', Data\Order::class, ['limit' => 50]);
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>
php
// 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->data; // Access via payload
}
php


namespace App\Listeners;

use Danestves\LaravelPolar\Events\CheckoutCreated;

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


namespace App\Listeners;

use Danestves\LaravelPolar\Events\SubscriptionUpdated;

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


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->data;
        // 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']
        );
    }
}
php


namespace App\Providers;

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

class EventServiceProvider extends ServiceProvider
{
    protected $subscribe = [
        PolarEventListener::class,
    ];
}
php
$fake = LaravelPolar::fake([
    'GET /v1/products/' => [
        'items' => [],
        'pagination' => ['total_count' => 0, 'max_page' => 1],
    ],
]);

$products = LaravelPolar::listProducts(); // Page<Data\Product>

$fake->assertSent('GET', '/v1/products/');
$fake->assertSentCount(1);
php
$webhook = LaravelPolar::fakeWebhook('subscription.created', $data);

$this->postJson('/polar/webhook', $webhook['payload'], $webhook['headers'])
    ->assertOk();
php
$webhook = LaravelPolar::fakeWebhook('order.paid', $data, secret: 'whsec_test', timestamp: time(), id: 'msg_test');