PHP code example of mrroot / orange-money-bundle

1. Go to this page and download the library: Download mrroot/orange-money-bundle 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/ */

    

mrroot / orange-money-bundle example snippets




return [
    Mrroot\OrangeMoneyBundle\OrangeMoneyBundle::class => ['all' => true],
];



namespace App\Controller;

use Mrroot\OrangeMoneyBundle\Model\PaymentRequest;
use Mrroot\OrangeMoneyBundle\Service\OrangeMoneyService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class PaymentController extends AbstractController
{
    #[Route('/payment/initiate', name: 'payment_initiate', methods: ['POST'])]
    public function initiatePayment(
        Request $request,
        OrangeMoneyService $orangeMoneyService
    ): JsonResponse {
        try {
            // Create payment request
            $paymentRequest = new PaymentRequest(
                orderId: 'ORDER_' . uniqid(),
                amount: 10000, 
                currency: 'GNF', 
                reference: 'REF_' . time(),
                merchantKey: $this->getParameter('OM_MERCHANT_KEY'),
                returnUrl: $this->getParameter('OM_RETURN_URL'),
                cancelUrl: $this->getParameter('OM_CANCEL_URL'),
                notifUrl: $this->getParameter('OM_NOTIF_URL')
            );

            // Initiate payment
            $paymentResponse = $orangeMoneyService->initiatePayment($paymentRequest);

            // IMPORTANT: Save these values for webhook validation
            // - $paymentResponse->getPayToken() (payToken)
            // - $paymentRequest->getOrderId() (orderId)
            // - $paymentResponse->getNotifToken() (notifToken)

            return new JsonResponse([
                'success' => true,
                'payment_url' => $paymentResponse->getPaymentUrl(),
                'pay_token' => $paymentResponse->getPayToken(),
                'notif_token' => $paymentResponse->getNotifToken(),
                'order_id' => $paymentRequest->getOrderId()
            ]);

        } catch (\Exception $e) {
            return new JsonResponse([
                'success' => false,
                'error' => $e->getMessage()
            ], 400);
        }
    }
}

#[Route('/payment/status/{payToken}', name: 'payment_status')]
public function checkPaymentStatus(
    string $payToken,
    string $orderId,
    float $amount,
    OrangeMoneyService $orangeMoneyService
): JsonResponse {
    try {
        // Enhanced status check with           'amount' => $response->getAmount(),
            'currency' => $response->getCurrency(),
            'txn_id' => $response->getTxnId()
        ]);

    } catch (\Exception $e) {
        return new JsonResponse([
            'error' => $e->getMessage()
        ], 400);
    }
}

#[Route('/payment/webhook', name: 'payment_webhook', methods: ['POST'])]
public function handleWebhook(
    Request $request,
    OrangeMoneyService $orangeMoneyService
): JsonResponse {
    try {
        // Retrieve stored values from your database/session
        // These values should have been saved during payment initiation:
        $payToken = "your-stored-pay-token";     // Get from database
        $orderId = "your-stored-order-id";       // Get from database  
        $notifToken = "your-stored-notif-token"; // Get from database
        $amount = 50.0;                          // Get from database

        // Optional: Check transaction status separately if needed
        // $checkResponse = $orangeMoneyService->checkTransactionStatus(
        //     $payToken,
        //     $orderId, 
        //     $amount
        // );
        
        $webhookData = json_decode($request->getContent(), true);
        
        // Automatic notif_token verification
        $paymentStatus = $orangeMoneyService->processNotification($webhookData, $notifToken);
        
        // Your business logic here
        if ($paymentStatus->getStatus() === 'SUCCESS') {
            // Confirm order
            $this->confirmOrder($paymentStatus->getOrderId());
        }

        return new JsonResponse([
            'status' => 'success',
            'message' => 'Notification processed',
            'txn_id' => $paymentStatus->getTxnId()
        ]);

    } catch (\Exception $e) {
        return new JsonResponse([
            'status' => 'error',
            'message' => $e->getMessage()
        ], 500);
    }

    private function getStoredNotifToken(?string $orderId): ?string
    {
        // Retrieve the notification token stored during payment initiation
        // This could be from database, cache, session, etc.
        return $orderId ? $this->paymentRepository->getNotifTokenByOrderId($orderId) : null;
    }

    private function confirmOrder(string $orderId): void
    {
        // Your order confirmation logic
    }
}

public function checkStatus(OrangeMoneyService $orangeMoneyService): JsonResponse
{
    try {
        // Use values saved during payment initiation
        $response = $orangeMoneyService->checkTransactionStatus(
            'pay-token-from-initiation',  // Saved payment token
            'ORDER-123',                  // Saved order ID
            10000                         // Saved amount
        );
        
        return new JsonResponse([
            'status' => $response->getStatus(),
            'transaction_id' => $response->getTxnId(),
            'order_id' => $response->getOrderId()
        ]);
        
    } catch (OrangeMoneyException $e) {
        return new JsonResponse([
            'error' => $e->getMessage()
        ], 400);
    }
}

$paymentRequest = new PaymentRequest(
    orderId: 'ORDER_123',        // Unique order ID
    amount: 10000,               // Amount 
    currency: 'OUV',             // Currency (OUV for Ouguiya)
    reference: 'REF_123',        // Optional reference
    merchantKey: 'merchant_key', // Merchant key
    returnUrl: 'https://...',    // Success return URL
    cancelUrl: 'https://...',    // Cancellation URL
    notifUrl: 'https://...'      // Notification URL
);

// Available methods
$response->getPaymentUrl();    // Payment URL
$response->getPayToken();      // Payment token
$response->getNotifToken();    // Notification token (for webhook validation)
$response->getTxnId();         // Transaction ID
$response->getStatus();        // Payment status
$response->getOrderId();       // Order ID
$response->getAmount();        // Amount
$response->getCurrency();      // Currency
$response->isSuccessful();     // Success verification
$response->hasError();         // Error verification
$response->getErrorMessage();  // Error message
$response->getErrorCode();     // Error code
$response->hasPaymentUrl();    // Payment URL validation
$response->getRawData();       // Raw data

// Required fields validated automatically
$tion
$paymentStatus = $orangeMoneyService->processNotification($data, $expectedNotifToken);

$paymentResponse = $orangeMoneyService->initiatePayment($paymentRequest);
$notifToken = $paymentResponse->getNotifToken();
// Store this token securely (database, cache, etc.)
$this->storeNotifToken($paymentRequest->getOrderId(), $notifToken);

$expectedToken = $this->getStoredNotifToken($orderId);
$paymentStatus = $orangeMoneyService->processNotification($webhookData, $expectedToken);

try {
    $paymentResponse = $orangeMoneyService->initiatePayment($paymentRequest);
} catch (OrangeMoneyException $e) {
    // Orange Money specific error
    $errorMessage = $e->getMessage();
    $errorData = $e->getData();
}

src/OrangeMoneyBundle/
├── DependencyInjection/
│   ├── Configuration.php          # Bundle configuration
│   └── OrangeMoneyExtension.php    # Symfony extension
├── Exception/
│   └── OrangeMoneyException.php    # Custom exceptions
├── Model/
│   ├── PaymentRequest.php          # Payment request model
│   └── PaymentResponse.php         # Payment response model
├── Service/
│   └── OrangeMoneyService.php      # Main service
└── OrangeMoneyBundle.php           # Main bundle class