定制 bits-devteam/xpay-php-sdk 二次开发

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

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

bits-devteam/xpay-php-sdk

Composer 安装命令:

composer require bits-devteam/xpay-php-sdk

包简介

Official PHP SDK for X-Pay payment processing platform

README 文档

README

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 PHP Version License

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

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

Installation

Install via Composer:

composer require xpay/php-sdk

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

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

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

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

// 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

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

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

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

Register the Middleware

Add to your app/Http/Kernel.php:

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

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

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

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

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

Run the test suite:

composer test

Run tests with coverage:

composer test-coverage

Run static analysis:

composer phpstan

Laravel Testing

# Test API connectivity
php artisan xpay:test

# List payment methods
php artisan xpay:payment-methods

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

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

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

See the examples/ directory for complete working examples:

API Reference

Core Classes

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

Data Types

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

Utilities

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

Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup

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

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

See CHANGELOG.md for release history.

Security

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

License

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

Support

Made with ❤️ by the X-Pay team

bits-devteam/xpay-php-sdk 适用场景与选型建议

bits-devteam/xpay-php-sdk 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 0 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 01 月 01 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 bits-devteam/xpay-php-sdk 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-01-01