PHPackages                             ownpay/ownpay-laravel - 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. ownpay/ownpay-laravel

ActiveLibrary[Payment Processing](/categories/payments)

ownpay/ownpay-laravel
=====================

Official OwnPay Payment Gateway SDK for Laravel

v1.0.0(1mo ago)01MITPHPPHP ^8.3CI passing

Since Jul 16Pushed 1w agoCompare

[ Source](https://github.com/own-pay/ownpay-laravel)[ Packagist](https://packagist.org/packages/ownpay/ownpay-laravel)[ Docs](https://github.com/own-pay/ownpay-laravel)[ Fund](https://ownpay.org/donate)[ RSS](/packages/ownpay-ownpay-laravel/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (1)Dependencies (9)Versions (3)Used By (0)

OwnPay Laravel SDK
==================

[](#ownpay-laravel-sdk)

[![Latest Version on Packagist](https://camo.githubusercontent.com/10e01953886df34844add9a70ee58d0e88a2567ae84df7d68967544603f2f1d2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6f776e7061792f6f776e7061792d6c61726176656c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ownpay/ownpay-laravel)[![Total Downloads](https://camo.githubusercontent.com/ddffcfc0e98449b79e46f2217414000584a049d76fa7ee9af581fa25f118b556/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6f776e7061792f6f776e7061792d6c61726176656c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ownpay/ownpay-laravel)[![License](https://camo.githubusercontent.com/d686655d6cad5bbbaae3e9b3bf90f364427a858618a01fecfd0bffab76bd8299/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6f776e7061792f6f776e7061792d6c61726176656c2e7376673f7374796c653d666c61742d737175617265)](https://github.com/own-pay/ownpay-laravel/blob/main/LICENSE)

Official Laravel SDK for the [OwnPay](https://ownpay.org) payment gateway platform. This package provides a clean, fluent interface for integrating OwnPay payments into your Laravel application.

Features
--------

[](#features)

- 🔐 **Secure Authentication** - Bearer token authentication with SHA-256 hashing
- 💳 **Payment Management** - Create, retrieve, and manage payment intents
- 🔄 **Transaction Tracking** - Query and filter transactions with pagination
- 💰 **Refund Processing** - Create and track refunds
- 👥 **Customer Management** - Create and manage customer profiles
- 🔔 **Webhook Handling** - HMAC-SHA256 signature verification
- 🛡️ **Error Handling** - Comprehensive exception hierarchy
- 📊 **Type Safety** - PHP 8.3+ enums, readonly classes, and value objects
- 🧪 **Testing Ready** - Mock-friendly HTTP client integration
- 📝 **PSR Compliant** - PSR-4, PSR-12, and PSR-18 standards

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

[](#requirements)

- PHP 8.3+
- Laravel 11.x, 12.x, or 13.x

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

[](#installation)

Install the package via Composer:

```
composer require ownpay/ownpay-laravel
```

The package will automatically register its service provider and facade.

### Publish Configuration

[](#publish-configuration)

Publish the configuration file:

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

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

### Publish Migrations (Optional)

[](#publish-migrations-optional)

If you want to log webhooks to a database table:

```
php artisan vendor:publish --tag=ownpay-migrations
php artisan migrate
```

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

[](#configuration)

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

```
OWNPAY_API_KEY=op_your_api_key_here
OWNPAY_WEBHOOK_SECRET=your_webhook_secret_here
OWNPAY_BASE_URL=https://pay.ownpay.org
OWNPAY_TIMEOUT=30
OWNPAY_RETRY_ATTEMPTS=3
OWNPAY_RETRY_DELAY=100
OWNPAY_VERIFY_SSL=true
```

### Configuration Options

[](#configuration-options)

OptionDefaultDescription`api_key``null`Your OwnPay API key (starts with `op_`)`webhook_secret``null`Webhook signing secret for verification`base_url``https://pay.ownpay.org`Your OwnPay instance URL`timeout``30`Request timeout in seconds`retry_attempts``3`Number of retry attempts for failed requests`retry_delay``100`Base delay in milliseconds between retries`verify_ssl``true`Whether to verify SSL certificates`log_channel``null`Log channel for SDK logging`cache_ttl``0`Cache TTL in seconds (0 to disable)Usage
-----

[](#usage)

### Using the Facade

[](#using-the-facade)

```
use OwnPay\Laravel\Facades\OwnPay;

// Create a payment
$payment = OwnPay::createPayment([
    'amount' => '1250.00',
    'currency' => 'BDT',
    'description' => 'Premium Subscription',
    'redirect_url' => 'https://example.com/success',
    'cancel_url' => 'https://example.com/cancel',
    'callback_url' => 'https://example.com/webhook',
    'customer_name' => 'John Doe',
    'customer_mail' => 'john@example.com',
]);

// Redirect customer to checkout
return redirect($payment->checkoutUrl);

// Get payment status
$payment = OwnPay::getPayment($payment->paymentId);
echo $payment->status->label(); // "Pending", "Completed", etc.

// List transactions
$result = OwnPay::listTransactions([
    'page' => 1,
    'per_page' => 25,
    'status' => 'completed',
]);

foreach ($result['data'] as $transaction) {
    echo $transaction->trxId; // "OP-XXXXX"
    echo $transaction->amount;
}

// Create a refund
$refund = OwnPay::createRefund([
    'trx_id' => 'OP-XXXXX',
    'amount' => '500.00',
    'reason' => 'Customer request',
]);

// Create a customer
$customer = OwnPay::createCustomer([
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'phone' => '+8801700000000',
]);

// Test webhook endpoint
$result = OwnPay::testWebhook();
```

### Using Dependency Injection

[](#using-dependency-injection)

```
use OwnPay\Laravel\Client\OwnPayClient;

class PaymentController extends Controller
{
    public function __construct(
        private readonly OwnPayClient $ownpay,
    ) {}

    public function store(Request $request)
    {
        $payment = $this->ownpay->createPayment([
            'amount' => $request->input('amount'),
            'currency' => $request->input('currency'),
            'callback_url' => route('webhook.ownpay'),
        ]);

        return response()->json([
            'checkout_url' => $payment->checkoutUrl,
            'payment_id' => $payment->paymentId,
        ]);
    }
}
```

### Payment Flow

[](#payment-flow)

```
use OwnPay\Laravel\Facades\OwnPay;
use OwnPay\Laravel\Exception\OwnPayExceptionInterface;

class CheckoutController extends Controller
{
    public function initiate(Request $request)
    {
        try {
            $payment = OwnPay::createPayment([
                'amount' => $request->input('amount'),
                'currency' => $request->input('currency'),
                'description' => $request->input('description'),
                'redirect_url' => route('payment.success'),
                'cancel_url' => route('payment.cancel'),
                'callback_url' => route('webhook.ownpay'),
                'customer_name' => $request->input('customer_name'),
                'customer_mail' => $request->input('customer_email'),
                'metadata' => [
                    'order_id' => $request->input('order_id'),
                ],
            ]);

            // Store payment_id in your database
            // Redirect to checkout
            return redirect($payment->checkoutUrl);

        } catch (OwnPayExceptionInterface $e) {
            return back()->withErrors([
                'payment' => $e->getMessage(),
            ]);
        }
    }

    public function success(Request $request)
    {
        $paymentId = $request->query('payment_id');
        $payment = OwnPay::getPayment($paymentId);

        if ($payment->isSuccess()) {
            // Payment completed successfully
            return view('payment.success', ['payment' => $payment]);
        }

        return view('payment.pending', ['payment' => $payment]);
    }
}
```

### Webhook Handling

[](#webhook-handling)

#### Setup Webhook Route

[](#setup-webhook-route)

The package automatically registers a webhook route at `/webhooks/ownpay`. You can customize this in your routes:

```
use OwnPay\Laravel\Laravel\Middleware\VerifyWebhookSignature;

Route::post('/webhooks/ownpay', [WebhookController::class, 'handle'])
    ->middleware(VerifyWebhookSignature::class);
```

#### Listen for Webhook Events

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

Create an event listener in your `EventServiceProvider`:

```
protected $listen = [
    \OwnPay\Laravel\Laravel\Events\WebhookReceived::class => [
        \App\Listeners\HandleOwnPayWebhook::class,
    ],
];
```

#### Example Listener

[](#example-listener)

```
namespace App\Listeners;

use OwnPay\Laravel\Laravel\Events\WebhookReceived;

class HandleOwnPayWebhook
{
    public function handle(WebhookReceived $event): void
    {
        match ($event->event) {
            'payment.completed' => $this->handlePaymentCompleted($event),
            'payment.failed' => $this->handlePaymentFailed($event),
            'refund.completed' => $this->handleRefundCompleted($event),
            default => null,
        };
    }

    private function handlePaymentCompleted(WebhookReceived $event): void
    {
        $transactionId = $event->getTransactionId();
        $amount = $event->getAmount();
        $currency = $event->getCurrency();

        // Update your database
        // Send confirmation email
        // etc.
    }

    private function handlePaymentFailed(WebhookReceived $event): void
    {
        // Handle failed payment
    }

    private function handleRefundCompleted(WebhookReceived $event): void
    {
        // Handle completed refund
    }
}
```

### Transaction Management

[](#transaction-management)

```
use OwnPay\Laravel\Facades\OwnPay;

// List all transactions
$transactions = OwnPay::listTransactions();

// List with filters
$transactions = OwnPay::listTransactions([
    'status' => 'completed',
    'gateway' => 'bkash',
    'from' => '2024-01-01',
    'to' => '2024-12-31',
    'page' => 1,
    'per_page' => 50,
]);

// Get specific transaction
$transaction = OwnPay::getTransaction('OP-XXXXX');

// Check if refundable
if ($transaction->isRefundable()) {
    // Can create refund
}
```

### Customer Management

[](#customer-management)

```
use OwnPay\Laravel\Facades\OwnPay;

// Create customer
$customer = OwnPay::createCustomer([
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'phone' => '+8801700000000',
]);

// List customers
$customers = OwnPay::listCustomers(['page' => 1]);

// Get customer by email or phone
$customer = OwnPay::getCustomer('john@example.com');
```

### API Key Management

[](#api-key-management)

```
use OwnPay\Laravel\Facades\OwnPay;

// List API keys
$keys = OwnPay::listApiKeys();

// Generate new key
$result = OwnPay::generateApiKey([
    'name' => 'Production Key',
    'scopes' => ['read', 'write'],
]);

echo $result['key']; // Show this to the user ONCE
echo $result['prefix'];

// Revoke key
OwnPay::revokeApiKey($keyId);
```

Error Handling
--------------

[](#error-handling)

The package provides a comprehensive exception hierarchy:

```
use OwnPay\Laravel\Exception\OwnPayExceptionInterface;
use OwnPay\Laravel\Exception\AuthenticationException;
use OwnPay\Laravel\Exception\InvalidRequestException;
use OwnPay\Laravel\Exception\NotFoundException;
use OwnPay\Laravel\Exception\RateLimitException;
use OwnPay\Laravel\Exception\ConnectionException;
use OwnPay\Laravel\Exception\PaymentFailedException;

try {
    $payment = OwnPay::createPayment([...]);
} catch (AuthenticationException $e) {
    // Invalid API key or insufficient permissions
    Log::error('OwnPay auth error: ' . $e->getMessage());
} catch (InvalidRequestException $e) {
    // Validation error
    $errors = $e->getErrorDetails();
    // $errors is an array of {code, message, field}
} catch (NotFoundException $e) {
    // Resource not found
} catch (RateLimitException $e) {
    // Rate limit exceeded
    $retryAfter = $e->getRetryAfter();
} catch (ConnectionException $e) {
    // Network error
} catch (OwnPayExceptionInterface $e) {
    // Catch all OwnPay exceptions
}
```

Value Objects
-------------

[](#value-objects)

The package uses type-safe value objects:

### Money

[](#money)

```
use OwnPay\Laravel\ValueObjects\Money;

$money = new Money('100.00', 'USD');
$money->amount; // "100.00"
$money->currency; // "USD"
$money->toFloat(); // 100.0
$money->toCents(); // 10000
$money->format(); // "USD 100.00"

// Arithmetic
$a = new Money('100.00', 'USD');
$b = new Money('50.00', 'USD');
$sum = $a->add($b); // Money('150.00', 'USD')
$diff = $a->subtract($b); // Money('50.00', 'USD')

// Comparison
$a->isGreaterThan($b); // true
$a->equals(new Money('100.00', 'USD')); // true
```

### Status Enums

[](#status-enums)

```
use OwnPay\Laravel\ValueObjects\PaymentStatus;
use OwnPay\Laravel\ValueObjects\TransactionStatus;
use OwnPay\Laravel\ValueObjects\RefundStatus;

// Payment status
$status = PaymentStatus::from('completed');
$status->isSuccess(); // true
$status->isTerminal(); // true
$status->isActive(); // false
$status->label(); // "Completed"

// Transaction status
$status = TransactionStatus::from('completed');
$status->isRefundable(); // true

// Refund status
$status = RefundStatus::from('completed');
$status->isSuccess(); // true
```

Testing
-------

[](#testing)

### Running Tests

[](#running-tests)

```
# Run all tests
composer test

# Run with coverage
composer test:coverage

# Run static analysis
composer analyse

# Format code
composer format
```

### Mocking HTTP Calls

[](#mocking-http-calls)

```
use Illuminate\Support\Facades\Http;

Http::fake([
    'test.ownpay.org/api/v1/payments' => Http::response([
        'success' => true,
        'data' => [
            'payment_id' => 'pay_123',
            'token' => 'tok_123',
            'checkout_url' => 'https://checkout.ownpay.org/pay_123',
            'status' => 'pending',
        ],
    ], 201),
]);

// Your test code here
$payment = OwnPay::createPayment([...]);
$this->assertSame('pay_123', $payment->paymentId);
```

### Verifying Webhooks in Tests

[](#verifying-webhooks-in-tests)

```
use OwnPay\Laravel\Webhook\WebhookVerifier;

$verifier = new WebhookVerifier('test-secret');
$payload = '{"event":"payment.completed","transaction_id":"OP-12345"}';
$signature = $verifier->sign($payload);

$result = $verifier->verify($payload, $signature);
$this->assertSame('payment.completed', $result['event']);
```

Artisan Commands
----------------

[](#artisan-commands)

### Test Connection

[](#test-connection)

```
php artisan ownpay:test
php artisan ownpay:test --json
```

### Verify Webhook

[](#verify-webhook)

```
php artisan ownpay:verify-webhook \
    --payload='{"event":"payment.completed"}' \
    --signature='abc123...' \
    --timestamp=1234567890
```

Security
--------

[](#security)

### API Key Security

[](#api-key-security)

- API keys are stored securely using `#[\SensitiveParameter]` attribute
- Keys are never logged or exposed in error messages
- Use environment variables for sensitive configuration

### Webhook Verification

[](#webhook-verification)

All incoming webhooks are verified using HMAC-SHA256 signatures:

- Signature: `hash_hmac('sha256', $payload, $secret)`
- Timing-safe comparison using `hash_equals()`
- Timestamp validation to prevent replay attacks

### Best Practices

[](#best-practices)

1. **Never commit API keys** to version control
2. **Use HTTPS** for all API communication
3. **Verify webhook signatures** before processing
4. **Implement idempotency** for critical operations
5. **Handle rate limits** gracefully with retry logic
6. **Log all payment events** for audit trail

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

[](#api-reference)

### Payments

[](#payments)

MethodDescription`createPayment(array $data)`Create a new payment intent`getPayment(string $id)`Get payment by ID### Transactions

[](#transactions)

MethodDescription`listTransactions(array $params)`List transactions with filters`getTransaction(string $id)`Get transaction by ID### Refunds

[](#refunds)

MethodDescription`createRefund(array $data)`Create a refund`listRefunds(array $params)`List refunds with filters`getRefund(string $id)`Get refund by transaction ID### Customers

[](#customers)

MethodDescription`createCustomer(array $data)`Create a customer`listCustomers(array $params)`List customers`getCustomer(string $id)`Get customer by email or phone### Webhooks

[](#webhooks)

MethodDescription`testWebhook()`Test webhook endpoint`listWebhookDeliveries()`List webhook deliveries### API Keys

[](#api-keys)

MethodDescription`listApiKeys()`List API keys`generateApiKey(array $params)`Generate new API key`revokeApiKey(int $id)`Revoke API key### Health

[](#health)

MethodDescription`health()`Check API health statusChangelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

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

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

If you discover a security vulnerability, please email . All security vulnerabilities will be promptly addressed.

License
-------

[](#license)

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

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance95

Actively maintained with recent releases

Popularity1

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity50

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

Unknown

Total

1

Last Release

46d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/eafce6cac78f6bed768952b715582db472b6b0d0541623dd69d7480a48a8ad6b?d=identicon)[ownpay](/maintainers/ownpay)

---

Top Contributors

[![fattain-naime](https://avatars.githubusercontent.com/u/25886142?v=4)](https://github.com/fattain-naime "fattain-naime (15 commits)")

---

Tags

fintechgatewaylaravelopen-sourceownpaypaymentpaymentsphpsdkwebhookslaravelpaymentgatewayfintechownpay

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/ownpay-ownpay-laravel/health.svg)

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

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3365.5M359](/packages/psalm-plugin-laravel)[api-platform/laravel

API Platform support for Laravel

58190.1k22](/packages/api-platform-laravel)[laravel/mcp

Rapidly build MCP servers for your Laravel applications.

80732.6M270](/packages/laravel-mcp)[laravel/socialite

Laravel wrapper around OAuth 1 &amp; OAuth 2 libraries.

5.7k118.2M1.0k](/packages/laravel-socialite)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k17.6M165](/packages/laravel-pulse)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

255.2k](/packages/aedart-athenaeum)

PHPackages © 2026

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