PHP code example of wayofdev / laravel-stripe-webhooks

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

    

wayofdev / laravel-stripe-webhooks example snippets




declare(strict_types=1);

use WayOfDev\StripeWebhooks\Profile\StripeWebhookProfile;
use WayOfDev\WebhookClient\Entities\WebhookCall;
use WayOfDev\WebhookClient\Persistence\ORMWebhookCallRepository;

return [
    /*
     * Stripe will sign each webhook using a secret. You can find the used secret at the
     * webhook configuration settings: https://dashboard.stripe.com/account/webhooks.
     */
    'signing_secret' => env('STRIPE_WEBHOOK_SECRET'),

    /*
     * You can define a default job that should be run for all other Stripe 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 Stripe event type with the `.` replaced by a `_`.
     *
     * You can find a list of Stripe webhook types here:
     * https://stripe.com/docs/api#event_types.
     */
    'jobs' => [
        // 'source_chargeable' => \App\Jobs\StripeWebhooks\HandleChargeableSource::class,
        // 'charge_failed' => \App\Jobs\StripeWebhooks\HandleFailedCharge::class,
    ],

    /*
     * The classname of the entity to be used to store webhook calls. The class should
     * be equal or extend WayOfDev\WebhookClient\Entities\WebhookCall.
     */
    'entity' => WebhookCall::class,

    /*
     * The classname of the repository to be used to store webhook calls. The class should
     * implement WayOfDev\WebhookClient\Contracts\WebhookCallRepository.
     */
    'entity_repository' => ORMWebhookCallRepository::class,

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

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

    /*
     * When disabled, the package will not verify if the signature is valid.
     * This can be handy in local environments.
     */
    'verify_signature' => env('STRIPE_SIGNATURE_VERIFY', true),
];

   // ...
   
   'tokenizer' => [
       /*
        * Directories to scan for entities.
        */
       'directories' => [
           __DIR__ . '/../src/Domain', // Your current project Entities
           __DIR__ . '/../vendor/wayofdev/laravel-webhook-client/src/Entities', // Register new Entity
       ],
     
     	// ...
   ],
   

Route::stripeWebhooks('webhook-route-configured-at-the-stripe-dashboard');

protected $except = [
    'webhook-route-configured-at-the-stripe-dashboard',
];


  
declare(strict_types=1);

namespace Infrastructure\Stripe\Webhooks\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use WayOfDev\WebhookClient\Entities\WebhookCall;

class HandleChargeableSource implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    public WebhookCall $webhookCall;

    public function __construct(WebhookCall $webhookCall)
    {
        $this->webhookCall = $webhookCall;
    }

    public function handle()
    {
        // do your work here

        // you can access the payload of the webhook call with `$this->webhookCall->payload()`
    }
}

// config/stripe-webhooks.php

'jobs' => [
    'source_chargeable' => \Infrastructure\Stripe\Webhooks\Jobs\HandleChargeableSource::class,
],

// ...

// config/stripe-webhooks.php

'default_job' => \Infrastructure\Stripe\Webhooks\Jobs\HandleOtherEvent::class,

// ...

/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    'stripe-webhooks::source.chargeable' => [
        Infrastructure\Stripe\Listeners\ChargeSource::class,
    ],
];



namespace Infrastructure\Stripe\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use WayOfDev\WebhookClient\Entities\WebhookCall;

class ChargeSource implements ShouldQueue
{
    public function handle(WebhookCall $webhookCall)
    {
        // do your work here

        // you can access the payload of the webhook call with `$webhookCall->payload()`
    }
}

use WayOfDev\WebhookClient\Contracts\WebhookCallRepository;
use WayOfDev\StripeWebhooks\Bridge\Laravel\Jobs\ProcessStripeWebhookJob;

class RetryWebhooks
{
    public function __construct(private WebhookCallRepository $repository)
    {
    }

  	public function handle()
    {
        dispatch(new ProcessStripeWebhookJob($repository->findById($id)));
    }
}

use WayOfDev\StripeWebhooks\Bridge\Laravel\Jobs\ProcessStripeWebhookJob;

class MyCustomStripeWebhookJob extends ProcessStripeWebhookJob
{
    public function handle(): void
    {
        // do some custom stuff beforehand

        parent::handle();

        // do some custom stuff afterwards
    }
}



declare(strict_types=1);

namespace WayOfDev\StripeWebhooks\Profile;

use Cycle\Database\Injection\Parameter;
use Cycle\ORM\ORMInterface;
use Illuminate\Http\Request;
use WayOfDev\WebhookClient\Contracts\WebhookProfile;
use WayOfDev\WebhookClient\Entities\WebhookCall;
use WayOfDev\WebhookClient\Persistence\ORMWebhookCallRepository;

class StripeWebhookProfile implements WebhookProfile
{
    public function __construct(private readonly ORMInterface $orm)
    {
    }

    public function shouldProcess(Request $request): bool
    {
        /** @var ORMWebhookCallRepository $webhookCallsRepository */
        $webhookCallsRepository = $this->orm->getRepository(WebhookCall::class);

        $exists = $webhookCallsRepository
            ->select()
            ->where(['name' => 'stripe'])
            ->andWhere("JSON_EXTRACT(payload, '$.id')", '=', new Parameter(['payloadId' => $request->get('id')]))
            ->count();

        return 0 === $exists;
    }
}


Route::stripeWebhooks('webhook-url/{configKey}');

Route::post(
  'webhook-url/{configKey}',
  \WayOfDev\StripeWebhooks\Bridge\Laravel\Http\Controllers\StripeWebhooksController::class,
);

// secret for when Stripe posts to webhook-url/account
'signing_secret_account' => 'whsec_abc',
// secret for when Stripe posts to webhook-url/connect
'signing_secret_connect' => 'whsec_123', 

use Stripe\Event;

// ...

public function handle(WebhookCall $webhookCall)
{
    /** @var \Stripe\StripeObject|null */
    $stripeObject = Event::constructFrom($webhookCall->payload())->data?->object;
}

/** @var \Stripe\StripeInvoice|null */
$stripeInvoice = Event::constructFrom($webhookCall->payload())->data?->object;

// $stripeInvoice->status
// $stripeInvoice->amount_due
// $stripeInvoice->amount_paid
// $stripeInvoice->amount_remaining

foreach ($stripeInvoice->lines as $invoiceLine) {
    // ...
}
bash
   $ php artisan cycle:orm:migrate
   
bash
   $ php artisan cycle:migrate
   
bash
$ make lint-php