| 1 |
<?php |
| 2 |
namespace Sellkit\Blocks\Optin; |
| 3 |
|
| 4 |
defined( 'ABSPATH' ) || die(); |
| 5 |
|
| 6 |
/** |
| 7 |
* Webhook class. |
| 8 |
* |
| 9 |
* @since 2.3.0 |
| 10 |
*/ |
| 11 |
class Webhook { |
| 12 |
/** |
| 13 |
* Object of helper class. |
| 14 |
* |
| 15 |
* @since 2.3.0 |
| 16 |
* @var object |
| 17 |
*/ |
| 18 |
private static $helper; |
| 19 |
|
| 20 |
/** |
| 21 |
* Run the Drip process. |
| 22 |
* |
| 23 |
* @param object $helper The helper class instance. |
| 24 |
*/ |
| 25 |
public static function run( $helper ) { |
| 26 |
self::$helper = $helper; |
| 27 |
|
| 28 |
if ( empty( self::$helper ) ) { |
| 29 |
return; |
| 30 |
} |
| 31 |
|
| 32 |
self::handle_webhook(); |
| 33 |
} |
| 34 |
|
| 35 |
/** |
| 36 |
* Handle the webhook. |
| 37 |
*/ |
| 38 |
private static function handle_webhook() { |
| 39 |
$webhook_url = isset( self::$helper->attributes['webhookURL'] ) ? self::$helper->attributes['webhookURL'] : ''; |
| 40 |
|
| 41 |
if ( empty( self::$helper->attributes['webhookURL'] ) ) { |
| 42 |
return self::$helper->add_response( 'admin_errors', esc_html__( 'Webhook error: Missing configuration.', 'sellkit' ) ); |
| 43 |
} |
| 44 |
|
| 45 |
$body = self::get_form_data(); |
| 46 |
$args = [ 'body' => wp_json_encode( $body ) ]; |
| 47 |
|
| 48 |
$response = wp_remote_post( $webhook_url, $args ); |
| 49 |
|
| 50 |
$response_code = (int) wp_remote_retrieve_response_code( $response ); |
| 51 |
|
| 52 |
if ( $response_code < 200 || $response_code >= 300 ) { |
| 53 |
self::$helper->add_response( 'admin_errors', esc_html__( 'Webhook Action: Webhook Error.', 'sellkit' ) ); |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
/** |
| 58 |
* Get form data. |
| 59 |
* |
| 60 |
* @since 2.3.0 |
| 61 |
* @return array |
| 62 |
* @SuppressWarnings(PHPMD.NPathComplexity) |
| 63 |
*/ |
| 64 |
private static function get_form_data() { |
| 65 |
$fields = self::$helper->form_data['fields']; |
| 66 |
$locations = ! empty( self::$helper->attributes['locations'] ) ? self::$helper->attributes['locations'] : []; |
| 67 |
|
| 68 |
if ( empty( $locations ) || empty( $fields ) ) { |
| 69 |
return []; |
| 70 |
} |
| 71 |
|
| 72 |
$body = []; |
| 73 |
|
| 74 |
foreach ( $fields as $key => $value ) { |
| 75 |
if ( ! isset( $locations[ $key ] ) ) { |
| 76 |
continue; |
| 77 |
} |
| 78 |
|
| 79 |
$label = ! empty( $locations[ $key ]['label'] ) ? $locations[ $key ]['label'] : esc_html__( 'No Label', 'sellkit' ) . ' ' . $key; |
| 80 |
|
| 81 |
$field_value = empty( $value ) ? '' : $value; |
| 82 |
|
| 83 |
if ( ! empty( $field_value ) ) { |
| 84 |
$field_value = self::$helper->get_address_field( $fields[ $key ], 'address' ); |
| 85 |
} |
| 86 |
|
| 87 |
if ( 'acceptance' === $locations[ $key ]['type'] ) { |
| 88 |
$field_value = empty( $field_value ) ? esc_html__( 'No', 'sellkit' ) : esc_html__( 'Yes', 'sellkit' ); |
| 89 |
} |
| 90 |
|
| 91 |
$body[ $label ] = $field_value; |
| 92 |
} |
| 93 |
|
| 94 |
return $body; |
| 95 |
} |
| 96 |
} |
| 97 |
|
| 98 |
|