PHPackages                             mbsoft31/loyalty-rewards - 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. mbsoft31/loyalty-rewards

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

mbsoft31/loyalty-rewards
========================

A flexible loyalty rewards system for PHP applications

v1.3.1(3w ago)044MITPHPPHP ^8.3CI failing

Since Sep 26Pushed 3w agoCompare

[ Source](https://github.com/mbsoft31/loyalty-rewards)[ Packagist](https://packagist.org/packages/mbsoft31/loyalty-rewards)[ RSS](/packages/mbsoft31-loyalty-rewards/feed)WikiDiscussions main Synced today

READMEChangelog (3)Dependencies (14)Versions (8)Used By (0)

Loyalty Rewards System
======================

[](#loyalty-rewards-system)

[![Tests](https://github.com/mbsoft31/loyalty-rewards/actions/workflows/tests.yml/badge.svg)](https://github.com/mbsoft31/loyalty-rewards/actions/workflows/tests.yml)[![PHP Version](https://camo.githubusercontent.com/ef0054230522e542bc1f908ac005c6c75888dea255bac910f9015e12095e31d7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e332d626c7565)](https://php.net)[![License](https://camo.githubusercontent.com/f8df3091bbe1149f398a5369b2c39e896766f9f6efba3477c63e9b4aa940ef14/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e)](LICENSE)[![Latest Version](https://camo.githubusercontent.com/0e2d3e3ef0556b566cedce6525923a512d39eed70d460275f8e67bdb98785eda/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f72656c656173652f6d62736f667433312f6c6f79616c74792d72657761726473)](https://github.com/mbsoft31/loyalty-rewards/releases)[![Laravel Adapter](https://camo.githubusercontent.com/09f7b5fa439dd2df0dab46ec8582632a9677ab061abbe60c4008cdf2a0126a1f/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d416461707465722d626c756576696f6c6574)](https://github.com/mbsoft31/loyalty-laravel-pro)

A comprehensive, enterprise-grade loyalty rewards system for PHP applications. Built with Domain-Driven Design principles, this package provides flexible point earning/redemption, fraud detection, audit logging, and multi-tier reward programs.

Features
--------

[](#features)

- Flexible Rewards Engine — Category multipliers, tier bonuses, time-based promotions
- Built-in Fraud Detection — Velocity checks, amount validation, suspicious activity alerts
- Complete Audit Trail — Full transaction logging with compliance support
- High Performance — Handles 1000+ transactions/second with optimized database queries
- Comprehensive Test Suite — Unit, feature, integration, and coverage-gated CI checks
- Framework Agnostic — Works with Laravel, Symfony, or standalone PHP applications
- Type Safe — Full PHP 8.3+ type declarations with strict type checking

Quick Start
-----------

[](#quick-start)

### Installation

[](#installation)

composer require mbsoft31/loyalty-rewards

### Basic Usage

[](#basic-usage)

```
declare(strict_types=1);

use LoyaltyRewards\Core\Services\LoyaltyService;
use LoyaltyRewards\Core\Services\AuditService;
use LoyaltyRewards\Core\Services\FraudDetectionService;
use LoyaltyRewards\Core\Engine\RulesEngine;
use LoyaltyRewards\Domain\ValueObjects\{ConversionRate, Currency, CustomerId, Money, Points, TransactionContext};
use LoyaltyRewards\Infrastructure\Database\DatabaseAccountRepository;
use LoyaltyRewards\Infrastructure\Database\DatabaseAuditRepository;
use LoyaltyRewards\Infrastructure\Database\DatabaseConnectionFactory;
use LoyaltyRewards\Infrastructure\Database\DatabaseTransactionRepository;
use LoyaltyRewards\Rules\Earning\CategoryMultiplierRule;
use LoyaltyRewards\Rules\Earning\TierBonusRule;
use LoyaltyRewards\Rules\Redemption\BasicRedemptionRule;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Log\NullLogger;

$pdo = DatabaseConnectionFactory::create([
    'driver' => 'sqlite',
    'database' => ':memory:',
]);

$accountRepository = new DatabaseAccountRepository(
    $pdo,
    new DatabaseTransactionRepository($pdo)
);
$auditRepository = new DatabaseAuditRepository($pdo);

$rulesEngine = new RulesEngine(new NullLogger);
$rulesEngine->addEarningRule(new CategoryMultiplierRule('electronics', 2.0, ConversionRate::standard()));
$rulesEngine->addEarningRule(new TierBonusRule('gold', 1.25, ConversionRate::standard()));
$rulesEngine->addRedemptionRule(new BasicRedemptionRule(Currency::USD(), 100, 100));

$loyaltyService = new LoyaltyService(
    $accountRepository,
    $rulesEngine,
    new FraudDetectionService(new NullLogger),
    new AuditService($auditRepository, new NullLogger),
    new class implements EventDispatcherInterface {
        public function dispatch(object $event): object
        {
            return $event;
        }
    },
    new NullLogger
);

// Create customer account
$customerId = CustomerId::fromString('customer_12345');
$loyaltyService->createAccount($customerId);

// Earn points from purchase
$result = $loyaltyService->earnPoints(
    $customerId,
    Money::fromDollars(99.99, Currency::USD()),
    TransactionContext::earning('electronics', 'online_store')
);
$loyaltyService->confirmPendingPoints($customerId);
$availableBalance = $loyaltyService->getAccountBalance($customerId);

echo "Earned: {$result->pointsEarned->value()} points\n";
echo "Balance (available): {$availableBalance->value()} points\n";

// Redeem points
$redemption = $loyaltyService->redeemPoints(
    $customerId,
    Points::fromInt(1000),
    TransactionContext::redemption(['channel' => 'store'])
);

echo "Redeemed: {$redemption->redemptionValue->toDollars()} {$redemption->redemptionValue->currency()->code()}";
```

Architecture Overview
---------------------

[](#architecture-overview)

```
loyalty-rewards/
├── src/
│   ├── Core/                 # Business logic core
│   │   ├── Engine/           # Rules processing engine
│   │   ├── Services/         # Domain services
│   │   └── Exceptions/       # Custom exceptions
│   ├── Domain/               # Domain models and contracts
│   │   ├── Models/           # Core business entities
│   │   ├── ValueObjects/     # Immutable value types
│   │   ├── Events/           # Domain events
│   │   └── Repositories/     # Data access contracts
│   ├── Infrastructure/       # External concerns
│   │   ├── Database/         # Database implementations
│   │   └── Audit/            # Audit logging
│   ├── Application/          # Use cases and DTOs
│   └── Rules/                # Business rules library
└── tests/                    # Comprehensive test suite

```

Real-World Examples
-------------------

[](#real-world-examples)

### E-commerce Rewards Program

[](#e-commerce-rewards-program)

```
use LoyaltyRewards\Domain\ValueObjects\{ConversionRate, Currency, CustomerId, Money, TransactionContext};
use LoyaltyRewards\Rules\Earning\{CategoryMultiplierRule, TierBonusRule};

$goldCustomerId = CustomerId::fromString('customer_gold_100');
$loyaltyService->createAccount($goldCustomerId);

// Setup category-based earning
$rulesEngine->addEarningRule(new CategoryMultiplierRule('electronics', 3.0, ConversionRate::standard()));
$rulesEngine->addEarningRule(new CategoryMultiplierRule('books', 2.0, ConversionRate::standard()));
$rulesEngine->addEarningRule(new CategoryMultiplierRule('groceries', 1.5, ConversionRate::standard()));

// Tier-based bonuses
$rulesEngine->addEarningRule(new TierBonusRule('gold', 1.25, ConversionRate::standard()));
$rulesEngine->addEarningRule(new TierBonusRule('platinum', 1.5, ConversionRate::standard()));

// Customer purchases $200 laptop (electronics + gold tier)
$result = $loyaltyService->earnPoints(
    $goldCustomerId,
    Money::fromDollars(200.00, Currency::USD()),
    TransactionContext::earning('electronics', null, ['tier' => 'gold'])
);
// Earns: 200 * 100 * 3.0 * 1.25 = 75,000 points
```

### Restaurant Chain Program

[](#restaurant-chain-program)

```
use DateTimeImmutable;
use LoyaltyRewards\Domain\ValueObjects\{ConversionRate, Currency, CustomerId, Money, TransactionContext};
use LoyaltyRewards\Rules\Earning\TimeBasedRule;

$customerId = CustomerId::fromString('customer_restaurant_100');
$loyaltyService->createAccount($customerId);

// Happy hour promotions
$happyHourRule = new TimeBasedRule(
    new DateTimeImmutable('2025-01-01 14:00:00'),
    new DateTimeImmutable('2025-12-31 17:00:00'),
    2.0, // Double points
    ConversionRate::standard(),
    ['monday', 'tuesday', 'wednesday']
);

$rulesEngine->addEarningRule($happyHourRule);

// Customer orders during happy hour
$result = $loyaltyService->earnPoints(
    $customerId,
    Money::fromDollars(12.50, Currency::USD()),
    TransactionContext::earning('food', 'mobile_app')
);
// Earns: 12.50 * 100 * 2.0 = 2,500 points
```

### SaaS Referral Program

[](#saas-referral-program)

```
use LoyaltyRewards\Domain\ValueObjects\{Currency, CustomerId, Money, TransactionContext};

$referrerId = CustomerId::fromString('customer_referrer_200');
$loyaltyService->createAccount($referrerId);

// Referral bonus
$result = $loyaltyService->earnPoints(
    $referrerId,
    Money::zero(Currency::USD()), // No monetary transaction
    TransactionContext::create([
        'type' => 'referral_conversion',
        'referred_customer' => 'new_customer_789',
        'subscription_tier' => 'pro'
    ])
);
```

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

[](#configuration)

### Database Setup

[](#database-setup)

```
use LoyaltyRewards\Infrastructure\Database\DatabaseConnectionFactory;

$pdo = DatabaseConnectionFactory::create([
    'driver' => 'sqlite',
    'database' => '/absolute/path/to/loyalty.sqlite',
]);
```

### Dependency Injection

[](#dependency-injection)

```
use LoyaltyRewards\Core\Services\LoyaltyService;
use LoyaltyRewards\Core\Services\AuditService;
use LoyaltyRewards\Core\Services\FraudDetectionService;
use LoyaltyRewards\Core\Engine\RulesEngine;
use LoyaltyRewards\Infrastructure\Database\DatabaseAccountRepository;
use LoyaltyRewards\Infrastructure\Database\DatabaseAuditRepository;
use LoyaltyRewards\Infrastructure\Database\DatabaseConnectionFactory;
use LoyaltyRewards\Infrastructure\Database\DatabaseTransactionRepository;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Log\NullLogger;

$pdo = DatabaseConnectionFactory::create([
    'driver' => 'sqlite',
    'database' => ':memory:',
]);

$accountRepository = new DatabaseAccountRepository(
    $pdo,
    new DatabaseTransactionRepository($pdo)
);
$auditRepository = new DatabaseAuditRepository($pdo);

$loyaltyService = new LoyaltyService(
    $accountRepository,
    new RulesEngine(new NullLogger),
    new FraudDetectionService(new NullLogger),
    new AuditService($auditRepository, new NullLogger),
    new class implements EventDispatcherInterface {
        public function dispatch(object $event): object
        {
            return $event;
        }
    },
    new NullLogger
);
```

### Rules Configuration

[](#rules-configuration)

```
use LoyaltyRewards\Core\Engine\RulesEngine;
use LoyaltyRewards\Domain\ValueObjects\ConversionRate;
use LoyaltyRewards\Rules\Earning\{CategoryMultiplierRule, TierBonusRule};

$rulesEngine = new RulesEngine();

// Base earning: 1 point per cent spent
$rulesEngine->addEarningRule(
    new CategoryMultiplierRule('default', 1.0, ConversionRate::standard())
);

// Category bonuses
$rulesEngine->addEarningRule(
    new CategoryMultiplierRule('premium', 5.0, ConversionRate::standard())
);

// Tier bonuses stack with category multipliers
$rulesEngine->addEarningRule(
    new TierBonusRule('vip', 2.0, ConversionRate::standard())
);
```

Testing
-------

[](#testing)

The package includes comprehensive tests with a CI coverage gate:

Run all tests
=============

[](#run-all-tests)

```
composer test
```

Run specific test suites
========================

[](#run-specific-test-suites)

```
composer test:unit
composer test:feature
composer test:integration
```

Run with coverage report
========================

[](#run-with-coverage-report)

```
composer test:coverage
```

### Test Results

[](#test-results)

- Full suite includes unit, feature, and integration tests
- Unit tests: Value objects, domain models, rules engine
- Integration tests: Database operations, repository behavior, full service workflows
- Integration coverage includes high-volume transaction workflows

Security &amp; Fraud Detection
------------------------------

[](#security--fraud-detection)

Built-in fraud detection with configurable rules:

```
use LoyaltyRewards\Core\Exceptions\FraudDetectedException;
use LoyaltyRewards\Core\Services\FraudDetectionService;
use LoyaltyRewards\Domain\ValueObjects\{Currency, CustomerId, Money, TransactionContext};

$fraudDetection = new FraudDetectionService();
$customerId = CustomerId::fromString('customer_12345');
$account = $accountRepository->findByCustomerId($customerId);
$amount = Money::fromDollars(99.99, Currency::USD());
$context = TransactionContext::earning('electronics', 'online_store');

// Automatic fraud checking on all transactions
$fraudResult = $fraudDetection->analyze($account, $amount, $context);

if ($fraudResult->shouldBlock()) {
    throw new FraudDetectedException('Transaction blocked');
}
```

Detection Methods:

- Velocity checking (transaction frequency)
- Amount anomaly detection
- Pattern recognition
- Account behavior analysis

Performance
-----------

[](#performance)

Benchmarked Performance:

- Single Transaction: &lt; 100ms average
- Bulk Operations: 1000 transactions in &lt; 10 seconds
- Memory Usage: &lt; 50MB for 1000 transactions
- Database Queries: Optimized with proper indexing

Scalability Features:

- Connection pooling support
- Caching layer integration
- Async queue processing
- Horizontal scaling ready

Enterprise Features
-------------------

[](#enterprise-features)

### Audit &amp; Compliance

[](#audit--compliance)

- Complete transaction audit trails
- Regulatory compliance reporting
- Data retention policies
- Encrypted sensitive data storage

### Multi-Currency Support

[](#multi-currency-support)

- 7+ supported currencies (USD, EUR, GBP, NGN, etc.)
- Automatic currency conversion
- Regional formatting
- Exchange rate integration ready

### Event-Driven Architecture

[](#event-driven-architecture)

- Domain events for all state changes
- Easy integration with external systems
- Webhook support ready
- Real-time notifications

Documentation
-------------

[](#documentation)

- [API Reference (API.md)](API.md) — Complete method documentation
- [Architecture Guide (ARCHITECTURE.md)](ARCHITECTURE.md) — Technical design decisions
- [Core Policy Engine Guide (CORE\_POLICY\_ENGINE.md)](CORE_POLICY_ENGINE.md) — Plan config, typed policy results, adapter boundaries, and release checklist
- [Examples (EXAMPLES.md)](EXAMPLES.md) — 10+ real-world implementations
- [Configuration (CONFIGURATION.md)](CONFIGURATION.md) — Setup and customization options
- [Laravel Adapter](https://github.com/mbsoft31/loyalty-laravel-pro) — Service provider, config, and migrations

Release Guide
-------------

[](#release-guide)

To cut a release:

```
# bump version via git tag (Composer reads tags)
git tag -a v1.3.1 -m "v1.3.1"
git push origin v1.3.1

# (optional) update Packagist after pushing tags
# core:     https://packagist.org/packages/mbsoft31/loyalty-rewards
# adapter:  https://packagist.org/packages/mbsoft31/loyalty-laravel-pro
```

CI runs unit + integration tests on PHP 8.3, 8.4, and 8.5. Coverage gate enforces ≥80% on PHP 8.3.

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

[](#contributing)

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

### Development Setup

[](#development-setup)

```
git clone https://github.com/mbsoft31/loyalty-rewards.git
cd loyalty-rewards
composer install
composer test
```

License
-------

[](#license)

This project is licensed under the MIT License — see the LICENSE file for details.

Links
-----

[](#links)

- GitHub Repository:
- Issues:
- Discussions:
- Releases:

Built by mbsoft31 — Empowering businesses with flexible, scalable loyalty solutions.

###  Health Score

45

—

FairBetter than 91% of packages

Maintenance94

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 60.6% 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

Every ~42 days

Recently: every ~1 days

Total

7

Last Release

27d ago

PHP version history (2 changes)v1.0.0PHP ^8.2

v1.1.1PHP ^8.3

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/425849?v=4)[Jim Welch](/maintainers/mbsoft)[@mbsoft](https://github.com/mbsoft)

---

Top Contributors

[![mbsoft31](https://avatars.githubusercontent.com/u/14237661?v=4)](https://github.com/mbsoft31 "mbsoft31 (20 commits)")[![nexus-scholar](https://avatars.githubusercontent.com/u/233639653?v=4)](https://github.com/nexus-scholar "nexus-scholar (13 commits)")

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/mbsoft31-loyalty-rewards/health.svg)

```
[![Health](https://phpackages.com/badges/mbsoft31-loyalty-rewards/health.svg)](https://phpackages.com/packages/mbsoft31-loyalty-rewards)
```

###  Alternatives

[symfony/symfony

The Symfony PHP framework

31.4k87.2M2.2k](/packages/symfony-symfony)[symfony/mailer

Helps sending emails

1.6k409.1M1.4k](/packages/symfony-mailer)[shopware/platform

The Shopware e-commerce core

3.4k1.5M3](/packages/shopware-platform)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

585.6M577](/packages/shopware-core)[grumpydictator/firefly-iii

Firefly III: a personal finances manager.

23.9k69.5k](/packages/grumpydictator-firefly-iii)[phpro/soap-client

A general purpose SoapClient library

8896.1M54](/packages/phpro-soap-client)

PHPackages © 2026

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