PHPackages                             asciisd/cashier-core - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Payment Processing](/categories/payments)
4. /
5. asciisd/cashier-core

ActiveLibrary[Payment Processing](/categories/payments)

asciisd/cashier-core
====================

A flexible payment processing system for Laravel using Factory Pattern

1.2.0(3mo ago)0722↓84.1%1MITPHPPHP ^8.3

Since Sep 29Pushed 3mo agoCompare

[ Source](https://github.com/asciisd/cashier-core)[ Packagist](https://packagist.org/packages/asciisd/cashier-core)[ RSS](/packages/asciisd-cashier-core/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (16)Versions (6)Used By (1)

Cashier Core
============

[](#cashier-core)

[![Latest Version on Packagist](https://camo.githubusercontent.com/0b352a8dd6afdc20af1da460fbad2da10e73b676b3c203f6362948836afe9f4b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f617363696973642f636173686965722d636f72652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/asciisd/cashier-core)[![Total Downloads](https://camo.githubusercontent.com/1f8d381a9583d63602bc7d02dc3eb4a20739b12776848cb4a39957de78a77997/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f617363696973642f636173686965722d636f72652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/asciisd/cashier-core)[![License](https://camo.githubusercontent.com/da39b8114684889e2880d18f3f947c333963a882621d768b0abd74c5c6e5499e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f617363696973642f636173686965722d636f72652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/asciisd/cashier-core)

A flexible payment processing system for Laravel using the Factory Pattern. This package provides a unified interface for multiple payment processors, making it easy to add new payment gateways without changing your application code.

Features
--------

[](#features)

- **Factory Pattern**: Easy to extend with new payment processors
- **Unified Interface**: Consistent API across all payment processors
- **Laravel Integration**: Native Laravel package with service provider
- **Database Models**: Built-in models for transactions, payments, and payment methods
- **Configurable**: Flexible configuration system
- **Testable**: Comprehensive test suite included
- **Multiple Processors**: Support for custom processors
- **Refund Support**: Full and partial refunds
- **Authorization &amp; Capture**: Pre-authorization and later capture
- **Payment Methods**: Store and manage customer payment methods
- **Webhooks**: Built-in webhook handling support
- **Security**: Encrypted sensitive data storage
- **Logging**: Comprehensive payment logging

Installation
------------

[](#installation)

```
composer require asciisd/cashier-core
```

Configuration
-------------

[](#configuration)

Publish the configuration file:

```
php artisan vendor:publish --provider="Asciisd\CashierCore\CashierCoreServiceProvider" --tag="config"
```

Publish and run the migrations:

```
php artisan vendor:publish --provider="Asciisd\CashierCore\CashierCoreServiceProvider" --tag="migrations"
php artisan migrate
```

Environment Configuration
-------------------------

[](#environment-configuration)

Add the following environment variables to your `.env` file:

```
# Default processor
CASHIER_DEFAULT_PROCESSOR=stripe

# General Settings
CASHIER_CURRENCY=USD
CASHIER_LOGGING_ENABLED=true
```

Usage
-----

[](#usage)

### Basic Payment Processing

[](#basic-payment-processing)

```
use Asciisd\CashierCore\Facades\PaymentFactory;

// Create a payment processor
$processor = PaymentFactory::create('stripe');

// Process a payment
$result = $processor->charge([
    'amount' => 20, // $20.00
    'currency' => 'USD',
    'source' => 'tok_visa',
    'description' => 'Order #12345',
    'metadata' => [
        'order_id' => '12345',
        'customer_id' => 'cust_123',
    ],
]);

if ($result->isSuccessful()) {
    echo "Payment successful! Transaction ID: {$result->transactionId}";
} else {
    echo "Payment failed: {$result->message}";
}
```

### Working with Different Processors

[](#working-with-different-processors)

```
// Check available processors
$processors = PaymentFactory::getProcessorNames();
// Returns: []
```

### Refund Processing

[](#refund-processing)

```
$processor = PaymentFactory::create('stripe');

// Full refund
$refundResult = $processor->refund('ch_transaction_id');

// Partial refund
$partialRefundResult = $processor->refund('ch_transaction_id', 500); // $5.00

if ($refundResult->isSuccessful()) {
    echo "Refund successful! Refund ID: {$refundResult->refundId}";
}
```

### Authorization and Capture

[](#authorization-and-capture)

```
$processor = PaymentFactory::create('stripe');

// Authorize payment
$authResult = $processor->authorize([
    'amount' => 3000,
    'currency' => 'USD',
    'source' => 'tok_visa',
    'description' => 'Pre-authorization',
]);

if ($authResult->isSuccessful()) {
    // Later, capture the payment
    $captureResult = $processor->capture($authResult->transactionId, 2500);
}
```

### Database Models

[](#database-models)

#### Using the Payable Trait

[](#using-the-payable-trait)

Add the `Payable` trait to your models that can make payments:

```
use Asciisd\CashierCore\Traits\Payable;

class User extends Model
{
    use Payable;

    // Your model code...
}
```

This provides helpful methods:

```
$user = User::find(1);

// Get all transactions
$transactions = $user->transactions;

// Get successful transactions
$successful = $user->getSuccessfulTransactions();

// Get total amount spent
$totalSpent = $user->getTotalSpent(); // Returns total amount
$formattedTotal = $user->getFormattedTotalSpent(); // Returns formatted string

// Payment methods
$paymentMethods = $user->paymentMethods;
$defaultMethod = $user->getDefaultPaymentMethod();
```

#### Working with Transactions

[](#working-with-transactions)

```
use Asciisd\CashierCore\Models\Transaction;

// Create a transaction record
$transaction = Transaction::create([
    'processor_name' => 'stripe',
    'processor_transaction_id' => $result->transactionId,
    'payable_type' => 'App\\Models\\User',
    'payable_id' => $user->id,
    'amount' => $result->amount,
    'currency' => $result->currency,
    'status' => $result->status,
    'description' => 'Order payment',
    'processed_at' => now(),
]);

// Query transactions
$successfulTransactions = Transaction::successful()->get();
$stripeTransactions = Transaction::byProcessor('stripe')->get();
$recentTransactions = Transaction::where('created_at', '>=', now()->subDays(7))->get();
```

#### Managing Payment Methods

[](#managing-payment-methods)

```
use Asciisd\CashierCore\Models\PaymentMethod;

// Create a payment method
$paymentMethod = PaymentMethod::create([
    'user_type' => 'App\\Models\\User',
    'user_id' => $user->id,
    'processor_name' => 'stripe',
    'processor_payment_method_id' => 'pm_1234567890',
    'type' => 'credit_card',
    'brand' => 'visa',
    'last_four' => '4242',
    'exp_month' => 12,
    'exp_year' => 2025,
    'is_default' => true,
]);

// Make it the default
$paymentMethod->makeDefault();

// Check expiration
if ($paymentMethod->is_expired) {
    // Handle expired payment method
}
```

### Adding Custom Payment Processors

[](#adding-custom-payment-processors)

1. Create a class that extends `AbstractPaymentProcessor`:

```
use Asciisd\CashierCore\Abstracts\AbstractPaymentProcessor;
use Asciisd\CashierCore\DataObjects\PaymentResult;
use Asciisd\CashierCore\DataObjects\RefundResult;

class CustomProcessor extends AbstractPaymentProcessor
{
    protected array $supportedFeatures = ['charge', 'refund'];

    public function getName(): string
    {
        return 'custom';
    }

    public function charge(array $data): PaymentResult
    {
        $validatedData = $this->validatePaymentData($data);

        // Your payment processing logic here

        return $this->createSuccessResult(
            transactionId: 'custom_' . uniqid(),
            amount: $validatedData['amount'],
            currency: $validatedData['currency']
        );
    }

    public function refund(string $transactionId, ?int $amount = null): RefundResult
    {
        // Your refund logic here
    }
}
```

2. Register it in your configuration:

```
// config/cashier-core.php
'processors' => [
    'custom' => [
        'class' => \App\PaymentProcessors\CustomProcessor::class,
        'config' => [
            'api_key' => env('CUSTOM_API_KEY'),
            'secret' => env('CUSTOM_SECRET'),
        ],
    ],
],
```

3. Use it through the factory:

```
$processor = PaymentFactory::create('custom');
```

### Error Handling

[](#error-handling)

```
use Asciisd\CashierCore\Exceptions\InvalidPaymentDataException;
use Asciisd\CashierCore\Exceptions\PaymentProcessingException;
use Asciisd\CashierCore\Exceptions\ProcessorNotFoundException;

try {
    $processor = PaymentFactory::create('stripe');
    $result = $processor->charge($paymentData);

} catch (InvalidPaymentDataException $e) {
    // Handle validation errors
    echo "Invalid payment data: {$e->getMessage()}";

} catch (PaymentProcessingException $e) {
    // Handle payment processing errors
    echo "Payment failed: {$e->getMessage()}";
    if ($e->getTransactionId()) {
        echo "Transaction ID: {$e->getTransactionId()}";
    }

} catch (ProcessorNotFoundException $e) {
    // Handle unknown processor
    echo "Processor not found: {$e->getMessage()}";
}
```

Testing
-------

[](#testing)

Run the test suite:

```
composer test
```

Run tests with coverage:

```
composer test-coverage
```

Configuration Options
---------------------

[](#configuration-options)

The package provides extensive configuration options. See the published config file for all available settings:

- **Processors**: Configure multiple payment processors
- **Currency**: Set default and supported currencies
- **Database**: Customize table names and connections
- **Webhooks**: Configure webhook handling
- **Logging**: Control payment logging
- **Security**: Configure data encryption and masking
- **Retry Logic**: Set up retry mechanisms for failed payments
- **Feature Flags**: Enable/disable specific features

Supported Payment Processors
----------------------------

[](#supported-payment-processors)

### Built-in Processors

[](#built-in-processors)

### Extensible Architecture

[](#extensible-architecture)

The Factory Pattern makes it easy to add new processors:

1. Implement the `PaymentProcessorInterface`
2. Extend `AbstractPaymentProcessor` for common functionality
3. Register in configuration
4. Use immediately through the factory

Security Features
-----------------

[](#security-features)

- **Data Encryption**: Sensitive data is encrypted before storage
- **Card Masking**: Credit card numbers are automatically masked
- **Webhook Verification**: Secure webhook signature verification
- **Input Validation**: Comprehensive input validation for all processors

Examples
--------

[](#examples)

Check the `examples/BasicUsage.php` file for comprehensive usage examples covering:

- Basic payment processing
- Refund handling
- Authorization and capture
- Payment method management
- Error handling
- Custom processor registration
- Database queries

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

Support
-------

[](#support)

For support, please open an issue on GitHub or contact us at .

###  Health Score

44

—

FairBetter than 90% of packages

Maintenance80

Actively maintained with recent releases

Popularity18

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~43 days

Total

5

Last Release

106d ago

PHP version history (2 changes)1.0.0PHP ^8.2

1.2.0PHP ^8.3

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/77636067?v=4)[ASCII SD](/maintainers/asciisd)[@asciisd](https://github.com/asciisd)

---

Top Contributors

[![aemaddin](https://avatars.githubusercontent.com/u/11630742?v=4)](https://github.com/aemaddin "aemaddin (13 commits)")

---

Tags

laravelpayment processingpaymentcashierfactory-pattern

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/asciisd-cashier-core/health.svg)

```
[![Health](https://phpackages.com/badges/asciisd-cashier-core/health.svg)](https://phpackages.com/packages/asciisd-cashier-core)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[api-platform/laravel

API Platform support for Laravel

58171.8k14](/packages/api-platform-laravel)[laravel/ai

The official AI SDK for Laravel.

1.0k3.2M203](/packages/laravel-ai)[illuminate/queue

The Illuminate Queue package.

21332.6M1.6k](/packages/illuminate-queue)[pressbooks/pressbooks

Pressbooks is an open source book publishing tool built on a WordPress multisite platform. Pressbooks outputs books in multiple formats, including PDF, EPUB, web, and a variety of XML flavours, using a theming/templating system, driven by CSS.

45444.2k1](/packages/pressbooks-pressbooks)[simplestats-io/laravel-client

Server-side analytics for Laravel that follows the full funnel from visit to registration to payment, attributed to the channel that drove it. Revenue, MRR, churn and ad-spend profit (ROAS/CAC) per channel. GDPR compliant, ad-blocker proof.

5022.0k](/packages/simplestats-io-laravel-client)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
