PHP code example of bhhaskin / laravel-billing

1. Go to this page and download the library: Download bhhaskin/laravel-billing 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/ */

    

bhhaskin / laravel-billing example snippets


// $19.99 in cents
$plan = Plan::create(['name' => 'Pro', 'price' => 1999, ...]);

// $50.00 refund
$invoice->refund(amount: 5000);

// $25.00 promotional credit
$user->customer->addCredit(amount: 2500, type: 'promotional');

use Bhhaskin\Billing\Concerns\Billable;

class User extends Authenticatable
{
    use Billable;
}

use Bhhaskin\Billing\Models\Plan;

$plan = Plan::create([
    'name' => 'Professional',
    'slug' => 'professional',
    'price' => 1999, // $19.99 in cents
    'interval' => 'monthly',
    'features' => ['feature1', 'feature2'],
    'limits' => ['websites' => 5, 'storage_gb' => 100],
]);

$user = User::find(1);
$plan = Plan::where('slug', 'professional')->first();

$subscription = $user->subscribe($plan);

// Check if user has any active subscription
if ($user->hasActiveSubscription()) {
    // ...
}

// Check if user is subscribed to specific plan
if ($user->subscribedToPlan($plan)) {
    // ...
}

// Get combined limits from all subscriptions
$limits = $user->getCombinedLimits();
$websiteLimit = $user->getLimit('websites');

// Check if user has specific feature
if ($user->hasFeature('ssl_certificate')) {
    // ...
}

$subscription = $user->subscriptions()->first();
$newPlan = Plan::where('slug', 'enterprise')->first();

// Immediate plan change with proration
$subscription->changePlan($newPlan, [
    'prorate' => true,
]);

// Schedule plan change for end of period
$subscription->changePlan($newPlan, [
    'schedule' => true,
    'schedule_for' => $subscription->current_period_end,
]);

// Preview plan change costs before applying
$preview = $subscription->previewPlanChange($newPlan);
// Returns: amount, proration_credit, upgrade_charge, is_upgrade, etc.

// Cancel scheduled plan change
$subscription->cancelScheduledPlanChange();

// Add credit to customer balance ($25.00 = 2500 cents)
$user->customer->addCredit(
    amount: 2500,
    type: 'promotional',
    description: 'Holiday promotion credit',
    options: ['expires_at' => now()->addMonths(3)]
);

// Get available credit balance (in cents)
$balance = $user->customer->getAvailableCredit();

// Credits are automatically applied to invoices
// Or manually apply credits to an invoice
$amountApplied = $user->customer->applyCreditsToInvoice($invoice);

// View credit history
$credits = $user->customer->credits()
    ->where('type', 'refund')
    ->get();

$invoice = $user->invoices()->where('status', 'paid')->first();

// Full refund (defaults to remaining refundable amount)
$refund = $invoice->refund();

// Partial refund ($10.00 = 1000 cents)
$refund = $invoice->refund(
    amount: 1000,
    reason: 'requested_by_customer',
    description: 'Partial service credit'
);

// Check refund status
if ($refund->isSucceeded()) {
    // Refund completed - customer credit created
}

// Get refund information
$totalRefunded = $invoice->getTotalRefunded();
$remainingRefundable = $invoice->getRemainingRefundable();

if ($invoice->isFullyRefunded()) {
    // Invoice completely refunded
}

// Record usage for a quota (e.g., disk space in MB)
$user->recordUsage('disk_space', 150.5);

// Get current usage
$currentUsage = $user->getUsage('disk_space');

// Set absolute usage (useful for syncing from external sources)
$user->setUsage('bandwidth', 5000);

// Decrement usage (e.g., when files are deleted)
$user->decrementUsage('disk_space', 50);

// Check if over quota
if ($user->isOverQuota('disk_space')) {
    // Prevent new uploads
}

// Get remaining quota
$remaining = $user->getRemainingQuota('websites'); // Returns remaining count

// Get percentage used
$percentage = $user->getQuotaPercentage('disk_space'); // Returns 0-100

// Reset usage to zero
$user->resetUsage('disk_space');

// Listen to quota events in your EventServiceProvider
use Bhhaskin\Billing\Events\QuotaWarning;
use Bhhaskin\Billing\Events\QuotaExceeded;

protected $listen = [
    QuotaWarning::class => [
        SendQuotaWarningNotification::class,
    ],
    QuotaExceeded::class => [
        ArchiveUserFiles::class,
        SendQuotaExceededNotification::class,
    ],
];

'quota_warning_thresholds' => [80, 90, 95], // Fire warnings at these percentages

Route::middleware('auth:sanctum')->group(function () {
    

// routes/api.php (or web.php)
use Bhhaskin\Billing\Http\Controllers\WebhookController;

Route::post('/billing/webhook/stripe', [WebhookController::class, 'handle'])
    ->name('billing.webhook.stripe');

// app/Http/Middleware/VerifyCsrfToken.php (Laravel 10) or
// bootstrap/app.php (Laravel 11+)
protected $except = [
    'billing/webhook/stripe',
];

use Bhhaskin\Billing\Http\Controllers\WebhookController as BaseWebhookController;

class StripeWebhookController extends BaseWebhookController
{
    protected function handleInvoicePaymentSucceeded($stripeInvoice): void
    {
        parent::handleInvoicePaymentSucceeded($stripeInvoice);
        // Application-specific side effects here
    }
}

use Bhhaskin\Billing\Events\PaymentMethodExpiring;

protected $listen = [
    PaymentMethodExpiring::class => [
        SendCardExpiringNotification::class,
    ],
];

// Listener:
public function handle(PaymentMethodExpiring $event): void
{
    $event->paymentMethod->customer->billable->notify(
        new CardExpiringSoon($event->paymentMethod, $event->daysUntilExpiry)
    );
}
bash
php artisan vendor:publish --tag=billing-config
bash
php artisan vendor:publish --tag=billing-migrations
php artisan migrate
bash
php artisan billing:prune-webhook-events
bash
php artisan billing:check-expiring-payment-methods
php artisan billing:check-expiring-payment-methods --days=30 --dry-run
php artisan billing:check-expiring-payment-methods --force
bash
php artisan billing:process