PHP code example of fevinta / cashier-asaas

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

    

fevinta / cashier-asaas example snippets


'plans' => [
    'basic' => [
        'price' => 29.90,
        'name' => 'Plano Básico',
    ],
    'pro' => [
        'price' => 99.90,
        'name' => 'Plano Pro',
    ],
    'enterprise' => [
        'price' => 299.90,
        'name' => 'Plano Enterprise',
    ],
],

use Fevinta\CashierAsaas\Billable;

class User extends Authenticatable
{
    use Billable;
    
    // Optional: customize customer data for Asaas
    public function asaasCpfCnpj(): ?string
    {
        return $this->document;
    }
}

// Basic subscription with credit card
$user->newSubscription('default', 'pro')
    ->withCreditCard([
        'holderName' => 'John Doe',
        'number' => '4111111111111111',
        'expiryMonth' => '12',
        'expiryYear' => '2025',
        'ccv' => '123',
    ], [
        'name' => 'John Doe',
        'email' => '[email protected]',
        'cpfCnpj' => '12345678901',
        'postalCode' => '01310100',
        'addressNumber' => '123',
    ])
    ->create();

// Subscription with boleto
$user->newSubscription('default', 'basic')
    ->withBoleto()
    ->create();

// Subscription with PIX
$user->newSubscription('default', 'basic')
    ->withPix()
    ->create();

// Let customer choose payment method
$user->newSubscription('default', 'pro')
    ->askCustomer()
    ->create();

// With trial period
$user->newSubscription('default', 'pro')
    ->trialDays(14)
    ->withCreditCardToken($token)
    ->create();

// Yearly subscription
$user->newSubscription('default', 'pro')
    ->yearly()
    ->withCreditCardToken($token)
    ->create();

// Custom price (override plan config)
$user->newSubscription('default', 'custom')
    ->price(149.90)
    ->monthly()
    ->withBoleto()
    ->create();

// Check if subscribed
if ($user->subscribed('default')) {
    // Has active subscription
}

// Check specific plan
if ($user->subscribedToPlan('pro', 'default')) {
    // Subscribed to Pro plan
}

// Check trial
if ($user->onTrial('default')) {
    // On trial period
}

// Get subscription
$subscription = $user->subscription('default');

// Check subscription state
$subscription->active();     // Is active
$subscription->onTrial();    // On trial
$subscription->cancelled();  // Has been cancelled
$subscription->onGracePeriod(); // Cancelled but still active
$subscription->ended();      // Completely ended

$subscription = $user->subscription('default');

// Cancel (at period end)
$subscription->cancel();

// Cancel immediately
$subscription->cancelNow();

// Resume cancelled subscription (if on grace period)
$subscription->resume();

// Swap to different plan
$subscription->swap('enterprise');

// Update price
$subscription->updateValue(149.90);

// Change billing type
$subscription->changeBillingType(BillingType::PIX);

// Update credit card
$subscription->updateCreditCard($cardData, $holderInfo);

// Or with token
$subscription->updateCreditCardToken($newToken);

// Swap using config price
$subscription->swap('premium');

// Swap with custom price
$subscription->swap('custom', 99.90);

// Just update price without changing plan name
$subscription->updateValue(99.90);

use Fevinta\CashierAsaas\Enums\BillingType;

// Charge with PIX
$payment = $user->charge(100.00, BillingType::PIX, [
    'description' => 'Product purchase',
    'dueDate' => now()->addDays(3),
]);

// Charge with boleto
$payment = $user->charge(100.00, BillingType::BOLETO, [
    'description' => 'Service fee',
    'dueDate' => now()->addDays(5),
]);

// Charge with credit card
$payment = $user->charge(100.00, BillingType::CREDIT_CARD, [
    'description' => 'Premium feature',
    'creditCardToken' => $token,
]);

// Installment payment (credit card only)
$payment = $user->chargeInstallments(600.00, 6, [
    'description' => 'Annual plan',
    'creditCardToken' => $token,
]);

// In EventServiceProvider
protected $listen = [
    \Fevinta\CashierAsaas\Events\PaymentReceived::class => [
        \App\Listeners\HandlePaymentReceived::class,
    ],
    \Fevinta\CashierAsaas\Events\PaymentOverdue::class => [
        \App\Listeners\HandlePaymentOverdue::class,
    ],
    \Fevinta\CashierAsaas\Events\PaymentRefunded::class => [
        \App\Listeners\HandlePaymentRefunded::class,
    ],
];

Route::middleware(['auth', 'subscribed'])->group(function () {
    Route::get('/premium', PremiumController::class);
});

protected $middlewareAliases = [
    'subscribed' => \Fevinta\CashierAsaas\Http\Middleware\EnsureUserIsSubscribed::class,
];

$user->newSubscription('default', 'pro')
    ->split('wallet_partner_id', fixedValue: 10.00)  // R$ 10 fixed
    ->split('wallet_affiliate_id', percentualValue: 10)  // 10%
    ->withCreditCardToken($token)
    ->create();

use Fevinta\CashierAsaas\Checkout;

// Quick checkout for existing customer
$checkout = $user->checkoutCharge(99.90, 'Premium Feature');

// Redirect to checkout page
return $checkout->redirect();

// Or get the URL
$url = $checkout->url();

use Fevinta\CashierAsaas\Checkout;

// Guest checkout - customer data collected on checkout page
$checkout = Checkout::guest()
    ->charge(199.90, 'Product Purchase')
    ->allowAllPaymentMethods()
    ->successUrl('https://your-app.com/success')
    ->create();

return $checkout->redirect();

// Or pre-fill customer data
$checkout = Checkout::guest()
    ->charge(199.90, 'Product Purchase')
    ->customerName('John Doe')
    ->customerEmail('[email protected]')
    ->customerCpfCnpj('12345678901')
    ->create();

// Using the Billable trait
$checkout = $user->newCheckout()
    ->charge(99.90, 'Premium Feature')
    ->onlyPix()
    ->successUrl('https://your-app.com/success')
    ->create();

// Multiple items
$checkout = $user->checkout([
    ['name' => 'Product A', 'value' => 50.00, 'quantity' => 2],
    ['name' => 'Product B', 'value' => 30.00, 'quantity' => 1],
]);

// Allow all payment methods (PIX, Boleto, Credit Card)
$checkout = $user->newCheckout()
    ->charge(100.00, 'Order #123')
    ->allowAllPaymentMethods()
    ->create();

// Only specific methods
$checkout = $user->newCheckout()
    ->charge(100.00, 'Order #123')
    ->onlyPix()
    ->create();

$checkout = $user->newCheckout()
    ->charge(100.00, 'Order #123')
    ->onlyBoleto()
    ->create();

$checkout = $user->newCheckout()
    ->charge(100.00, 'Order #123')
    ->onlyCreditCard()
    ->create();

// Combine methods
$checkout = $user->newCheckout()
    ->charge(100.00, 'Order #123')
    ->withPix()
    ->withCreditCard()
    ->create();

// Fixed installments (credit card only)
$checkout = $user->newCheckout()
    ->charge(600.00, 'Annual Plan')
    ->installments(6) // 6x R$100.00
    ->create();

// Let customer choose installments (up to max)
$checkout = $user->newCheckout()
    ->charge(1200.00, 'Premium Package')
    ->maxInstallments(12) // Customer chooses 1-12x
    ->create();

use Fevinta\CashierAsaas\Enums\SubscriptionCycle;

// Monthly subscription via checkout
$checkout = $user->newCheckout()
    ->charge(99.90, 'Pro Plan')
    ->monthly()
    ->create();

// Yearly subscription
$checkout = $user->newCheckout()
    ->charge(999.00, 'Pro Plan - Annual')
    ->yearly()
    ->create();

// Other cycles
$checkout = $user->newCheckout()
    ->charge(49.90, 'Basic Plan')
    ->weekly()
    ->create();

$checkout = $user->newCheckout()
    ->charge(79.90, 'Standard Plan')
    ->quarterly()
    ->create();

$checkout = $user->newCheckout()
    ->charge(100.00, 'Order #123')
    ->successUrl('https://your-app.com/checkout/success')
    ->cancelUrl('https://your-app.com/checkout/canceled')
    ->expiredUrl('https://your-app.com/checkout/expired')
    ->create();

'checkout' => [
    'success_url' => env('ASAAS_CHECKOUT_SUCCESS_URL'),
    'cancel_url' => env('ASAAS_CHECKOUT_CANCEL_URL'),
    'expired_url' => env('ASAAS_CHECKOUT_EXPIRED_URL'),
    'expiration_minutes' => env('ASAAS_CHECKOUT_EXPIRATION', 60),
],

$checkout = $user->newCheckout()
    ->charge(100.00, 'Order #123')
    ->expiresIn(60) // Expires in 60 minutes
    ->dueDateLimitDays(5) // Boleto due date limit
    ->externalReference('order-123')
    ->description('Purchase from My Store')
    ->withMetadata(['order_id' => 123])
    ->create();

$checkout = $user->newCheckout()
    ->charge(100.00, 'Marketplace Order')
    ->split('wallet_seller_id', fixedValue: 80.00)
    ->split('wallet_platform_id', percentualValue: 20)
    ->create();

$checkout = $user->newCheckout()
    ->charge(100.00, 'Order')
    ->create();

// Get checkout data
$id = $checkout->id();
$url = $checkout->url();
$status = $checkout->status();
$session = $checkout->session(); // Full API response

// Redirect (in controller)
return $checkout->redirect();

// Or return as response (implements Responsable)
return $checkout; // Auto-redirects

// JSON response
return response()->json($checkout->toArray());

// In EventServiceProvider
protected $listen = [
    \Fevinta\CashierAsaas\Events\CheckoutCreated::class => [
        \App\Listeners\HandleCheckoutCreated::class,
    ],
    \Fevinta\CashierAsaas\Events\CheckoutPaid::class => [
        \App\Listeners\HandleCheckoutPaid::class,
    ],
    \Fevinta\CashierAsaas\Events\CheckoutCanceled::class => [
        \App\Listeners\HandleCheckoutCanceled::class,
    ],
    \Fevinta\CashierAsaas\Events\CheckoutExpired::class => [
        \App\Listeners\HandleCheckoutExpired::class,
    ],
];

use Fevinta\CashierAsaas\Asaas;

$result = Asaas::invoice()->schedule([
    'customer'             => $asaasCustomerId,
    'serviceDescription'   => 'Software Development',
    'value'                => 5000.00,
    'effectiveDate'        => '2026-01-28',
    'municipalServiceName' => 'Desenvolvimento de software',
    'deductions'           => 500.00,  // optional
    'taxes'                => [        // optional, overrides .env defaults
        'retainIss' => true,
        'iss'       => 5.0,
    ],
]);

use Fevinta\CashierAsaas\Invoice;

$invoice = Invoice::find($id);

// Issue the NFS-e immediately
$invoice->authorize();

// Request cancellation
$invoice->cancel();

// Refresh local data from the Asaas API
$invoice->syncFromAsaas();

// Check status
$invoice->isScheduled();
$invoice->isSynchronized();
$invoice->isAuthorized();
$invoice->isCanceled();
$invoice->hasError();

// Get document URLs
$invoice->pdfUrl();
$invoice->xmlUrl();

// Query scopes
Invoice::authorized()->get();
Invoice::scheduled()->where('customer_id', $customerId)->get();

Asaas::invoice()->findByPayment($paymentId);
Asaas::invoice()->findByCustomer($customerId);
Asaas::invoice()->findByDateRange('2026-01-01', '2026-01-31');
Asaas::invoice()->findByStatus('AUTHORIZED');

// Fiscal and municipal service info
Asaas::invoice()->fiscalInfo();
Asaas::invoice()->saveFiscalInfo([...]);
Asaas::invoice()->municipalServices();

Asaas::invoice()->configureSubscriptionInvoice($subscriptionId, [
    'effectiveDatePeriod' => 'ON_PAYMENT_CONFIRMATION',
    'serviceDescription'  => 'Monthly SaaS Service',
]);

Asaas::invoice()->getSubscriptionInvoiceSettings($subscriptionId);
Asaas::invoice()->deleteSubscriptionInvoiceSettings($subscriptionId);

use Fevinta\CashierAsaas\Events\InvoiceAuthorized;
use Fevinta\CashierAsaas\Events\InvoiceError;

// In EventServiceProvider
protected $listen = [
    InvoiceAuthorized::class => [
        \App\Listeners\SendInvoiceNotification::class,
    ],
    InvoiceError::class => [
        \App\Listeners\HandleInvoiceError::class,
    ],
];

use Fevinta\CashierAsaas\Cashier;

Cashier::useInvoiceModel(YourCustomInvoice::class);
bash
php artisan vendor:publish --tag=cashier-asaas-config
php artisan vendor:publish --tag=cashier-asaas-migrations
php artisan migrate
bash
php artisan migrate