| 1 |
<?php |
| 2 |
/** |
| 3 |
* Rest API |
| 4 |
* |
| 5 |
* @package AutomatorWP\Webhooks\Rest_API |
| 6 |
* @author AutomatorWP <[email protected]>, Ruben Garcia <[email protected]> |
| 7 |
* @since 1.0.0 |
| 8 |
*/ |
| 9 |
// Exit if accessed directly |
| 10 |
if( !defined( 'ABSPATH' ) ) exit; |
| 11 |
|
| 12 |
/** |
| 13 |
* Register receive data from activecampaign endpoints on the WordPress Rest API |
| 14 |
* |
| 15 |
* @since 1.0.0 |
| 16 |
*/ |
| 17 |
function automatorwp_activecampaign_rest_api_init() { |
| 18 |
|
| 19 |
register_rest_route( 'activecampaign/webhooks', automatorwp_activecampaign_get_webhook_slug(), array( |
| 20 |
'methods' => 'POST', |
| 21 |
'callback' => 'automatorwp_activecampaign_rest_api_cb', |
| 22 |
'permission_callback' => '__return_true', |
| 23 |
) ); |
| 24 |
|
| 25 |
} |
| 26 |
add_action( 'rest_api_init', 'automatorwp_activecampaign_rest_api_init'); |
| 27 |
|
| 28 |
/** |
| 29 |
* Callback used to handle activecampaign received requests |
| 30 |
* |
| 31 |
* @since 1.0.0 |
| 32 |
* |
| 33 |
* @param WP_REST_Request $data |
| 34 |
* |
| 35 |
* @return WP_REST_Response |
| 36 |
*/ |
| 37 |
function automatorwp_activecampaign_rest_api_cb( $data ) { |
| 38 |
|
| 39 |
// Request response received from ActiveCampaign |
| 40 |
$params = $data->get_params(); |
| 41 |
|
| 42 |
if ( ! isset( $params ) ) { |
| 43 |
return new WP_REST_Response( array( 'success' => false, 'message' => __( 'No parameters received', 'automatorwp' ) ), 400 ); |
| 44 |
} |
| 45 |
|
| 46 |
// Sanitize params array |
| 47 |
$params = map_deep( $params, 'sanitize_text_field' ); |
| 48 |
|
| 49 |
// Sanitize specific fields |
| 50 |
if ( isset( $params['contact'] ) && is_array( $params['contact'] ) ) { |
| 51 |
|
| 52 |
$params['contact']['id'] = absint( $params['contact']['id'] ); |
| 53 |
$params['contact']['email'] = sanitize_email( $params['contact']['email'] ); |
| 54 |
|
| 55 |
if ( isset( $params['contact']['fields'] ) && is_array( $params['contact']['fields'] ) ) { |
| 56 |
$params['contact']['fields'] = map_deep( $params['contact']['fields'], 'sanitize_text_field' ); |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
$type = $params['type']; |
| 61 |
$email = $params['contact']['email']; |
| 62 |
$user = get_user_by( 'email', $email ); |
| 63 |
|
| 64 |
// Actions when a user/contact is subscribed |
| 65 |
if ( $type === 'subscribe' ) { |
| 66 |
do_action( 'automatorwp_activecampaign_contact_subscribed', $params, ( $user ? $user->ID : 0 ) ); |
| 67 |
} |
| 68 |
|
| 69 |
// Actions when a tag is added to user/contact |
| 70 |
if ( $type === 'contact_tag_added') { |
| 71 |
do_action( 'automatorwp_activecampaign_contact_tag_added', $params, ( $user ? $user->ID : 0 ) ); |
| 72 |
} |
| 73 |
|
| 74 |
return new WP_REST_Response( array( 'success' => true ), 200 ); |
| 75 |
|
| 76 |
} |