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

Library Laravel Package

myfatoorah/library

PHP library for integrating MyFatoorah payment gateway. Create invoices, execute and verify payments, handle callbacks, and manage payment status in your Laravel or PHP app with a simple API wrapper and configuration options.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require myfatoorah/library
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="MyFatoorah\Library\MyFatoorahServiceProvider" --tag="config"
    
  2. Configuration Set your API credentials in .env:

    MYFATOORAH_MERCHANT_ID=your_merchant_id
    MYFATOORAH_API_USERNAME=your_username
    MYFATOORAH_API_PASSWORD=your_password
    MYFATOORAH_API_KEY=your_api_key
    MYFATOORAH_API_SECRET=your_api_secret
    MYFATOORAH_API_URL=https://api.myfatoorah.com
    
  3. First Use Case: Create an Invoice

    use MyFatoorah\Library\MyFatoorah;
    
    $myFatoorah = new MyFatoorah([
        'merchant_id' => env('MYFATOORAH_MERCHANT_ID'),
        'api_username' => env('MYFATOORAH_API_USERNAME'),
        'api_password' => env('MYFATOORAH_API_PASSWORD'),
        'api_key' => env('MYFATOORAH_API_KEY'),
        'api_secret' => env('MYFATOORAH_API_SECRET'),
        'api_url' => env('MYFATOORAH_API_URL'),
    ]);
    
    $invoice = $myFatoorah->createInvoice([
        'invoice_number' => 'INV-123',
        'amount' => 100.00,
        'currency_code' => 'SAR',
        'customer' => [
            'name' => 'John Doe',
            'email' => 'john@example.com',
            'phone_number' => '123456789',
        ],
        'items' => [
            [
                'name' => 'Product 1',
                'quantity' => 1,
                'price' => 100.00,
            ],
        ],
    ]);
    
    dd($invoice);
    

Implementation Patterns

Common Workflows

  1. Invoice Management

    • Create: Use createInvoice() for new invoices.
    • Query: Use getInvoice() to fetch an invoice by ID.
    • Cancel: Use cancelInvoice() to void a payment.
  2. Payment Links Generate a payment link for customer checkout:

    $paymentLink = $myFatoorah->createPaymentLink([
        'invoice_number' => 'INV-123',
        'amount' => 100.00,
        'currency_code' => 'SAR',
        'customer' => [...],
        'success_url' => route('payment.success'),
        'failure_url' => route('payment.failure'),
    ]);
    
  3. Webhooks Configure webhook endpoints in the MyFatoorah dashboard and validate payloads in Laravel:

    public function handleWebhook(Request $request)
    {
        $myFatoorah = new MyFatoorah([...]);
        $isValid = $myFatoorah->validateWebhook($request->all());
    
        if ($isValid) {
            // Process payment status update
        }
    }
    
  4. Refunds Refund a paid invoice:

    $refund = $myFatoorah->createRefund([
        'invoice_id' => 123,
        'amount' => 50.00,
        'reason' => 'Partial refund',
    ]);
    

Integration Tips

  • Laravel Service Provider: Bind the client to the container for dependency injection:
    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(MyFatoorah::class, function ($app) {
            return new MyFatoorah([
                'merchant_id' => env('MYFATOORAH_MERCHANT_ID'),
                // ...
            ]);
        });
    }
    
  • Form Requests: Validate invoice data using Laravel’s FormRequest:
    use Illuminate\Foundation\Http\FormRequest;
    
    class CreateInvoiceRequest extends FormRequest
    {
        public function rules()
        {
            return [
                'invoice_number' => 'required|string',
                'amount' => 'required|numeric|min:0.01',
                'currency_code' => 'required|string|size:3',
            ];
        }
    }
    
  • Logging: Enable debug logging for API calls:
    $myFatoorah = new MyFatoorah([...], [
        'debug' => true,
        'log_file' => storage_path('logs/myfatoorah.log'),
    ]);
    

Gotchas and Tips

Pitfalls

  1. API Rate Limits

    • MyFatoorah enforces rate limits (e.g., 10 requests/second). Cache responses where possible and handle 429 Too Many Requests gracefully:
      try {
          $invoice = $myFatoorah->getInvoice($id);
      } catch (\MyFatoorah\Library\Exceptions\RateLimitException $e) {
          // Retry with exponential backoff
      }
      
  2. Webhook Validation

    • Always validate webhook payloads using validateWebhook() to prevent spoofing:
      $isValid = $myFatoorah->validateWebhook($request->all(), $request->get('signature'));
      if (!$isValid) {
          abort(403, 'Invalid webhook signature');
      }
      
  3. Currency and Amount Precision

    • Ensure amounts are passed as strings or with sufficient decimal precision (e.g., 100.00 instead of 100) to avoid rounding errors.
  4. Invoice Number Uniqueness

    • MyFatoorah requires globally unique invoice numbers. Use UUIDs or a combination of prefix + timestamp:
      $invoiceNumber = 'ORD-' . Str::upper(Strings::uuid());
      

Debugging

  • Enable Debug Mode: Set 'debug' => true in the client config to log API requests/responses to storage/logs/myfatoorah.log.
  • Test in Sandbox: Use the sandbox environment (MYFATOORAH_API_URL=https://sandbox.myfatoorah.com) for development:
    $myFatoorah = new MyFatoorah([...], [
        'api_url' => 'https://sandbox.myfatoorah.com',
    ]);
    
  • Common Errors:
    • InvalidSignatureException: Verify api_key and api_secret in .env.
    • InvalidRequestException: Check payload structure against MyFatoorah’s API docs.

Extension Points

  1. Custom Responses Extend the library to transform responses:

    $myFatoorah->setResponseTransformer(function ($response) {
        return [
            'data' => $response->data,
            'meta' => [
                'status' => $response->status,
                'message' => $response->message,
            ],
        ];
    });
    
  2. Middleware for API Calls Add middleware to log or modify requests:

    $myFatoorah->setRequestMiddleware(function ($request) {
        $request->headers->set('X-Custom-Header', 'value');
    });
    
  3. Event Dispatching Trigger Laravel events for payment status changes:

    $myFatoorah->on('payment.succeeded', function ($payload) {
        event(new PaymentSucceeded($payload));
    });
    
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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony