PHPackages                             bits-devteam/xpay-php-sdk - 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. bits-devteam/xpay-php-sdk

ActiveLibrary

bits-devteam/xpay-php-sdk
=========================

Official PHP SDK for X-Pay payment processing platform

v1.0.9(4mo ago)00MITPHPPHP ^8.1CI failing

Since Jan 1Pushed 4mo agoCompare

[ Source](https://github.com/Sound-X-Team/xpay-php-sdk)[ Packagist](https://packagist.org/packages/bits-devteam/xpay-php-sdk)[ RSS](/packages/bits-devteam-xpay-php-sdk/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (12)Versions (11)Used By (0)

X-Pay PHP SDK
=============

[](#x-pay-php-sdk)

The official PHP SDK for the X-Pay payment processing platform. This SDK provides a simple and intuitive interface for integrating X-Pay's payment services into your PHP applications, with special support for Laravel.

[![Latest Version](https://camo.githubusercontent.com/717e32982bb3f33583e75a352f21a3f7ea25fe9df9d89e1e9cca1f70ede70be4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f787061792f7068702d73646b2e737667)](https://packagist.org/packages/xpay/php-sdk)[![PHP Version](https://camo.githubusercontent.com/3f6653d30e55bf445bbd857d50c204972e0aa5dc5a055a5e911e85a5334f7795/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f787061792f7068702d73646b2e737667)](https://packagist.org/packages/xpay/php-sdk)[![License](https://camo.githubusercontent.com/02c35b1c952dfabb7c7c370020595971b8ebb15f4845d050f5a3f64c72fb181a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f787061792f7068702d73646b2e737667)](https://packagist.org/packages/xpay/php-sdk)

Features
--------

[](#features)

- 🚀 **Easy Integration**: Simple, intuitive API design
- 💳 **Multiple Payment Methods**: Stripe, Mobile Money (Ghana, Liberia, Nigeria, Uganda, Rwanda), X-Pay Wallet
- 🏗️ **Laravel Support**: Service provider, facade, middleware, and Artisan commands
- 🔐 **Secure**: Built-in signature verification for webhooks
- 💰 **Currency Utilities**: Proper handling of currency conversion and formatting
- 🛡️ **Type Safety**: Full PHP 8.1+ type hints and readonly classes
- ✅ **Well Tested**: Comprehensive unit and integration tests
- 📖 **Documentation**: Complete API documentation and examples

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- ext-json
- ext-openssl
- Laravel 10+ (for Laravel integration features)

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

[](#installation)

Install via Composer:

```
composer require xpay/php-sdk
```

### Laravel Integration

[](#laravel-integration)

If you're using Laravel, the service provider will be auto-discovered. Publish the configuration file:

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

Add your X-Pay credentials to your `.env` file:

```
XPAY_API_KEY=xpay_sandbox_your_api_key_here
XPAY_ENVIRONMENT=sandbox
XPAY_WEBHOOK_SECRET=your_webhook_secret_here
```

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

[](#quick-start)

### Basic Usage

[](#basic-usage)

```
use XPay\Types\XPayConfig;
use XPay\Types\PaymentRequest;
use XPay\Types\PaymentMethodData;
use XPay\XPay;

// Initialize the client
$config = new XPayConfig(
    apiKey: 'xpay_sandbox_your_api_key_here',
    environment: 'sandbox'
);

$xpay = new XPay($config);

// Create a payment
$payment = $xpay->payments->create(new PaymentRequest(
    amount: '10.00',
    paymentMethod: 'stripe',
    currency: 'USD',
    description: 'Test payment',
    paymentMethodData: new PaymentMethodData(
        paymentMethodTypes: ['card']
    )
));

echo "Payment ID: {$payment->id}\n";
echo "Status: {$payment->status}\n";
echo "Client Secret: {$payment->clientSecret}\n";
```

### Laravel Usage

[](#laravel-usage)

```
use XPay\Laravel\Facades\XPay;
use XPay\Types\PaymentRequest;

// Using the facade
$payment = XPay::payments()->create(new PaymentRequest(
    amount: '25.00',
    paymentMethod: 'momo',
    currency: 'GHS',
    description: 'Mobile money payment'
));

// Test API connectivity
php artisan xpay:test

// List available payment methods
php artisan xpay:payment-methods
```

Payment Methods
---------------

[](#payment-methods)

### Stripe Payments

[](#stripe-payments)

```
$payment = $xpay->payments->create(new PaymentRequest(
    amount: '10.00',
    paymentMethod: 'stripe',
    currency: 'USD',
    paymentMethodData: new PaymentMethodData(
        paymentMethodTypes: ['card']
    ),
    successUrl: 'https://yourapp.com/success',
    cancelUrl: 'https://yourapp.com/cancel'
));
```

### Mobile Money

[](#mobile-money)

```
// Ghana Mobile Money
$payment = $xpay->payments->create(new PaymentRequest(
    amount: '50.00',
    paymentMethod: 'momo',
    currency: 'GHS',
    paymentMethodData: new PaymentMethodData(
        phoneNumber: '+233541234567'
    )
));

// Other countries
$payment = $xpay->payments->create(new PaymentRequest(
    amount: '25.00',
    paymentMethod: 'momo_nigeria', // or momo_liberia, momo_uganda, momo_rwanda
    currency: 'USD',
    paymentMethodData: new PaymentMethodData(
        phoneNumber: '+2341234567890'
    )
));
```

### X-Pay Wallet

[](#x-pay-wallet)

```
$payment = $xpay->payments->create(new PaymentRequest(
    amount: '15.00',
    paymentMethod: 'xpay_wallet',
    currency: 'USD',
    paymentMethodData: new PaymentMethodData(
        walletId: 'wallet_123',
        pin: '1234'
    )
));
```

Customer Management
-------------------

[](#customer-management)

```
use XPay\Types\CreateCustomerRequest;

// Create a customer
$customer = $xpay->customers->create(new CreateCustomerRequest(
    email: 'john@example.com',
    name: 'John Doe',
    phone: '+1234567890',
    metadata: ['source' => 'website']
));

// Retrieve a customer
$customer = $xpay->customers->retrieve('cust_123');

// Update a customer
$customer = $xpay->customers->update('cust_123', [
    'phone' => '+1987654321',
    'metadata' => ['updated' => true]
]);

// List customers
$result = $xpay->customers->list([
    'limit' => 20,
    'email' => 'john@example.com'
]);
```

Webhook Management
------------------

[](#webhook-management)

```
use XPay\Types\CreateWebhookRequest;

// Create a webhook
$webhook = $xpay->webhooks->create(new CreateWebhookRequest(
    url: 'https://yourapp.com/webhooks/xpay',
    events: ['payment.succeeded', 'payment.failed']
));

// Verify webhook signature
$isValid = $xpay->webhooks->verifySignature(
    $payload,
    $signature,
    $webhook->secret
);

// Parse webhook payload
$event = $xpay->webhooks->parsePayload($payload);
```

Laravel Webhook Handling
------------------------

[](#laravel-webhook-handling)

### Register the Middleware

[](#register-the-middleware)

Add to your `app/Http/Kernel.php`:

```
protected $routeMiddleware = [
    // ...
    'xpay.webhook' => \XPay\Laravel\Middleware\VerifyWebhookSignature::class,
];
```

### Create a Webhook Controller

[](#create-a-webhook-controller)

```
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class WebhookController extends Controller
{
    public function handle(Request $request): Response
    {
        $webhookData = $request->input('webhook_data');

        match ($webhookData['type']) {
            'payment.succeeded' => $this->handlePaymentSucceeded($webhookData['data']),
            'payment.failed' => $this->handlePaymentFailed($webhookData['data']),
            default => logger()->info('Unhandled webhook event', ['type' => $webhookData['type']])
        };

        return response('OK', 200);
    }

    private function handlePaymentSucceeded(array $data): void
    {
        // Handle successful payment
        $payment = $data['payment'];
        // Update order status, send confirmation email, etc.
    }
}
```

### Register the Route

[](#register-the-route)

```
// routes/api.php
Route::post('/webhooks/xpay', [WebhookController::class, 'handle'])
    ->middleware('xpay.webhook');
```

Currency Utilities
------------------

[](#currency-utilities)

```
use XPay\Utils\CurrencyUtils;

// Convert to smallest unit (cents)
$cents = CurrencyUtils::toSmallestUnit(10.50, 'USD'); // 1050

// Convert from smallest unit
$dollars = CurrencyUtils::fromSmallestUnit(1050, 'USD'); // 10.50

// Format for display
$formatted = CurrencyUtils::formatAmount(10.50, 'USD'); // $10.50

// Check supported currencies for payment method
$currencies = CurrencyUtils::getSupportedCurrencies('stripe'); // ['USD', 'EUR', 'GBP', 'GHS']

// Validate currency for payment method
CurrencyUtils::validateCurrency('momo', 'GHS'); // OK
CurrencyUtils::validateCurrency('momo', 'USD'); // Throws ValidationException
```

Error Handling
--------------

[](#error-handling)

The SDK provides structured error handling with specific exception types:

```
use XPay\Exceptions\XPayException;
use XPay\Exceptions\AuthenticationException;
use XPay\Exceptions\ValidationException;
use XPay\Exceptions\NetworkException;

try {
    $payment = $xpay->payments->create($paymentRequest);
} catch (AuthenticationException $e) {
    // Handle authentication errors (invalid API key, etc.)
    echo "Auth Error: {$e->getMessage()}";
} catch (ValidationException $e) {
    // Handle validation errors (invalid input data)
    echo "Validation Error: {$e->getMessage()}";
    echo "Details: " . json_encode($e->getDetails());
} catch (NetworkException $e) {
    // Handle network connectivity issues
    echo "Network Error: {$e->getMessage()}";
} catch (XPayException $e) {
    // Handle other X-Pay specific errors
    echo "X-Pay Error: {$e->getMessage()}";
    echo "Error Code: {$e->getErrorCode()}";
    echo "HTTP Status: {$e->getHttpStatus()}";
}
```

Testing
-------

[](#testing)

Run the test suite:

```
composer test
```

Run tests with coverage:

```
composer test-coverage
```

Run static analysis:

```
composer phpstan
```

Laravel Testing
---------------

[](#laravel-testing)

```
# Test API connectivity
php artisan xpay:test

# List payment methods
php artisan xpay:payment-methods
```

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

[](#configuration)

### Standalone Configuration

[](#standalone-configuration)

```
$config = new XPayConfig(
    apiKey: 'your_api_key',
    merchantId: 'merchant_123', // Optional
    environment: 'sandbox', // or 'live'
    baseUrl: 'https://custom-api.com', // Optional
    timeout: 30 // seconds
);
```

### Laravel Configuration

[](#laravel-configuration)

The configuration file (`config/xpay.php`) supports:

```
return [
    'api_key' => env('XPAY_API_KEY'),
    'merchant_id' => env('XPAY_MERCHANT_ID'),
    'environment' => env('XPAY_ENVIRONMENT', 'sandbox'),
    'base_url' => env('XPAY_BASE_URL'),
    'timeout' => env('XPAY_TIMEOUT', 30),

    'webhook' => [
        'secret' => env('XPAY_WEBHOOK_SECRET'),
        'tolerance' => env('XPAY_WEBHOOK_TOLERANCE', 300),
        'verify_signature' => env('XPAY_WEBHOOK_VERIFY_SIGNATURE', true),
    ],
];
```

Environment Detection
---------------------

[](#environment-detection)

The SDK automatically detects the environment from your API key prefix:

- `xpay_sandbox_*` or `pk_sandbox_*` → sandbox
- `xpay_live_*` or `pk_live_*` → live
- Unknown format → defaults to sandbox

Examples
--------

[](#examples)

See the [`examples/`](examples/) directory for complete working examples:

- [Basic Payment Processing](examples/basic-payment.php)
- [Webhook Management](examples/webhooks.php)
- [Customer Management](examples/customers.php)
- [Laravel Payment Controller](examples/laravel-payment-controller.php)
- [Laravel Webhook Controller](examples/laravel-webhook-controller.php)

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

[](#api-reference)

### Core Classes

[](#core-classes)

- `XPay` - Main client class
- `XPayConfig` - Configuration object
- `Payments` - Payment operations
- `Webhooks` - Webhook management
- `Customers` - Customer management

### Data Types

[](#data-types)

- `PaymentRequest` - Payment creation data
- `Payment` - Payment object
- `CreateWebhookRequest` - Webhook creation data
- `WebhookEndpoint` - Webhook object
- `CreateCustomerRequest` - Customer creation data
- `Customer` - Customer object

### Utilities

[](#utilities)

- `CurrencyUtils` - Currency conversion and validation
- `WebhookUtils` - Webhook signature verification
- `VerifyWebhookSignature` - Laravel middleware

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

[](#contributing)

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

### Development Setup

[](#development-setup)

```
git clone https://github.com/xpay/php-sdk.git
cd php-sdk
composer install
composer test
```

### IDE Support

[](#ide-support)

The SDK includes an `ide-helper.php` file to provide better IDE support during development. If your IDE shows errors about missing Laravel classes when not in a Laravel project, you can include this file in your IDE configuration.

For PhpStorm:

1. Go to Settings → PHP → Include Paths
2. Add the `ide-helper.php` file

For VSCode with Intelephense:

1. Add to your workspace settings:

```
{
    "intelephense.stubs": ["../ide-helper.php"]
}
```

**Note**: The Laravel-related warnings will be resolved when the SDK is used in an actual Laravel project with Laravel dependencies installed.

Changelog
---------

[](#changelog)

See [CHANGELOG.md](CHANGELOG.md) for release history.

Security
--------

[](#security)

If you discover any security vulnerabilities, please email  instead of using the issue tracker.

License
-------

[](#license)

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

Support
-------

[](#support)

- 📧 Email:
- 📖 Documentation:
- 🐛 Issues:
- 💬 Community:

---

Made with ❤️ by the X-Pay team

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance75

Regular maintenance activity

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 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

Every ~0 days

Total

10

Last Release

137d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/dc59720b36aded413d2a6a117111939355f4c499059b64694cb75e272e58e7e3?d=identicon)[bits-innovative](/maintainers/bits-innovative)

---

Top Contributors

[![sir-george2500](https://avatars.githubusercontent.com/u/51964478?v=4)](https://github.com/sir-george2500 "sir-george2500 (12 commits)")

---

Tags

phplaravelsdkpaymentsxpay

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/bits-devteam-xpay-php-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/bits-devteam-xpay-php-sdk/health.svg)](https://phpackages.com/packages/bits-devteam-xpay-php-sdk)
```

###  Alternatives

[kreait/firebase-php

Firebase Admin SDK

2.4k39.7M72](/packages/kreait-firebase-php)[openai-php/laravel

OpenAI PHP for Laravel is a supercharged PHP API client that allows you to interact with the Open AI API

3.7k7.6M74](/packages/openai-php-laravel)[aporat/store-receipt-validator

PHP receipt validator for Apple App Store and Amazon Appstore

6503.9M9](/packages/aporat-store-receipt-validator)[mozex/anthropic-laravel

Anthropic PHP for Laravel is a supercharged PHP API client that allows you to interact with the Anthropic API

71226.4k1](/packages/mozex-anthropic-laravel)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)[bushlanov-dev/max-bot-api-client-php

Max Bot API Client library

281.6k](/packages/bushlanov-dev-max-bot-api-client-php)

PHPackages © 2026

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