CartAbandoned.php
79 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Hostinger\Reach\Api\Webhooks\Handlers; |
| 4 | |
| 5 | use Hostinger\Reach\Api\Handlers\IntegrationsApiHandler; |
| 6 | use Hostinger\Reach\Api\Handlers\ReachApiHandler; |
| 7 | use Hostinger\Reach\Models\Cart; |
| 8 | use Hostinger\Reach\Dto\Cart as CartDto; |
| 9 | use Hostinger\Reach\Repositories\CartRepository; |
| 10 | use Hostinger\Reach\Repositories\FormRepository; |
| 11 | use WC_Customer; |
| 12 | use Exception; |
| 13 | |
| 14 | class CartAbandoned extends WebhookHandler { |
| 15 | const WEBHOOK_NAME = 'cart.abandoned'; |
| 16 | |
| 17 | private CartRepository $cart_repository; |
| 18 | private IntegrationsApiHandler $integrations_api_handler; |
| 19 | |
| 20 | public function __construct( ReachApiHandler $reach_api_handler, IntegrationsApiHandler $integrations_api_handler, CartRepository $cart_repository, FormRepository $form_repository ) { |
| 21 | parent::__construct( $reach_api_handler, $form_repository ); |
| 22 | $this->integrations_api_handler = $integrations_api_handler; |
| 23 | $this->cart_repository = $cart_repository; |
| 24 | } |
| 25 | |
| 26 | public function get_name(): string { |
| 27 | return self::WEBHOOK_NAME; |
| 28 | } |
| 29 | |
| 30 | public function get_metadata( mixed $data ): array { |
| 31 | if ( ! $data instanceof CartDto ) { |
| 32 | return array(); |
| 33 | } |
| 34 | |
| 35 | return $data->to_array(); |
| 36 | } |
| 37 | |
| 38 | public function send( string $cart_hash ): void { |
| 39 | try { |
| 40 | $cart = $this->cart_repository->get( $cart_hash ); |
| 41 | $email = $this->get_customer_email( $cart ); |
| 42 | if ( $email ) { |
| 43 | $result = $this->handle( $email, CartDto::from_array( $cart ) ); |
| 44 | if ( $result ) { |
| 45 | $this->cart_repository->set_status( $cart_hash, Cart::STATUS_ABANDONED ); |
| 46 | } else { |
| 47 | $this->cart_repository->set_status( $cart_hash, Cart::STATUS_ERROR ); |
| 48 | } |
| 49 | } |
| 50 | } catch ( Exception $e ) { |
| 51 | return; |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | public function get_customer_email( array $cart ): string { |
| 56 | if ( isset( $cart['customer_email'] ) && $cart['customer_email'] ) { |
| 57 | return $cart['customer_email']; |
| 58 | } |
| 59 | |
| 60 | $customer_id = $cart['customer_id'] ?? null; |
| 61 | |
| 62 | if ( $customer_id > 0 ) { |
| 63 | $customer = new WC_Customer( $customer_id ); |
| 64 | |
| 65 | return $customer->get_email(); |
| 66 | } |
| 67 | |
| 68 | return ''; |
| 69 | } |
| 70 | |
| 71 | public function is_enabled(): bool { |
| 72 | return parent::is_enabled() && $this->integrations_api_handler->is_active( 'woocommerce' ); |
| 73 | } |
| 74 | |
| 75 | public function init_hooks(): void { |
| 76 | return; |
| 77 | } |
| 78 | } |
| 79 |