PHP code example of cyrus-48 / paysasa

1. Go to this page and download the library: Download cyrus-48/paysasa 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/ */

    

cyrus-48 / paysasa example snippets


use Paysasa\Payments\Facades\Payment;

// Initiate an M-Pesa STK push
$response = Payment::driver('mpesa')
    ->amount(2500)
    ->currency('KES')
    ->phone('0712345678')
    ->customer($user)
    ->reference('INV-1001')
    ->description('School Fees')
    ->metadata(['student_id' => 10])
    ->charge();

if ($response->successful()) {
    // Synchronous providers (e.g. pre-authorized cards) settle immediately
    $receipt = $response->receiptNumber();
} elseif ($response->pending()) {
    // Asynchronous providers (STK push, hosted checkouts) settle via webhook or reconciler
    $checkoutId = $response->providerReference();
}

// Stripe Card (Tokenized)
Payment::driver('stripe')
    ->amount(25)
    ->currency('USD')
    ->paymentMethod($paymentMethodId)
    ->reference('INV-1002')
    ->charge();

// PesaLink Bank Transfer (Experimental)
Payment::driver('pesalink')
    ->amount(50000)
    ->reference('PAYOUT-99')
    ->metadata(['account_number' => '0123456789', 'bank_code' => '01'])
    ->payout();

Payment::driver('stripe')
    ->amount(2500)
    ->currency('KES')
    ->paymentMethod($stripePaymentMethodId)
    ->reference('INV-1004')
    ->charge();

use Illuminate\Support\Facades\Event;
use Paysasa\Payments\Events\PaymentSuccessful;
use Paysasa\Payments\Events\PaymentFailed;
use Paysasa\Payments\Events\PaymentExpired;

// In your EventServiceProvider or listener:
Event::listen(PaymentSuccessful::class, function (PaymentSuccessful $event) {
    $payment = $event->payment;
    // Dispatch order, send SMS receipt, update subscription...
});

Event::listen(PaymentFailed::class, function (PaymentFailed $event) {
    // Alert customer, log failure reason...
});

use Paysasa\Payments\Facades\Payment;

Payment::fake();

// Run your application code...
$user->checkout();

// Assertions:
Payment::assertCharged(fn ($request) => $request->amountMajor() === 2500.0);
Payment::assertChargedOn('mpesa');
Payment::assertChargedTimes(1);

Payment::fake([
    PaymentResponse::makeFailed(PaymentProvider::Mpesa, message: 'DS timeout user cannot be reached'),
]);