| 1 |
<?php |
| 2 |
/** |
| 3 |
* Pabbly Service |
| 4 |
* |
| 5 |
* Handles Pabbly Connect integration for Booktics orders via webhook. |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace Booktics\Module\Pabbly; |
| 9 |
|
| 10 |
if ( ! defined( 'ABSPATH' ) ) exit; |
| 11 |
|
| 12 |
use Booktics\Contracts\Hookable_Service_Contract; |
| 13 |
use Booktics\Abstracts\Booktics_Database; |
| 14 |
use Booktics\Models\Guest_Model; |
| 15 |
|
| 16 |
class Pabbly_Service implements Hookable_Service_Contract { |
| 17 |
/** |
| 18 |
* Register hooks |
| 19 |
*/ |
| 20 |
public function register() { |
| 21 |
add_action( 'booktics_after_order_created', array( $this, 'send_to_pabbly' ), 10, 2 ); |
| 22 |
} |
| 23 |
|
| 24 |
/** |
| 25 |
* Send customer data to the configured Pabbly webhook. |
| 26 |
* |
| 27 |
* @param object $order_model The order model. |
| 28 |
* @param array $appointments Created appointments (unused). |
| 29 |
*/ |
| 30 |
public function send_to_pabbly( $order_model, $appointments = array() ) { |
| 31 |
$webhook_url = booktics_get_option( 'pabbly_webhook_url' ); |
| 32 |
if ( empty( $webhook_url ) ) { |
| 33 |
return; |
| 34 |
} |
| 35 |
|
| 36 |
// Get customer details. customer_id is a Booktics guest record id, not a WP user id. |
| 37 |
$customer = ( new Guest_Model( new Booktics_Database() ) )->find( array( 'id' => $order_model->customer_id ) ); |
| 38 |
if ( ! $customer || is_wp_error( $customer ) ) { |
| 39 |
return; |
| 40 |
} |
| 41 |
|
| 42 |
$name_parts = preg_split( '/\s+/', trim( (string) $customer->name ), 2 ); |
| 43 |
|
| 44 |
$customer_data = array( |
| 45 |
'email' => $customer->email, |
| 46 |
'first_name' => $name_parts[0] ?? '', |
| 47 |
'last_name' => $name_parts[1] ?? '', |
| 48 |
'status' => 'subscribed', |
| 49 |
); |
| 50 |
|
| 51 |
try { |
| 52 |
$this->send_webhook( $webhook_url, $customer_data ); |
| 53 |
} catch ( \Throwable $e ) { |
| 54 |
// Ensures silent failure in case of any error. |
| 55 |
if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) { |
| 56 |
error_log( 'Pabbly Error: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log |
| 57 |
} |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
private function send_webhook( $url, $data ) { |
| 62 |
$response = wp_remote_post( |
| 63 |
$url, |
| 64 |
array( |
| 65 |
'body' => wp_json_encode( $data ), |
| 66 |
'headers' => array( |
| 67 |
'Content-Type' => 'application/json', |
| 68 |
), |
| 69 |
'timeout' => 15, |
| 70 |
) |
| 71 |
); |
| 72 |
|
| 73 |
if ( is_wp_error( $response ) ) { |
| 74 |
if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) { |
| 75 |
error_log( 'Pabbly Webhook Error: ' . $response->get_error_message() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log |
| 76 |
} |
| 77 |
} |
| 78 |
} |
| 79 |
} |
| 80 |
|