PHP code example of serenity_technologies / cashier-gumroad

1. Go to this page and download the library: Download serenity_technologies/cashier-gumroad 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/ */

    

serenity_technologies / cashier-gumroad example snippets




namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use SerenityTechnologies\Gumroad\Cashier\Billable;

class User extends Authenticatable
{
    use Billable;

    // ...
}

// app/Http/Middleware/VerifyCsrfToken.php
namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    protected $except = [
        'cashier/gumroad/webhook', // Or your custom webhook URI
    ];
}

// config/cashier-gumroad.php

return [
    // Currency display settings
    'currency' => 'usd',
    'currency_locale' => 'en_US',
    
    // Billable model class
    'billable_model' => \App\Models\User::class,
    
    // Table names (all prefixed)
    'tables' => [
        'table_prefix' => 'gumroad_cashier_',
        'subscriptions' => 'subscriptions',
        'subscription_items' => 'subscription_items',
        'webhook_calls' => 'webhook_calls',
        'licenses' => 'licenses',
        'sales' => 'sales',
        'offer_codes' => 'offer_codes',
    ],
    
    // Overlay checkout widget settings
    'overlay' => [
        'button_text' => 'Buy on Gumroad',
        'button_class' => 'gumroad-button',
        'auto_trigger' => true,  // Skip product page, go direct to checkout
    ],
    
    // Webhook security
    'webhook' => [
        'uri' => 'cashier/gumroad/webhook',
        'tolerance' => 300,  // seconds
        'verify_signature' => true,
        'secret' => env('CASHIER_GUMROAD_WEBHOOK_SECRET'),
        'allowed_ips' => [],  // IP whitelist
        'rate_limit' => '60,1',  // 60 requests per minute
    ],
    
    // Subscription settings
    'subscription' => [
        'trial_days' => 0,
        'grace_period_days' => 3,
    ],
    
    // Queue settings
    'queue' => [
        'enabled' => true,
        'connection' => 'default',
        'queue' => 'default',
    ],
    
    // License settings
    'license' => [
        'enabled' => true,
        'verification_header' => 'X-License-Key',
        'cache_ttl' => 3600,
        'default_product_id' => env('CASHIER_GUMROAD_DEFAULT_PRODUCT_ID'),
    ],
    
    // Analytics cache
    'analytics' => [
        'cache_ttl' => 3600,
        'default_period' => '30_days',
    ],
];

// config/cashier-gumroad.php
'tables' => [
    'table_prefix' => 'app_',
    'subscriptions' => 'subs',  // Results in table: app_subs
],

use SerenityTechnologies\Gumroad\Cashier\Billable;

class User extends Authenticatable
{
    use Billable;
}

use SerenityTechnologies\Gumroad\Cashier\Services\CheckoutService;
use SerenityTechnologies\Gumroad\Cashier\Services\SubscriptionService;
use SerenityTechnologies\Gumroad\Cashier\Services\LicenseService;
use SerenityTechnologies\Gumroad\Cashier\Services\OfferCodeService;
use SerenityTechnologies\Gumroad\Cashier\Services\RevenueAnalyticsService;

use SerenityTechnologies\Gumroad\Cashier\Models\Subscription;
use SerenityTechnologies\Gumroad\Cashier\Models\Sale;
use SerenityTechnologies\Gumroad\Cashier\Models\License;
use SerenityTechnologies\Gumroad\Cashier\Models\OfferCode;
use SerenityTechnologies\Gumroad\Cashier\Models\WebhookCall;

use SerenityTechnologies\Gumroad\Cashier\Cashier;

Cashier::formatAmount(1999);           // "$19.99"
Cashier::customerModel();              // "App\Models\User"
Cashier::webhookUri();                 // "cashier/gumroad/webhook"
Cashier::generatIdempotencyKey($payload);  // SHA-256 hash
Cashier::determineEventType($payload); // Event type from payload

{{ route('cashier.gumroad.checkout', ['product_id' => 'your-product-id']) }}

$embed = $checkout->generateEmbedWidget('your-product-id', [
    'width' => 100,  // percentage
    'height' => 600, // pixels
]);

// Get all products
$products = $checkout->getProducts();

// Get product by ID
$product = $checkout->getProductById('your-product-id');

// Get product by permalink (legacy method)
$product = $checkout->getProductByPermalink('product-slug');

$user = Auth::user();

// Check if subscribed to specific product
if ($user->subscribedToProduct('product-id')) {
    // User has active subscription
}

// Check if has any valid subscription
if ($user->hasValidSubscription()) {
    // User has valid subscription (active or on grace period)
}

// Check if on trial
if ($user->onTrial('product-id')) {
    // User is on trial
}

// Check if cancelled
if ($user->hasCancelledSubscription('product-id')) {
    // User has cancelled subscription (but may still have access)
}

// Get all active subscriptions
$activeSubs = $user->activeSubscriptions();

// Get specific subscription
$sub = $user->subscriptionByGumroadId('gumroad-sub-id');

use SerenityTechnologies\Gumroad\Cashier\Models\Subscription;

$subscription = Subscription::first();

// Status checks
$subscription->active();         // true if active or on grace period
$subscription->cancelled();      // true if cancelled
$subscription->onGracePeriod();  // true if in grace period after cancellation
$subscription->onTrial();        // true if on trial
$subscription->failed();         // true if payment failed
$subscription->ended();          // true if subscription ended
$subscription->valid();          // true if active or on trial

// Get recurrence label
$subscription->recurrence();  // "Monthly", "Yearly", etc.

// Check product
$subscription->hasProduct('product-id');  // true if matches

// Scopes
Subscription::active()->get();
Subscription::forProduct('product-id')->get();
Subscription::withRecurrence('monthly')->get();

use SerenityTechnologies\Gumroad\Cashier\Services\SubscriptionService;

$subscriptionService = app(SubscriptionService::class);

// Sync single subscriber
$subscription = $subscriptionService->syncSubscriber('subscriber-id');

// Sync all subscribers for product
$synced = $subscriptionService->syncProductSubscribers('product-id');

// Refresh subscription status from API
$subscriptionService->refreshSubscriptionStatus($subscription);

$key = Cashier::generateIdempotencyKey($payload);
// Hash of: sale_id:subscription_id:timestamp

$eventType = Cashier::determineEventType($payload);

// Logic:
// - Has cancelled/cancelled_at? → cancellation
// - Has type (upgrade/downgrade)? → subscription_updated
// - Has ended_at/ended_reason? → subscription_ended
// - Has restarted_at? → subscription_restarted
// - Has refunded=true? → refund
// - Has disputed=true? → dispute
// - Default → sale

// Example validation rules
'sale_id' => 'nullable|string|max:255',
'email' => 'nullable|email|max:255',
'price' => 'nullable|integer|min:0',
'recurrence' => 'nullable|string|max:50',
'cancelled' => 'nullable|boolean',
'ended_at' => 'nullable|string|max:50',

$sensitiveFields = [
    'card',
    'shipping_information',
    'custom_fields',
    'url_params',
];

use SerenityTechnologies\Gumroad\Cashier\Http\Middleware\VerifyLicense;

Route::get('/premium-feature', function () {
    return view('premium-feature');
})->middleware(['auth', 'verify.license:your-product-id']);

// app/Http/Kernel.php
protected $routeMiddleware = [
    'verify.license' => \SerenityTechnologies\Gumroad\Cashier\Http\Middleware\VerifyLicense::class,
];

use SerenityTechnologies\Gumroad\Cashier\Services\LicenseService;

$licenseService = app(LicenseService::class);

// Verify license with Gumroad
$verification = $licenseService->verifyLicense('product-id', 'LICENSE-KEY');

// Enable license
$licenseService->enableLicense('product-id', 'LICENSE-KEY');

// Disable license
$licenseService->disableLicense('product-id', 'LICENSE-KEY', 'license-id');

// Decrement uses
$licenseService->decrementLicenseUses('product-id', 'LICENSE-KEY');

// Rotate license key
$licenseService->rotateLicense('product-id', 'LICENSE-KEY');

// Find license locally
$license = $licenseService->findByKey('LICENSE-KEY');

// Find and verify
$verification = $licenseService->findAndVerify('LICENSE-KEY');

use SerenityTechnologies\Gumroad\Cashier\Models\License;

$license = License::first();

// Status checks
$license->isActive();            // true if active
$license->isDisabled();          // true if disabled
$license->hasUnlimitedUses();    // true if max_uses is null
$license->hasReachedUseLimit();  // true if uses >= max_uses
$license->canBeUsed();           // true if active AND not at limit

// Actions
$license->activate();
$license->disable();
$license->recordUse();  // Increments uses_count

// Scopes
License::active()->get();
License::forProduct('product-id')->get();
License::useLimitReached()->get();

use SerenityTechnologies\Gumroad\Cashier\Services\OfferCodeService;

$offerCodeService = app(OfferCodeService::class);

// Create offer code
$offerCode = $offerCodeService->createOfferCode(
    productId: 'your-product-id',
    name: 'SAVE20',
    amountOff: 0,        // Fixed amount off (cents)
    percentOff: 20,      // Percentage off
    type: 'percent',     // 'cents' or 'percent'
    maxPurchaseCount: 100,
    universal: false     // true = applies to all products
);

// Update offer code
$offerCodeService->updateOfferCode(
    productId: 'your-product-id',
    offerCodeId: 'offer-id',
    amountOff: 0,
    percentOff: 30,
    maxPurchaseCount: 200
);

// Delete offer code
$offerCodeService->deleteOfferCode('your-product-id', 'offer-id');

// Sync from Gumroad API to local database
$offerCodes = $offerCodeService->syncOfferCodes('your-product-id');

// Get offer codes
$offerCodes = $offerCodeService->getOfferCodes('your-product-id');

// Find by name
$offerCode = $offerCodeService->findByName('your-product-id', 'SAVE20');

use SerenityTechnologies\Gumroad\Cashier\Models\OfferCode;

$offerCode = OfferCode::first();

// Check discount type
$offerCode->isAmountDiscount();   // true if amount_cents set
$offerCode->isPercentDiscount();  // true if percent_off set

// Check usage limits
$offerCode->hasReachedUsageLimit();  // true if at limit
$offerCode->canBeUsed();             // true if can still be used

// Get description
$offerCode->discountDescription();  // "20% off" or "$5.00 off"

// Record usage
$offerCode->incrementUsage();

// Scopes
OfferCode::universal()->get();
OfferCode::forProduct('product-id')->get();
OfferCode::available()->get();  // Not at usage limit

use SerenityTechnologies\Gumroad\Cashier\Services\OfferCodeService;

$offerCodeService = app(OfferCodeService::class);

// Generate checkout URL with offer code
$url = $offerCodeService->generateCheckoutUrl('product-id', 'SAVE20');

// Or use CheckoutService
use SerenityTechnologies\Gumroad\Cashier\Services\CheckoutService;

$checkoutService = app(CheckoutService::class);
$url = $checkoutService->generateDiscountedCheckoutUrl('product-id', 'SAVE20');

use SerenityTechnologies\Gumroad\Cashier\Models\Sale;

$sale = Sale::first();

// Type checks
$sale->isSubscription();        // true if has subscription
$sale->isRecurringCharge();     // true if recurring payment
$sale->isFullyRefunded();       // true if fully refunded
$sale->isPartiallyRefunded();   // true if partially refunded
$sale->
Sale::subscriptions()->get();
Sale::oneTime()->get();
Sale::refunded()->get();
Sale::forProduct('product-id')->get();
Sale::recurring()->get();

use SerenityTechnologies\Gumroad\Cashier\Services\RevenueAnalyticsService;

$analytics = app(RevenueAnalyticsService::class);

// Monthly Recurring Revenue (MRR)
$mrr = $analytics->getMRR();  // In cents
$mrrProduct = $analytics->getMRR('product-id');

// Annual Recurring Revenue (ARR)
$arr = $analytics->getARR();

// Churn Rate (30-day default)
$churnRate = $analytics->getChurnRate();  // Percentage
$churnRate90 = $analytics->getChurnRate(90);

// Customer Lifetime Value (LTV)
$ltv = $analytics->getCustomerLifetimeValue();

// Average Revenue Per Customer
$avgRevenue = $analytics->getAverageRevenuePerCustomer();

// Total Revenue (30-day default)
$totalRevenue = $analytics->getTotalRevenue();
$totalRevenue90 = $analytics->getTotalRevenue(90);

// Net Revenue (after fees)
$netRevenue = $analytics->getNetRevenue();

// Revenue by Product
$revenueByProduct = $analytics->getRevenueByProduct();
// Returns: ['product-id' => ['total_cents' => 10000, 'sales_count' => 10]]

// Recurring vs One-time Revenue
$breakdown = $analytics->getRecurringVsOneTimeRevenue();
// Returns: ['recurring_cents' => 5000, 'one_time_cents' => 3000, 'total_cents' => 8000]

// Subscription Counts
$newSubs = $analytics->getNewSubscriptions();
$cancelledSubs = $analytics->getCancelledSubscriptions();

// Clear analytics cache
$analytics->clearCache();

LTV = Average Revenue Per Customer / (Churn Rate / 100)

// Capped at 100 years to prevent absurd values at low churn
Max LTV = Average Revenue Per Customer × 1200

// Cache key format: "cashier-analytics:{metric}"
// Example: "cashier-analytics:mrr"

// Compatible with all cache drivers (no tags 

// app/Providers/EventServiceProvider.php
protected $listen = [
    \SerenityTechnologies\Gumroad\Cashier\Events\SubscriptionCreated::class => [
        \App\Listeners\SendWelcomeEmail::class,
        \App\Listeners\GrantAccess::class,
    ],
    
    \SerenityTechnologies\Gumroad\Cashier\Events\SubscriptionCancelled::class => [
        \App\Listeners\RevokeAccess::class,
        \App\Listeners\SendCancellationEmail::class,
    ],
    
    \SerenityTechnologies\Gumroad\Cashier\Events\PaymentReceived::class => [
        \App\Listeners\SendReceipt::class,
    ],
    
    \SerenityTechnologies\Gumroad\Cashier\Events\PaymentRefunded::class => [
        \App\Listeners\ProcessRefund::class,
    ],
];

// app/Listeners/GumroadEventSubscriber.php
class GumroadEventSubscriber
{
    public function handleSubscriptionCreated($event)
    {
        $user = $event->subscription->billable;
        $user->notify(new WelcomeToPremium($event->subscription));
    }
    
    public function handlePaymentReceived($event)
    {
        // Send receipt
    }
    
    public function subscribe($events)
    {
        $events->listen(
            \SerenityTechnologies\Gumroad\Cashier\Events\SubscriptionCreated::class,
            [self::class, 'handleSubscriptionCreated']
        );
        
        $events->listen(
            \SerenityTechnologies\Gumroad\Cashier\Events\PaymentReceived::class,
            [self::class, 'handlePaymentReceived']
        );
    }
}

// app/Providers/EventServiceProvider.php
protected $subscribe = [
    \App\Listeners\GumroadEventSubscriber::class,
];

namespace App\Listeners;

use SerenityTechnologies\Gumroad\Cashier\Events\SubscriptionCreated;
use App\Mail\WelcomeToPremium;
use Illuminate\Support\Facades\Mail;

class SendWelcomeEmail
{
    public function handle(SubscriptionCreated $event): void
    {
        $user = $event->subscription->billable;
        
        Mail::to($user)->send(new WelcomeToPremium(
            $user,
            $event->subscription
        ));
    }
}

// app/Http/Middleware/VerifyCsrfToken.php
protected $except = [
    'cashier/gumroad/webhook',
];

use SerenityTechnologies\Gumroad\Cashier\Models\WebhookCall;

// Get unprocessed webhooks
$unprocessed = WebhookCall::unprocessed()->get();

// Get failed webhooks
$failed = WebhookCall::whereNotNull('exception')->get();

// app/Http/Controllers/ProductController.php
public function show(string $permalink, CheckoutService $checkout)
{
    $product = $checkout->getProductByPermalink($permalink);
    
    if (! $product) {
        abort(404);
    }
    
    $widget = $checkout->generateOverlayWidget($product->id, [
        'button_text' => 'Subscribe to ' . $product->name,
        'email' => auth()->check() ? auth()->user()->email : null,
        'auto_trigger' => false,
    ]);
    
    return view('products.show', compact('product', 'widget'));
}

// app/Http/Middleware/RequireSubscription.php
public function handle($request, Closure $next)
{
    $productId = config('services.gumroad.premium_product_id');
    
    if (! $request->user()->subscribedToProduct($productId)) {
        return redirect('/subscribe')->with('error', 'Premium subscription 

// app/Http/Controllers/PricingController.php
public function index(CheckoutService $checkout)
{
    $plans = [
        'monthly' => [
            'product_id' => 'monthly-product-id',
            'name' => 'Monthly Plan',
            'price' => '$19/month',
        ],
        'yearly' => [
            'product_id' => 'yearly-product-id',
            'name' => 'Yearly Plan',
            'price' => '$199/year',
        ],
    ];
    
    foreach ($plans as $key => $plan) {
        $plans[$key]['widget'] = $checkout->generateOverlayWidget(
            $plan['product_id'],
            [
                '

// app/Http/Controllers/SubscriptionController.php
public function show()
{
    $user = Auth::user();
    $subscriptions = $user->subscriptions;
    
    return view('account.subscription', compact('subscriptions'));
}

// app/Listeners/SendWelcomeEmail.php
class SendWelcomeEmail
{
    public function handle(SubscriptionCreated $event): void
    {
        $user = $event->subscription->billable;
        $subscription = $event->subscription;
        
        $user->notify(new WelcomeToPremium(
            $user,
            $subscription
        ));
        
        // Grant access to premium features
        $user->update(['has_premium_access' => true]);
    }
}

// app/Http/Controllers/Admin/AnalyticsController.php
public function index(RevenueAnalyticsService $analytics)
{
    return view('admin.analytics', [
        'mrr' => $analytics->getMRR(),
        'arr' => $analytics->getARR(),
        'churnRate' => $analytics->getChurnRate(),
        'ltv' => $analytics->getCustomerLifetimeValue(),
        'totalRevenue' => $analytics->getTotalRevenue(30),
        'netRevenue' => $analytics->getNetRevenue(30),
        'revenueByProduct' => $analytics->getRevenueByProduct(),
        'newSubscriptions' => $analytics->getNewSubscriptions(30),
        'cancelledSubscriptions' => $analytics->getCancelledSubscriptions(30),
    ]);
}

// routes/api.php
Route::middleware(['auth:api', 'verify.license'])
    ->get('/premium-api/data', function (Request $request) {
        return response()->json([
            'data' => 'Premium API Response',
        ]);
    });

use SerenityTechnologies\Gumroad\Cashier\Cashier;

// Format cents to dollars
echo Cashier::formatAmount(1999);  // "$19.99"
echo Cashier::formatAmount(9900);  // "$99.00"

// In Blade views
{{ \SerenityTechnologies\Gumroad\Cashier\Cashier::formatAmount($subscription->price_cents) }}

// app/Http/Middleware/VerifyCsrfToken.php
protected $except = [
    'cashier/gumroad/webhook',
];

// Correct usage
$url = $checkout->generateCheckoutUrl('your-product-id');

// NOT this (old method):
// $url = "https://gumroad.com/l/permalink";

// Check for unprocessed webhooks
WebhookCall::unprocessed()->get();

// Add gumroad_purchaser_id to users table for better matching
Schema::table('users', function (Blueprint $table) {
    $table->string('gumroad_purchaser_id')->nullable();
});

$analytics = app(RevenueAnalyticsService::class);
$analytics->clearCache();

// Or dynamically
Cashier::formatAmount(1999);  // Uses configured locale

// Example: Add index for analytics
Schema::table('gumroad_cashier_sales', function (Blueprint $table) {
    $table->index(['sale_timestamp', 'refunded'], 'idx_sales_timestamp_refunded');
});
bash
php artisan vendor:publish --provider="SerenityTechnologies\Gumroad\Cashier\CashierServiceProvider" --tag="cashier-gumroad-config"
bash
# Publish migrations
php artisan vendor:publish --provider="SerenityTechnologies\Gumroad\Cashier\CashierServiceProvider" --tag="cashier-gumroad-migrations"

# Run migrations
php artisan migrate
bash
php -r "echo bin2hex(random_bytes(32));"
bash
php artisan queue:work --queue=default --tries=3
blade
{{-- resources/views/account/subscription.blade.php --}}
@forelse($subscriptions as $subscription)
    <div class="subscription-card">
        <h3>{{ $subscription->type }}</h3>
        <p>Status: {{ $subscription->status }}</p>
        <p>Recurrence: {{ $subscription->recurrence() }}</p>
        <p>Price: {{ \SerenityTechnologies\Gumroad\Cashier\Cashier::formatAmount($subscription->price_cents) }}</p>
        
        @if($subscription->onTrial())
            <span class="badge badge-trial">On Trial</span>
        @elseif($subscription->active())
            <span class="badge badge-active">Active</span>
        @elseif($subscription->cancelled())
            <span class="badge badge-cancelled">Cancelled</span>
        @endif
        
        @if($subscription->ends_at)
            <p>Access until: {{ $subscription->ends_at->format('M d, Y') }}</p>
        @endif
    </div>
@empty
    <p>No active subscriptions</p>
@endforelse
bash
# Check failed jobs
php artisan queue:failed

# Retry failed jobs
php artisan queue:retry all

# Clear failed queue
php artisan queue:flush
bash
php artisan queue:work --queue=default --tries=3
bash
composer update serenity_technologies/cashier-gumroad

# Republish migrations if needed
php artisan vendor:publish --provider="SerenityTechnologies\Gumroad\Cashier\CashierServiceProvider" --tag="cashier-gumroad-migrations" --force

# Run new migrations
php artisan migrate