Download the PHP package serenity_technologies/cashier-gumroad without Composer
On this page you can find all versions of the php package serenity_technologies/cashier-gumroad. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download serenity_technologies/cashier-gumroad
More information about serenity_technologies/cashier-gumroad
Files in serenity_technologies/cashier-gumroad
Package cashier-gumroad
Short Description Laravel Cashier for Gumroad - Subscription billing and payment management
License MIT
Informations about the package cashier-gumroad
Laravel Cashier for Gumroad - Complete Documentation
Table of Contents
- Overview
- Installation & Setup
- Configuration
- Database Schema
- Core Concepts
- Checkout Flows
- Subscription Management
- Webhook Handling
- License Management
- Offer Codes & Discounts
- Sales Tracking
- Revenue Analytics
- Console Commands
- Events & Listeners
- Security Best Practices
- Common Patterns & Examples
- API Limitations
- Troubleshooting
Overview
Laravel Cashier for Gumroad provides a fluent, expressive interface to Gumroad's subscription billing and payment services. It handles almost all of the boilerplate code needed for subscription management, including:
- Checkout URLs & Widgets - Generate overlay/embed widgets and direct checkout URLs
- Subscription Management - Track and manage subscriptions locally
- Webhook Handling - Process all Gumroad webhook events securely
- License Management - Verify and manage license keys
- Offer Codes - Create and manage discount codes
- Sales Tracking - Record and analyze sales data
- Revenue Analytics - MRR, ARR, churn rate, LTV, and more
Package Architecture
Installation & Setup
Prerequisites
- PHP 8.1 or higher
- Laravel 9.0 or higher
- Gumroad account with API access token
- Composer
Step 1: Install Package
Step 2: Add Billable Trait to User Model
The Billable trait provides subscription management methods to your user model:
What the Billable trait provides:
subscriptions()- Get all subscriptions for the usersubscribedToProduct($productId)- Check if user is subscribed to a producthasValidSubscription($productId)- Check if user has a valid subscriptionactiveSubscriptions()- Get all active subscriptionsonTrial($productId)- Check if user is on trialhasCancelledSubscription($productId)- Check if user has cancelled subscriptionsubscriptionByGumroadId($gumroadSubscriptionId)- Get subscription by Gumroad IDcreateOrUpdateSubscriptionFromWebhook($payload)- Create/update from webhookcancelSubscriptionFromWebhook($payload)- Cancel from webhookupdateSubscriptionFromWebhook($payload)- Update from webhookendSubscriptionFromWebhook($payload)- End from webhookrestartSubscriptionFromWebhook($payload)- Restart from webhook
Step 3: Publish Configuration
This creates config/cashier-gumroad.php with all configuration options.
Step 4: Publish & Run Migrations
This creates 6 database tables (with configured prefix, default gumroad_cashier_):
gumroad_cashier_subscriptions- Local subscription recordsgumroad_cashier_subscription_items- Subscription line itemsgumroad_cashier_sales- Sale recordsgumroad_cashier_licenses- License key recordsgumroad_cashier_offer_codes- Discount code recordsgumroad_cashier_webhook_calls- Webhook call tracking
Step 5: Configure Webhook Route (CSRF Exclusion)
CRITICAL: The webhook endpoint must be excluded from CSRF protection.
Step 6: Configure Gumroad API Access Token
The package uses the serenity_technologies/gumroad package for API calls. Configure your access token:
Get your access token from: Gumroad Dashboard → Settings → Advanced → Generate access token
Configuration
Environment Variables
Configuration File Breakdown
Custom Table Prefix Example
Database Schema
1. Subscriptions Table
Purpose: Tracks subscription lifecycle for each user.
Key Fields:
id(ULID) - Primary keybillable_id,billable_type- Polymorphic relation to user modelgumroad_subscription_id- Gumroad's subscription IDgumroad_product_id- Product being subscribed tostatus- Current status (active,cancelled,ended,past_due)recurrence- Billing frequency (monthly,yearly, etc.)price_cents- Current price in centstrial_ends_at- Trial expiration timestampends_at- Subscription end timestampcancelled_at- Cancellation timestamplicense_key- Associated license key
Indexes:
- Unique:
(billable_id, billable_type, gumroad_subscription_id) - Composite:
(status, recurrence, gumroad_product_id) - Composite:
(status, ends_at)
2. Subscription Items Table
Purpose: Line items within a subscription (for multi-product subscriptions).
Key Fields:
id(ULID) - Primary keysubscription_id- Foreign key to subscriptionsgumroad_variant_id- Variant ID if applicablegumroad_product_id- Product IDprice_cents- Item pricequantity- Item quantity
3. Sales Table
Purpose: Records all sales (one-time and recurring).
Key Fields:
id(ULID) - Primary keybillable_id,billable_type- Polymorphic relationgumroad_sale_id- Gumroad's sale ID (unique)gumroad_product_id- Product soldgumroad_subscription_id- Associated subscription (nullable)price_cents,gumroad_fee_cents,net_cents- Revenue trackingemail,full_name- Customer inforefunded,partially_refunded,refund_amount_cents- Refund trackinglicense_key- License key if generatedoffer_code- Discount code usedis_recurring_charge- Is this a recurring payment?sale_timestamp- When sale occurred
Foreign Keys:
gumroad_subscription_id→subscriptions.gumroad_subscription_id
4. Licenses Table
Purpose: Track license keys for software products.
Key Fields:
id(ULID) - Primary keybillable_id,billable_type- Polymorphic relationgumroad_license_key- The license key (unique)gumroad_product_id- Product the license is foruses_count- Current usage countmax_uses- Maximum allowed uses (nullable for unlimited)status- License status (active,disabled)last_verified_at- Last verification timestamp
5. Offer Codes Table
Purpose: Local cache of Gumroad discount codes.
Key Fields:
id(ULID) - Primary keygumroad_offer_code_id- Gumroad's offer code IDgumroad_product_id- Product the code applies toname- The coupon code (e.g., "SAVE20")amount_cents- Fixed discount amount (nullable)percent_off- Percentage discount (nullable)max_purchase_count- Usage limit (nullable for unlimited)times_used- Current usage countuniversal- Applies to all products?
Unique: (gumroad_product_id, name)
6. Webhook Calls Table
Purpose: Track and idempotent webhook processing.
Key Fields:
id(ULID) - Primary keyevent_type- Type of event (sale,refund, etc.)gumroad_sale_id,gumroad_subscription_id- Related entitiesidempotency_key- SHA-256 hash to prevent duplicatespayload- Sanitized webhook payload (JSON)processed- Has this been processed?processed_at- Processing timestampexception- Error message if failed
Core Concepts
Billable Model
The billable model (typically User) is the entity that can have subscriptions. Add the Billable trait:
Services
The package provides several services (auto-injected via dependency injection):
Models
All models use ULIDs and configurable table names:
Cashier Static Helper
The Cashier class provides static helper methods:
Checkout Flows
The package supports two primary checkout methods.
1. New Window Checkout (Recommended)
Opens the Gumroad checkout page in a new browser tab. This is now the default behavior for all generated buttons.
Using Blade Directives:
This generates a standard anchor tag with target="_blank" and rel="noopener noreferrer".
Dedicated Checkout Route:
You can link directly to a hosted launcher:
2. Embed Checkout
Embeds the full product page in an iframe.
Getting Products
Subscription Management
Checking Subscription Status
Subscription Model Methods
Syncing Subscribers from Gumroad
Sync subscribers from Gumroad API to local database:
Programmatic sync:
Subscription Lifecycle States
- active - Subscription is active and current
- past_due - Payment failed, but still within grace period
- cancelled - User cancelled, but still has access until
ends_at - ended - Subscription has fully ended
Webhook Handling
Before your application can receive webhook events, you must first subscribe to the specific resources you want to listen to. Use the provided artisan commands to manage these subscriptions.
Available Artisan Commands for Webhook Subscriptions:
Supported Resources:
sale, refund, dispute, dispute_won, cancellation, subscription_updated, subscription_ended, subscription_restarted.
Supported Events
| The package handles all 8 Gumroad webhook events: ... | Gumroad Event | Local Action | Events Dispatched |
|---|---|---|---|
sale |
Create sale record, create subscription | PaymentReceived, SubscriptionCreated |
|
refund |
Update sale, cancel subscription | PaymentRefunded, SubscriptionCancelled |
|
cancellation |
Cancel subscription | SubscriptionCancelled |
|
subscription_updated |
Update subscription details | SubscriptionUpdated |
|
subscription_ended |
End subscription | SubscriptionEnded |
|
subscription_restarted |
Reactivate subscription | SubscriptionRestarted |
|
dispute |
Log dispute | DisputeCreated |
|
dispute_won |
Log dispute outcome | DisputeWon |
How Webhooks Work
- Gumroad sends POST to your webhook endpoint (
/cashier/gumroad/webhook) - Middleware verifies the request (secret token, IP whitelist)
- Controller validates payload (50+ fields validated)
- Idempotency check prevents duplicate processing
- Event type determined from payload (never trust headers)
- Webhook call recorded in database
- Job dispatched to queue (or processed synchronously)
- Handler processes the webhook in a database transaction
- Events dispatched after transaction commits
Webhook Security
Three layers of protection:
-
Secret Token Verification (optional):
-
IP Whitelisting (optional):
- Rate Limiting (default: 60 req/min):
Idempotency
Webhooks are protected against duplicate processing using SHA-256 idempotency keys:
Event Type Detection
The package determines event type from payload fields (never trusts client headers):
Webhook Payload Validation
All incoming webhooks are validated with 50+ field rules:
Payload Sanitization
Sensitive fields are removed before storage:
License Management
License keys are used to verify software purchases.
Verify License Middleware
Protect routes with license verification:
Or apply globally:
How it works:
- Checks for
X-License-Keyheader orlicense_keyquery parameter - Verifies with Gumroad API (cached for 1 hour)
- Updates local license record
- Throws
AccessDeniedHttpExceptionif invalid
License Service Methods
License Model Methods
Offer Codes & Discounts
Creating Offer Codes
Syncing Offer Codes
Offer Code Model Methods
Checkout with Offer Code
Sales Tracking
Sale Model Methods
Syncing Sales
Revenue Analytics
The package provides comprehensive revenue analytics.
Key Metrics
How MRR is Calculated
MRR normalizes different recurrence periods to monthly:
LTV Calculation
Caching
All analytics queries are cached (default: 1 hour) using prefixed keys:
Console Commands
1. Sync Subscribers
Syncs subscribers from Gumroad API to local database.
Options:
--product-id- Sync subscribers for specific product--all- Sync subscribers for all products--queue- Queue sync jobs instead of synchronous
2. Sync Sales
Syncs sales from Gumroad API to local database.
Options:
--product-id- Sync sales for specific product--all- Sync all sales--since- Only sync sales since date (YYYY-MM-DD)--queue- Queue sync jobs
3. Webhook Subscriptions
Manage real-time notifications by subscribing to Gumroad resources (Ping/Webhooks).
Supported Resources:
sale, refund, dispute, dispute_won, cancellation, subscription_updated, subscription_ended, subscription_restarted.
Setting Up Cron Jobs
For automatic syncing, add to your server's crontab:
Events & Listeners
Available Events
| Event | When Dispatched | Parameters |
|---|---|---|
GumroadWebhookReceived |
Every webhook received | $eventType, $payload, $saleId, $subscriptionId |
PaymentReceived |
Sale completed | $payload, $saleId, $subscriptionId |
PaymentRefunded |
Refund processed | $payload, $saleId |
SubscriptionCreated |
New subscription created | $subscription, $payload |
SubscriptionCancelled |
Subscription cancelled | $subscription, $payload, $cancelledByAdmin, $cancelledByBuyer, $cancelledBySeller, $cancelledDueToRefund |
SubscriptionUpdated |
Subscription details updated | $subscription, $payload, $updateType |
SubscriptionEnded |
Subscription ended | $subscription, $payload, $endedReason |
SubscriptionRestarted |
Subscription reactivated | $subscription, $payload |
DisputeCreated |
Dispute raised | $payload, $saleId |
DisputeWon |
Dispute resolved in buyer's favor | $payload, $saleId |
Registering Event Listeners
Method 1: EventServiceProvider
Method 2: Event Subscribers
Example Listener
Security Best Practices
1. Exclude Webhook from CSRF
CRITICAL: This is required for webhooks to work.
2. Enable Webhook Verification
Generate a strong secret:
3. IP Whitelisting (Optional)
If Gumroad provides static IPs, whitelist them:
4. Use Queue for Webhooks
Queue webhook processing to ensure fast response times:
Configure queue worker:
5. Rate Limiting
Default rate limiting is 60 requests per minute. Adjust as needed:
6. Protect Sensitive Data
The package automatically sanitizes webhook payloads before storage. Do not store:
- Card details
- Full PII in logs
- Raw webhook payloads with sensitive fields
7. Use HTTPS in Production
Always use HTTPS for webhook endpoints in production.
8. Monitor Failed Webhooks
Check for failed webhook processing:
Common Patterns & Examples
1. Product Checkout Page
2. Access Control Middleware
3. Pricing Page with Multiple Plans
4. Subscription Status Page
5. Event Listener for Welcome Email
6. Admin Dashboard Analytics
7. License-Protected API Route
Client request:
8. Formatting Currency
API Limitations
Gumroad's API has several limitations to be aware of:
What Gumroad Does NOT Support:
-
Direct Checkout on Your Site
- Cannot process payments directly
- Must use overlay widget or redirect to Gumroad
-
Payment Method Updates
- Cannot update payment methods via API
- Users must manage via Gumroad dashboard
-
Proration Calculations
- No API support for proration on plan changes
- Gumroad handles this internally
-
Subscription Cancellation via API
- Cannot cancel subscriptions via API
- Must be done via Gumroad dashboard or by user
-
Custom Checkout CSS
- Cannot customize checkout appearance
- Limited to overlay widget styling
- Price Retrieval for Subscribers
- Subscriber API doesn't return pricing info
- Must track locally or query sales API
Workarounds:
- Overlay Checkout: Provides seamless UX without leaving your site
- Local Tracking: Store all subscription data locally via webhooks
- Sales API Sync: Periodically sync sales for accurate pricing
- Webhook Events: Use events to track lifecycle changes
Troubleshooting
Issue: Webhook Returns 403 (Invalid Webhook Secret)
Cause: The HMAC signature validation failed. This usually means:
- The
CASHIER_GUMROAD_WEBHOOK_SECRETin your.envdoes not match the one used during subscription. - The URL signature was generated with a different secret or event type.
Solution:
- Verify
CASHIER_GUMROAD_WEBHOOK_SECRETis identical in your environment. - Re-subscribe to your resources using the
cashier-gumroad:subscribe --url=https://yourdomain.comcommand to regenerate valid URLs with the correct resource-specific signatures. - If using
TestWebhookCommand, it automatically uses the correct logic, but verify your.envconfiguration matches.
Issue: Webhook Returns 419 (CSRF Token Mismatch)
Solution: Exclude webhook route from CSRF protection.
Issue: generateCheckoutUrl Returns 404
Cause: The URL was being constructed manually without fetching from Gumroad.
Solution: The method now:
- Accepts product ID (not permalink)
- Fetches product from Gumroad API
- Uses the actual
short_urlfrom API response
Issue: Duplicate Webhook Processing
Solution: Idempotency is handled automatically using SHA-256 keys. If duplicates still occur, check:
- Queue worker isn't running multiple instances
- Webhook call record exists and is marked as processed
Issue: Subscriber Sync Fails
Common causes:
- User not found - Email in Gumroad doesn't match local user
- Invalid subscriber ID - Check subscriber ID format
Solution: Ensure users have matching emails:
Issue: Queue Jobs Failing
Check:
Ensure queue worker is running:
Issue: License Verification Failing
Common causes:
- Product ID not provided - Set default in config
- Invalid license key - Check key format
- API rate limit - Verification is cached for 1 hour
Solution:
Issue: Analytics Showing Zero
Check:
- Sales are being synced:
Sale::count() - Webhooks are processing:
WebhookCall::unprocessed()->count() - Cache is not stale: Clear analytics cache
Issue: Currency Formatting Incorrect
Solution: Configure locale:
Additional Resources
Recommended Queue Configuration
For production, use Redis or database queue driver:
Supervisor configuration for queue worker:
Database Indexes
All necessary indexes are created in migrations. If adding custom queries, consider:
Testing Webhooks Locally
Use ngrok or similar to expose local server:
Update Gumroad webhook URL to: https://your-ngrok-url.ngrok.io/cashier/gumroad/webhook
Package Updates
When updating the package:
Changelog Highlights
Recent Improvements
- Fixed:
generateCheckoutUrlnow fetches product from API to get correctshort_url(prevents 404s) - Fixed: Webhook race conditions using
firstOrCreatefor atomicity - Fixed: Analytics memory issues using SQL aggregation
- Fixed: Double-counting in churn rate calculation
- Added:
getProductByIdmethod - Added: Idempotency protection for webhooks
- Added: Payload sanitization (removes sensitive fields)
- Improved: Queue job retry logic with safe logging
Support & Contributing
For issues, suggestions, or contributions, please refer to the project repository.
License
This package is open-sourced software licensed under the MIT license.
All versions of cashier-gumroad with dependencies
ext-intl Version *
guzzlehttp/guzzle Version ^7.0
illuminate/http Version ^9.0|^10.0|^11.0|^12.0|^13.0
illuminate/support Version ^9.0|^10.0|^11.0|^12.0|^13.0
laravel/framework Version ^9.0|^10.0|^11.0|^12.0|^13.0
moneyphp/money Version ^4.0
serenity_technologies/gumroad Version ^1.2