PHP code example of opsofts / laravel-mtn-momo

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

    

opsofts / laravel-mtn-momo example snippets


use Opsofts\LaravelMtnMomo\Facades\MtnMomo;

// Step 1: provision an API User (only needs your subscription key, already in .env)
$result = MtnMomo::provisionApiUser(callbackHost: 'yourapp.com');
// $result['apiUserId'] -- save this as MOMO_API_USER

// Step 2: generate that user's API Key
$result = MtnMomo::createApiKey($apiUserId);
// $result['apiKey'] -- save this as MOMO_API_KEY

use Opsofts\LaravelMtnMomo\Facades\MtnMomo;
use Illuminate\Support\Str;

// Request a payment - pushes an approval prompt to the customer's phone
$request = MtnMomo::requestToPay([
    'amount' => '5000',
    'currency' => 'NGN', // or "GHS" for Ghana, etc.
    'externalId' => $order->reference,
    'payer' => [
        'partyIdType' => 'MSISDN',
        'partyId' => '2348012345678', // customer's MoMo-registered phone number
    ],
    'payerMessage' => 'Payment for order #1234',
    'payeeNote' => 'Internal note',
], referenceId: (string) Str::uuid());

// $request['referenceId'] -- store this against the order; you need it to check status

// Poll for the result (or wait for your configured webhook, then confirm with this call)
$status = MtnMomo::getTransactionStatus($request['referenceId']);

if ($status['status'] === 'SUCCESSFUL') {
    // mark the order/payment as paid
} elseif ($status['status'] === 'FAILED') {
    // handle failure
}
// otherwise still PENDING -- keep polling (e.g. from a queued job) or wait for the webhook