PHP code example of mhaggag / laravel-payments

1. Go to this page and download the library: Download mhaggag/laravel-payments 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/ */

    

mhaggag / laravel-payments example snippets


use MHaggag\Payments\Console\PaypalWebhookCommand;
use MHaggag\Payments\Console\StripeWebhookCommand;
use MHaggag\Payments\Enums\GatewayName;

return [
    /*
    |--------------------------------------------------------------------------
    | Default Payment Gateway
    |--------------------------------------------------------------------------
    */
    'default' => env('PAYMENT_DEFAULT_GATEWAY', GatewayName::STRIPE),

    /*
    |--------------------------------------------------------------------------
    | Default Currency
    |--------------------------------------------------------------------------
    */
    'default_currency' => env('PAYMENT_DEFAULT_CURRENCY', 'USD'),

    /*
    |--------------------------------------------------------------------------
    | Route Configuration
    |--------------------------------------------------------------------------
    | * On enable it, will set 3 routes
    |        POST  payments/checkout ............ payments.checkout › MHaggag\Payments\Http\Controllers\PaymentController@checkout
    |        GET   payments/success/{gateway} ... payments.success  › MHaggag\Payments\Http\Controllers\PaymentController@success
    |        GET   payments/cancel/{gateway} .... payments.cancel   › MHaggag\Payments\Http\Controllers\PaymentController@cancel
    */
    'route' => [
        'enabled' => env('PAYMENT_ROUTE_ENABLED', true),
        'prefix' => env('PAYMENT_ROUTE_PREFIX', 'payments'),
        'middleware' => ['web'],
        'name_prefix' => env('PAYMENT_ROUTE_NAME_PREFIX', 'payments.'),
    ],

    /*
    |--------------------------------------------------------------------------
    | Model Configuration
    |--------------------------------------------------------------------------
    */
    'models' => [
        'payment' => \MHaggag\Payments\Models\Payment::class,
        'subscription' => \MHaggag\Payments\Models\Subscription::class,
    ],

    /*
    |--------------------------------------------------------------------------
    | Payment Gateways Configuration
    |--------------------------------------------------------------------------
    */
    'gateways' => [
        GatewayName::STRIPE => [
            'class' => \MHaggag\Payments\Gateways\StripeGateway::class,
            'api_key' => env('STRIPE_API_KEY'),
            'secret_key' => env('STRIPE_SECRET_KEY'),
            'webhook_secret' => env('STRIPE_WEBHOOK_SECRET'),
            'mode' => env('STRIPE_MODE', 'test'),
            'currency' => env('STRIPE_CURRENCY', 'usd'),
        ],

        GatewayName::PAYPAL => [
            'class' => \MHaggag\Payments\Gateways\PaypalGateway::class,
            'client_id' => env('PAYPAL_CLIENT_ID'),
            'client_secret' => env('PAYPAL_CLIENT_SECRET'),
            'webhook_id' => env('PAYPAL_WEBHOOK_ID'),
            'mode' => env('PAYPAL_MODE', 'sandbox'),
            'currency' => env('PAYPAL_CURRENCY', 'USD'),
        ],

        GatewayName::PAYMOB => [
            'class' => \MHaggag\Payments\Gateways\PaymobGateway::class,
            'api_key' => env('PAYMOB_API_KEY'),
            'secret_key' => env('PAYMOB_SECRET_KEY'),
            'public_key' => env('PAYMOB_PUBLIC_KEY'),
            'hmac_secret' => env('PAYMOB_HMAC_SECRET'),
            'integration_id' => env('PAYMOB_INTEGRATION_ID'),
            'moto_integration_id' => env('PAYMOB_MOTO_INTEGRATION_ID'),
            'mode' => env('PAYMOB_MODE', 'test'),
            'currency' => env('PAYMOB_CURRENCY', 'EGP'),
            'region' => env('PAYMOB_REGION', 'EGY'),
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Webhook Configuration
    |--------------------------------------------------------------------------
    |
    | * with built in payments.verify_signature midlleware that you can remove it to prevent the signature verification.
    | * On enable it, will set 3 routes
    |       POST  payments/webhook/{gateway} ........ MHaggag\Payments\Http\Controllers\WebhookController@handle
    */
    'webhook' => [
        'enabled' => env('PAYMENT_ROUTE_WEBHOOK_ENABLED', true),
        'prefix' => '/payments/webhook',
        'middleware' => ['api', 'payments.verify_signature'],

        'events' => [
            'stripe' => StripeWebhookCommand::DEFAULT_EVENTS,
            'paypal' => PaypalWebhookCommand::DEFAULT_EVENTS,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Events Configuration
    |--------------------------------------------------------------------------
    */
    'events' => [
        'payment' => [
            'received' => \MHaggag\Payments\Events\PaymentRedirectReceived::class,
            'processed' => \MHaggag\Payments\Events\PaymentRedirectProcessed::class,
        ],
        'webhook' => [
            'received' => \MHaggag\Payments\Events\PaymentWebhookReceived::class,
            'processed' => \MHaggag\Payments\Events\PaymentWebhookProcessed::class,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Logging Configuration
    |--------------------------------------------------------------------------
    */
    'logging' => [
        'enabled' => env('PAYMENT_LOGGING_ENABLED', false),
        'channel' => env('PAYMENT_LOGGING_CHANNEL', 'stack'),
        'level' => env('PAYMENT_LOGGING_LEVEL', 'info'),
    ],
];

use MHaggag\Payments\Enums\GatewayName;

GatewayName::STRIPE;
GatewayName::PAYPAL;
GatewayName::PAYMOB;

use MHaggag\Payments\Facades\Payment;

Payment::gateway(GatewayName::Stripe);

use MHaggag\Payments\Facades\Payment;
use MHaggag\Payments\Enums\GatewayName;

Payment::gateway(GatewayName::PAYPAL)
    ->amount(50)
    ->currency('EUR')
    ->description('Order #123')
    ->redirectUrls(route('payment.success'), route('payment.cancel'))
    ->isSubscription()
    ->items([
        {
            'name' => 'Product A',
            'price' => 10,
            'quantity' => 2,
        },
        {
            'name' => 'Product B',
            'price' => 20,
            'quantity' => 1,
        },
    ])
    ->metadata([
        'order_id' => 123,
    ])
    ->checkout();

// Or can you set all with
Payment::gateway(GatewayName::PAYPAL)
    ->withPayload([
        'amount' => 50,
        'currency' => 'EUR',
        'description' => 'Order #123',
        'success_url' => route('payment.success'),
        'cancel_url' => route('payment.cancel'),
        'allow_promotion_codes' => true,
        'is_subscription' => false,
        'items' => [
            {
                'name' => 'Product A',
                'amount' => 10,
                'quantity' => 2,
            },
            {
                'name' => 'Product B',
                'amount' => 20,
                'quantity' => 1,
            },
        ],
        'metadata' => [
            'order_id' => 123,
        ],
    ])
    ->checkout();

use MHaggag\Payments\Traits\Payable;

class User extends Model
{
    use Payable;
}

$user->payment(GatewayName::STRIPE)
    ->amount(100)
    ->currency('USD')
    ->checkout();

use MHaggag\Payments\Traits\Subscribable;

class User extends Model
{
    use Subscribable;
}

$user->subscribe(GatewayName::PAYPAL)
    ->amount(20)
    ->currency('USD')
    ->checkout();

Payment::gateway(GatewayName::STRIPE)
    // Special parameters for stripe
    ->payload([
        'payment_method_types' => ['card'],
        'customer' => $user->name,
        'customer_email' => $user->email,
        'client_reference_id' => $user->id, // Optional, the default will be payment->uuid
        'subscription_data' => [], // if you want to create a subscription
        'allow_promotion_codes' => true,
        'source' => '', // Token, card reference, etc when using create method instead of checkout
        'items' => [
            // items can be 
            {
                'name' => 'Product A',
                'amount' => 10,
                'quantity' => 2,
            },
            
            // Or
            {
                'price_id' => 'stripe_price_id',
                'quantity' => 1,
            },

            // if you do not pass any items, the default will be the payment amount, and name will be description.
        ],
    ]);

/**
 * Note: By using isSubscription() method to enable subscription mode
 * You must provide at least one recurring price in `subscription` mode when using prices.
 */
Payment::gateway(GatewayName::STRIPE)
    ->withPayload([])
    ->isSubscription()
    ->items([
        ['price_id' => 'price_1St7q................', 'quantity' => 1]
    ])

Payment::gateway(GatewayName::PAYPAL)
    // Special parameters for paypal
    ->payload([
        'brand_name' => 'Your Brand', // default will be app name
        'locale' => 'en_US', // default will be 'en_US'
        'source' => '', // Token, card reference, etc when using create method instead of checkout
        'items' => [
            // items can be 
            {
                'name' => 'Product A',
                'amount' => 10,
                'quantity' => 2,
                'description' => 'Product A description'
            },

            // if you do not pass any items, the default will be the payment amount, and name will be description.
        ],
    ]);

/**
 * Note: By using isSubscription() method to enable subscription mode
 * You must send plan_id that you created in paypal.
 */
Payment::gateway(GatewayName::PAYPAL)
    ->withPayload([
        'plan_id' => 'paypal_plan_id',
    ])
    ->isSubscription()

Payment::gateway(GatewayName::PAYMOB)
    ->withPayload([
        'notification_url' => 'notification_url', // default will be configured in config/payments.php under the webhook key
        'billing_data' => [
            "email" => "[email protected]", //      "building" => "dumy", // optional
            "city" => "dumy", // optional
            "country" => "dumy", // optional
            "floor" => "dumy", // optional
            "state" => "dumy" // optional
        ],
        'items' => [ // optional
            [
                'name' => 'Item name',
                'amount' => 100,
                'quantity' => 1,
                'description' => 'Item description'
            ],
        ],
        'special_reference' => $user->uuid, // Optional, the default will be payment->uuid
    ]);

/**
 * Note: By using isSubscription() method to enable subscription mode
 * You must send plan_id that you created in next step.
 */
$plan = Payment::driver(GatewayName::PAYMOB)->createSubscriptionPlan([
    'name' => 'Test Plan',
    'amount' => 100,
    'frequency' => 7, // Values can be (7, 15, 30, 60, 90, 180, 360)
    'use_transaction_amount' => true, // default is true
    'reminder_days' => 2, // optional
    'retrial_days' => 2, // optional
    'number_of_deductions' => 2, // default is null
    'webhook_url' => 'webhook_url', // default will be configured in config/payments.php under the webhook key
]);

Payment::gateway(GatewayName::PAYMOB)
    ->withPayload([
        'plan_id' => $plan['id'],
    ])
    ->isSubscription()
/**
 * Subscription creation is being done by completing one 3DS transaction to save the customer's card and connect it with the subscription.
 */

'route' => [
    'enabled' => env('PAYMENT_ROUTE_ENABLED', true),
    'prefix' => env('PAYMENT_ROUTE_PREFIX', 'payments'),
    'middleware' => ['web'],
    'name_prefix' => env('PAYMENT_ROUTE_NAME_PREFIX', 'payments.'),
]

'webhook' => [
    'enabled' => env('PAYMENT_ROUTE_WEBHOOK_ENABLED', true),
    'prefix' => '/payments/webhook',
    'middleware' => ['api', 'payments.verify_signature'],
]

'events' => [
    'payment' => [
        'received' => \MHaggag\Payments\Events\PaymentRedirectReceived::class,
        'processed' => \MHaggag\Payments\Events\PaymentRedirectProcessed::class,
    ],
    'webhook' => [
        'received' => \MHaggag\Payments\Events\PaymentWebhookReceived::class,
        'processed' => \MHaggag\Payments\Events\PaymentWebhookProcessed::class,
    ],
]

Event::listen(PaymentRedirectProcessed::class, function ($event) {
    logger('Payment success:', $event->payment->toArray());
});

Event::listen(PaymentWebhookProcessed::class, function ($event) {
    logger('Webhook processed:', $event->payment->toArray());
});

'models' => [
    'payment' => \MHaggag\Payments\Models\Payment::class,
    'subscription' => \MHaggag\Payments\Models\Subscription::class,
],

namespace App\Payments\Gateways;

use MHaggag\Payments\Gateways\BaseGateway;
use Illuminate\Database\Eloquent\Model;

class MyCustomGateway extends BaseGateway
{
    public function createCheckout(array $payload): array
    {
        // Implement logic to create checkout session/transaction
        // Return ['checkout_url' => '...', 'session_id' => '...']
    }

    public function handleRedirect(array $payload): Model
    {
        // Verify payment status and update the payment model
    }
    
    // Implement other 

'gateways' => [
    'custom_gateway' => [
        'class' => \App\Payments\Gateways\MyCustomGateway::class,
        'api_key' => env('CUSTOM_API_KEY'),
    ],
],
bash
php artisan vendor:publish --provider="MHaggag\Payments\PaymentsServiceProvider"
bash
# Migrations (REQUIRED)
php artisan vendor:publish --tag=payments-migrations

# Config (OPTIONAL)
php artisan vendor:publish --tag=payments-config

# Views (OPTIONAL)
php artisan vendor:publish --tag=payments-views

# Translations (OPTIONAL)
php artisan vendor:publish --tag=payments-translations
bash
php artisan migrate
bash
php artisan stripe:webhook
            # Available options (optional)
            --url=https://domain.com/payments/webhook/stripe
            --api-version=2022-08-01
            --disabled=false

php artisan paypal:webhook
            # Available options (optional)
            --url=https://domain.com/payments/webhook/paypal
bash
php artisan vendor:publish --tag=payments-views
bash
php artisan vendor:publish --tag=payments-translations
text
lang/fr/success.php
bash
php artisan test