PHP code example of asciisd / cashier-core

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

    

asciisd / cashier-core example snippets


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}";
}

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

$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}";
}

$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);
}

use Asciisd\CashierCore\Traits\Payable;

class User extends Model
{
    use Payable;
    
    // Your model code...
}

$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();

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();

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
}

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
    }
}

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

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

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()}";
}
bash
php artisan vendor:publish --provider="Asciisd\CashierCore\CashierCoreServiceProvider" --tag="config"
bash
php artisan vendor:publish --provider="Asciisd\CashierCore\CashierCoreServiceProvider" --tag="migrations"
php artisan migrate