Maxlego08 icon

Stripe Webhook

Maxlego08 | PRO | 10/02/21 08:45:54 AM UTC (Edited) | 0 ⭐ | 442 👁️ | Never ⏰ | []
PHP |

2.6 KB

|

None

|

0 👍

/

0 👎

<?php
 
namespace App\Payment\Utils;
 
use App\Models\Payment\PaymentGateway;
use Stripe\Exception\ApiErrorException;
use Stripe\StripeClient;
 
class StripeWebhook
{
 
    /**
     * @var StripeClient
     */
    private $stripe;
 
    /**
     * @var string
     */
    private $gatewayName = "stripe";
 
    /**
     *
     */
    public function __construct()
    {
        $sk = env('STRIPE_SK');
        $this->stripe = new StripeClient($sk);
    }
 
    /**
     * Permet de créer le webhook de stripe
     *
     * @throws ApiErrorException
     */
    public function make()
    {
        $gateway = PaymentGateway::where('name', $this->gatewayName)->first();
        if ($this->endpointIsAlreadyCreate() && isset($gateway))
            return;
 
        $this->deleteEndPointIfAlreadyExist();
 
        $response = $this->stripe->webhookEndpoints->create([
            'url' => $this->getRouteEndPoint(),
            'enabled_events' => [
                'checkout.session.completed',
                'checkout.session.async_payment_succeeded',
                'checkout.session.async_payment_failed',
                'charge.dispute.created',
                'charge.refunded',
            ],
            'description' => 'Webhook for groupez.xyz'
        ]);
        if (isset($gateway))
            $gateway->update(['data' => $response->secret]);
        else {
            PaymentGateway::create([
                'name' => $this->gatewayName,
                'data' => $response->secret,
            ]);
        }
    }
 
    /**
     * Permet de vérifier si le endpoint existe ou pas
     *
     * @return bool
     * @throws ApiErrorException
     */
    private function endpointIsAlreadyCreate(): bool
    {
        foreach ($this->stripe->webhookEndpoints->all() as $endpoint) {
            if ($endpoint->url === $this->getRouteEndPoint())
                return true;
        }
        return false;
    }
 
    /**
     * Permet de supprimer les routes en trop
     */
    private function deleteEndPointIfAlreadyExist()
    {
        try {
            foreach ($this->stripe->webhookEndpoints->all() as $endpoint) {
                if ($endpoint->url === $this->getRouteEndPoint())
                    $this->stripe->webhookEndpoints->delete($endpoint->id);
            }
        } catch (ApiErrorException $e) {
        }
    }
 
    /**
     * Permet de retourner la route
     * @return string
     */
    private function getRouteEndPoint(): string
    {
        return route('api.v1.notification', ['gateway' => $this->gatewayName]);
    }
 
}
 

Comments