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

Easypaisa Laravel Package

zfhassaan/easypaisa

Unofficial Laravel package for integrating Easypaisa payments with Direct (REST API) and Hosted Checkout (redirect) flows. Includes config publishing, .env settings for sandbox/production, credentials, hash keys, callback URL, and helper methods to send payment requests.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require zfhassaan/easypaisa
    

    Publish the config file:

    php artisan vendor:publish --provider="Zfhassaan\EasyPaisa\EasyPaisaServiceProvider" --tag=easypaisa-config
    
  2. Configure .env Add your EasyPaisa credentials:

    EASYPAISA_MERCHANT_ID=your_merchant_id
    EASYPAISA_SECRET_KEY=your_secret_key
    EASYPAISA_API_URL=https://api.easypaisa.com.pk/api/
    
  3. First Use Case: Initiate a Payment

    use Zfhassaan\EasyPaisa\Facades\EasyPaisa;
    
    $response = EasyPaisa::initiatePayment([
        'amount' => 100.00,
        'order_id' => 'ORDER123',
        'customer_name' => 'John Doe',
        'customer_email' => 'john@example.com',
        'customer_phone' => '03001234567',
        'callback_url' => route('easypaisa.callback'),
    ]);
    
    if ($response->success()) {
        return redirect()->to($response->getPaymentUrl());
    }
    
  4. Callback Handling Add a route and controller method to handle the callback:

    Route::post('/easypaisa/callback', [PaymentController::class, 'handleCallback']);
    
    public function handleCallback(Request $request)
    {
        $response = EasyPaisa::verifyCallback($request->all());
        if ($response->success()) {
            // Payment verified, update order status
        }
    }
    

Implementation Patterns

Common Workflows

  1. Initiating Payments Use EasyPaisa::initiatePayment() for one-time payments. Pass an associative array with required fields:

    $paymentData = [
        'amount' => 500.00,
        'order_id' => 'INV-'.Str::uuid(),
        'customer_name' => 'Customer Name',
        'customer_email' => 'customer@example.com',
        'customer_phone' => '03001234567',
        'callback_url' => route('easypaisa.callback'),
        'description' => 'Product Purchase',
    ];
    
  2. Subscription Payments For recurring payments, use the subscription_id and plan_id fields:

    $response = EasyPaisa::initiateSubscriptionPayment([
        'amount' => 200.00,
        'subscription_id' => 'SUB_123',
        'plan_id' => 'PLAN_456',
        'customer_phone' => '03001234567',
    ]);
    
  3. Handling Callbacks Always verify the callback using EasyPaisa::verifyCallback() before processing:

    public function handleCallback(Request $request)
    {
        $callbackData = $request->all();
        $response = EasyPaisa::verifyCallback($callbackData);
    
        if ($response->success()) {
            // Update order status, send confirmation, etc.
            return response()->json(['status' => 'success']);
        }
        return response()->json(['status' => 'failed'], 400);
    }
    
  4. Webhooks For real-time updates, configure webhooks in the EasyPaisa merchant dashboard and point them to a Laravel endpoint. Use middleware to validate signatures:

    public function handleWebhook(Request $request)
    {
        $signature = $request->header('X-EasyPaisa-Signature');
        $payload = $request->getContent();
    
        if (EasyPaisa::verifyWebhook($payload, $signature)) {
            // Process webhook event
        }
    }
    

Integration Tips

  • Laravel Cashier Integration Extend the package to work with Laravel Cashier for subscription management:

    use Laravel\Cashier\Subscription;
    
    $subscription = Subscription::create('plan_name', 200.00);
    $easypaisaResponse = EasyPaisa::initiateSubscriptionPayment([
        'subscription_id' => $subscription->id,
        'plan_id' => 'PLAN_456',
        'customer_phone' => auth()->user()->phone,
    ]);
    
  • Logging Enable logging for debugging:

    EASYPAISA_LOG_ENABLED=true
    
  • Testing Use the EasyPaisa::setTestMode(true) to test payments without processing real transactions:

    EasyPaisa::setTestMode(true);
    

Gotchas and Tips

Pitfalls

  1. Callback Verification

    • Issue: Always verify callbacks using verifyCallback(). Skipping this can lead to fraudulent transactions.
    • Fix: Ensure the callback URL in your initiatePayment() matches the route handling the callback.
  2. Amount Precision

    • Issue: EasyPaisa expects amounts in paise (e.g., 100.00 becomes 10000). The package handles this internally, but ensure your input is correct.
    • Fix: Pass amounts as floats or strings (e.g., 100.00), not integers.
  3. Phone Number Format

    • Issue: Pakistani phone numbers must include the country code (e.g., +923001234567). Missing this can cause failures.
    • Fix: Validate and format phone numbers before passing them to the package.
  4. Test Mode Quirks

    • Issue: Test mode may not simulate all error cases. Use the EasyPaisa Sandbox for thorough testing.
    • Fix: Manually test edge cases like invalid amounts or expired transactions.
  5. Webhook Signatures

    • Issue: Webhook payloads must be verified with the correct signature. Mismatches will cause failures.
    • Fix: Use EasyPaisa::verifyWebhook($payload, $signature) and ensure the EASYPAISA_WEBHOOK_SECRET in .env matches the one in your EasyPaisa dashboard.

Debugging Tips

  1. Enable Logging Set EASYPAISA_LOG_ENABLED=true in .env to log API requests/responses to storage/logs/easypaisa.log.

  2. Check HTTP Status Codes The package returns response objects with success(), getStatusCode(), and getMessage(). Log these for debugging:

    $response = EasyPaisa::initiatePayment([...]);
    if (!$response->success()) {
        logger()->error('EasyPaisa Error: ' . $response->getMessage());
    }
    
  3. Validate API URLs Ensure EASYPAISA_API_URL in .env is correct (e.g., https://api.easypaisa.com.pk/api/ for live, https://sandbox.easypaisa.com.pk/api/ for test).

  4. Order ID Uniqueness EasyPaisa requires unique order_ids. Reuse can cause conflicts. Use UUIDs or database checks:

    $orderId = 'ORDER_' . Str::uuid();
    

Extension Points

  1. Custom Responses Override the default response handling by extending the Zfhassaan\EasyPaisa\EasyPaisa class:

    namespace App\Services;
    
    use Zfhassaan\EasyPaisa\EasyPaisa as BaseEasyPaisa;
    
    class CustomEasyPaisa extends BaseEasyPaisa
    {
        public function initiatePayment(array $data)
        {
            $response = parent::initiatePayment($data);
            // Custom logic here
            return $response;
        }
    }
    
  2. Additional Fields EasyPaisa supports custom fields. Pass them via the custom_fields key:

    $response = EasyPaisa::initiatePayment([
        'amount' => 100.00,
        'custom_fields' => [
            'user_id' => auth()->id(),
            'product_id' => 123,
        ],
    ]);
    
  3. Retry Logic Implement retry logic for failed payments using Laravel's retry helper or a queue job:

    use Illuminate\Support\Facades\Retry;
    
    Retry::times(3)->attempt(function () {
        $response = EasyPaisa::initiatePayment([...]);
        if (!$response->success()) {
            throw new \Exception('Payment failed');
        }
    });
    
  4. Localization Customize error messages by overriding the language file:

    // config/easypaisa.php
    'messages' => [
        'payment_f
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky