PHP code example of paynecta / paynecta-laravel-sdk

1. Go to this page and download the library: Download paynecta/paynecta-laravel-sdk 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/ */

    

paynecta / paynecta-laravel-sdk example snippets


use Paynecta\LaravelSdk\Facades\Paynecta;

try {
    $user = Paynecta::verifyAuth();
    
    echo "Authentication successful!";
    echo "User: " . $user['data']['email'];
    
} catch (\Paynecta\LaravelSdk\Exceptions\AuthenticationException $e) {
    echo "Authentication failed: " . $e->getMessage();
}

use Paynecta\LaravelSdk\Facades\Paynecta;

// Get all payment links
$links = Paynecta::paymentLinks()->getAll();

// Get specific link
$link = Paynecta::paymentLinks()->get('ABC123');

// Get only invoices
$invoices = Paynecta::paymentLinks()->getInvoices();

// Search links
$results = Paynecta::paymentLinks()->search('subscription');

// Count total links
$count = Paynecta::paymentLinks()->count();

use Paynecta\LaravelSdk\Facades\Paynecta;

// Initialize payment
$payment = Paynecta::payments()->initialize(
    'ABC123',           // Payment link code
    '254700000000',     // Mobile number
    100                 // Amount in KES (1-250,000)
);

// With validation
$payment = Paynecta::payments()->initializeWithValidation(
    'ABC123',
    '0700000000',       // Accepts 07XX format
    500
);

// Get transaction reference
$reference = Paynecta::payments()->getTransactionReference($payment);
echo "Transaction Reference: {$reference}";

use Paynecta\LaravelSdk\Facades\Paynecta;

// Query status
$status = Paynecta::payments()->queryStatus('ABCP20240803123456ABCD');

// Check status
if (Paynecta::payments()->isCompleted($status)) {
    $receipt = Paynecta::payments()->getMpesaReceiptNumber($status);
    echo "Payment completed! Receipt: {$receipt}";
}

if (Paynecta::payments()->isFailed($status)) {
    $reason = Paynecta::payments()->getFailureReason($status);
    echo "Payment failed: {$reason}";
}

// Poll until complete (checks every 2 seconds, max 30 attempts)
$finalStatus = Paynecta::payments()->pollStatus($reference, 30, 2);

use Paynecta\LaravelSdk\Facades\Paynecta;

// Get all currency rates (160+ currencies)
$rates = Paynecta::currencyRates()->getAll();

// Get specific currency rate
$usdRate = Paynecta::currencyRates()->get('USD');

// Convert currency
$converted = Paynecta::currencyRates()->convert(100, 'USD', 'KES');

// Convert with specific date
$converted = Paynecta::currencyRates()->convert(100, 'USD', 'KES', '2025-10-01');

// Get historical rates
$history = Paynecta::currencyRates()->getHistory('KES', 'USD', '2025-10-01', '2025-10-13');

// Helper methods
$rate = Paynecta::currencyRates()->getRate($usdRate);
$amount = Paynecta::currencyRates()->getConvertedAmount($converted);
$allRates = Paynecta::currencyRates()->getRates($rates);

use Paynecta\LaravelSdk\Facades\Paynecta;

// Get all banks
$banks = Paynecta::banks()->getAll();

// Get specific bank
$bank = Paynecta::banks()->get('jR3kL9');

// Search banks
$results = Paynecta::banks()->search('equity');

// Find by name
$kcb = Paynecta::banks()->findByName('KCB Bank');

// Find by paybill
$bank = Paynecta::banks()->findByPaybill('247247');

// For dropdowns (returns bank_id => bank_name)
$options = Paynecta::banks()->getForDropdown();

// Simple list (returns bank_name => paybill_number)
$list = Paynecta::banks()->getAllAsList();

// Grouped by first letter
$grouped = Paynecta::banks()->getGroupedByLetter();

protected $except = [
    'paynecta/webhook',
];



namespace App\Listeners;

use Paynecta\LaravelSdk\Events\PaymentCompletedEvent;
use Illuminate\Contracts\Queue\ShouldQueue;

class HandlePaymentCompleted implements ShouldQueue
{
    public function handle(PaymentCompletedEvent $event)
    {
        // Access payment data
        $reference = $event->transactionReference;
        $amount = $event->amount;
        $receipt = $event->mpesaReceiptNumber;
        $mobile = $event->mobileNumber;
        
        // Update database
        \DB::table('payments')
            ->where('transaction_reference', $reference)
            ->update([
                'status' => 'completed',
                'mpesa_receipt' => $receipt,
                'paid_at' => now()
            ]);
        
        // Send confirmation, fulfill order, etc.
    }
}

use Paynecta\LaravelSdk\Events\PaymentCompletedEvent;
use Paynecta\LaravelSdk\Events\PaymentFailedEvent;
use Paynecta\LaravelSdk\Events\PaymentCancelledEvent;

protected $listen = [
    PaymentCompletedEvent::class => [
        HandlePaymentCompleted::class,
    ],
    PaymentFailedEvent::class => [
        HandlePaymentFailed::class,
    ],
    PaymentCancelledEvent::class => [
        HandlePaymentCancelled::class,
    ],
];



namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Paynecta\LaravelSdk\Facades\Paynecta;
use App\Models\Order;

class CheckoutController extends Controller
{
    public function initiatePayment(Request $request)
    {
        $validated = $request->validate([
            'order_id' => ' $validated['mobile_number'],
                $order->total_amount
            );
            
            $reference = Paynecta::payments()->getTransactionReference($payment);
            
            // Save transaction reference
            $order->update([
                'transaction_reference' => $reference,
                'payment_status' => 'pending'
            ]);
            
            return response()->json([
                'success' => true,
                'message' => 'Check your phone for STK push',
                'transaction_reference' => $reference
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 400);
        }
    }
    
    public function checkStatus($reference)
    {
        try {
            $status = Paynecta::payments()->queryStatus($reference);
            
            return response()->json([
                'success' => true,
                'status' => Paynecta::payments()->getStatus($status),
                'is_completed' => Paynecta::payments()->isCompleted($status),
                'mpesa_receipt' => Paynecta::payments()->getMpesaReceiptNumber($status),
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 404);
        }
    }
}

return [
    // API credentials
    'api_key' => env('PAYNECTA_API_KEY'),
    'email' => env('PAYNECTA_EMAIL'),
    
    // API endpoint
    'base_url' => env('PAYNECTA_BASE_URL', 'https://paynecta.co.ke/api/v1'),
    
    // Request timeout in seconds
    'timeout' => env('PAYNECTA_TIMEOUT', 30),
    
    // Enable logging for debugging
    'logging' => env('PAYNECTA_LOGGING', false),
    
    // Log channel
    'log_channel' => env('PAYNECTA_LOG_CHANNEL', 'stack'),
    
    // Webhook settings
    'webhook_path' => env('PAYNECTA_WEBHOOK_PATH', 'paynecta/webhook'),
    'webhook_duplicate_detection' => env('PAYNECTA_WEBHOOK_DUPLICATE_DETECTION', true),
    'webhook_middleware' => ['api'],
];

use Paynecta\LaravelSdk\PaynectaClient;

class PaymentController extends Controller
{
    public function __construct(
        protected PaynectaClient $paynecta
    ) {}
    
    public function processPayment()
    {
        $user = $this->paynecta->verifyAuth();
        $links = $this->paynecta->paymentLinks()->getAll();
    }
}

$user = Paynecta::setTimeout(60)->verifyAuth();

// In .env
PAYNECTA_LOGGING=true

// Or programmatically
Paynecta::setLogging(true)->verifyAuth();

Paynecta::setBaseUrl('https://sandbox.paynecta.co.ke/api/v1');

use Paynecta\LaravelSdk\Exceptions\AuthenticationException;
use Paynecta\LaravelSdk\Exceptions\ValidationException;
use Paynecta\LaravelSdk\Exceptions\NotFoundException;
use Paynecta\LaravelSdk\Exceptions\RateLimitException;
use Paynecta\LaravelSdk\Exceptions\PaynectaException;

try {
    $result = Paynecta::payments()->initialize('ABC123', '254700000000', 100);
    
} catch (AuthenticationException $e) {
    // Invalid API key or email (401)
    $errorCode = $e->getErrorCode();
    $responseBody = $e->getResponseBody();
    
} catch (ValidationException $e) {
    // Invalid request data (400)
    $errors = $e->getResponseBody()['errors'] ?? [];
    
} catch (NotFoundException $e) {
    // Resource not found (404)
    
} catch (RateLimitException $e) {
    // Too many requests (429)
    
} catch (PaynectaException $e) {
    // Any other Paynecta error
    
} catch (\Exception $e) {
    // Network or other errors
}

$exception->getMessage();      // Human-readable error message
$exception->getCode();         // HTTP status code
$exception->getErrorCode();    // API-specific error code
$exception->getResponseBody(); // Full API response body
$exception->hasErrorCode();    // Check if error code exists

Route::get('/test-payment', function () {
    try {
        // Test authentication
        $user = Paynecta::verifyAuth();
        echo "✓ Authentication successful\n";
        
        // Test payment links
        $links = Paynecta::paymentLinks()->getAll();
        echo "✓ Found {$links['data']['total']} payment links\n";
        
        // Test banks
        $banks = Paynecta::banks()->getAll();
        echo "✓ Found {$banks['data']['total']} banks\n";
        
        return 'All tests passed!';
        
    } catch (\Exception $e) {
        return "Error: " . $e->getMessage();
    }
});
bash
php artisan vendor:publish --tag=paynecta-config
bash
php artisan make:listener HandlePaymentCompleted