1. Go to this page and download the library: Download paynexus/laravel-paynexus library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
paynexus / laravel-paynexus example snippets
use PayNexus\Facades\PayNexus;
// 1. Initiate an M-Pesa STK Push payment
$result = PayNexus::initiatePayment([
'amount' => 1500,
'phone' => '254712345678',
'description' => 'Order #1001 - Wireless Headphones',
]);
if ($result['success']) {
$checkoutRequestId = $result['data']['checkout_request_id'];
$reference = $result['data']['reference'];
echo "STK Push sent! Reference: {$reference}";
}
// 2. Check status immediately
$status = PayNexus::getPaymentByCheckoutId($checkoutRequestId);
echo $status['data']['status']; // 'pending', 'completed', 'failed'
// 3. Or poll until completion (blocks up to 120s by default)
$final = PayNexus::pollStatus($checkoutRequestId);
if ($final['data']['status'] === 'completed') {
echo 'Payment completed!';
}
// By PayNexus reference
$status = PayNexus::getPaymentByReference('PNXABCD1234');
// By PayNexus payment ID
$status = PayNexus::getPaymentById(42);
// By M-Pesa checkout request ID (also syncs local record)
$status = PayNexus::getPaymentByCheckoutId('ws_CO_...');
// Real-time M-Pesa query via Daraja (most accurate, also syncs local record)
$status = PayNexus::checkMpesaStatus('ws_CO_...');
$result = PayNexus::pollStatus(
checkoutRequestId: 'ws_CO_...',
intervalSeconds: 3, // check every 3 seconds (default)
timeoutSeconds: 120, // give up after 2 minutes (default)
);
if ($result['data']['status'] === 'completed') {
// Payment is done
}
use PayNexus\Events\PaymentCompleted;
use PayNexus\Events\PaymentFailed;
protected $listen = [
PaymentCompleted::class => [
\App\Listeners\HandlePaymentSuccess::class,
],
PaymentFailed::class => [
\App\Listeners\HandlePaymentFailure::class,
],
];
use PayNexus\Models\PaynexusPayment;
// Find by reference
$payment = PaynexusPayment::where('reference', 'PNXABCD1234')->first();
// Find by checkout request ID
$payment = PaynexusPayment::where('checkout_request_id', 'ws_CO_...')->first();
// Query scopes
$pending = PaynexusPayment::pending()->get();
$completed = PaynexusPayment::completed()->get();
$failed = PaynexusPayment::failed()->get();
// Check state
$payment->isPending(); // true/false
$payment->isCompleted(); // true/false
$payment->isTerminal(); // completed, failed, or timeout
$payment->isVerified(); // true/false - if payment was verified with provider
$payment->isManuallyConfirmed(); // true/false - if manually confirmed by admin
$payment->canRetry(); // true/false - if failed payment can be retried
// Helper methods
$payment->markCompleted($transactionId, $providerReference);
$payment->markFailed($reason);
$payment->markVerified($verifiedAmount, $verifiedPhone, $verificationMethod);
$payment->markManuallyConfirmed('[email protected]');
// Link to your models via polymorphic relation
$payment->payable; // → App\Models\Order, App\Models\Invoice, etc.
$payment = PaynexusPayment::where('reference', 'PNXABCD1234')->first();
// Check if payment has been verified with provider
if ($payment->isVerified()) {
echo "Verified on: " . $payment->verified_date->format('Y-m-d H:i:s');
echo "Verified amount: " . $payment->verified_amount;
echo "Verification method: " . $payment->verification_method;
}
// Manually mark as verified (e.g., after checking with bank)
$payment->markVerified(
verifiedAmount: 1500.00,
verifiedPhone: '254712345678',
verificationMethod: 'bank_statement'
);
// Mark payment as manually confirmed by an admin
$payment->markManuallyConfirmed('[email protected]');
// Check if manually confirmed
if ($payment->isManuallyConfirmed()) {
echo "Confirmed by: " . $payment->confirmed_by;
echo "Confirmed at: " . $payment->confirmed_at->format('Y-m-d H:i:s');
}
// In your Order model
class Order extends Model
{
public function payments()
{
return $this->morphMany(\PayNexus\Models\PaynexusPayment::class, 'payable');
}
}
// When initiating payment, set payable after creation:
$result = PayNexus::initiatePayment([...]);
if ($result['success']) {
$localPayment = PaynexusPayment::where('checkout_request_id', $result['data']['checkout_request_id'])->first();
$localPayment->update([
'payable_type' => Order::class,
'payable_id' => $order->id,
]);
}
// app/Models/Order.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use PayNexus\Models\PaynexusPayment;
class Order extends Model
{
protected $fillable = [
'user_id', 'order_number', 'total', 'currency', 'status',
'customer_name', 'customer_email', 'customer_phone',
];
public function payments()
{
return $this->morphMany(PaynexusPayment::class, 'payable');
}
public function latestPayment()
{
return $this->morphOne(PaynexusPayment::class, 'payable')->latestOfMany();
}
public function isPaid(): bool
{
return $this->payments()->completed()->exists();
}
public function markAsPaid(): void
{
$this->update(['status' => 'paid']);
}
}
// app/Http/Controllers/CheckoutController.php
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\Request;
use PayNexus\Facades\PayNexus;
use PayNexus\Models\PaynexusPayment;
class CheckoutController extends Controller
{
/**
* Step 1: Show checkout page with cart summary.
*/
public function show(Request $request)
{
$cart = $request->user()->cart; // your cart logic
return view('checkout', compact('cart'));
}
/**
* Step 2: Create order and initiate M-Pesa payment.
*/
public function pay(Request $request)
{
$request->validate([
'phone' => 'der->order_number,
'description' => "Payment for {$order->order_number}",
'metadata' => ['order_id' => $order->id],
]);
if (!$result['success']) {
return back()->withErrors(['payment' => $result['message'] ?? 'Payment initiation failed.']);
}
// Link the local PaynexusPayment to the order
$checkoutRequestId = $result['data']['checkout_request_id'];
$localPayment = PaynexusPayment::where('checkout_request_id', $checkoutRequestId)->first();
if ($localPayment) {
$localPayment->update([
'payable_type' => Order::class,
'payable_id' => $order->id,
]);
}
// Redirect to a page that polls for payment status
return redirect()->route('checkout.status', [
'order' => $order->id,
'checkout_request_id' => $checkoutRequestId,
]);
}
/**
* Step 3: Show payment status page (polls via AJAX or Livewire).
*/
public function status(Request $request, Order $order)
{
return view('checkout.status', [
'order' => $order,
'checkoutRequestId' => $request->query('checkout_request_id'),
]);
}
/**
* AJAX endpoint: check payment status from the browser.
*/
public function checkStatus(Request $request)
{
$request->validate(['checkout_request_id' => '
// app/Livewire/PaymentStatus.php
namespace App\Livewire;
use Livewire\Component;
use PayNexus\Facades\PayNexus;
use PayNexus\Models\PaynexusPayment;
class PaymentStatus extends Component
{
public string $checkoutRequestId;
public string $status = 'pending';
public ?string $transactionId = null;
public ?string $reference = null;
public function mount(string $checkoutRequestId)
{
$this->checkoutRequestId = $checkoutRequestId;
$this->checkPaymentStatus();
}
public function checkPaymentStatus(): void
{
$result = PayNexus::getPaymentByCheckoutId($this->checkoutRequestId);
$this->status = $result['data']['status'] ?? 'pending';
$this->transactionId = $result['data']['provider_transaction_id'] ?? null;
$this->reference = $result['data']['reference'] ?? null;
if ($this->status === 'completed') {
$local = PaynexusPayment::where('checkout_request_id', $this->checkoutRequestId)->first();
if ($local && $local->payable && method_exists($local->payable, 'markAsPaid')) {
$local->payable->markAsPaid();
}
}
}
public function render()
{
return view('livewire.payment-status');
}
}
// app/Listeners/HandlePaymentSuccess.php
namespace App\Listeners;
use PayNexus\Events\PaymentCompleted;
class HandlePaymentSuccess
{
public function handle(PaymentCompleted $event): void
{
$payment = $event->payment;
// Update the linked order
if ($payment->payable && method_exists($payment->payable, 'markAsPaid')) {
$payment->payable->markAsPaid();
}
// Send confirmation email, SMS, etc.
// Mail::to($payment->payable->customer_email)->send(new OrderConfirmation($payment->payable));
}
}
// app/Listeners/HandlePaymentFailure.php
namespace App\Listeners;
use PayNexus\Events\PaymentFailed;
class HandlePaymentFailure
{
public function handle(PaymentFailed $event): void
{
$payment = $event->payment;
// Update order status
if ($payment->payable) {
$payment->payable->update(['status' => 'payment_failed']);
}
// Notify the customer
// Notification::send($payment->payable->user, new PaymentFailedNotification($event->reason));
}
}
// app/Models/Subscription.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use PayNexus\Models\PaynexusPayment;
class Subscription extends Model
{
protected $fillable = [
'user_id',
'plan_id',
'status',
'expires_at',
];
public function payments()
{
return $this->morphMany(PaynexusPayment::class, 'payable');
}
public function activate()
{
$this->update([
'status' => 'active',
'expires_at' => now()->addMonth(),
]);
}
}