Skip to content

Getting Started - Payment Gateway Development

Minimum Version Requirement

This feature requires WhatsMarkSaaS v2.0.0 or higher. Ensure your installation meets this requirement before proceeding.

Overview

This guide demonstrates how to integrate third-party payment gateways into WhatsMarkSaaS. You will implement the PaymentGatewayInterface and register your gateway with the multi-tenant billing system.

Payment gateway modules are self-contained extensions that add new payment processing capabilities to the platform while maintaining multi-tenant isolation and clean architecture.


Prerequisites

You must meet the following requirements before proceeding:

System Requirements

RequirementVersionPurpose
WhatsMarkSaaS2.0.0+Platform version
Laravel12+Framework
PHP8.3+Runtime environment
Livewire3.6+Dynamic UI components

Required Knowledge

You must have working knowledge of:

  • Laravel 12+ - Service providers, events, middleware
  • PHP 8.3+ - Object-oriented programming, interfaces, traits
  • Multi-tenant architecture - Tenant isolation using Spatie Laravel Multitenancy
  • Payment gateway APIs - HTTP requests, JSON responses, webhook handling
  • Webhook security - Signature verification, replay attack prevention

Payment Gateway Development Workflow

Implementation Steps

  1. Generate payment gateway module using custom type command
  2. Configure module metadata for payment gateway
  3. Create payment gateway service implementing PaymentGatewayInterface
  4. Implement gateway API service for payment provider communication
  5. Add payment event listeners to register gateway
  6. Create admin settings for gateway configuration
  7. Build payment flow with checkout and callback handling
  8. Test payment processing and webhook handling
  9. Enable module and verify integration

Step 1: Create Payment Gateway Module

Execute the module generation command:

bash
php artisan module:make TapGateway --type=custom

Command output:

text
[TapGateway] module created successfully.
Module type: Custom
To activate the module, run: php artisan module:activate TapGateway

Generated structure:

Modules/TapGateway/
 Config/
    config.php
 Database/
    Migrations/
    Seeders/
 Http/
    Controllers/
    Middleware/
 Providers/
    TapGatewayServiceProvider.php
    RouteServiceProvider.php
 resources/
    assets/
    lang/
    views/
 Routes/
    web.php
    api.php
 TapGateway.php
 module.json

Step 2: Configure Module Metadata

Update module.json with payment gateway metadata:

json
{
  "name": "TapGateway",
  "alias": "tap-gateway",
  "namespace": "Modules\\TapGateway\\",
  "provider": "Modules\\TapGateway\\Providers\\TapGatewayServiceProvider",
  "author": "Your Name",
  "version": "1.0.0",
  "description": "Tap Payment Gateway Integration",
  "keywords": ["payment", "gateway", "tap"],
  "order": 0,
  "providers": [
    "Modules\\TapGateway\\Providers\\TapGatewayServiceProvider"
  ],
  "require": [],
  "requires_at": "2.0.0",
  "conflicts": [],
  "type": "custom"
}

Critical fields:

FieldValueDescription
typecustomRequired for payment gateway modules
requires_at2.0.0Minimum WhatsMarkSaaS version
namespaceModules\\TapGateway\\PSR-4 namespace with trailing backslash

Step 3: Create Payment Settings Migration

Payment gateways require database settings for configuration storage.

Create settings migration:

bash
php artisan module:make-migration create_tap_gateway_settings TapGateway

Migration file (Database/Migrations/):

php
<?php

use Spatie\LaravelSettings\Migrations\SettingsMigration;

return new class extends SettingsMigration
{
    protected array $settings = [
        // Gateway controls
        'payment.tap_gateway_enabled' => false,

        // API configuration
        'payment.tap_gateway_api_key' => '',
        'payment.tap_gateway_secret_key' => '',

        // Environment settings
        'payment.tap_gateway_sandbox_mode' => true,

        // Webhook configuration
        'payment.tap_gateway_webhook_secret' => '',

        // Payment preferences
        'payment.tap_gateway_currency' => 'USD',
        'payment.tap_gateway_description' => 'Payment via Tap Gateway',
    ];

    public function up(): void
    {
        foreach ($this->settings as $key => $value) {
            if (! $this->migrator->exists($key)) {
                $this->migrator->add($key, $value);
            }
        }
    }

    public function down(): void
    {
        foreach (array_keys($this->settings) as $key) {
            if ($this->migrator->exists($key)) {
                $this->migrator->delete($key);
            }
        }
    }
};

Run migration:

bash
php artisan migrate --path=Modules/TapGateway/Database/Migrations

Step 4: Implement PaymentGatewayInterface

Create gateway service class implementing the required interface:

File: Services/TapGatewayService.php

php
<?php

namespace Modules\TapGateway\Services;

use App\Contracts\PaymentGatewayInterface;
use Illuminate\Http\Request;

class TapGatewayService implements PaymentGatewayInterface
{
    /**
     * Get gateway identifier.
     */
    public function getName(): string
    {
        return 'tap_gateway';
    }

    /**
     * Get gateway display name.
     */
    public function getDisplayName(): string
    {
        return 'Tap Gateway';
    }

    /**
     * Check if gateway is enabled.
     */
    public function isEnabled(): bool
    {
        return settings('payment.tap_gateway_enabled', false);
    }

    /**
     * Create payment session.
     *
     * @param array $data Payment data (amount, currency, description, etc.)
     * @return array Payment session response
     */
    public function createPayment(array $data): array
    {
        // Implement payment creation logic
        // Return payment session URL and transaction ID
    }

    /**
     * Handle payment callback.
     *
     * @param Request $request Callback request
     * @return array Payment status response
     */
    public function handleCallback(Request $request): array
    {
        // Implement callback handling logic
        // Verify payment status and return result
    }

    /**
     * Process webhook notification.
     *
     * @param Request $request Webhook request
     * @return bool Webhook processing success
     */
    public function handleWebhook(Request $request): bool
    {
        // Implement webhook verification and processing
        // Return true if webhook is valid and processed
    }

    /**
     * Verify webhook signature.
     *
     * @param Request $request Webhook request
     * @return bool Signature validity
     */
    public function verifyWebhookSignature(Request $request): bool
    {
        // Implement signature verification logic
    }
}

Step 5: Register Payment Gateway

Register the gateway with the payment system using event listeners:

File: Providers/TapGatewayServiceProvider.php

php
<?php

namespace Modules\TapGateway\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Event;
use Modules\TapGateway\Services\TapGatewayService;

class TapGatewayServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // Register views
        $this->loadViewsFrom(__DIR__.'/../resources/views', 'tapgateway');

        // Register translations
        $this->loadTranslationsFrom(
            module_path('TapGateway', 'resources/lang'),
            'tapgateway'
        );

        // Register migrations
        $this->loadMigrationsFrom(
            module_path('TapGateway', 'Database/Migrations')
        );

        // Register payment gateway
        Event::listen('payment.gateways.register', function () {
            return new TapGatewayService();
        });
    }

    public function register(): void
    {
        $this->app->register(RouteServiceProvider::class);
    }
}

Step 6: Create Admin Settings Page

Create Livewire component for admin configuration:

File: Livewire/TapGatewaySettings.php

php
<?php

namespace Modules\TapGateway\Livewire;

use Livewire\Component;

class TapGatewaySettings extends Component
{
    public bool $enabled;
    public string $api_key;
    public string $secret_key;
    public bool $sandbox_mode;
    public string $webhook_secret;
    public string $currency;
    public string $description;

    public function mount(): void
    {
        $this->enabled = settings('payment.tap_gateway_enabled', false);
        $this->api_key = settings('payment.tap_gateway_api_key', '');
        $this->secret_key = settings('payment.tap_gateway_secret_key', '');
        $this->sandbox_mode = settings('payment.tap_gateway_sandbox_mode', true);
        $this->webhook_secret = settings('payment.tap_gateway_webhook_secret', '');
        $this->currency = settings('payment.tap_gateway_currency', 'USD');
        $this->description = settings('payment.tap_gateway_description', '');
    }

    public function save(): void
    {
        $this->validate([
            'api_key' => 'required|string',
            'secret_key' => 'required|string',
            'currency' => 'required|string|size:3',
        ]);

        settings([
            'payment.tap_gateway_enabled' => $this->enabled,
            'payment.tap_gateway_api_key' => $this->api_key,
            'payment.tap_gateway_secret_key' => $this->secret_key,
            'payment.tap_gateway_sandbox_mode' => $this->sandbox_mode,
            'payment.tap_gateway_webhook_secret' => $this->webhook_secret,
            'payment.tap_gateway_currency' => $this->currency,
            'payment.tap_gateway_description' => $this->description,
        ]);

        session()->flash('success', 'Settings saved successfully.');
    }

    public function render()
    {
        return view('tapgateway::livewire.settings');
    }
}

Register Livewire component:

php
use Livewire\Livewire;

public function boot(): void
{
    // ... existing registrations ...

    Livewire::component('tap-gateway::settings', \Modules\TapGateway\Livewire\TapGatewaySettings::class);
}

Step 7: Create Routes

Define routes for payment processing and webhooks:

File: Routes/web.php

php
<?php

use Illuminate\Support\Facades\Route;
use Modules\TapGateway\Http\Controllers\TapGatewayController;

Route::middleware('web')->group(function () {
    Route::prefix('tap-gateway')->group(function () {
        // Payment callback
        Route::get('/callback', [TapGatewayController::class, 'callback'])
            ->name('tap-gateway.callback');

        // Payment success
        Route::get('/success', [TapGatewayController::class, 'success'])
            ->name('tap-gateway.success');

        // Payment cancel
        Route::get('/cancel', [TapGatewayController::class, 'cancel'])
            ->name('tap-gateway.cancel');
    });
});

File: Routes/api.php

php
<?php

use Illuminate\Support\Facades\Route;
use Modules\TapGateway\Http\Controllers\Api\WebhookController;

Route::middleware('api')->prefix('api')->group(function () {
    Route::prefix('tap-gateway')->group(function () {
        // Webhook endpoint (no authentication)
        Route::post('/webhook', [WebhookController::class, 'handle'])
            ->name('tap-gateway.webhook');
    });
});

Step 8: Activate Module

Activate the payment gateway module:

bash
php artisan module:activate TapGateway

Activation process:

  1. Migrations run automatically (if auto_migrations enabled)
  2. Seeders execute after migrations
  3. Routes are registered
  4. Payment gateway is registered with system
  5. Module becomes available in admin settings

Essential Module Commands

CommandPurpose
php artisan module:make {Name} --type=customCreate payment gateway module
php artisan module:activate {Name}Activate module
php artisan module:deactivate {Name}Deactivate module
php artisan module:listList all modules
php artisan module:make-controller {Name} {Module}Generate controller
php artisan module:make-migration {Name} {Module}Generate migration
php artisan module:make-listener {Name} {Module}Generate event listener

Payment Gateway Requirements

Mandatory Implementation

You must implement the following:

  1. PaymentGatewayInterface - Core gateway methods
  2. Settings migration - Gateway configuration storage
  3. Admin settings page - Configuration UI
  4. Payment routes - Checkout, callback, webhook endpoints
  5. Webhook verification - Signature validation
  6. Multi-tenant support - Tenant-aware operations

Security Requirements

  1. API credentials encryption - Store sensitive data securely
  2. Webhook signature verification - Validate webhook authenticity
  3. HTTPS enforcement - Use secure connections only
  4. Rate limiting - Prevent abuse
  5. Logging - Audit payment operations

Testing Requirements

Local Testing

  1. Sandbox mode - Use test API credentials
  2. Test card numbers - Verify payment flows
  3. Webhook testing - Use ngrok or webhook.site for local testing
  4. Error scenarios - Test payment failures, timeouts

Production Checklist

  • [ ] Sandbox mode disabled
  • [ ] Production API credentials configured
  • [ ] Webhook signature verification enabled
  • [ ] HTTPS enabled on all endpoints
  • [ ] Error logging configured
  • [ ] Payment success/failure flows tested
  • [ ] Webhook processing tested
  • [ ] Multi-tenant isolation verified

Next Steps

You have successfully created a payment gateway module. Proceed with:

  1. Payment Gateway Guide - Detailed implementation guide
  2. Step-by-Step Tutorial - Complete TapGateway example
  3. Tenant Billing Integration - Billing system integration
  4. Language Synchronization - Multi-language support

Troubleshooting

Module not appearing in payment settings

Solutions:

  1. Verify module is activated: php artisan module:list
  2. Check PaymentGatewayInterface implementation
  3. Verify event listener is registered
  4. Clear cache: php artisan cache:clear

Webhook not receiving notifications

Solutions:

  1. Verify webhook URL is publicly accessible
  2. Check webhook signature verification logic
  3. Review payment gateway webhook configuration
  4. Check server logs for errors

Payment gateway settings not saving

Solutions:

  1. Verify settings migration ran successfully
  2. Check database settings table for entries
  3. Verify Spatie settings package is installed
  4. Clear config cache: php artisan config:clear

This guide is for WhatsMarkSaaS v2.0.0+ payment gateway development.

© 2024 - Corbital Technologies. All rights reserved.