PHPackages                             nedarta/yii2-omnipay - 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. nedarta/yii2-omnipay

ActiveYii2-extension[Payment Processing](/categories/payments)

nedarta/yii2-omnipay
====================

An elegant Omnipay payment processing extension for the Yii 2 framework.

v1.0.0(1mo ago)03MITPHP &gt;=7.4

Since May 27Pushed 1mo agoCompare

[ Source](https://github.com/nedarta/yii2-omnipay)[ Packagist](https://packagist.org/packages/nedarta/yii2-omnipay)[ RSS](/packages/nedarta-yii2-omnipay/feed)WikiDiscussions main Synced 1w ago

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

Yii 2 Omnipay Extension
=======================

[](#yii-2-omnipay-extension)

[![Latest Stable Version](https://camo.githubusercontent.com/4bca19e9178a26d746c34e832d698b904651eae9099abd44e510476d88999a0f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6e6564617274612f796969322d6f6d6e697061792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/nedarta/yii2-omnipay)[![Total Downloads](https://camo.githubusercontent.com/3d60c1f05c8fbe244772370a759a2f1da7922d9342709096b360cee38709cc06/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6e6564617274612f796969322d6f6d6e697061792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/nedarta/yii2-omnipay)[![License](https://camo.githubusercontent.com/5032d65529a736223e4e9a170f6de305673d87cb6bc911af3bcbb87ae5fb71f5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6e6564617274612f796969322d6f6d6e697061792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/nedarta/yii2-omnipay)

A premium, elegant, and lightweight payment processing integration for the Yii 2 framework, built on top of the powerful [Omnipay](https://github.com/thephpleague/omnipay) library. Configure payment gateways as standard Yii 2 components with clean, modern magic delegation.

---

Features
--------

[](#features)

- ✨ **One Component, One Gateway:** Simple, modular architecture that integrates seamlessly into Yii 2's dependency injection container.
- 💳 **Clean Magic Delegation:** Call gateway methods (like `purchase`, `completePurchase`, etc.) directly on the component.
- 🛡️ **Strict &amp; Safe:** Safe lazy-initialization guards and robust type validation to prevent runtime errors.
- ⚙️ **Immutable Config &amp; Reinitialization:** Built to support reactive changes in dynamic execution contexts (e.g. CLI, tests).
- 🧪 **Test-Driven:** Structured to work seamlessly with PHPUnit.

---

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

[](#installation)

Install the package via [Composer](https://getcomposer.org/):

```
composer require nedarta/yii2-omnipay
```

To use specific gateways, you should also require their respective Omnipay drivers:

```
# For Stripe
composer require omnipay/stripe

# For PayPal
composer require omnipay/paypal
```

---

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

[](#configuration)

Add the gateway components directly to your application configuration file (usually `config/web.php` or `common/config/main.php`):

```
return [
    'components' => [
        'stripe' => [
            'class' => 'nedarta\omnipay\OmniPayComponent',
            'gateway' => 'Stripe',
            'parameters' => [
                'apiKey' => 'sk_test_51Px...your_stripe_secret_key...',
            ],
        ],
        'paypal' => [
            'class' => 'nedarta\omnipay\OmniPayComponent',
            'gateway' => 'PayPal_Express',
            'parameters' => [
                'username' => 'paypal-developer_api1.example.com',
                'password' => 'ABC123XYZ456',
                'signature' => 'AFcWxV21C7fd0xs3bSMuz153.4VeA1F-34zQv1F.c7',
            ],
            'testMode' => true, // Optional global shortcut
        ],
    ],
];
```

---

Usage Examples
--------------

[](#usage-examples)

### 1. Stripe Checkout

[](#1-stripe-checkout)

Because of magic-method delegation, you can call all underlying gateway methods directly on the Yii 2 component (`Yii::$app->stripe`).

```
namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\web\BadRequestHttpException;

class PaymentController extends Controller
{
    /**
     * Process a direct credit card charge via Stripe
     */
    public function actionStripeCharge()
    {
        $request = Yii::$app->request;

        // Stripe token generated on the frontend by Stripe.js Elements
        $token = $request->post('stripeToken');
        $amount = 29.99; // Amount in USD

        if (!$token) {
            throw new BadRequestHttpException('Missing stripe payment token.');
        }

        try {
            // Direct call to Stripe gateway purchase() via magic method delegation
            $response = Yii::$app->stripe->purchase([
                'amount' => $amount,
                'currency' => 'USD',
                'token' => $token,
                'description' => 'Order #1042 Payment',
            ])->send();

            if ($response->isSuccessful()) {
                $transactionReference = $response->getTransactionReference();
                Yii::$app->session->setFlash('success', "Payment successful! Ref: {$transactionReference}");
                return $this->redirect(['site/success']);
            } elseif ($response->isRedirect()) {
                // Redirect to 3D Secure / off-site authentication if required
                return $response->redirect();
            } else {
                $errorMessage = $response->getMessage();
                Yii::$app->session->setFlash('error', "Payment failed: {$errorMessage}");
            }
        } catch (\Exception $e) {
            Yii::$app->session->setFlash('error', "An error occurred: " . $e->getMessage());
        }

        return $this->redirect(['site/checkout']);
    }
}
```

---

### 2. PayPal Express Checkout Workflow

[](#2-paypal-express-checkout-workflow)

PayPal Express requires a redirection to PayPal's checkout page and a secondary step to capture the payment on return.

#### Step A: Initiate the PayPal Purchase

[](#step-a-initiate-the-paypal-purchase)

```
namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\helpers\Url;

class PaypalController extends Controller
{
    /**
     * Start the PayPal Express Checkout flow
     */
    public function actionCheckout()
    {
        $amount = 99.00;

        try {
            // Direct call to purchase() via magic method delegation on the paypal component
            $response = Yii::$app->paypal->purchase([
                'amount' => $amount,
                'currency' => 'USD',
                'description' => 'Premium Subscription - Annual Plan',
                'returnUrl' => Url::to(['paypal/success'], true),
                'cancelUrl' => Url::to(['paypal/cancel'], true),
            ])->send();

            if ($response->isRedirect()) {
                // Redirect to PayPal checkout page
                return $response->redirect();
            } else {
                Yii::$app->session->setFlash('error', $response->getMessage());
            }
        } catch (\Exception $e) {
            Yii::$app->session->setFlash('error', "Could not initiate payment: " . $e->getMessage());
        }

        return $this->redirect(['site/checkout']);
    }
}
```

#### Step B: Capture and Complete the Purchase

[](#step-b-capture-and-complete-the-purchase)

```
    /**
     * Complete the PayPal payment after successful return
     */
    public function actionSuccess()
    {
        $request = Yii::$app->request;

        $token = $request->get('token');
        $payerId = $request->get('PayerID');

        try {
            // Direct call to completePurchase() via magic method delegation
            $response = Yii::$app->paypal->completePurchase([
                'amount' => 99.00,
                'currency' => 'USD',
                'transactionReference' => $token,
                'payerId' => $payerId,
            ])->send();

            if ($response->isSuccessful()) {
                $data = $response->getData();
                $transactionId = $data['PAYMENTINFO_0_TRANSACTIONID'] ?? 'Unknown';

                Yii::$app->session->setFlash('success', "PayPal payment completed successfully! Transaction ID: {$transactionId}");
                return $this->redirect(['site/success']);
            } else {
                Yii::$app->session->setFlash('error', "Transaction completion failed: " . $response->getMessage());
            }
        } catch (\Exception $e) {
            Yii::$app->session->setFlash('error', "An error occurred during verification: " . $e->getMessage());
        }

        return $this->redirect(['site/checkout']);
    }

    /**
     * Handle user cancellation
     */
    public function actionCancel()
    {
        Yii::$app->session->setFlash('info', 'You have cancelled the PayPal payment checkout process.');
        return $this->redirect(['site/checkout']);
    }
```

---

Advanced Usage: Dynamic Reinitialization
----------------------------------------

[](#advanced-usage-dynamic-reinitialization)

In multi-tenant setups, SaaS environments, or instances where merchant credentials must be loaded dynamically from a database at runtime, you can reconfigure components on the fly.

### 1. Update Parameters Dynamically

[](#1-update-parameters-dynamically)

To update configuration parameters for the current gateway:

```
Yii::$app->stripe->setParameters([
    'apiKey' => 'sk_test_dynamic_merchant_key...',
]);
```

### 2. Complete Gateway Rebuilding

[](#2-complete-gateway-rebuilding)

To reconfigure the entire component dynamically (e.g., swapping gateway drivers, updating test mode flags, and resetting parameters all at once):

```
Yii::$app->stripe->reinitialize([
    'gateway' => 'PayPal_Express',
    'testMode' => true,
    'parameters' => [
        'username' => 'merchant-dynamic_api1.example.com',
        'password' => 'SECRET_PWD_123',
        'signature' => 'SIG_XYZ...',
    ],
]);
```

Note

The `reinitialize()` method uses strict safety validation. Attempting to assign unknown or read-only properties will throw a `yii\base\InvalidConfigException` immediately to prevent silent typos or configuration bugs in production.

---

Webhooks &amp; CSRF Validation
------------------------------

[](#webhooks--csrf-validation)

When integrating payment gateways, they will send asynchronous payment update notifications via webhooks (e.g. Stripe webhooks or PayPal IPN notifications) as standard HTTP POST requests.

By default, Yii 2 validates CSRF tokens on all POST requests, which will block incoming gateway webhooks with an **HTTP 400 Bad Request** error. To resolve this, disable CSRF validation for your webhook action inside your payment controller:

```
namespace app\controllers;

use Yii;
use yii\web\Controller;

class WebhookController extends Controller
{
    /**
     * @inheritdoc
     */
    public function beforeAction($action)
    {
        if ($action->id === 'stripe-webhook' || $action->id === 'paypal-ipn') {
            $this->enableCsrfValidation = false;
        }

        return parent::beforeAction($action);
    }

    public function actionStripeWebhook()
    {
        // Process Stripe webhook signature and handle notification
    }
}
```

---

Running Tests
-------------

[](#running-tests)

This library includes automated unit tests written in PHPUnit. To run tests, use the following command:

```
composer test
```

Tests are located in the `/tests/` directory.

---

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENCE.md](LICENCE.md) file for details.

Developed with ❤️ by **[Edgars Karlsons](mailto:edgars@nedarta.com)**.

###  Health Score

34

—

LowBetter than 75% of packages

Maintenance88

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity33

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.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

58d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/16962105?v=4)[Nedarta](/maintainers/nedarta)[@nedarta](https://github.com/nedarta)

---

Top Contributors

[![nedarta](https://avatars.githubusercontent.com/u/16962105?v=4)](https://github.com/nedarta "nedarta (1 commits)")

---

Tags

stripeyii2extensionpaymentpaypalomnipay

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/nedarta-yii2-omnipay/health.svg)

```
[![Health](https://phpackages.com/badges/nedarta-yii2-omnipay/health.svg)](https://phpackages.com/packages/nedarta-yii2-omnipay)
```

###  Alternatives

[payum/payum-bundle

One million downloads of Payum already! Payum offers everything you need to work with payments. Check more visiting site.

59710.9M51](/packages/payum-payum-bundle)[omnipay/paypal

PayPal gateway for Omnipay payment processing library

3267.1M57](/packages/omnipay-paypal)[omnipay/stripe

Stripe driver for the Omnipay payment processing library

1936.2M39](/packages/omnipay-stripe)[payum/payum-laravel-package

Rich payment solutions for Laravel framework. Paypal, payex, authorize.net, be2bill, omnipay, recurring paymens, instant notifications and many more

12342.5k](/packages/payum-payum-laravel-package)[skeeks/cms

SkeekS CMS — control panel and tools based on php framework Yii2

13725.8k63](/packages/skeeks-cms)[recca0120/laravel-payum

Rich payment solutions for Laravel framework. Paypal, payex, authorize.net, be2bill, omnipay, recurring paymens, instant notifications and many more

741.5k](/packages/recca0120-laravel-payum)

PHPackages © 2026

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