PHPackages                             sequra/integration-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. [Utility &amp; Helpers](/categories/utility)
4. /
5. sequra/integration-core

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

sequra/integration-core
=======================

Core SeQura integration library

v4.1.0(2mo ago)122.4k↓30.3%2proprietaryPHPPHP &gt;=7.2CI passing

Since Jun 7Pushed 2mo ago18 watchersCompare

[ Source](https://github.com/sequra/integration-core)[ Packagist](https://packagist.org/packages/sequra/integration-core)[ RSS](/packages/sequra-integration-core/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (6)Versions (46)Used By (2)

SeQura Integration Core Library
===============================

[](#sequra-integration-core-library)

Table of Contents
-----------------

[](#table-of-contents)

- [📘 Overview](#%F0%9F%93%98-overview)
    - [What is the SeQura Integration Core?](#what-is-the-sequra-integration-core)
    - [Problems Solved by Integration Core](#problems-solved-by-integration-core)
- [🛠 Installation](#%F0%9F%9B%A0-installation)
    - [Requirements](#requirements)
    - [Installing via Composer](#installing-via-composer)
    - [Developer guide](#developer-guide)
- [🚀 Quick Start Guide](#%F0%9F%9A%80-quick-start-guide)
    - [Services](#services)
    - [Repositories](#repositories)
    - [Using the BootstrapComponent](#using-the-bootstrapcomponent)
        - [Core Infrastructure Services (Required)](#core-infrastructure-services-required)
        - [Business Logic Services (Required)](#business-logic-services-required)
        - [Order Management Services (Required)](#order-management-services-required)
        - [Integration Services (Required)](#integration-services-required)
        - [Widget Services (Optional but Recommended)](#widget-services-optional-but-recommended)
        - [Repository Registrations (Required)](#repository-registrations-required)
        - [Minimum Implementation Checklist](#minimum-implementation-checklist)
- [📦 Platform Integration Examples](#%F0%9F%93%A6-platform-integration-examples)
- [📚 Public API Documentation](#%F0%9F%93%9A-public-api-documentation)
    - [Architecture Overview](#architecture-overview)
    - [Infrastructure Components](#infrastructure-components)
    - [Admin API Layer](#admin-api-layer)
    - [Checkout API Layer](#checkout-api-layer)
    - [Webhook API Layer](#webhook-api-layer)
    - [Configuration Webhook API Layer](#configuration-webhook-api-layer)
    - [API Proxy Layer](#api-proxy-layer)
    - [Task Execution System](#task-execution-system)
    - [ORM &amp; Data Persistence Layer](#orm--data-persistence-layer)
    - [Multi-store Context Management](#multi-store-context-management)
    - [SeQura API Proxy Layer](#sequra-api-proxy-layer)
- [🧩 Customization and Extensibility](#-customization-and-extensibility)

📘 Overview
----------

[](#-overview)

### What is the SeQura Integration Core?

[](#what-is-the-sequra-integration-core)

The `sequra/integration-core` library is a platform-agnostic PHP library that provides the foundational business logic and API communication layer for integrating SeQura payment methods into any e-commerce platform. It is built following clean architecture principles, ensuring that the payment processing logic remains centralised and consistent across implementations.

One of the main goals of the library is to provide this shared, centralised logic, while still allowing for customisation and extension to adapt behaviour and structure to different systems. At the same time, it avoids dependencies on system-specific or third-party components, relying only on pure PHP and vanilla JavaScript to keep the core flexible, lightweight, and portable.

The library is designed with the following non-functional requirements, which are to be consistently upheld across all SeQura integrations:

- **Platform-agnostic**: Works with any PHP-based e-commerce platform
- **Modular**: Components can be used independently or together
- **Extensible**: Allows custom implementations of interfaces
- **Testable**: Clear separation of concerns with dependency injection

These attributes are not just desirable qualities, but mandatory design goals that ensure long-term maintainability and alignment with SeQura’s architectural principles. They represent core priorities, though not the entirety of the non-functional requirements defined for the CORE. For a complete overview, refer to the architectural documentation, which describes in detail how these and other quality attributes shape both the design and implementation of the system.

Problems Solved by Integration Core
-----------------------------------

[](#problems-solved-by-integration-core)

### Architectural Overview

[](#architectural-overview)

To ensure maintainability and alignment with clean architecture principles, the **integration-core** library separates responsibilities into distinct layers, following the Onion Architecture model.
This structure avoids mixing concerns, keeps the core logic centralised, and ensures consistency across all SeQura integrations.

---

#### CORE – Infrastructure

[](#core--infrastructure)

Provides the **technical foundation** to support business logic, ensuring consistency and portability across platforms:

- **Logging** – unified logger for consistent monitoring and troubleshooting
- **HTTP Infrastructure** – standardized communication with external services
- **ORM Abstraction** – repository pattern for persistence without platform lock-in
- **Task Runner** – scheduling and background task execution

---

#### CORE – Business Logic

[](#core--business-logic)

Encapsulates **SeQura’s domain logic**, centralized and reusable across all platforms:

- **API Facades** – simplified access to SeQura API endpoints
- **Checkout Services** – consistent handling of payment initiation and processing
- **Order Management Services** – standardized order lifecycle handling
- **Plugin Administration Services** – centralized configuration and credential management
- **API Proxy &amp; JS Library** – abstraction for frontend–backend communication

---

#### Integration Interfaces

[](#integration-interfaces)

Defines **extension points** that allow business logic to interact with diverse e-commerce systems without leaking system-specific dependencies.

---

#### Concrete Integrations

[](#concrete-integrations)

Implements **shop-specific adapters and extensions**, bridging CORE with the host platform:

- **Platform-specific Implementations** – e.g., order state transitions, checkout extensions
- **UI/UX Extensions** – extensions to checkout or order screens
- **Bootstrap Components** – initialization of the integration in the host platform
- **Event Listeners** – handling shop-specific events (orders, payments, refunds, etc.)

🛠 Installation
--------------

[](#-installation)

### Requirements

[](#requirements)

- **PHP**: &gt;= 7.2
- **Extensions**: `json`, `ctype`, `mbstring`
- **Composer**: For dependency management

### Installing via Composer

[](#installing-via-composer)

```
composer require sequra/integration-core
```

### Developer guide

[](#developer-guide)

If you are planning to contribute to the development of this library, please refer to the [Developer Guide](DEVELOPER_GUIDE.md) for instructions on setting up your development environment, debugging, and running tests.

🚀 Quick Start Guide
-------------------

[](#-quick-start-guide)

The library uses a **bootstrap pattern** for initialization. This step must be performed after installing the library.

Its main goal is to ensure **independence from the dependency injection (DI) mechanisms** of different systems, and to provide a way for services to be **overridden or extended** in concrete platform integrations.

The **dependency inversion principle** is applied here as a best practice to achieve this flexibility, but it is not the primary objective of the bootstrap process.

This library provides a `BootstrapComponent` class that should be extended by the platform integration. The `BootstrapComponent` is responsible for registering all required services, repositories and dependencies.

Before going deeper into the BootstrapComponent, let's see take a quick look at the concept of Services, Repositories and how to register them.

### Services

[](#services)

Services are intended to handle use-cases. The way you should use to register a new Service is through the `SeQura\Core\Infrastructure\ServiceRegister` class. The following example shows how to register the implementation for the SeQura\\WC\\Services\\Core\\Encryptor service required to encrypt and decrypt text.

```
ServiceRegister::registerService(
    EncryptorInterface::class,
    static function () {
        return new Encryptor();
    }
);
```

For retrieving the instance, use this method instead:

```
$encryptor = ServiceRegister::getService(EncryptorInterface::class);
```

### Repositories

[](#repositories)

Repositories define a way to read and write data to a datasource (like a database) and map raw data to entities. They must implement `SeQura\Core\Infrastructure\ORM\Interfaces\RepositoryInterface`. The integration-core provides for this the `SeQura\Core\Infrastructure\ORM\RepositoryRegistry`, similar to the service alternative.

To register a new repository implementation, see the following example:

```
RepositoryRegistry::registerRepository( ConfigEntity::class, EntityRepository::class );
```

To retrieve a repository:

```
$configRepository = RepositoryRegistry::getRepository(ConfigEntity::class);
```

### Using the BootstrapComponent

[](#using-the-bootstrapcomponent)

To use the `BootstrapComponent`, extend it in your platform integration and implement the `init` method to register all required services and repositories. Here's an example for a Magento 2 integration:

```
namespace YourNamespace\Integration;

use SeQura\Core\BusinessLogic\BootstrapComponent;

class Bootstrap extends BootstrapComponent
{
    public static function init(): void
    {
        // Customize initialization logic here as needed.
        // For example, register constant values required by services.

        // Then call the parent init method.
        parent::init();
    }

    protected static function initRepositories(): void
    {
        parent::initRepositories();
        // Register your repositories here
    }

    protected static function initServices(): void
    {
        parent::initServices();
        // Register your services here
    }
}
```

After implementing the `Bootstrap` class, you can call `Bootstrap::init()` in your platform's bootstrap process to initialize the integration core library.

Here are the essential components your bootstrap implementation must provide:

### Core Infrastructure Services (Required)

[](#core-infrastructure-services-required)

These services must be implemented by every platform integration:

#### 1. Configuration Service

[](#1-configuration-service)

```
// Must extend SeQura\Core\Infrastructure\Configuration\Configuration
class PlatformConfiguration extends Configuration
{
    // Platform-specific configuration storage and retrieval
    public function getConfigValue($key, $defaultValue = null) { /* */ }
    public function setConfigValue($key, $value) { /* */ }
    public function getAsyncProcessUrl($guid) { /* */ }
    // ... other required methods
}
```

#### 2. Logger Service

[](#2-logger-service)

```
// Must implement SeQura\Core\Infrastructure\Logger\Interfaces\ShopLoggerAdapter
class PlatformLogger implements ShopLoggerAdapter
{
    public function logMessage($level, $message, array $context = []) { /* */ }
    public function isLoggingEnabled() { /* */ }
    // ... other required methods
}
```

#### 3. Encryptor Service

[](#3-encryptor-service)

```
// Must implement SeQura\Core\BusinessLogic\Utility\EncryptorInterface
class PlatformEncryptor implements EncryptorInterface
{
    public function encrypt($data) { /* */ }
    public function decrypt($data) { /* */ }
}
```

### Business Logic Services (Required)

[](#business-logic-services-required)

#### 4. Store Service

[](#4-store-service)

```
// Must implement StoreServiceInterface
class PlatformStoreService implements StoreServiceInterface
{
    public function getStoreId() { /* */ }
    public function getStoreName() { /* */ }
    public function getStores() { /* */ }
    public function getDefaultStore() { /* */ }
}
```

#### 5. Version Service

[](#5-version-service)

```
// Must implement VersionServiceInterface
class PlatformVersionService implements VersionServiceInterface
{
    public function getShopName() { /* */ }
    public function getShopVersion() { /* */ }
    public function getModuleVersion() { /* */ }
}
```

#### 6. Category Service

[](#6-category-service)

```
// Must implement CategoryServiceInterface
class PlatformCategoryService implements CategoryServiceInterface
{
    public function getCategory($categoryId) { /* */ }
    public function getAllCategories() { /* */ }
}
```

#### 7. Product Service

[](#7-product-service)

```
// Must implement ProductServiceInterface
class PlatformProductService implements ProductServiceInterface
{
    public function getProductById($productId) { /* */ }
    public function getProductsByIds(array $productIds) { /* */ }
}
```

### Order Management Services (Required)

[](#order-management-services-required)

#### 8. Order Creation Service

[](#8-order-creation-service)

```
// Must implement OrderCreationInterface
class PlatformOrderCreation implements OrderCreationInterface
{
    public function createOrder($cartData, $sequraOrderReference) { /* */ }
    public function updateOrderStatus($orderId, $status) { /* */ }
}
```

#### 9. Merchant Data Provider

[](#9-merchant-data-provider)

```
// Must implement MerchantDataProviderInterface
class PlatformMerchantDataProvider implements MerchantDataProviderInterface
{
    public function getMerchantData($orderId) { /* */ }
    public function getOrderItems($orderId) { /* */ }
    public function getShippingInfo($orderId) { /* */ }
}
```

#### 10. Order Report Service

[](#10-order-report-service)

```
// Must implement OrderReportServiceInterface
class PlatformOrderReportService implements OrderReportServiceInterface
{
    public function getOrdersForReporting($from, $to) { /* */ }
    public function markOrderAsReported($orderId) { /* */ }
}
```

### Integration Services (Required)

[](#integration-services-required)

#### 11. Selling Countries Service

[](#11-selling-countries-service)

```
// Must implement SellingCountriesServiceInterface
class PlatformSellingCountriesService implements SellingCountriesServiceInterface
{
    public function getSellingCountries() { /* */ }
    public function getCountryByCode($countryCode) { /* */ }
}
```

#### 12. Disconnect Service

[](#12-disconnect-service)

```
// Must implement DisconnectServiceInterface
class PlatformDisconnectService implements DisconnectServiceInterface
{
    public function disconnect() { /* */ }
    public function cleanup() { /* */ }
}
```

### Widget Services (Optional but Recommended)

[](#widget-services-optional-but-recommended)

#### 13. Widget Configurator

[](#13-widget-configurator)

```
// Must implement WidgetConfiguratorInterface
class PlatformWidgetConfigurator implements WidgetConfiguratorInterface
{
    public function getWidgetAssetsHtml() { /* */ }
    public function getWidgetScriptUrl() { /* */ }
    public function getSelectors() { /* */ }
}
```

#### 14. Mini Widget Messages Provider

[](#14-mini-widget-messages-provider)

```
// Must implement MiniWidgetMessagesProviderInterface
class PlatformMiniWidgetMessagesProvider implements MiniWidgetMessagesProviderInterface
{
    public function getMessages($productId, $price) { /* */ }
}
```

### Repository Registrations (Required)

[](#repository-registrations-required)

Your bootstrap must also register repositories for entity persistence:

```
protected static function initRepositories(): void
{
    parent::initRepositories();

    // Register entity repositories with your platform's storage implementation
    RepositoryRegistry::registerRepository(ConfigEntity::class, PlatformBaseRepository::class);
    RepositoryRegistry::registerRepository(QueueItem::class, PlatformQueueRepository::class);
    RepositoryRegistry::registerRepository(SeQuraOrder::class, PlatformOrderRepository::class);
    // ... register all required entities
}
```

### Minimum Implementation Checklist

[](#minimum-implementation-checklist)

✅ **Infrastructure Layer**

- Configuration service extending `Configuration`
- Logger service implementing `ShopLoggerAdapter`
- Encryptor service implementing `EncryptorInterface`
- Serializer service (usually `JsonSerializer` is sufficient)

✅ **Platform Integration Layer**

- Store service implementing `StoreServiceInterface`
- Version service implementing `VersionServiceInterface`
- Category service implementing `CategoryServiceInterface`
- Product service implementing `ProductServiceInterface`

✅ **Order Management Layer**

- Order creation service implementing `OrderCreationInterface`
- Merchant data provider implementing `MerchantDataProviderInterface`
- Order report service implementing `OrderReportServiceInterface`

✅ **Business Services Layer**

- Selling countries service implementing `SellingCountriesServiceInterface`
- Disconnect service implementing `DisconnectServiceInterface`

✅ **Data Persistence Layer**

- Repository implementations for all core entities
- Database schema creation/migration support

✅ **Optional Enhancement Layer**

- Widget configurator for promotional widgets
- Mini widget messages provider
- Shop order statuses service

This comprehensive list ensures your platform integration provides all necessary components for the SeQura Core library to function properly across all supported use cases.

📦 Platform Integration Examples
-------------------------------

[](#-platform-integration-examples)

You can take a look at existing implementations of the integration-core library in the following repositories:

- [Magento 2](https://github.com/sequra/magento2-core)
- [WooCommerce](https://github.com/sequra/woocommerce-sequra)

📚 Public API Documentation
--------------------------

[](#-public-api-documentation)

### Architecture Overview

[](#architecture-overview)

The Core will be implemented by following the onion architecture comprised of multiple concentric layers interfacing with each other towards the core that represents the business logic, as displayed in the diagram below. Onion Architecture is based on the inversion of control principle where inner layers' dependencies are abstracted as required interfaces:

 ```
graph TB
    subgraph "Platform Layer"
        Controllers[Controllers]
        Services[Platform Services]
        Adapters[Platform Adapters]
    end

    subgraph "Integration Core Library"
        AdminAPI[Admin API Layer]
        CheckoutAPI[Checkout API Layer]
        BusinessLogic[Business Logic Layer]
        DataAccess[Data Access Layer]
        Infrastructure[Infrastructure Layer]
    end

    subgraph "SeQura API"
        OrderAPI[Orders API]
        PaymentAPI[Payment Methods API]
        WebhookAPI[Webhooks API]
        CredentialsAPI[Credentials API]
    end

    Controllers --> AdminAPI
    Controllers --> CheckoutAPI
    Services --> BusinessLogic
    Adapters --> DataAccess

    AdminAPI --> BusinessLogic
    CheckoutAPI --> BusinessLogic
    BusinessLogic --> DataAccess
    BusinessLogic --> Infrastructure
    Infrastructure --> OrderAPI
    Infrastructure --> PaymentAPI
    Infrastructure --> WebhookAPI
    Infrastructure --> CredentialsAPI
```

      Loading The library structure is organized the following way:

```
SeQura\Core\
├── BusinessLogic/
│   ├── AdminAPI/           # Admin panel management
│   ├── CheckoutAPI/        # Checkout process handling
│   ├── DataAccess/         # Repository interfaces and entities
│   ├── Domain/             # Core domain services
│   ├── Providers/          # Service providers
│   ├── SeQuraAPI/          # API client implementations
│   ├── TransactionLog/     # Transaction logging
│   ├── Utility/            # Helper utilities
│   ├── Webhook/            # Webhook processing
│   └── WebhookAPI/         # Webhook API handling
└── Infrastructure/
    ├── Configuration/      # Configuration management
    ├── Http/               # HTTP client abstractions
    ├── Logger/             # Logging interfaces
    ├── ORM/                # Data persistence abstractions
    └── ServiceRegister/    # Dependency injection container

```

### Infrastructure Components

[](#infrastructure-components)

The **Infrastructure Components** form the foundation of any SeQura integration, providing essential services for logging, HTTP communication, configuration storage, task execution, and data persistence. Understanding and properly implementing these components is critical for a robust, scalable integration.

#### Overview

[](#overview)

The infrastructure layer follows **Dependency Inversion Principle** and uses **Abstract Factory Pattern** to provide platform-agnostic implementations of core services while allowing platform-specific customizations through interface implementations.

#### Core Infrastructure Components

[](#core-infrastructure-components)

##### 1. **HTTP Client Infrastructure**

[](#1-http-client-infrastructure)

- **Purpose**: Handles all HTTP communication with SeQura APIs
- **Features**: Request/response handling, SSL verification, proxy support, timeout management
- **Extensibility**: Custom authentication, retry logic, caching

##### 2. **Logging Infrastructure**

[](#2-logging-infrastructure)

- **Purpose**: Centralized logging for debugging, monitoring, and audit trails
- **Features**: Multiple log levels, structured logging, log rotation, remote logging
- **Integration**: Platform logging systems, external monitoring tools

Implementation example based on Magento 2:

```
namespace YourNamespace\Integration\Core\Infrastructure;

use SeQura\Core\Infrastructure\Configuration\Configuration;
use SeQura\Core\Infrastructure\Logger\Interfaces\ShopLoggerAdapter;
use SeQura\Core\Infrastructure\Logger\LogData;
use SeQura\Core\Infrastructure\Logger\Logger;
use SeQura\Core\Infrastructure\ServiceRegister;
use SeQura\Core\Infrastructure\Singleton;
use Sequra\Core\Services\BusinessLogic\ConfigurationService;
use Psr\Log\LoggerInterface;

class LoggerService extends Singleton implements ShopLoggerAdapter
{
    /**
     * Singleton instance of this class.
     *
     * @var static
     */
    protected static $instance;
    /**
     * Log level names for corresponding log level codes.
     *
     * @var array
     */
    private static $logLevelName = [
        Logger::ERROR => 'error',
        Logger::WARNING => 'warning',
        Logger::INFO => 'info',
        Logger::DEBUG => 'debug',
    ];
    /**
     * Magento logger interface.
     *
     * @var LoggerInterface
     */
    private $logger;

    /**
     * Logger service constructor.
     *
     * @param LoggerInterface $logger Magento logger interface.
     */
    public function __construct(LoggerInterface $logger)
    {
        parent::__construct();

        $this->logger = $logger;

        static::$instance = $this;
    }

    /**
     * Logs message in the system.
     *
     * @param LogData $data
     */
    public function logMessage(LogData $data): void
    {
        /** @var ConfigurationService $configService */
        $configService = ServiceRegister::getService(Configuration::CLASS_NAME);
        $minLogLevel = $configService->getMinLogLevel();
        $logLevel = $data->getLogLevel();

        if (($logLevel > $minLogLevel) && !$configService->isDebugModeEnabled()) {
            return;
        }

        $message = 'SEQURA LOG:
            Date: ' . date('d/m/Y') . '
            Time: ' . date('H:i:s') . '
            Log level: ' . self::$logLevelName[$logLevel] . '
            Message: ' . $data->getMessage();
        $context = $data->getContext();
        if (!empty($context)) {
            $message .= '
            Context data: [';
            foreach ($context as $item) {
                $message .= '"' . $item->getName() . '" => "' . print_r($item->getValue(), true) . '", ';
            }

            $message .= ']';
        }
        \call_user_func([$this->logger, self::$logLevelName[$logLevel]], $message);
    }
}
```

##### 3. **Configuration Infrastructure**

[](#3-configuration-infrastructure)

- **Purpose**: Secure storage and retrieval of integration settings
- **Features**: Encryption, validation, environment management, multi-store support
- **Security**: Credential protection, secure defaults, audit logging

Implementation example based on Magento 2:

```
namespace YourNamespace\Integration\Core\Infrastructure;

use Magento\Framework\Exception\NoSuchEntityException;
use Sequra\Core\Helper\UrlHelper;
use SeQura\Core\Infrastructure\Configuration\Configuration;

class ConfigurationService extends Configuration
{
    public const MIN_LOG_LEVEL = 1;
    private const INTEGRATION_NAME = 'Magento2';

    /**
     * @var UrlHelper
     */
    private $urlHelper;

    /**
     * @param UrlHelper $urlHelper
     */
    public function __construct(UrlHelper $urlHelper)
    {
        parent::__construct();

        $this->urlHelper = $urlHelper;
    }

    /**
     * @inheritDoc
     */
    public function getIntegrationName(): string
    {
        return self::INTEGRATION_NAME;
    }

    /**
     * @inheritDoc
     *
     * @throws NoSuchEntityException
     */
    public function getAsyncProcessUrl($guid): string
    {
        $params = [
            'guid' => $guid,
            'ajax' => 1,
            '_nosid' => true,
        ];

        return $this->urlHelper->getFrontendUrl('sequra/asyncprocess/asyncprocess', $params);
    }
}
```

##### 4. **Task Execution Infrastructure**

[](#4-task-execution-infrastructure)

- **Purpose**: Background task processing and queue management
- **Features**: Priority queues, retry mechanisms, progress tracking, failure recovery
- **Scalability**: Distributed processing, load balancing, horizontal scaling

##### 5. **ORM Infrastructure**

[](#5-orm-infrastructure)

- **Purpose**: Database abstraction and entity management
- **Features**: Query building, connection management, transaction handling, migration support
- **Performance**: Connection pooling, query optimization, caching

##### 6. **Regex Provider Infrastructure**

[](#6-regex-provider-infrastructure)

- **Purpose**: Provides regular expressions for common validation tasks
- **Features**: IP address validation, email format validation, URL structure validation
- **Extensibility**: Custom regex patterns can be added as needed

If you're using the Integration Core UI library you must provide the regular expressions for validating user input in the admin panel when the `SequraFE` object is initialized. The `RegexProvider` service provides a function `toArray()` for this purpose. Example:

```
