Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Apimtnmomo Laravel Package

roazagba/apimtnmomo

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require roazagba/apimtnmomo
    

    Publish the config file:

    php artisan vendor:publish --provider="Roazagba\Apimtnmomo\ApimtnmomoServiceProvider"
    
  2. Configuration Update .env with MTN MoMo credentials:

    MTN_MOMO_API_KEY=your_api_key
    MTN_MOMO_SECRET_KEY=your_secret_key
    MTN_MOMO_BASE_URL=https://sandboxapi.momodeveloper.mtn.com/v1/
    
  3. First Use Case: Initiate a Transaction

    use Roazagba\Apimtnmomo\Facades\Apimtnmomo;
    
    $response = Apimtnmomo::pay(
        amount: 1000, // Amount in cedi (₵)
        phone: '233551234567',
        reference: 'ORDER-12345',
        currency: 'GHS',
        callbackUrl: 'https://yourdomain.com/momo/callback'
    );
    

Where to Look First

  • Documentation: Official Docs (covers endpoints, error codes, and examples).
  • Config File: config/apimtnmomo.php (adjust sandbox/live mode, timeouts, and logging).
  • Facade: Roazagba\Apimtnmomo\Facades\Apimtnmomo (primary entry point for all API calls).

Implementation Patterns

Core Workflows

1. Transaction Processing

  • Payments (Collect Money)

    $response = Apimtnmomo::pay([
        'amount' => 5000,
        'phone' => '233541234567',
        'reference' => 'INV-'.Str::uuid(),
        'currency' => 'GHS',
        'callbackUrl' => route('momo.callback'),
    ]);
    
    • Callback Handling: Implement a route to handle MTN’s webhook:
      Route::post('/momo/callback', [MomoCallbackController::class, 'handle']);
      
      Use Apimtnmomo::verifyCallback() to validate the signature.
  • Disbursements (Send Money)

    $response = Apimtnmomo::disburse([
        'amount' => 2000,
        'phone' => '233541234567',
        'reference' => 'REF-'.Str::uuid(),
        'currency' => 'GHS',
    ]);
    

2. Transaction Status Checks

$status = Apimtnmomo::checkTransactionStatus('REF-12345');

3. Airtime Top-Up

$response = Apimtnmomo::airtime([
    'phone' => '233541234567',
    'amount' => 5,
    'network' => 'MTN', // or 'VODAFONE', 'AIRTEL', 'TIGO'
]);

4. Bulk Transactions

$bulkResponse = Apimtnmomo::bulkPay([
    'transactions' => [
        ['amount' => 1000, 'phone' => '233541234567', 'reference' => 'REF1'],
        ['amount' => 1500, 'phone' => '233541234568', 'reference' => 'REF2'],
    ],
    'currency' => 'GHS',
]);

Integration Tips

  1. Environment Separation Use .env to toggle between sandbox and live mode:

    MTN_MOMO_ENV=sandbox # or 'live'
    
  2. Logging Enable debug logging in config/apimtnmomo.php:

    'debug' => env('MTN_MOMO_DEBUG', false),
    

    Logs are stored in storage/logs/momo.log.

  3. Retry Logic Implement exponential backoff for failed requests (e.g., using retry package):

    use Illuminate\Support\Facades\Retry;
    
    Retry::times(3)->attempt(function () {
        $response = Apimtnmomo::pay([...]);
    });
    
  4. Database Storage Store transaction references in your DB for reconciliation:

    // Example model
    class MomoTransaction extends Model {
        protected $fillable = ['reference', 'amount', 'phone', 'status', 'raw_response'];
    }
    
  5. Webhook Validation Always verify MTN’s callback signature:

    public function handle(Request $request) {
        if (!Apimtnmomo::verifyCallback($request)) {
            abort(403, 'Invalid callback');
        }
        // Process the transaction
    }
    

Gotchas and Tips

Pitfalls

  1. Sandbox vs. Live Mode

    • Issue: Forgetting to switch from sandbox to live before production.
    • Fix: Use feature flags or environment checks:
      if (config('apimtnmomo.env') === 'live') {
          // Enable production-specific logic
      }
      
  2. Phone Number Format

    • Issue: MTN requires international format (e.g., 233541234567 for Ghana).
    • Fix: Validate and format phone numbers before sending:
      $phone = '233'.ltrim($rawPhone, '0');
      
  3. Callback Timeouts

    • Issue: MTN’s callback may take >5 seconds to process.
    • Fix: Increase PHP’s max_execution_time or use queue jobs:
      Queue::push(MomoCallbackJob::class, $request->all());
      
  4. Rate Limits

    • Issue: MTN throttles requests (e.g., 10 calls/minute in sandbox).
    • Fix: Implement rate limiting middleware:
      Route::middleware(['throttle:10,1'])->group(function () {
          Route::post('/momo/webhook', [...]);
      });
      
  5. Currency Mismatch

    • Issue: Using currency: 'USD' when MTN only supports GHS for Ghana.
    • Fix: Hardcode currency: 'GHS' for Ghanaian endpoints.

Debugging

  1. Enable Debug Mode

    MTN_MOMO_DEBUG=true
    

    Check storage/logs/momo.log for raw API responses.

  2. Test with Sandbox First

    • Use MTN’s sandbox docs to generate test phones (e.g., 08090909090).
  3. Common Error Codes

    Code Meaning Solution
    400 Invalid request Validate input data
    401 Authentication failed Check api_key/secret_key
    403 Insufficient funds Notify user
    404 Resource not found Verify transaction reference
    500 Server error Retry or contact MTN support

Extension Points

  1. Custom Responses Override default responses by extending the facade:

    class CustomApimtnmomo extends \Roazagba\Apimtnmomo\Facades\Apimtnmomo {
        public static function pay(array $data) {
            $response = parent::pay($data);
            // Transform response (e.g., add custom fields)
            return $response->merge(['custom_field' => 'value']);
        }
    }
    
  2. Add New Endpoints The package follows a simple Apimtnmomo::method() pattern. To add a custom endpoint:

    // In a service class
    public function customEndpoint(array $data) {
        return Http::withHeaders([
            'Authorization' => 'Bearer '.config('apimtnmomo.api_key'),
            'Content-Type' => 'application/json',
        ])->post(config('apimtnmomo.base_url').'custom', $data);
    }
    
  3. Event Dispatching Trigger events for transactions (e.g., MomoTransactionProcessed):

    event(new MomoTransactionProcessed($response));
    
  4. Testing Use Laravel’s HTTP tests to mock MTN responses:

    $response = Http::fake([
        'sandboxapi.momodeveloper.mtn
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui