PHP code example of soap / laravel-omise-webhooks

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

    

soap / laravel-omise-webhooks example snippets


use Soap\OmiseWebhooks\OmiseWebhooksProfile;
use Soap\OmiseWebhooks\ProcessOmiseWebhooksJob;
use Spatie\WebhookClient\Models\WebhookCall;

return [
    /*
     * The webhook secret (base64-encoded) shown in the Omise dashboard.
     * It is used to verify the `Omise-Signature` header of incoming webhooks.
     * See https://docs.omise.co/api-webhooks#webhook-signature-verification
     */
    'signing_secret' => env('OMISE_WEBHOOK_SECRET'),

    /*
     * You can define a default job that should be run for all other Omise event type
     * without a job defined in next configuration.
     * You may leave it empty to store the job in database but without processing it.
     */
    'default_job' => '',

    /*
     * You can define the job that should be run when a certain webhook hits your application
     * here. The key is the name of the Omise event type (called key for Omise) with the `.` replaced by a `_`.
     *
     * You can find a list of Omise webhook types here:
     * https://docs.opn.ooo/api-webhooks#supported-events.
     */
    'jobs' => [
        // 'card_destroy' => \App\Jobs\OmiseWebhooks\HandleCardDestroy::class,
        // 'card_update' => \App\Jobs\OmiseWebhooks\HandleCardUpdate::class,

        // 'charge_capture' => \App\Jobs\OmiseWebhooks\HandleChargeCapture::class,
        // 'charge_complete' => \App\Jobs\OmiseWebhooks\HandleChargeComplete::class,
        // 'charge_create' => \App\Jobs\OmiseWebhooks\HandleChargeCreate::class,
        // 'charge_expire' => \App\Jobs\OmiseWebhooks\HandleChargeExpire::class,
        // 'charge_reverse' => \App\Jobs\OmiseWebhooks\HandleChargeReverse::class,
        // 'charge_update' => \App\Jobs\OmiseWebhooks\HandleChargeUpdate::class,

        // ... customer_*, dispute_*, refund_*, schedule_* and transfer_* events
    ],

    /*
     * The classname of the model to be used. The class should equal or extend
     * Spatie\WebhookClient\Models\WebhookCall.
     */
    'model' => WebhookCall::class,

    /**
     * This class determines if the webhook call should be stored and processed.
     */
    'profile' => OmiseWebhooksProfile::class,

    /*
     * The job that fires the events and dispatches your jobs for a stored webhook call.
     * The class should equal or extend Soap\OmiseWebhooks\ProcessOmiseWebhooksJob.
     */
    'process_webhook_job' => ProcessOmiseWebhooksJob::class,

    /*
     * Specify a connection and or a queue to process the webhooks
     */
    'connection' => env('OMISE_WEBHOOK_CONNECTION'),
    'queue' => env('OMISE_WEBHOOK_QUEUE'),

    /*
     * Signatures are verified by default; requests without a valid signature, or for which
     * no signing secret is configured, are rejected with a 403 response.
     * Only disable this in local environments.
     */
    'verify_signature' => env('OMISE_SIGNATURE_VERIFICATION', true),

    /*
     * The maximum age (in seconds) of the `Omise-Signature-Timestamp` header,
     * used to protect against replay attacks. Set to 0 to disable this check.
     */
    'signature_tolerance' => env('OMISE_SIGNATURE_TOLERANCE', 300),

    /*
     * When `verify_ip` is enabled, this setting determines if the signature should be
     * validated using request 's IP address.
     */
    'verify_ip' => env('OMISE_IP_VERIFICATION', false),
];

// routes/web.php
Route::omiseWebhooks('omise/webhooks');

->withMiddleware(function (Middleware $middleware) {
    $middleware->validateCsrfTokens(except: [
        'omise/webhooks',
    ]);
})

protected $except = [
    'omise/webhooks',
];

use Soap\OmiseWebhooks\OmiseSignatureValidator;

// From a request
OmiseSignatureValidator::verify($request, $base64Secret, tolerance: 300); // bool

// From raw headers and body
OmiseSignatureValidator::verifySignature($rawBody, $signatureHeader, $timestampHeader, $base64Secret, 300); // bool

// Throws Soap\OmiseWebhooks\Exceptions\InvalidOmiseSignature with the reason of the failure
OmiseSignatureValidator::assertValid($rawBody, $signatureHeader, $timestampHeader, $base64Secret, 300);



namespace App\Jobs\OmiseWebhooks;

use App\Models\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Spatie\WebhookClient\Models\WebhookCall;

class HandleChargeComplete implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(public WebhookCall $webhookCall) {}

    public function handle(): void
    {
        // The Omise event is available in $this->webhookCall->payload
        $charge = $this->webhookCall->payload['data'];

        if ($charge['status'] !== 'successful') {
            return;
        }

        Order::where('id', $charge['metadata']['order_id'] ?? null)
            ->update([
                'status' => 'paid',
                'omise_charge_id' => $charge['id'],
            ]);
    }
}

// config/omise-webhooks.php

'jobs' => [
    'charge_complete' => \App\Jobs\OmiseWebhooks\HandleChargeComplete::class,
    'charge_expire' => \App\Jobs\OmiseWebhooks\HandleChargeExpire::class,
    'refund_create' => \App\Jobs\OmiseWebhooks\HandleRefundCreate::class,
],

// config/omise-webhooks.php

'default_job' => \App\Jobs\OmiseWebhooks\HandleOtherEvent::class,

use App\Listeners\ChargeCompleteListener;
use Illuminate\Support\Facades\Event;

public function boot(): void
{
    Event::listen('omise-webhooks::charge.complete', ChargeCompleteListener::class);
}

/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    'omise-webhooks::charge.complete' => [
        App\Listeners\ChargeCompleteListener::class,
    ],
];



namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Spatie\WebhookClient\Models\WebhookCall;

class ChargeCompleteListener implements ShouldQueue
{
    public function handle(WebhookCall $webhookCall): void
    {
        $charge = $webhookCall->payload['data'];

        // do your work here
    }
}

Event::listen('omise-webhooks::*', function (string $eventName, array $data) {
    /** @var \Spatie\WebhookClient\Models\WebhookCall $webhookCall */
    $webhookCall = $data[0];

    logger()->info("Received Omise event {$webhookCall->payload['key']}");
});

use Soap\LaravelOmise\Omise\Error;

public function handle(): void
{
    $chargeId = $this->webhookCall->payload['data']['id'];

    $charge = app('omise')->charge()->find($chargeId);

    if ($charge instanceof Error) {
        // the charge could not be retrieved, let the job be retried
        $this->release(60);

        return;
    }

    if ($charge->isPaid()) {
        // mark the order as paid
    }
}

use Soap\OmiseWebhooks\ProcessOmiseWebhooksJob;
use Spatie\WebhookClient\Models\WebhookCall;

dispatch(new ProcessOmiseWebhooksJob(WebhookCall::find($id)));



namespace App\Jobs\OmiseWebhooks;

use Soap\OmiseWebhooks\ProcessOmiseWebhooksJob;

class MyCustomOmiseWebhookJob extends ProcessOmiseWebhooksJob
{
    public function handle()
    {
        // do some custom stuff beforehand

        parent::handle();

        // do some custom stuff afterwards
    }
}

// config/omise-webhooks.php

'process_webhook_job' => \App\Jobs\OmiseWebhooks\MyCustomOmiseWebhookJob::class,



namespace App\Webhooks;

use Illuminate\Http\Request;
use Soap\OmiseWebhooks\OmiseWebhooksProfile;

class LiveOnlyOmiseWebhookProfile extends OmiseWebhooksProfile
{
    public function shouldProcess(Request $request): bool
    {
        if (app()->isProduction() && ! $request->boolean('livemode')) {
            return false;
        }

        return parent::shouldProcess($request);
    }
}

// config/omise-webhooks.php

'profile' => \App\Webhooks\LiveOnlyOmiseWebhookProfile::class,

Route::omiseWebhooks('omise/webhooks/{configKey}');

// config/omise-webhooks.php

'signing_secret_account1' => env('OMISE_WEBHOOK_SECRET_ACCOUNT1'),
'signing_secret_account2' => env('OMISE_WEBHOOK_SECRET_ACCOUNT2'),

use Illuminate\Http\Request;
use Soap\OmiseWebhooks\OmiseWebhooks;

OmiseWebhooks::resolveSigningSecretUsing(function (Request $request, ?string $configKey) {
    return PaymentAccount::where('account_key', $configKey)->first()?->webhook_secret; // decrypted by an encrypted cast
});

// config/omise-webhooks.php

'model' => \App\Models\OmiseWebhookCall::class,

use Illuminate\Support\Facades\Bus;
use Soap\OmiseWebhooks\ProcessOmiseWebhooksJob;

it('stores an omise webhook call', function () {
    Bus::fake();

    $this->postJson('omise/webhooks', [
        'object' => 'event',
        'id' => 'evnt_test_123',
        'key' => 'charge.complete',
        'data' => ['object' => 'charge', 'id' => 'chrg_test_123'],
    ])->assertSuccessful();

    $this->assertDatabaseHas('webhook_calls', ['name' => 'omise']);

    Bus::assertDispatched(ProcessOmiseWebhooksJob::class);
});
bash
php artisan vendor:publish --tag="omise-webhooks-config"
bash
php artisan vendor:publish --provider="Spatie\WebhookClient\WebhookClientServiceProvider" --tag="webhook-client-migrations"
bash
php artisan migrate