定制 digitaldev-lx/laravel-eupago 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

digitaldev-lx/laravel-eupago

Composer 安装命令:

composer require digitaldev-lx/laravel-eupago

包简介

A Laravel package for making payments through the EuPago API.

README 文档

README

laravel-eupago-repo-banner

Laravel EuPago

A comprehensive Laravel package for integrating with the EuPago payment gateway API. Support for Multibanco, MB Way, Credit Card, Google Pay, Apple Pay, and Payouts management.

Latest version GitHub license

Requirements

Release PHP Laravel
3.0.0 >= 8.4 11 || 12 || 13
2.3.0 8.3, 8.4 11 || 12
2.2.0 >= 8.3 11
2.1.0 >= 8.1 10

Installation

composer require digitaldev-lx/laravel-eupago

Publish the migration

php artisan vendor:publish --provider=DigitaldevLx\\LaravelEupago\\Providers\\EuPagoServiceProvider --tag=migrations

Run the migration

php artisan migrate

Publish the configuration file (optional)

php artisan vendor:publish --provider=DigitaldevLx\\LaravelEupago\\Providers\\EuPagoServiceProvider --tag=config

Publish the translations files (optional)

php artisan vendor:publish --provider=DigitaldevLx\\LaravelEupago\\Providers\\EuPagoServiceProvider --tag=translations

Configuration

Environment Variables

Add the following to your .env file:

EUPAGO_ENV=test          # or 'prod'
EUPAGO_API_KEY=your_api_key
EUPAGO_CHANNEL=your_channel

# Optional callback hardening
EUPAGO_ALLOWED_IPS=        # comma-separated EuPago source IPs; empty = accept all
EUPAGO_LOG_CALLBACKS=true  # log a redacted callback summary (never the API key)

There are two environments available: "test" and "prod". Use the "test" environment during development and switch to "prod" when your application is ready for production.

Callback Security

The callback endpoint (GET /eupago/callback) is the trust boundary that confirms payments, so it is hardened as follows:

  • API key authentication — the chave_api parameter is compared against EUPAGO_API_KEY in constant time (hash_equals). Invalid callbacks are rejected with an HTTP 422 and never reveal which field failed.
  • No secret leakage — the API key is never logged (only a redacted summary is, when EUPAGO_LOG_CALLBACKS=true) and is stripped from the CallbackReceived event payload.
  • Atomic confirmation — payments are confirmed inside a locked transaction, so concurrent callbacks for the same reference cannot fire the "paid" event twice.
  • Rate limiting — the route is throttled to 60 requests/minute per IP.
  • Optional IP allowlist — set EUPAGO_ALLOWED_IPS to the EuPago callback source IPs to reject any other origin. Leave it empty to accept all (default).

Payment Methods

Multibanco (MB) References

Usage

use DigitaldevLx\LaravelEupago\MB\MB;

$order = Order::find(1);

$mb = new MB(
    $order->value,              // float: payment amount
    $order->id,                 // string: external identifier
    $order->date,               // string: start date (Y-m-d)
    $order->payment_limit_date, // string: end date (Y-m-d)
    $order->value,              // float: minimum value
    $order->value,              // float: maximum value
    0                           // bool: allow duplicated payments
);

try {
    $mbReferenceData = $mb->create();

    if ($mb->hasErrors()) {
        // handle errors
    }

    $order->mbReferences()->create($mbReferenceData);
} catch (\Exception $e) {
    // handle exception
}

Response format:

[
    'success' => true,
    'state' => 0,
    'response' => "OK",
    'reference' => "000001236",
    'value' => "3.00000",
    'entity' => "11249",
]

Using the Trait

use DigitaldevLx\LaravelEupago\Traits\Mbable;

class Order extends Model
{
    use Mbable;
}

// Retrieve references
$order = Order::find(1);
$mbReferences = $order->mbReferences;

Callback

The package handles callbacks automatically, updating the payment state and triggering events.

Endpoint: GET /eupago/callback Payment Method Code: PC:PT

MB Way References

Usage

use DigitaldevLx\LaravelEupago\MBWay\MBWay;

$order = Order::find(1);

$mbway = new MBWay(
    $order->value,      // float: payment amount
    $order->id,         // int: external identifier
    $customer->phone,   // string: phone number (alias)
    'Order payment'     // string|null: optional description
);

try {
    $mbwayReferenceData = $mbway->create();

    if ($mbway->hasErrors()) {
        // handle errors
    }

    $order->mbwayReferences()->create($mbwayReferenceData);
} catch (\Exception $e) {
    // handle exception
}

Using the Trait

use DigitaldevLx\LaravelEupago\Traits\Mbwayable;

class Order extends Model
{
    use Mbwayable;
}

// Retrieve references
$order = Order::find(1);
$mbwayReferences = $order->mbwayReferences;

Callback

Endpoint: GET /eupago/callback Payment Method Code: MW:PT

Credit Card

Single Payment

use DigitaldevLx\LaravelEupago\CreditCard\CreditCard;

$creditCard = new CreditCard(
    150.00,                                // float: amount
    'ORDER-456',                           // string: identifier
    'https://example.com/success',         // string: success URL
    'https://example.com/fail',            // string: fail URL
    'https://example.com/back',            // string: back URL
    'EN',                                  // string: language (PT, EN, FR, ES)
    'EUR',                                 // string: currency
    'customer@example.com',                // string|null: customer email
    60                                     // int|null: minutes form up
);

try {
    $result = $creditCard->create();

    if ($result['success']) {
        // Redirect user to $result['redirect_url']
        // Store $result['reference'] and $result['transaction_id']
    }
} catch (\Exception $e) {
    // handle exception
}

Maximum: €3,999 per transaction Callback Code: CC:PT

Recurring Payments (Subscriptions)

Step 1: Create Authorization

use DigitaldevLx\LaravelEupago\CreditCard\CreditCardRecurrence;

$recurrence = new CreditCardRecurrence(
    'SUBSCRIPTION-123',                    // string: identifier
    'https://example.com/success',         // string: success URL
    'https://example.com/fail',            // string: fail URL
    'https://example.com/back',            // string: back URL
    'PT'                                   // string: language
);

try {
    $result = $recurrence->create();

    if ($result['success']) {
        // Redirect user to authorize subscription
        // Store $result['subscription_id']
    }
} catch (\Exception $e) {
    // handle exception
}

Step 2: Execute Recurring Payment

use DigitaldevLx\LaravelEupago\CreditCard\CreditCardRecurringPayment;

$payment = new CreditCardRecurringPayment(
    'subscription-id-from-authorization',  // string: subscription ID
    50.00,                                 // float: amount
    'customer@example.com',                // string|null: customer email
    true                                   // bool: notify customer
);

try {
    $result = $payment->create();

    if ($result['success']) {
        // Payment processed
    }
} catch (\Exception $e) {
    // handle exception
}

Using the Trait

use DigitaldevLx\LaravelEupago\Traits\Creditcardable;
use DigitaldevLx\LaravelEupago\Traits\Creditcardrecurrable;

class Order extends Model
{
    use Creditcardable;
}

class Subscription extends Model
{
    use Creditcardrecurrable;
}

Google Pay

use DigitaldevLx\LaravelEupago\GooglePay\GooglePay;

$googlePay = new GooglePay(
    150.00,                                // float: amount
    'ORDER-456',                           // string: identifier
    'https://example.com/success',         // string: success URL
    'https://example.com/fail',            // string: fail URL
    'https://example.com/back',            // string: back URL
    'EN',                                  // string: language
    'EUR',                                 // string: currency
    'customer@example.com',                // string|null: email
    'John',                                // string|null: first name
    'Doe',                                 // string|null: last name
    'PT',                                  // string|null: country code
    true,                                  // bool: notify customer
    60                                     // int|null: minutes form up
);

try {
    $result = $googlePay->create();

    if ($result['success']) {
        // Redirect to $result['redirect_url']
    }
} catch (\Exception $e) {
    // handle exception
}

Maximum: €99,999 per transaction Callback Code: GP:PT

Using the Trait

use DigitaldevLx\LaravelEupago\Traits\Googlepayable;

class Order extends Model
{
    use Googlepayable;
}

Apple Pay

use DigitaldevLx\LaravelEupago\ApplePay\ApplePay;

$applePay = new ApplePay(
    150.00,                                // float: amount
    'ORDER-456',                           // string: identifier
    'https://example.com/success',         // string: success URL
    'https://example.com/fail',            // string: fail URL
    'https://example.com/back',            // string: back URL
    'EN',                                  // string: language
    'EUR',                                 // string: currency
    'customer@example.com',                // string|null: email
    'John',                                // string|null: first name
    'Doe',                                 // string|null: last name
    'PT',                                  // string|null: country code
    true,                                  // bool: notify customer
    60                                     // int|null: minutes form up
);

try {
    $result = $applePay->create();

    if ($result['success']) {
        // Redirect to $result['redirect_url']
    }
} catch (\Exception $e) {
    // handle exception
}

Callback Code: AP:PT

Using the Trait

use DigitaldevLx\LaravelEupago\Traits\Applepayable;

class Order extends Model
{
    use Applepayable;
}

Payouts Management

List Payouts

Retrieve all payouts for a specific date range using OAuth Bearer Token authentication.

use DigitaldevLx\LaravelEupago\Payouts\Payout;

$payout = new Payout(
    '2024-01-01',              // string: start date (yyyy-mm-dd)
    '2024-01-31',              // string: end date (yyyy-mm-dd)
    'your-bearer-token'        // string: OAuth Bearer Token
);

try {
    $result = $payout->list();

    if ($result['success']) {
        foreach ($result['payouts'] as $payout) {
            // Process payout data
        }
    }
} catch (\Exception $e) {
    // handle exception
}

List Payout Transactions

Retrieve all transaction details within a date range.

use DigitaldevLx\LaravelEupago\Payouts\PayoutTransaction;

$transactions = new PayoutTransaction(
    '2024-01-01',              // string: start date (yyyy-mm-dd)
    '2024-01-31',              // string: end date (yyyy-mm-dd)
    'your-bearer-token'        // string: OAuth Bearer Token
);

try {
    $result = $transactions->list();

    if ($result['success']) {
        foreach ($result['transactions'] as $transaction) {
            // Process transaction data
            // Includes: trid, date, amount, payment_method, status
        }
    }
} catch (\Exception $e) {
    // handle exception
}

Note: For single-day queries, use the same date for both start_date and end_date.

Callback Parameters

All payment callbacks receive the following parameters:

Name Type Description
valor float Payment amount
canal string Channel identifier
referencia string Payment reference
transacao string Transaction ID
identificador integer External identifier
mp string Payment method code
chave_api string API key
data date:Y-m-d H:i:s Transaction date
entidade string Entity code
comissao float Commission
local string Transaction location

Events

The package dispatches events throughout the payment lifecycle.

Reference Creation Events

  • MBReferenceCreated / MBReferenceCreationFailed
  • MBWayReferenceCreated / MBWayReferenceCreationFailed
  • CreditCardReferenceCreated / CreditCardReferenceCreationFailed
  • CreditCardRecurrenceAuthorizationCreated / CreditCardRecurrenceAuthorizationCreationFailed
  • CreditCardRecurringPaymentCreated / CreditCardRecurringPaymentCreationFailed
  • GooglePayReferenceCreated / GooglePayReferenceCreationFailed
  • ApplePayReferenceCreated / ApplePayReferenceCreationFailed

Payment Events

  • MBReferencePaid
  • MBWayReferencePaid
  • CreditCardReferencePaid
  • GooglePayReferencePaid
  • ApplePayReferencePaid

Expiration Events

  • MBReferenceExpired
  • MBWayReferenceExpired

Callback Events

  • CallbackReceived - Dispatched for every valid callback. The payload excludes the API key and channel.
  • InvalidCallbackReceived - Dispatched when a callback fails validation (wrong API key/channel, unknown payment method, malformed data). Carries the validation errors and a redacted callbackData (the API key and channel are excluded).

Invalid callbacks are rejected with a generic HTTP 422 response (no field-level detail), while listeners can still inspect the failure through InvalidCallbackReceived.

Listening to Events

Auto-discovery (recommended):

Create a listener class in app/Listeners/ — Laravel automatically discovers it via the type-hinted handle() method:

// app/Listeners/HandleMBPayment.php
namespace App\Listeners;

use DigitaldevLx\LaravelEupago\Events\MBReferencePaid;
use Illuminate\Support\Facades\Mail;

class HandleMBPayment
{
    public function handle(MBReferencePaid $event): void
    {
        $reference = $event->reference;

        $reference->mbable->update(['status' => 'paid']);

        Mail::to($reference->mbable->user)->send(
            new \App\Mail\PaymentConfirmed($reference)
        );
    }
}

No manual registration needed. Laravel scans app/Listeners/ automatically.

Manual registration:

Register listeners in your app/Providers/AppServiceProvider.php:

use DigitaldevLx\LaravelEupago\Events\MBReferencePaid;
use Illuminate\Support\Facades\Event;

public function boot(): void
{
    Event::listen(
        MBReferencePaid::class,
        SendPaymentConfirmationEmail::class,
    );
}

Closure listeners:

use DigitaldevLx\LaravelEupago\Events\MBReferencePaid;
use Illuminate\Support\Facades\Event;

Event::listen(function (MBReferencePaid $event) {
    $reference = $event->reference;
    $reference->mbable->update(['status' => 'paid']);
});

Commands

Check Expired References

Check for expired payment references and dispatch expiration events:

php artisan eupago:check-expired

This command finds all MB references where end_date has passed and state is 0 (unpaid), then dispatches MBReferenceExpired event for each.

Scheduling:

Laravel 11 & 12:

Add to your routes/console.php:

use Illuminate\Support\Facades\Schedule;

Schedule::command('eupago:check-expired')->daily();

Laravel 10:

Add to your app/Console/Kernel.php:

protected function schedule(Schedule $schedule)
{
    $schedule->command('eupago:check-expired')->daily();
}

Testing

The package includes comprehensive test coverage using Pest PHP.

Running Tests

# Run all tests
composer test

# Run with coverage (minimum 80% required)
composer test:coverage

# Run specific test file
vendor/bin/pest tests/Unit/MB/MBTest.php

Code Style

# Fix code style with Pint
composer lint

# Check code style without fixing
composer lint:check

Static Analysis

# Run Larastan Level 6 analysis
composer analyse

Using Factories in Tests

use DigitaldevLx\LaravelEupago\Models\MbReference;
use DigitaldevLx\LaravelEupago\Models\MbwayReference;
use DigitaldevLx\LaravelEupago\Models\CreditCardReference;
use DigitaldevLx\LaravelEupago\Models\GooglePayReference;
use DigitaldevLx\LaravelEupago\Models\ApplePayReference;

// Create unpaid reference
$reference = MbReference::factory()->create();

// Create paid reference
$paidReference = MbReference::factory()->paid()->create();

// Create expired reference
$expiredReference = MbReference::factory()->expired()->create();

// Other payment methods
$mbwayReference = MbwayReference::factory()->create();
$ccReference = CreditCardReference::factory()->paid()->create();
$googlePayReference = GooglePayReference::factory()->create();
$applePayReference = ApplePayReference::factory()->paid()->create();

Contributing

Please see CONTRIBUTING.md for details on how to contribute to this project.

Changelog

Please see CHANGELOG.md for details on recent changes.

License

digitaldev-lx/laravel-eupago is open-sourced software licensed under the MIT license.

About DigitalDev

DigitalDev is a digital transformation agency based in Lisbon, Portugal. We specialize in transforming ideas into digital solutions that drive business growth online.

With expertise in custom web development, system integration, DevOps, AI implementation, and advanced search systems, we help businesses scale beyond generic templates with practical, data-driven solutions. Our tech stack includes Laravel, Livewire, React, and modern cloud infrastructure.

Contact: geral@digitaldev.pt | +351 961 546 227

digitaldev-lx/laravel-eupago 适用场景与选型建议

digitaldev-lx/laravel-eupago 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 978 次下载、GitHub Stars 达 1, 最近一次更新时间为 2024 年 05 月 14 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「laravel」 「Eupago」 「codetech」 「mb references」 「laravel-eupago」 「referências multibanco」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 digitaldev-lx/laravel-eupago 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 digitaldev-lx/laravel-eupago 我们能提供哪些服务?
定制开发 / 二次开发

基于 digitaldev-lx/laravel-eupago 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 978
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 18
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 2
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-05-14