Download the PHP package climactic/laravel-polar without Composer

On this page you can find all versions of the php package climactic/laravel-polar. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package laravel-polar

Laravel Polar

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

Seamlessly integrate Polar.sh subscriptions and payments into your Laravel application. This package provides an elegant way to handle subscriptions, manage recurring payments, and interact with Polar's API. With built-in support for webhooks, subscription management, and a fluent API, you can focus on building your application while we handle the complexities of subscription billing.

Installation

Step 1: You can install the package via composer:

Step 2: Run :install:

This will publish the config, migrations and views, and ask to run the migrations.

Or publish and run the migrations individually:

This is the contents of the published config file:

Usage

Access Token

Configure your access token. Create a new token in the Polar Dashboard > Settings > Developers and paste it in the .env file.

Webhook Secret

Configure your webhook secret. Create a new webhook in the Polar Dashboard > Settings > Webhooks.

Configure the webhook for the following events that this package supports:

Billable Trait

Let’s make sure everything’s ready for your customers to checkout smoothly. 🛒

First, we’ll need to set up a model to handle billing—don’t worry, it’s super simple! In most cases, this will be your app’s User model. Just add the Billable trait to your model like this (you’ll import it from the package first, of course):

Now the user model will have access to the methods provided by the package. You can make any model billable by adding the trait to it, not just the User model.

Polar Script

Polar includes a JavaScript script that you can use to initialize the Polar Embedded Checkout. If you going to use this functionality, you can use the @polarEmbedScript directive to include the script in your views inside the <head> tag.

Blade Directives

The package provides Blade directives for conditionally rendering content based on subscription status.

@subscribed

Check if the authenticated user (or an explicit billable) has a valid subscription:

You can pass a subscription type and/or product ID:

You can also pass an explicit billable model as the first argument:

@onTrial

Check if the authenticated user's subscription is currently trialing:

Accepts a subscription type or an explicit billable, just like @subscribed:

Route Middleware

The polar.subscribed middleware protects routes so only subscribed users can access them:

The middleware accepts two optional parameters — subscription type (the label you assign when creating multiple subscriptions, defaults to 'default') and product ID (a specific Polar product the subscription must be for):

For API requests (when Accept: application/json is present), a 403 JSON response is returned. For web requests, you can configure a redirect URL in config/polar.php:

If middleware_redirect_url is null (the default), a 403 response is returned for web requests as well.

Webhooks

This package includes a webhook handler that will handle the webhooks from Polar.

Webhooks & CSRF Protection

Incoming webhooks should not be affected by CSRF protection. To prevent this, exclude polar/* in your application's bootstrap/app.php file:

Commands

This package includes a list of commands that you can use to retrieve information about your Polar account.

Command Description
php artisan polar:products List all available products with their ids
php artisan polar:products --id=123 List a specific product by id
php artisan polar:products --id=123 --id=321 List a specific products by ids

Checkouts

Single Payments

To create a checkout to show only a single payment, pass a single items to the array of products when creating the checkout.

If you want to show multiple products that the user can choose from, you can pass an array of product ids to the checkout method.

This could be useful if you want to offer monthly, yearly, and lifetime plans for example.

[!NOTE] If you are requesting the checkout a lot of times we recommend you to cache the URL returned by the checkout method.

Custom Price

You can override the price of a product using the charge method.

Embedded Checkout

Instead of redirecting the user you can create the checkout link, pass it to the page and use our blade component:

Now we can use the button like this:

The component accepts the normal props that a link element accepts. You can change the theme of the embedded checkout by using the following prop:

It defaults to light theme, so you only need to pass the prop if you want to change it.

Inertia

For projects usin Inertia you can render the button adding data-polar-checkout to the link in the following way:

button.vue

At the end is just a normal link but using an special attribute for the script to render the embedded checkout.

[!NOTE] Remember that you can use the theme attribute too to change the color system in the checkout

Prefill Customer Information

You can override the user data using the following methods in your models provided by the Billable trait.

Redirects After Purchase

You can redirect the user to a custom page after the purchase using the withSuccessUrl method:

You can also add the checkout_id={CHECKOUT_ID} query parameter to the URL to retrieve the checkout session id:

[!NOTE] When a checkout is returned from an Inertia request (the X-Inertia header is present), the response is automatically converted to an Inertia::location() external visit so the browser is redirected to Polar without tripping CORS. Regular requests continue to receive a 303 redirect.

Custom metadata and customer metadata

You can add custom metadata to the checkout session using the withMetadata method:

You can also add customer metadata to the checkout session using the withCustomerMetadata method:

These will then be available in the relevant webhooks for you.

Reserved Keywords

When working with custom data, this library has a few reserved terms.

Using any of these will result in an exception being thrown.

Customers

Customer Portal

Customers can update their personal information (e.g., name, email address) by accessing their self-service customer portal. To redirect customers to this portal, call the redirectToCustomerPortal() method on your billable model (e.g., the User model).

Optionally, you can obtain the signed customer portal URL directly:

Orders

Retrieving Orders

You can retrieve orders by using the orders relationship on the billable model:

Check order status

You can check the status of an order by using the status attribute:

Or you can use some of the helper methods offers by the Order model:

Aside from that, you can run two other checks: refunded, and partially refunded. If the order is refunded, you can utilize the refunded_at timestamp:

You may also see if an order was for a certain product:

Furthermore, you can check if a consumer has purchased a specific product:

Invoices

You can retrieve and generate invoices for orders:

Or use the facade directly:

Refunding Orders

You can refund an order. With no arguments it refunds the remaining unrefunded amount with reason customer_request:

Or use the facade for more control:

You can also list the refunds for a specific order:

Receipts

Get the receipt/invoice PDF URL for an order, or redirect the customer straight to it:

Listing Orders via API

You can list orders directly from the Polar API:

Subscriptions

Creating Subscriptions

Starting a subscription is simple. For this, we require our product's variant id. Copy the product id and start a new subscription checkout using your billable model:

When a customer completes their checkout, the incoming SubscriptionCreated event webhook connects it to your billable model in the database. You may then get the subscription from your billable model:

Checking Subscription Status

Once a consumer has subscribed to your services, you can use a variety of methods to check on the status of their subscription. The most basic example is to check if a customer has a valid subscription.

You can utilize this in a variety of locations in your app, such as middleware, rules, and so on, to provide services. To determine whether an individual subscription is valid, you can use the valid method:

This method, like the subscribed method, returns true if your membership is active, on trial, past due, or cancelled during its grace period.

You may also check if a subscription is for a certain product:

If you wish to check if a subscription is on a specific product while being valid, you can use:

Alternatively, if you use different subscription types, you can pass a type as an additional parameter:

Cancelled Status

To see if a user has cancelled their subscription, you can use the cancelled method:

When they are in their grace period, you can utilize the onGracePeriod check.

Past Due Status

If a recurring payment fails, the subscription will become past due. This indicates that the subscription is still valid, but your customer's payments will be retried in two weeks.

Subscription Scopes

There are several subscription scopes available for querying subscriptions in specific states:

Here's all available scopes:

Changing Plans

When a consumer is on a monthly plan, they may desire to upgrade to a better plan, alter their payments to an annual plan, or drop to a lower-cost plan. In these cases, you can allow them to swap plans by giving a different product id to the swap method:

This will change the customer's subscription plan, however billing will not occur until the next payment cycle. If you want to immediately invoice the customer, you can use the swapAndInvoice method instead.

Multiple Subscriptions

In certain situations, you may wish to allow your consumer to subscribe to numerous subscription kinds. For example, a gym may provide a swimming and weight lifting subscription. You can let your customers subscribe to one or both.

To handle the various subscriptions, you can offer a type of subscription as the second argument when creating a new one:

You can now always refer to this specific subscription type by passing the type argument when getting it:

Cancelling Subscriptions

To cancel a subscription, call the cancel method.

This will cause your subscription to be cancelled. If you cancel your subscription in the middle of the cycle, it will enter a grace period, and the ends_at column will be updated. The customer will continue to have access to the services offered for the duration of the period. You may check the grace period by calling the onGracePeriod method:

Polar does not offer immediate cancellation. To resume a subscription while it is still in its grace period, use the resume method.

When a cancelled subscription approaches the end of its grace period, it becomes expired and cannot be resumed.

Revoking Subscriptions

To immediately revoke a subscription (cancel without a grace period), use the revoke method:

This differs from cancel() which cancels at the end of the billing period. revoke() terminates the subscription immediately.

Discounts & Trials

Apply or remove a discount on a subscription (takes effect on the next billing cycle), or update the trial end date:

Subscription API Methods

You can interact with subscriptions directly via the Polar API:

Subscription Trials

The package supports subscription trials through the Polar SDK's Trialing status. You can check trial state on subscriptions:

You can also use "generic" trials on the customer model, independent of any subscription:

Generic trials use the trial_ends_at column on the polar_customers table.

Benefits

Benefits are automated features that are granted to customers when they purchase your products. You can manage benefits using both the LaravelPolar facade (for create/update/delete operations) and methods on your billable model (for listing and retrieving benefits).

Creating Benefits

Create benefits programmatically using the LaravelPolar facade:

Listing Benefits

List all benefits for an organization using your billable model:

Getting a Specific Benefit

Retrieve a specific benefit by ID using your billable model:

Listing Benefit Grants

Get all grants for a specific benefit using your billable model:

Updating Benefits

Update an existing benefit using the LaravelPolar facade:

Deleting Benefits

Delete a benefit using the LaravelPolar facade:

Customers API

Manage Polar customers directly via the API:

Products

Full CRUD operations for products via the facade:

Discounts

Create and manage discount codes for your products:

Apply a discount to a checkout using the existing withDiscountId method:

License Keys

Manage software license keys:

License Keys on Billable

The Billable trait includes license key management methods so you can validate, activate, and deactivate keys directly from your user model.

The organization_id is resolved from config('polar.organization_id') by default, so you only need to set it once in your .env:

You can still pass an explicit organization ID to any method if needed:

Updating a License Key (admin)

Seats

Manage seats on a subscription (for seat-based / per-member plans):

The same operations are available directly on a Subscription model:

Checkout Links

Reusable checkout links (admin-scoped):

Custom Fields

Metrics, Organizations & Files

Payment Methods

Your billable model can list and delete its saved payment methods. A short-lived customer session is minted under the hood, so you never expose your admin token:

Both methods throw InvalidCustomer if the billable has no associated Polar customer yet.

Usage-Based Billing

Track customer usage events for metered billing. This allows you to charge customers based on their actual usage of your service.

Tracking Usage Events

Track a single usage event for a customer:

Batch Event Ingestion

For usage-based billing, you can track multiple events at once:

Listing Customer Meters

List all meters for a customer:

Getting a Specific Customer Meter

Retrieve a specific customer meter by ID using the LaravelPolar facade:

[!NOTE] Usage events are sent to Polar for processing. They are not stored locally in your database. Use Polar's dashboard or API to view processed usage data.

Handling Webhooks

Polar can send webhooks to your app, allowing you to react. By default, this package handles the majority of the work for you. If you have properly configured webhooks, it will listen for incoming events and update your database accordingly. We recommend activating all event kinds so you may easily upgrade in the future.

Webhook Events

The package dispatches the following webhook events:

Order Events:

Subscription Events:

Benefit Grant Events:

Refund Events:

Checkout Events:

Customer Events:

Customer Seat Events:

Organization Events:

Product Events:

Benefit Events:

Each of these events has a $payload property containing the webhook payload. Some events also expose convenience properties for direct access to related models:

Events with Convenience Properties:

Event Convenience Properties
OrderCreated, OrderUpdated $billable, $order
SubscriptionCreated, SubscriptionUpdated, SubscriptionActive, SubscriptionCanceled, SubscriptionRevoked $billable, $subscription
BenefitGrantCreated, BenefitGrantUpdated, BenefitGrantRevoked $billable

Events with Only $payload:

Event Access Pattern
CheckoutCreated, CheckoutUpdated, CheckoutExpired $event->payload->checkout
CustomerCreated, CustomerUpdated, CustomerDeleted, CustomerStateChanged $event->payload->customer
ProductCreated, ProductUpdated $event->payload->product
BenefitCreated, BenefitUpdated $event->payload->benefit

Example Usage:

If you wish to respond to these events, you must establish listeners for them. You can create separate listener classes for each event type, or use a single listener class with multiple methods.

Using Separate Listener Classes

Create individual listener classes for each event:

Using a Single Listener Class

Alternatively, you can use a single listener class with multiple methods. For this approach, you'll need to register the listener as an event subscriber:

The Polar documentation includes an example payload.

Registering Listeners

For separate listener classes, register them in your EventServiceProvider:

For event subscribers, register the subscriber in your EventServiceProvider:

Laravel v11 and v12 will automatically discover listeners and subscribers if they follow Laravel's naming conventions.

Custom Webhook Handlers

For full control over how a specific webhook event is processed (including database updates), you can register custom handlers in config/polar.php. Custom handlers run instead of the built-in processing for that event type.

Your handler must implement Climactic\LaravelPolar\Contracts\WebhookHandler:

Unregistered event types continue to use the built-in handler.

Testing

Test Fake

Use LaravelPolar::fake() to prevent real API calls in your test suite. The fake records all calls and lets you assert against them:

You can stub return values for methods that your code depends on:

Assert that a method was called with specific arguments using a callback:

Remember to tear down the fake after each test (or in tearDown()):

Running Tests

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.


All versions of laravel-polar with dependencies

PHP Build Version
Package Version
Requires php Version ^8.3
illuminate/contracts Version ^11.0||^12.0||^13.0
pinkary-project/type-guard Version ^0.1.0
polar-sh/sdk Version ^0.10.0
spatie/laravel-data Version ^4.0
spatie/laravel-package-tools Version ^1
spatie/laravel-webhook-client Version ^3.0
standard-webhooks/standard-webhooks Version ^1.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package climactic/laravel-polar contains the following files

Loading the files please wait ...