| 1 |
<?php |
| 2 |
/** |
| 3 |
* Webhook Trigger |
| 4 |
* |
| 5 |
* @package WPbot_Automator |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace WPbot_Automator\Triggers; |
| 9 |
|
| 10 |
if ( ! defined( 'ABSPATH' ) ) { |
| 11 |
exit; |
| 12 |
} |
| 13 |
|
| 14 |
/** |
| 15 |
* Class Webhook |
| 16 |
*/ |
| 17 |
class Webhook extends Trigger { |
| 18 |
|
| 19 |
/** |
| 20 |
* Constructor |
| 21 |
*/ |
| 22 |
public function __construct() { |
| 23 |
$this->id = 'webhook'; |
| 24 |
$this->group = __( 'Universal', 'wpbot-automator' ); |
| 25 |
$this->title = __( 'Webhook Trigger', 'wpbot-automator' ); |
| 26 |
} |
| 27 |
|
| 28 |
/** |
| 29 |
* Register the triggers |
| 30 |
*/ |
| 31 |
public function register() { |
| 32 |
add_action( 'rest_api_init', array( $this, 'register_webhook_route' ) ); |
| 33 |
} |
| 34 |
|
| 35 |
/** |
| 36 |
* Register REST API route for incoming webhooks |
| 37 |
*/ |
| 38 |
public function register_webhook_route() { |
| 39 |
register_rest_route( |
| 40 |
'wpbot-automator/v1', |
| 41 |
'/webhook/(?P<token>[a-zA-Z0-9]+)', |
| 42 |
array( |
| 43 |
'methods' => array( 'GET', 'POST' ), |
| 44 |
'callback' => array( $this, 'handle_webhook' ), |
| 45 |
'permission_callback' => '__return_true', // Webhooks are usually public or handled by token |
| 46 |
) |
| 47 |
); |
| 48 |
} |
| 49 |
|
| 50 |
/** |
| 51 |
* Handle incoming webhook |
| 52 |
*/ |
| 53 |
public function handle_webhook( $request ) { |
| 54 |
$token = $request->get_param( 'token' ); |
| 55 |
$data = $request->get_params(); |
| 56 |
|
| 57 |
$this->run( array( |
| 58 |
'sub_id' => 'incoming_webhook', |
| 59 |
'data' => array_merge( $data, array( |
| 60 |
'target_node_id' => 'node-' . $token, |
| 61 |
) ), |
| 62 |
) ); |
| 63 |
|
| 64 |
return rest_ensure_response( array( |
| 65 |
'success' => true, |
| 66 |
'message' => 'Webhook received and workflow triggered.', |
| 67 |
) ); |
| 68 |
} |
| 69 |
} |
| 70 |
|