| 1 |
<?php |
| 2 |
/** |
| 3 |
* FluentCRM Service |
| 4 |
* |
| 5 |
* Handles FluentCRM integration for Booktics orders |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace Booktics\Module\FluentCrm; |
| 9 |
|
| 10 |
use Booktics\Contracts\Hookable_Service_Contract; |
| 11 |
|
| 12 |
class FluentCRM_Service implements Hookable_Service_Contract { |
| 13 |
/** |
| 14 |
* Register hooks |
| 15 |
*/ |
| 16 |
public function register() { |
| 17 |
add_action( 'booktics_order_created', array( $this, 'add_contact_to_fluentcrm' ) ); |
| 18 |
} |
| 19 |
|
| 20 |
/** |
| 21 |
* Add contact to FluentCRM |
| 22 |
* |
| 23 |
* @param object $order_model The order model |
| 24 |
*/ |
| 25 |
public function add_contact_to_fluentcrm( $order_model ) { |
| 26 |
// Check if FluentCRM is active |
| 27 |
if ( ! defined( 'FLUENTCRM' ) || ! function_exists( 'FluentCrmApi' ) ) { |
| 28 |
return; |
| 29 |
} |
| 30 |
|
| 31 |
// Get customer details |
| 32 |
$customer = get_user_by( 'id', $order_model->customer_id ); |
| 33 |
if ( ! $customer ) { |
| 34 |
return; |
| 35 |
} |
| 36 |
|
| 37 |
$customer_data = array( |
| 38 |
'email' => $customer->user_email, |
| 39 |
'first_name' => $customer->first_name, |
| 40 |
'last_name' => $customer->last_name ?: '', |
| 41 |
'status' => 'subscribed', |
| 42 |
); |
| 43 |
|
| 44 |
try { |
| 45 |
// Check if FluentCRM Pro is active (has webhooks) |
| 46 |
$is_pro_active = is_plugin_active('fluent-crm-pro/fluentcampaign-pro.php'); |
| 47 |
$fluentcrm_webhook_exists = !empty( booktics_get_option( 'fluentcrm_webhook_url') ); |
| 48 |
|
| 49 |
if ( $is_pro_active && $fluentcrm_webhook_exists ) { |
| 50 |
// Use webhook if Pro is active |
| 51 |
$webhook_url = booktics_get_option( 'fluentcrm_webhook_url'); |
| 52 |
|
| 53 |
if ( ! empty( $webhook_url ) ) { |
| 54 |
$this->send_webhook( |
| 55 |
$webhook_url, |
| 56 |
$customer_data, |
| 57 |
); |
| 58 |
|
| 59 |
// Returns if fluentCRM pro exists and is working properly |
| 60 |
return; |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
// Fallback to direct API for free version, gets used when fluentCRM pro is not active or webhook is not set. |
| 65 |
$contact_api = FluentCrmApi( 'contacts' ); |
| 66 |
$contact_api->createOrUpdate( $customer_data ); |
| 67 |
} catch ( \Throwable $e ) { |
| 68 |
// Ensures silent failure in case of any error |
| 69 |
error_log( 'FluentCRM Error: ' . $e->getMessage() ); |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
private function send_webhook( $url, $data ) { |
| 74 |
$response = wp_remote_post( |
| 75 |
$url, |
| 76 |
array( |
| 77 |
'body' => json_encode( $data ), |
| 78 |
'headers' => array( |
| 79 |
'Content-Type' => 'application/json', |
| 80 |
), |
| 81 |
'timeout' => 15, |
| 82 |
) |
| 83 |
); |
| 84 |
|
| 85 |
if ( is_wp_error( $response ) ) { |
| 86 |
error_log( 'FluentCRM Webhook Error: ' . $response->get_error_message() ); |
| 87 |
} |
| 88 |
} |
| 89 |
} |
| 90 |
|