PHPackages                             madarit/kashier-laravel-sdk - 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. madarit/kashier-laravel-sdk

ActiveLibrary[Payment Processing](/categories/payments)

madarit/kashier-laravel-sdk
===========================

Comprehensive Laravel SDK for Kashier payment gateway with refunds, webhooks, and event handling

00PHP

Since Nov 24Pushed 5mo agoCompare

[ Source](https://github.com/madarit/Kashier-Laravel-SDK)[ Packagist](https://packagist.org/packages/madarit/kashier-laravel-sdk)[ RSS](/packages/madarit-kashier-laravel-sdk/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Laravel Kashier SDK Payment Gateway Integration
===============================================

[](#laravel-kashier-sdk-payment-gateway-integration)

A comprehensive Laravel package for integrating Kashier payment gateway with advanced features including refunds, webhooks, and event handling.

Features
--------

[](#features)

- ✅ Easy installation via Composer
- ✅ Auto-discovery for Laravel 5.5+
- ✅ Support for both test and live modes
- ✅ iFrame and Hosted Payment Page (HPP) integration
- ✅ **Refund API support** (full and partial refunds)
- ✅ **Webhook handling** for asynchronous payment notifications
- ✅ **Event-driven architecture** for payment flows
- ✅ **Signature verification middleware** for security
- ✅ **Order status enum** with helper methods
- ✅ Automatic signature validation
- ✅ Customizable views
- ✅ Facade support for easy access
- ✅ Comprehensive logging

Requirements
------------

[](#requirements)

- PHP 8.0 or higher
- Laravel 9.0, 10.0, 11,0 or 12.0

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

[](#installation)

### 1. Install via Composer

[](#1-install-via-composer)

```
composer require madarit/kashier-laravel-sdk
```

The package will automatically register itself via Laravel's package auto-discovery.

### 2. Publish Configuration

[](#2-publish-configuration)

Publish the configuration file to customize settings:

```
php artisan vendor:publish --tag=kashier-config
```

This will create `config/kashier.php` in your application.

### 3. Publish Views (Optional)

[](#3-publish-views-optional)

If you want to customize the payment views:

```
php artisan vendor:publish --tag=kashier-views
```

Views will be published to `resources/views/vendor/kashier/`.

### 4. Configure Environment Variables

[](#4-configure-environment-variables)

Add the following to your `.env` file:

```
# Mode Configuration
KASHIER_MODE=test

# Test Credentials
KASHIER_TEST_API_KEY=your-test-api-key
KASHIER_TEST_MID=your-test-mid

# Live Credentials
KASHIER_LIVE_API_KEY=
KASHIER_LIVE_MID=

# Webhook Configuration
KASHIER_WEBHOOK_ENABLED=true
KASHIER_WEBHOOK_PREFIX=kashier

# Logging
KASHIER_LOGGING_ENABLED=true

# Payment Settings
KASHIER_CURRENCY=EGP
KASHIER_ALLOWED_METHODS=card,wallet,bank_installments
```

Replace the test credentials with your actual Kashier credentials from your merchant dashboard.

Usage
-----

[](#usage)

### Basic Payment Operations

[](#basic-payment-operations)

```
use Madarit\LaravelKashier\Facades\Kashier;

// Generate order hash
$hash = Kashier::generateOrderHash($orderId, $amount, $currency);

// Get HPP URL
$hppUrl = Kashier::getHppUrl($orderId, $amount, $currency, $callbackUrl);

// Validate callback signature
$isValid = Kashier::validateSignature($request->all());

// Get configuration
$config = Kashier::getConfig();
$mode = Kashier::getMode();
$mid = Kashier::getMid();
```

### Refund Operations

[](#refund-operations)

#### Full Refund

[](#full-refund)

```
use Madarit\LaravelKashier\Facades\Kashier;

try {
    $result = Kashier::fullRefund(
        orderId: 'order_123',
        transactionId: 'trans_456',
        reason: 'Customer requested refund'
    );

    if ($result['status'] === 'REFUNDED') {
        // Refund successful
        echo "Refund processed successfully";
    }
} catch (\Madarit\LaravelKashier\Exceptions\KashierRefundException $e) {
    // Handle refund error
    echo "Refund failed: " . $e->getMessage();
}
```

#### Partial Refund

[](#partial-refund)

```
use Madarit\LaravelKashier\Facades\Kashier;

try {
    $result = Kashier::partialRefund(
        orderId: 'order_123',
        transactionId: 'trans_456',
        amount: 50.00, // Refund 50 EGP out of total
        reason: 'Partial refund for one item'
    );

    // Check status
    if ($result['status'] === 'REFUNDED') {
        echo "Partial refund of {$result['amount']} processed";
    }
} catch (\Exception $e) {
    echo "Error: " . $e->getMessage();
}
```

#### Check Refund Status

[](#check-refund-status)

```
use Madarit\LaravelKashier\Facades\Kashier;

$status = Kashier::getRefundStatus('order_123', 'trans_456');
echo "Current status: " . $status['status'];
```

### Webhook Handling

[](#webhook-handling)

The package automatically handles webhooks at `/kashier/webhook`. Configure your webhook URL in Kashier dashboard:

```
https://yourdomain.com/kashier/webhook

```

#### Listen to Webhook Events

[](#listen-to-webhook-events)

Create an event listener to handle payment notifications:

```
// app/Listeners/HandleKashierWebhook.php
namespace App\Listeners;

use Madarit\LaravelKashier\Events\WebhookReceived;
use Illuminate\Support\Facades\Log;

class HandleKashierWebhook
{
    public function handle(WebhookReceived $event)
    {
        $payload = $event->payload;

        // Process webhook data
        Log::info('Webhook received', $payload);

        // Update order status in your database
        // Send notifications, etc.
    }
}
```

#### Listen to Payment Events

[](#listen-to-payment-events)

```
// app/Listeners/HandleSuccessfulPayment.php
namespace App\Listeners;

use Madarit\LaravelKashier\Events\PaymentSuccessful;
use App\Models\Order;

class HandleSuccessfulPayment
{
    public function handle(PaymentSuccessful $event)
    {
        $orderId = $event->getOrderId();
        $transactionId = $event->getTransactionId();
        $amount = $event->getAmount();

        // Update your order
        Order::where('id', $orderId)->update([
            'status' => 'paid',
            'transaction_id' => $transactionId,
            'paid_amount' => $amount,
        ]);

        // Send confirmation email, etc.
    }
}
```

#### Listen to Payment Failures

[](#listen-to-payment-failures)

```
// app/Listeners/HandleFailedPayment.php
namespace App\Listeners;

use Madarit\LaravelKashier\Events\PaymentFailed;

class HandleFailedPayment
{
    public function handle(PaymentFailed $event)
    {
        $orderId = $event->getOrderId();
        $reason = $event->getFailureReason();

        // Log failure
        \Log::warning("Payment failed for order {$orderId}: {$reason}");

        // Notify customer, update order status, etc.
    }
}
```

#### Listen to Refund Events

[](#listen-to-refund-events)

```
// app/Listeners/HandleRefundProcessed.php
namespace App\Listeners;

use Madarit\LaravelKashier\Events\RefundProcessed;

class HandleRefundProcessed
{
    public function handle(RefundProcessed $event)
    {
        if ($event->isSuccessful()) {
            $orderId = $event->getOrderId();
            $amount = $event->getRefundAmount();

            // Update order status
            // Send refund confirmation email
        }
    }
}
```

#### Register Event Listeners

[](#register-event-listeners)

Add to `app/Providers/EventServiceProvider.php`:

```
use Madarit\LaravelKashier\Events\WebhookReceived;
use Madarit\LaravelKashier\Events\PaymentSuccessful;
use Madarit\LaravelKashier\Events\PaymentFailed;
use Madarit\LaravelKashier\Events\RefundProcessed;

protected $listen = [
    WebhookReceived::class => [
        \App\Listeners\HandleKashierWebhook::class,
    ],
    PaymentSuccessful::class => [
        \App\Listeners\HandleSuccessfulPayment::class,
    ],
    PaymentFailed::class => [
        \App\Listeners\HandleFailedPayment::class,
    ],
    RefundProcessed::class => [
        \App\Listeners\HandleRefundProcessed::class,
    ],
];
```

### Using Order Status Enum

[](#using-order-status-enum)

```
use Madarit\LaravelKashier\Enums\OrderStatus;

// Get status from string
$status = OrderStatus::fromString('SUCCESS');

// Check status
if ($status->isSuccessful()) {
    echo "Payment succeeded!";
}

// Get display name
echo $status->displayName(); // "Success"

// Get description
echo $status->description(); // "Payment completed successfully"

// Get CSS class for styling
echo $status->styleClass(); // "status-success"

// Get text color
echo $status->textColor(); // "text-green-600"

// Status checks
$status->isPending();      // false
$status->isFailed();       // false
$status->isRefunded();     // false
```

### Using Dependency Injection

[](#using-dependency-injection)

```
use Madarit\LaravelKashier\KashierService;

class YourController extends Controller
{
    private $kashier;

    public function __construct(KashierService $kashier)
    {
        $this->kashier = $kashier;
    }

    public function processPayment()
    {
        $hash = $this->kashier->generateOrderHash('123', '100', 'EGP');
        // ...
    }
}
```

### Default Routes

[](#default-routes)

The package automatically registers these routes:

- `GET /kashier/checkout` - Display checkout page
- `GET /kashier/iframe/callback` - iFrame payment callback
- `GET /kashier/hpp/callback` - Hosted Payment Page callback
- `POST /kashier/webhook` - Webhook endpoint (secured with signature verification)

### Accessing the Demo

[](#accessing-the-demo)

After installation, visit:

```
http://your-app.test/kashier/checkout

```

### Test Cards

[](#test-cards)

- **Success:** 5111 1111 1111 1118 - 06/28 - 100
- **Success 3D Secure:** 5123 4500 0000 0008 - 06/28 - 100
- **Failure:** 5111 1111 1111 1118 - 05/28 - 102

Customization
-------------

[](#customization)

### Custom Views

[](#custom-views)

After publishing views, you can customize them in `resources/views/vendor/kashier/`:

- `payment/checkout.blade.php` - Checkout page
- `payment/success.blade.php` - Success page
- `payment/error.blade.php` - Error page

### Custom Controller

[](#custom-controller)

You can create your own controller and use the KashierService:

```
use Madarit\LaravelKashier\KashierService;
use Illuminate\Http\Request;

class CustomPaymentController extends Controller
{
    public function initiatePayment(KashierService $kashier)
    {
        $orderId = uniqid('order_');
        $amount = '100.00';
        $currency = 'EGP';

        $hppUrl = $kashier->getHppUrl(
            $orderId,
            $amount,
            $currency,
            route('payment.callback')
        );

        return redirect($hppUrl);
    }

    public function handleCallback(Request $request, KashierService $kashier)
    {
        if ($kashier->validateSignature($request->all())) {
            if ($request->get('paymentStatus') === 'SUCCESS') {
                // Handle successful payment
                return view('payment-success');
            }
        }

        return view('payment-failed');
    }
}
```

Package Structure
-----------------

[](#package-structure)

```
laravel-kashier/
├── src/
│   ├── Http/
│   │   └── Controllers/
│   │       └── PaymentController.php
│   ├── Facades/
│   │   └── Kashier.php
│   ├── KashierService.php
│   └── KashierServiceProvider.php
├── config/
│   └── kashier.php
├── resources/
│   └── views/
│       └── payment/
│           ├── checkout.blade.php
│           ├── success.blade.php
│           └── error.blade.php
├── routes/
│   └── web.php
├── composer.json
└── README.md

```

API Reference
-------------

[](#api-reference)

### KashierService Methods

[](#kashierservice-methods)

#### Payment Methods

[](#payment-methods)

##### `generateOrderHash($orderId, $amount, $currency, $customerReference = null)`

[](#generateorderhashorderid-amount-currency-customerreference--null)

Generate hash for order verification.

##### `validateSignature($queryParams)`

[](#validatesignaturequeryparams)

Validate callback signature for security.

##### `getHppUrl($orderId, $amount, $currency, $callbackUrl, $allowedMethods = 'card,wallet,bank_installments')`

[](#gethppurlorderid-amount-currency-callbackurl-allowedmethods--cardwalletbank_installments)

Generate Hosted Payment Page URL.

#### Refund Methods

[](#refund-methods)

##### `refund($orderId, $transactionId, $amount = null, $reason = null)`

[](#refundorderid-transactionid-amount--null-reason--null)

Process a refund (full or partial).

- **Parameters:**
    - `$orderId` (string): The order ID
    - `$transactionId` (string): The transaction ID
    - `$amount` (float|null): Amount to refund (null for full refund)
    - `$reason` (string|null): Refund reason
- **Returns:** array - Refund response
- **Throws:** `KashierRefundException`, `KashierConnectionException`

##### `fullRefund($orderId, $transactionId, $reason = null)`

[](#fullrefundorderid-transactionid-reason--null)

Process a full refund (convenience method).

##### `partialRefund($orderId, $transactionId, $amount, $reason = null)`

[](#partialrefundorderid-transactionid-amount-reason--null)

Process a partial refund (convenience method).

##### `getRefundStatus($orderId, $transactionId)`

[](#getrefundstatusorderid-transactionid)

Get the status of a refund.

#### Configuration Methods

[](#configuration-methods)

##### `getConfig()`

[](#getconfig)

Get current configuration (test/live).

##### `getMode()`

[](#getmode)

Get current mode (test/live).

##### `getMid()`

[](#getmid)

Get merchant ID.

##### `getBaseUrl()`

[](#getbaseurl)

Get Kashier checkout base URL.

##### `getApiBaseUrl()`

[](#getapibaseurl)

Get Kashier API base URL.

### Available Events

[](#available-events)

- `WebhookReceived` - Fired when any webhook is received
- `PaymentSuccessful` - Fired when payment succeeds
- `PaymentFailed` - Fired when payment fails
- `RefundProcessed` - Fired when refund is processed

### Available Middleware

[](#available-middleware)

- `kashier.webhook` - Verifies webhook signature
- `kashier.callback` - Verifies payment callback signature

### Exceptions

[](#exceptions)

- `KashierException` - Base exception class
- `KashierConnectionException` - API connection errors
- `KashierInvalidSignatureException` - Invalid signature errors
- `KashierConfigurationException` - Configuration errors
- `KashierRefundException` - Refund-specific errors

Payment Flow
------------

[](#payment-flow)

### iFrame Payment

[](#iframe-payment)

1. User visits `/payment/checkout`
2. Clicks the Kashier payment button
3. Payment popup opens on the same page
4. After payment, redirects to `/payment/iframe/callback`
5. Signature is validated
6. User sees success or error page

### Hosted Payment Page (HPP)

[](#hosted-payment-page-hpp)

1. User visits `/payment/checkout`
2. Clicks "Pay with Hosted Payment Page" link
3. Redirected to Kashier's hosted page
4. After payment, redirected back to `/payment/hpp/callback`
5. Signature is validated
6. User sees success or error page

Security
--------

[](#security)

### Signature Verification

[](#signature-verification)

All webhooks and callbacks are automatically verified using HMAC SHA256:

- **Webhook signatures** are verified via `VerifyWebhookSignature` middleware
- **Callback signatures** are verified via `VerifyCallbackSignature` middleware
- Invalid signatures throw `KashierInvalidSignatureException`

### Best Practices

[](#best-practices)

- ✅ Never expose your API keys in frontend code
- ✅ Always use HTTPS in production
- ✅ Validate signatures before processing payments
- ✅ Log failed signature validations for security monitoring
- ✅ Use webhook endpoints for critical payment confirmations
- ✅ Store sensitive data encrypted in your database
- ✅ Implement rate limiting on webhook endpoints

### Exception Handling

[](#exception-handling)

```
use Madarit\LaravelKashier\Exceptions\KashierInvalidSignatureException;
use Madarit\LaravelKashier\Exceptions\KashierConnectionException;

try {
    $result = Kashier::refund($orderId, $transactionId);
} catch (KashierInvalidSignatureException $e) {
    // Handle signature validation failure
    Log::error('Invalid signature: ' . $e->getMessage());
} catch (KashierConnectionException $e) {
    // Handle API connection error
    Log::error('Connection failed: ' . $e->getMessage());
} catch (\Exception $e) {
    // Handle other errors
    Log::error('Error: ' . $e->getMessage());
}
```

Going Live
----------

[](#going-live)

### Pre-Launch Checklist

[](#pre-launch-checklist)

- Obtain live credentials from Kashier merchant dashboard
- Update `.env` file with live credentials
- Change `KASHIER_MODE` to `live`
- Configure webhook URL in Kashier dashboard: `https://yourdomain.com/kashier/webhook`
- Test webhook endpoint with Kashier's webhook testing tool
- Implement proper event listeners for payment notifications
- Enable logging: `KASHIER_LOGGING_ENABLED=true`
- Test refund flow in live mode (with small amounts)
- Ensure HTTPS is enabled on your domain
- Set up monitoring and alerts for failed payments
- Document your refund policy
- Test thoroughly before processing real payments

### Webhook Configuration

[](#webhook-configuration)

1. Login to your Kashier merchant dashboard
2. Navigate to Webhook Settings
3. Add your webhook URL: `https://yourdomain.com/kashier/webhook`
4. Select events to receive (payment success, failure, refund)
5. Save and test the webhook connection

Support
-------

[](#support)

For issues or questions:

- Kashier Documentation:
- Kashier Support: Contact through merchant dashboard

About the Developer
-------------------

[](#about-the-developer)

This package is developed and maintained by **Madar IT** - a software development company specializing in creating robust and scalable solutions for businesses.

### Madar IT

[](#madar-it)

**Madar IT** provides professional software development services with expertise in:

- Laravel &amp; PHP Development
- Payment Gateway Integration
- API Development &amp; Integration
- Enterprise Application Development
- Custom Software Solutions

We are committed to delivering high-quality, secure, and well-documented packages that make developers' lives easier.

### Connect With Us

[](#connect-with-us)

- **GitHub:** [github.com/madarit](https://github.com/madarit)
- **Website:** [https://madar.it/home/Contact us](https://madar.it/home/contactus/) for custom development and integration services

For package-related issues, please open an issue on the GitHub repository. For custom development or integration services, feel free to reach out directly.

License
-------

[](#license)

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

###  Health Score

17

—

LowBetter than 6% of packages

Maintenance48

Moderate activity, may be stable

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity13

Early-stage or recently created project

 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/3ef1a98c0eb4c628e40bdcc2268fe9da2bc756acfe519e676d85595065cc1372?d=identicon)[madarit](/maintainers/madarit)

---

Top Contributors

[![Tarek-Elmoursi](https://avatars.githubusercontent.com/u/227709733?v=4)](https://github.com/Tarek-Elmoursi "Tarek-Elmoursi (1 commits)")

### Embed Badge

![Health badge](/badges/madarit-kashier-laravel-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/madarit-kashier-laravel-sdk/health.svg)](https://phpackages.com/packages/madarit-kashier-laravel-sdk)
```

###  Alternatives

[omnipay/paypal

PayPal gateway for Omnipay payment processing library

3156.8M53](/packages/omnipay-paypal)[eduardokum/laravel-boleto

Biblioteca com boletos para o laravel

626351.9k2](/packages/eduardokum-laravel-boleto)[tbbc/money-bundle

This is a Symfony bundle that integrates moneyphp/money library (Fowler pattern): https://github.com/moneyphp/money.

1961.9M](/packages/tbbc-money-bundle)[2checkout/2checkout-php

2Checkout PHP Library

83740.3k2](/packages/2checkout-2checkout-php)[smhg/sepa-qr-data

Generate QR code data for SEPA payments

61717.2k5](/packages/smhg-sepa-qr-data)[omnipay/dummy

Dummy driver for the Omnipay payment processing library

271.2M33](/packages/omnipay-dummy)

PHPackages © 2026

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