PHPackages                             matt-di/laravel-telebirr - 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. matt-di/laravel-telebirr

ActiveLibrary[Payment Processing](/categories/payments)

matt-di/laravel-telebirr
========================

Telebirr payment gateway integration for Laravel applications

v1.0.0(7mo ago)00[1 issues](https://github.com/Matt-di/laravel-telebirr/issues)MITPHPPHP ^8.1CI failing

Since Nov 14Pushed 1mo agoCompare

[ Source](https://github.com/Matt-di/laravel-telebirr)[ Packagist](https://packagist.org/packages/matt-di/laravel-telebirr)[ RSS](/packages/matt-di-laravel-telebirr/feed)WikiDiscussions master Synced today

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

Laravel Telebirr Payment Gateway
================================

[](#laravel-telebirr-payment-gateway)

[![Latest Version on Packagist](https://camo.githubusercontent.com/97fd51ac4a1b69ea3a098bbf81f72d86fbe981a31e1184866819dd1fdb70f42a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f4d6174742d64692f6c61726176656c2d74656c65626972722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/Matt-di/laravel-telebirr)[![Total Downloads](https://camo.githubusercontent.com/f8e2d176a703ed12bbb94e00cca87fc3287c7393b948e07702a354aee986cbd0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f4d6174742d64692f6c61726176656c2d74656c65626972722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/Matt-di/laravel-telebirr)[![License](https://camo.githubusercontent.com/2a8a1f21d8c16ac843e3bf7e3af65410e826a17d3485e06e00c207ac7a8ddec8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f4d6174742d64692f6c61726176656c2d74656c65626972722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/Matt-di/laravel-telebirr)

Telebirr payment gateway integration for Laravel applications with support for single and multi-merchant setups.

🎯 Integration Type
------------------

[](#-integration-type)

**This package is designed for Telebirr Super App integration** where the frontend handles payment requests through the Telebirr mobile application.

- **Backend Role:** Generates signed payment requests and handles webhooks
- **Frontend Role:** Uses Telebirr mobile SDK to process payments
- **📖 Frontend Integration:** Refer to [Telebirr Developer Documentation](https://developer.telebirr.et/) for mobile app integration details
- **🔗 Official Resources:** Check Telebirr's official documentation for SDK implementation and best practices

Features
--------

[](#features)

- 🚀 **Simple Setup** - Get started in minutes with zero configuration
- 🏪 **Multi-Merchant Support** - Perfect for multi-branch or multi-store applications
- 🔐 **Enterprise Security** - RSA PSS signatures, webhook verification, SSL controls
- ⚡ **High Performance** - Token caching, queue-based processing, retry logic
- 🛠 **Developer Friendly** - Artisan commands, comprehensive logging, extensive configuration
- 🔧 **Highly Configurable** - Extensive customization options for any use case
- 📱 **Mobile SDK Ready** - Raw request generation for Telebirr mobile applications
- 🎯 **Event Driven** - Laravel events for payment lifecycle hooks

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

[](#installation)

### Basic Setup (Single Merchant)

[](#basic-setup-single-merchant)

```
composer require matt-di/laravel-telebirr
php artisan telebirr:install
```

### Multi-Merchant Setup

[](#multi-merchant-setup)

```
composer require Matt-di/laravel-telebirr
php artisan telebirr:install --mode=multi --run-migrations
```

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

[](#quick-start)

### 1. Configure Environment

[](#1-configure-environment)

Add your Telebirr credentials to `.env`:

```
# Single merchant mode
TELEBIRR_MODE=single
TELEBIRR_FABRIC_APP_ID=your_fabric_app_id
TELEBIRR_MERCHANT_APP_ID=your_merchant_app_id
TELEBIRR_MERCHANT_CODE=123456
TELEBIRR_APP_SECRET=your_app_secret
TELEBIRR_RSA_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"
```

### 2. Create Payment Request

[](#2-create-payment-request)

```
use Telebirr\LaravelTelebirr\Facades\Telebirr;

$rawRequest = Telebirr::initiatePayment([
    'txn_ref' => 'TXN_' . time(),
    'amount' => 150.00,
    'subject' => 'Order Payment'
]);

// Returns: "appid=MERCHANT123&merch_code=MC456&nonce_str=abc...&prepay_id=PRE123...&timestamp=202512021200&sign_type=SHA256WithRSA&sign=signed_data..."
```

### 3. Handle Webhook (Automatically Done)

[](#3-handle-webhook-automatically-done)

The package handles webhook verification, signature checking, and payment verification automatically.

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

[](#usage-examples)

### Single Merchant

[](#single-merchant)

#### Step 1: Configure Environment

[](#step-1-configure-environment)

Add your Telebirr credentials to `.env`:

```
TELEBIRR_MODE=single
TELEBIRR_FABRIC_APP_ID=your_fabric_app_id
TELEBIRR_MERCHANT_APP_ID=your_merchant_app_id
TELEBIRR_MERCHANT_CODE=your_merchant_code
TELEBIRR_APP_SECRET=your_app_secret
TELEBIRR_RSA_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nYOUR_PRIVATE_KEY_HERE\n-----END PRIVATE KEY-----"
```

#### Step 2: Install the Package

[](#step-2-install-the-package)

```
php artisan telebirr:install
```

#### Step 3: Initiate a Payment

[](#step-3-initiate-a-payment)

```
use Telebirr\LaravelTelebirr\Facades\Telebirr;

$rawRequest = Telebirr::initiatePayment([
    'txn_ref' => 'TXN_' . time(),
    'amount' => 150.00,
    'subject' => 'Order Payment'
]);

// Returns a signed query string for the mobile SDK:
// "appid=MERCHANT123&merch_code=MC456&nonce_str=abc...&prepay_id=PRE123...&timestamp=202512021200&sign_type=SHA256WithRSA&sign=signed_data..."
```

#### Step 4: Web Checkout (Browser-based Payment)

[](#step-4-web-checkout-browser-based-payment)

For web-based checkout, the package provides a dedicated API endpoint that handles the entire flow:

**Using the API endpoint (recommended):**

```
// POST /api/telebirr/web-checkout
// Request:
{
    "invoice_id": "INV_12345",
    "amount": 150.00,
    "subject": "Order Payment"
}

// Response:
{
    "success": true,
    "data": {
        "invoice_id": "INV_12345",
        "prepay_id": "PRE123456789",
        "checkout_url": "https://developerportal.ethiotelebirr.et:38443/payment/web/paygate?appid=...&prepay_id=...&sign=...",
        "amount": 150.00,
        "subject": "Order Payment"
    }
}
```

Then redirect the user to the checkout URL:

```
// Frontend example
fetch("/api/telebirr/web-checkout", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    invoice_id: "INV_12345",
    amount: 150.0,
    subject: "Order Payment",
  }),
})
  .then((res) => res.json())
  .then((data) => {
    if (data.success) {
      window.location.href = data.data.checkout_url;
    }
  });
```

**Using the Facade directly:**

```
use Telebirr\LaravelTelebirr\Facades\Telebirr;

// First, initiate payment to get a prepay_id
$rawRequest = Telebirr::initiatePayment([
    'txn_ref' => 'TXN_' . time(),
    'amount' => 150.00,
    'subject' => 'Order Payment'
]);

// Parse the prepay_id from the raw request
parse_str($rawRequest, $params);
$prepayId = $params['prepay_id'];

// Generate the checkout URL
$checkoutUrl = Telebirr::generateCheckoutUrl($prepayId);

// Redirect user to the checkout URL
return redirect($checkoutUrl);
```

```

#### USSD Push Payment (C2B)

```php
use Telebirr\LaravelTelebirr\Facades\Telebirr;

// Initiate USSD push payment
$rawRequest = Telebirr::ussdPush([
    'phone'   => '0912345678', // or international format +2519...
    'txn_ref' => 'TXN_' . time(),
    'amount'  => 150.00,
    'subject' => 'Order Payment',
    // Optional overrides
    // 'trade_type' => 'Checkout',
    // 'timeout_express' => '30m',
]);

// $rawRequest is a signed query string that can be sent via USSD or SMS gateway

```

#### Custom Parameter Overrides

[](#custom-parameter-overrides)

You can override any request parameter by passing additional keys in the order data. For example:

```
$rawRequest = Telebirr::initiatePayment([
    'txn_ref' => 'TXN_' . time(),
    'amount'  => 200.00,
    'subject' => 'Custom Order',
    // Override trade type and timeout
    'trade_type' => 'Purchase',
    'timeout_express' => '45m',
]);
```

All other default parameters (like `appid`, `merch_code`, `nonce_str`) will be generated automatically.

```
The checkout URL is configured via environment variables:

```env
TELEBIRR_WEB_BASE_URL=https://developerportal.ethiotelebirr.et:38443/payment/web/paygate?
TELEBIRR_WEB_VERSION=1.0
TELEBIRR_WEB_TRADE_TYPE=Checkout

```

#### Step 5: Handle Webhook

[](#step-5-handle-webhook)

The package automatically handles incoming webhooks. Configure your webhook URL:

```
TELEBIRR_WEBHOOK_URL=https://your-domain.com/api/telebirr/webhook
```

Test your webhook:

```
php artisan telebirr:setup-webhook --test
```

### Multi-Merchant (Branch-Based)

[](#multi-merchant-branch-based)

```
// Payment for specific branch
Telebirr::initiatePayment([
    'txn_ref' => 'TXN_123',
    'amount' => 100.00,
    'subject' => 'Branch Order'
], ['branch_id' => 1]);
```

### Custom Context

[](#custom-context)

```
// Organized by stores
Telebirr::initiatePayment($data, ['store_id' => 5]);

// Or even custom types
Telebirr::initiatePayment($data, ['owner_type' => 'restaurant', 'owner_id' => 10]);
```

### Payment Verification

[](#payment-verification)

```
$result = Telebirr::verifyPayment('TXN_123');
if ($result && $result['order_status'] === 'PAY_SUCCESS') {
    // Payment successful
}
```

### Auth Token Retrieval

[](#auth-token-retrieval)

```
$userInfo = Telebirr::getAuthToken($accessToken);
```

### Error Handling

[](#error-handling)

```
try {
    $paymentRequest = Telebirr::initiatePayment([
        'txn_ref' => 'TXN_' . time(),
        'amount' => 150.00,
        'subject' => 'Order Payment',
    ]);

    // Process successful payment initiation

} catch (\Telebirr\LaravelTelebirr\Exceptions\TelebirrException $e) {
    // Handle payment initiation errors
    Log::error('Telebirr payment failed: ' . $e->getMessage());

    // Show user-friendly error message
    return back()->withErrors(['payment' => 'Payment initiation failed. Please try again.']);
}
```

Event Listeners
---------------

[](#event-listeners)

Listen to payment lifecycle events:

```
Event::listen(Telebirr\LaravelTelebirr\Events\PaymentInitiated::class, function ($event) {
    // Payment initiated
});

Event::listen(Telebirr\LaravelTelebirr\Events\PaymentVerified::class, function ($event) {
    // Payment verified and successful
    // Update your order/invoice status here
});

Event::listen(Telebirr\LaravelTelebirr\Events\WebhookReceived::class, function ($event) {
    // Raw webhook received
});
```

Testing
-------

[](#testing)

Test your integration:

```
# Test API connectivity
php artisan telebirr:test-connection

# Setup and test webhooks
php artisan telebirr:setup-webhook --test
```

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

[](#configuration)

### Single Merchant Mode

[](#single-merchant-mode)

- Uses global ENV configuration
- No database required
- Perfect for simple applications

### Multi-Merchant Mode

[](#multi-merchant-mode)

- Database-driven merchant management
- Configurable relationship mappings
- Enterprise-ready for complex applications

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

[](#api-reference)

### Facade Methods

[](#facade-methods)

```
Telebirr::initiatePayment(array $data, array $context = [])
Telebirr::verifyPayment(string $transactionId, array $context = [])
Telebirr::queryOrder(string $orderId, array $context = [])
Telebirr::getAuthToken(string $accessToken, array $context = [])
Telebirr::handleWebhook(Request $request)
```

### HTTP Endpoints

[](#http-endpoints)

- `POST /api/telebirr/order` - Create payment order
- `POST /api/telebirr/verify` - Verify payment status
- `POST /api/telebirr/query` - Query order details
- `POST /api/telebirr/auth` - Get auth token
- `POST /api/telebirr/webhook` - Webhook handler

Advanced Configuration
----------------------

[](#advanced-configuration)

Publish config for full customization:

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

### Custom Merchant Resolver

[](#custom-merchant-resolver)

```
// config/telebirr.php
'merchant' => [
    'resolver' => App\Services\CustomMerchantResolver::class,
],
```

### Custom Webhook Handler

[](#custom-webhook-handler)

```
'webhook' => [
    'handler' => App\Services\CustomWebhookHandler::class,
],
```

Migration Guide
---------------

[](#migration-guide)

### From Single to Multi-Merchant

[](#from-single-to-multi-merchant)

1. Change mode: `TELEBIRR_MODE=multi`
2. Run: `php artisan telebirr:install --mode=multi --run-migrations`
3. Add merchant records to `telebirr_merchants` table
4. Update code to pass merchant context where needed

Complete Integration Example
----------------------------

[](#complete-integration-example)

Here's a complete real-world integration example:

```
