Download the PHP package paynexus/laravel-paynexus without Composer
On this page you can find all versions of the php package paynexus/laravel-paynexus. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download paynexus/laravel-paynexus
More information about paynexus/laravel-paynexus
Files in paynexus/laravel-paynexus
Package laravel-paynexus
Short Description Laravel SDK for the PayNexus payment orchestration platform. Accept M-Pesa STK Push payments, track payment status in real time, and keep local payment records synchronized with PayNexus.
License MIT
Homepage https://www.paynexus.co.ke
Informations about the package laravel-paynexus
✨ Features
- 🚀 Easy Integration - Simple facade-based API for quick setup
- 💳 M-Pesa STK Push - Seamless mobile payment initiation
- 🔄 Real-time Tracking - Poll for payment completion or use webhooks
- 📊 Local Records - Automatic database synchronization
- 🔔 Webhook Events - Laravel events for payment state changes
- 🔒 Secure - HMAC signature verification for webhooks
- 🎯 Polymorphic Relations - Link payments to any model (Order, Invoice, etc.)
- ✅ Phone Validation - Built-in phone number normalization
⚠️ Plugin vs Platform
This plugin is for external Laravel applications (e.g., ecommerce stores, SaaS apps) that want to accept payments through PayNexus.
| Component | Description |
|---|---|
| PayNexus Platform | The payment gateway platform at paynexus.co.ke that processes payments |
| This Plugin | A Laravel package that YOUR application installs to connect to the PayNexus platform |
Note: If you're looking for the PayNexus platform source code, that's a separate repository. This plugin is the client SDK for merchants integrating with PayNexus.
📑 Table of Contents
- How It Works
- Installation
- Configuration
- Quick Start
- API Reference
- Merchant
- Businesses
- Payment Accounts
- Initiate Payment
- Payment Status
- Poll for Completion
- List Payments
- Phone Validation
- Webhooks
- Webhook Integration
- Events
- Local Payment Records
- Ecommerce Integration Guide
- Order Checkout Flow
- Cart Checkout Controller
- Payment Status Page (Livewire)
- Handling Webhooks in Your App
- Subscription Integration
- Manual Payment Verification
- Error Handling
- Testing
- JavaScript Polling
- Custom Webhook Handler
- Configuration Reference
- Getting API Keys
- Support
- Troubleshooting
- License
🔄 How It Works
Payment Flow:
- Initiate — Your app calls
PayNexus::initiatePayment(...). A payment record is created both on PayNexus and in your localpaynexus_paymentstable. - STK Push — PayNexus sends an M-Pesa STK Push to the customer's phone.
- Customer pays — The customer enters their PIN on their phone.
- Callback — M-Pesa sends a callback to PayNexus. PayNexus updates its record and fires a webhook to your app.
- Webhook received — This plugin receives the webhook, updates the local
paynexus_paymentsrecord, and dispatches a Laravel event (PaymentCompletedorPaymentFailed). - Your listener — Your
EventServiceProviderlistener marks the order as paid, sends a receipt, etc.
Both records always match. If the webhook is missed, you can call
PayNexus::pollStatus(...)orPayNexus::getPaymentByCheckoutId(...)to sync manually.
📦 Installation
Install the package via Composer:
The service provider and facade are auto-discovered by Laravel.
Publish Config and Migration
⚙️ Configuration
Add these to your .env file:
🔑 Where to Get Credentials
| Credential | Location | Usage |
|---|---|---|
Secret Key (sk_…) |
PayNexus Dashboard → API Keys | Write operations (initiate payments, manage webhooks). Keep server-side only. |
Public Key (pk_…) |
PayNexus Dashboard → API Keys | Read operations only (merchant info, payment status). Safe for client-side code. |
| Webhook Secret | PayNexus Dashboard → Webhooks | Generate a webhook pointing to https://yourapp.com/paynexus/webhook |
🔓 Public Key Allowed Operations
Public keys (pk_) can perform the following read-only operations:
Merchant Information
GET /api/merchant- Get merchant informationGET /api/merchant/businesses- List merchant businessesGET /api/merchant/payment-accounts- List payment accounts
Payment Read Operations
GET /api/payments/{reference}- Get payment status by referenceGET /api/payments/{id}/status-by-id- Get payment status by IDPOST /api/payments/status-by-checkout-id- Get payment status by checkout IDGET /api/payments- List all payments
M-Pesa Operations
GET /api/mpesa/health- M-Pesa service health checkPOST /api/mpesa/validate-phone- Validate phone numberPOST /api/mpesa/payment/status- Check M-Pesa transaction status
Webhook Read Operations
GET /api/webhooks- List registered webhooks
API Key Read Operations
GET /api/api-keys- List API keys
Invoice Read Operations
GET /api/invoices- List invoicesGET /api/invoices/{invoice}- View invoice details
Receipt Read Operations
GET /api/receipts- List receiptsGET /api/receipts/{receipt}- View receipt details
🔒 Public Key Blocked Operations
Public keys (pk_) are blocked from these write operations at the middleware level:
Payment Write Operations
POST /api/payments/initiate- Initiate paymentsPOST /api/mpesa/payment/initiate- Initiate STK push payment
Webhook Management
POST /api/webhooks/register- Register webhooksPUT /api/webhooks/{id}- Update webhooksDELETE /api/webhooks/{id}- Delete webhooks
API Key Management
POST /api/api-keys- Create API keysPUT /api/api-keys/{id}- Update API keysDELETE /api/api-keys/{id}- Delete API keys
Invoice Management
POST /api/invoices- Create invoicesPUT /api/invoices/{invoice}- Update invoicesDELETE /api/invoices/{invoice}- Delete invoicesPOST /api/invoices/{invoice}/send- Send invoices
Receipt Management
POST /api/receipts/{receipt}/resend- Resend receipts
🚀 Quick Start
📚 API Reference
👤 Merchant
🏢 Businesses
💳 Payment Accounts
💰 Initiate Payment
Two endpoints are available:
Idempotency Protection:
To prevent duplicate payments, you can provide an idempotency key:
If a payment with the same idempotency_key already exists, the existing payment details will be returned instead of creating a new one. This is especially useful for handling network retries and preventing duplicate charges.
Benefits of idempotency:
- Prevents duplicate payments on network retries
- Safe to retry payment initiation without side effects
- Atomic database transactions ensure consistency
- Existing payment returned if key matches
Response:
Both methods also create a local paynexus_payments record automatically.
📊 Payment Status
⏱️ Poll for Completion
Blocks until the payment reaches a terminal state or times out:
📋 List Payments
✅ Phone Validation
🔗 Webhooks
🔔 Webhook Integration
The plugin automatically registers a POST route at /paynexus/webhook (configurable via PAYNEXUS_WEBHOOK_PATH).
Queue Support for Webhooks
For production environments, you can enable queue processing for webhooks to improve reliability:
When enabled, webhooks are dispatched to a queue job (ProcessPayNexusWebhook) with configurable retry behavior:
Benefits of queue processing:
- Asynchronous processing prevents webhook timeouts
- Automatic retries with exponential backoff
- Better handling of high-volume webhook traffic
- Dead-letter queue support for failed webhooks
Handling Webhook Failures:
When a webhook job exhausts its retry attempts, a WebhookProcessingFailed event is dispatched. You can listen for this event:
PayNexus sends this payload when a payment completes:
| Headers sent with each webhook: | Header | Description |
|---|---|---|
X-PayNexus-Signature |
HMAC-SHA256 of the JSON body using your webhook secret | |
X-PayNexus-Timestamp |
Unix timestamp — used for replay protection |
The webhook controller:
- Verifies the
X-PayNexus-Signatureheader (HMAC-SHA256 of the JSON body using your webhook secret). - Checks
X-PayNexus-Timestampfor replay protection (rejects payloads older than 5 minutes by default). - Finds or creates the matching
paynexus_paymentsrecord. - Updates the local record's status.
- Dispatches a Laravel event (
PaymentCompletedorPaymentFailed).
Setup in PayNexus dashboard:
- Go to Webhooks in your PayNexus merchant panel.
- Add a webhook pointing to
https://yourapp.com/paynexus/webhook. - Copy the generated secret and set
PAYNEXUS_WEBHOOK_SECRETin your.env.
🎯 Events
| Event | When | Properties |
|---|---|---|
PayNexus\Events\PaymentCompleted |
Webhook reports payment.completed |
$payment (PaynexusPayment), $payload (array) |
PayNexus\Events\PaymentFailed |
Webhook reports payment.failed |
$payment (PaynexusPayment), $payload (array), $reason (string) |
PayNexus\Events\PaymentInitiated |
After initiatePayment() succeeds |
$payment (PaynexusPayment) |
Register listeners in your EventServiceProvider:
📦 Local Payment Records
Every payment initiated through the plugin creates a row in the paynexus_payments table.
🔍 Payment Verification
The plugin tracks verification data from the payment provider:
👤 Manual Confirmation
For payments that need manual review:
🔗 Polymorphic Relationship
Link payments to any of your models:
🛒 Ecommerce Integration Guide
📦 Order Checkout Flow
Here is a complete end-to-end checkout flow for an ecommerce store.
Step 1: Order Model Setup
Step 2: Orders Migration
🛍️ Cart Checkout Controller
Routes:
⚡ Payment Status Page (Livewire)
If you use Livewire, here is a component that polls automatically:
🎧 Handling Webhooks in Your App
🔄 Subscription Integration
For subscription-based applications:
Subscription Model:
Subscription Payment Controller:
� Manual Payment Verification
For payments that require manual admin review:
⚠️ Error Handling
The plugin provides specific exceptions for different error scenarios:
🧪 Testing
Mocking HTTP Requests
🌐 JavaScript Polling
For client-side payment status polling:
� Custom Webhook Handler
If you need custom webhook handling beyond the built-in controller:
Register your custom webhook route:
�� Configuration Reference
| Key | Env Variable | Default | Description |
|---|---|---|---|
secret_key |
PAYNEXUS_SECRET_KEY |
— | Your PayNexus secret key (sk_…) - Required for write operations |
public_key |
PAYNEXUS_PUBLIC_KEY |
— | Your PayNexus public key (pk_…) - Optional, for read operations |
base_url |
PAYNEXUS_BASE_URL |
https://paynexus.co.ke |
PayNexus API base URL |
currency |
PAYNEXUS_CURRENCY |
KES |
Default currency |
webhook.secret |
PAYNEXUS_WEBHOOK_SECRET |
— | HMAC secret for webhook signature verification |
webhook.path |
PAYNEXUS_WEBHOOK_PATH |
/paynexus/webhook |
Webhook receiver route |
webhook.tolerance |
— | 300 |
Max age (seconds) for webhook timestamp |
polling.interval |
PAYNEXUS_POLL_INTERVAL |
3 |
Seconds between pollStatus queries |
polling.timeout |
PAYNEXUS_POLL_TIMEOUT |
120 |
Max seconds pollStatus will block |
http.timeout |
PAYNEXUS_HTTP_TIMEOUT |
30 |
HTTP request timeout (seconds) |
http.retry_times |
PAYNEXUS_HTTP_RETRIES |
2 |
Number of retries on connection failure |
http.retry_sleep |
PAYNEXUS_HTTP_RETRY_SLEEP |
500 |
Milliseconds between retries |
log_channel |
PAYNEXUS_LOG_CHANNEL |
null |
Custom log channel |
queue.webhooks |
PAYNEXUS_QUEUE_WEBHOOKS |
false |
Enable queue processing for webhooks |
queue.connection |
PAYNEXUS_QUEUE_CONNECTION |
default |
Queue connection for webhooks |
queue.queue |
PAYNEXUS_QUEUE_NAME |
default |
Queue name for webhooks |
retry.webhook_max_attempts |
PAYNEXUS_WEBHOOK_MAX_ATTEMPTS |
3 |
Max retry attempts for webhook jobs |
retry.webhook_backoff |
PAYNEXUS_WEBHOOK_BACKOFF |
exponential |
Retry backoff strategy (linear, exponential, constant) |
retry.webhook_base_delay |
PAYNEXUS_WEBHOOK_BASE_DELAY |
1000 |
Base delay in milliseconds for retries |
Advanced Configuration Options
Queue Webhooks:
Retry Configuration:
Custom Webhook Path:
Custom Polling Settings:
HTTP Client Settings:
Custom Log Channel:
Then in config/logging.php:
🔑 Getting API Keys
To use this plugin, you need API keys from the PayNexus platform:
- Register at paynexus.co.ke to create an account
- Choose a subscription plan that fits your needs
- Navigate to the merchant panel after registration
- Create a business in your merchant dashboard
- Add a payment account (e.g., M-Pesa till number) to your business
- Navigate to API Keys and select the appropriate API key for the specific payment account you created
- Secret Key (
sk_): For initiating payments and write operations. Keep this server-side only. - Public Key (
pk_): For read operations like checking payment status. Safe to use in client-side code.
- Secret Key (
- Configure webhook in PayNexus dashboard pointing to
https://yourapp.com/paynexus/webhook - Copy the webhook secret and set
PAYNEXUS_WEBHOOK_SECRETin your.env
💬 Support
- Documentation: README.md
- Issues: GitHub Issues
- Email: [email protected]
- Platform: paynexus.co.ke
🔧 Troubleshooting
"PayNexus secret key is required"
- Set
PAYNEXUS_SECRET_KEY(orPAYNEXUS_API_KEYfor backwards compatibility) in your.env. - Run
php artisan config:clearafter changing environment variables.
"Unable to reach PayNexus API"
- Check your internet connection.
- Verify
PAYNEXUS_BASE_URLis correct (https://paynexus.co.ke, no trailing/api). - Test connectivity:
curl -H "X-API-Key: sk_..." https://paynexus.co.ke/api/merchant
"Invalid PayNexus webhook signature"
- Ensure
PAYNEXUS_WEBHOOK_SECRETmatches the secret shown in PayNexus when you created the webhook. - The webhook URL must be publicly accessible (PayNexus needs to reach it).
Payment stays "pending"
- The customer may not have confirmed the STK push on their phone.
- Call
PayNexus::checkMpesaStatus($checkoutRequestId)to query M-Pesa directly. - Check that your PayNexus callback URL is correctly configured in the M-Pesa Daraja portal.
Local record not updating
- Ensure your webhook endpoint is correctly registered with PayNexus.
- Check
storage/logs/laravel.logfor[PayNexus Webhook]entries. - Verify your
.envhasPAYNEXUS_WEBHOOK_SECRETset correctly. - You can manually sync by calling
PayNexus::getPaymentByCheckoutId(...).
📄 License
MIT — see LICENSE.
All versions of laravel-paynexus with dependencies
illuminate/support Version ^11.0|^12.0
illuminate/http Version ^11.0|^12.0
illuminate/database Version ^11.0|^12.0