PHP code example of emeroid / laravel-billing-core

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

    

emeroid / laravel-billing-core example snippets


// app/Models/User.php

use Emeroid\Billing\Traits\Billable;
use Illuminate{...};

class User extends Authenticatable
{
    use Billable, HasFactory, Notifiable;
    // ...
}

// database/seeders/PlanSeeder.php

use Emeroid\Billing\Models\Plan;
use Illuminate\Database\Seeder;

class PlanSeeder extends Seeder
{
    public function run(): void
    {
        Plan::create([
            'name' => 'Pro Plan',
            'slug' => 'pro-plan',
            'amount' => 500000, // 5000 NGN (in kobo)
            'interval' => 'monthly',
            'paystack_plan_id' => 'PL_abc123',
            'paypal_plan_id' => 'P-xyz456',
        ]);

        Plan::create([
            'name' => 'Business Plan',
            'slug' => 'business-plan',
            'amount' => 1000000, // 10000 NGN
            'interval' => 'monthly',
            'paystack_plan_id' => 'PL_def789',
            'paypal_plan_id' => 'P-ghi123',
        ]);
    }
}

use Emeroid\Billing\Facades\Billing;
use Illuminate\Http\Request;

class PaymentController
{
    public function startPayment(Request $request)
    {
        $user = $request->user();
        $amountInKobo = 50000; // 5000 NGN

        try {
            $payment = Billing::purchase($amountInKobo, $user->email, [
                'user_id' => $user->id,
                'currency' => 'NGN',
            ]);

            return redirect()->away($payment['authorization_url']);

        } catch (\Emeroid\Billing\Exceptions\PaymentInitializationFailedException $e) {
            return back()->with('error', $e->getMessage());
        }
    }
}

use Emeroid\Billing\Facades\Billing;
use Emeroid\Billing\Models\Plan;
use Illuminate\Http\Request;

class SubscriptionController
{
    public function startSubscription(Request $request)
    {
        $user = $request->user();
        $plan = Plan::where('slug', 'pro-plan')->firstOrFail();

        $gatewayPlanId = config('billing.default') === 'paypal'
            ? $plan->paypal_plan_id
            : $plan->paystack_plan_id;

        try {
            $subscription = Billing::subscribe(
                $gatewayPlanId,
                $user->email,
                [
                    'amount' => $plan->amount,
                    'user_id' => $user->id,
                    'currency' => 'NGN',
                ]
            );

            return redirect()->away($subscription['authorization_url']);

        } catch (\Emeroid\Billing\Exceptions\PaymentInitializationFailedException $e) {
            return back()->with('error', $e->getMessage());
        }
    }
}

$user = auth()->user();

// STATUS CHECKS
$user->isSubscribed();
$user->onGracePeriod();
$user->hasActiveSubscription();
$user->isSubscribedTo('pro-plan');
$user->isPastDue();

// MANAGEMENT
$subscription = $user->getSubscription('SUB_abc');

$user->cancelSubscription($subscription->gateway_subscription_id);
$user->swapPlan($subscription->gateway_subscription_id, 'business-plan');
$user->syncSubscription($subscription->gateway_subscription_id);

// app/Providers/EventServiceProvider.php

use Emeroid\Billing\Events\{
    TransactionSuccessful,
    SubscriptionStarted,
    SubscriptionCancelled,
    SubscriptionPlanSwapped,
    SubscriptionPaymentFailed
};

protected $listen = [
    TransactionSuccessful::class => [
        'App\Listeners\GrantAccessToProduct',
        'App\Listeners\SendInvoiceEmail',
    ],
    SubscriptionStarted::class => [
        'App\Listeners\ActivateProFeatures',
    ],
    SubscriptionCancelled::class => [
        'App\Listeners\RevokeProFeaturesAtPeriodEnd',
    ],
    SubscriptionPlanSwapped::class => [
        'App\Listeners\HandlePlanSwap',
    ],
    SubscriptionPaymentFailed::class => [
        'App\Listeners\SendDunningEmail',
    ],
];

public static function findByEmail(string $email): ?Model



namespace App\Lookups;

use App\Models\User;
use App\Models\Team;
use Illuminate\Database\Eloquent\Model;

class BillableLookup
{
    /**
     * Custom strategy to find the billable model instance (Team) from an email.
     *
     * @param string $email The email address received from the payment gateway.
     * @return Model|null The Billable Model instance (Team) or null if not found.
     */
    public static function findByEmail(string $email): ?Model
    {
        // 1. Find the User by email.
        $user = User::where('email', $email)->first();

        if (!$user) {
            return null;
        }

        // 2. Return the Billable model (Team) associated with this User.
        // Example: Team is linked to User via the 'owner_id' foreign key.
        return Team::where('owner_id', $user->id)->first();
    }
}

// File: config/billing.php

'email_lookup' => [
    \App\Lookups\BillableLookup::class,
    'findByEmail'
],

// ... rest of your config

// Excerpt from Emeroid\Billing\Drivers\AbstractDriver.php

protected function findBillableByEmail(string $email): ?Model
{
    // 1. Check for a custom lookup strategy defined in the billing config.
    $customLookup = config('billing.email_lookup');

    if (is_callable($customLookup)) {
        // Use the custom callable if defined.
        return call_user_func($customLookup, $email);
    }

    // 2. Fallback: Check the billable model directly.
    $modelClass = $this->billableModelClass();
    return $modelClass::where('email', $email)->first();
}
bash
php artisan vendor:publish --provider="Emeroid\Billing\BillingServiceProvider" --tag="billing-config"
bash
php artisan vendor:publish --provider="Emeroid\Billing\BillingServiceProvider" --tag="billing-migrations"
bash
php artisan migrate