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;
}
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(/* ... */));
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');
});
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();
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()) {
// ...
}
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(),
)
);
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(),
)
);
$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
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]);
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,
];
}