| 1 |
<?php |
| 2 |
|
| 3 |
namespace King_Addons; |
| 4 |
|
| 5 |
if (!defined('ABSPATH')) { |
| 6 |
exit; // Exit if accessed directly. |
| 7 |
} |
| 8 |
|
| 9 |
class MailChimp_Ajax |
| 10 |
{ |
| 11 |
public function __construct() |
| 12 |
{ |
| 13 |
add_action('wp_ajax_king_addons_mailchimp_subscribe', [$this, 'mailchimp_subscribe']); |
| 14 |
add_action('wp_ajax_nopriv_king_addons_mailchimp_subscribe', [$this, 'mailchimp_subscribe']); |
| 15 |
} |
| 16 |
|
| 17 |
public static function mailchimp_subscribe() |
| 18 |
{ |
| 19 |
// Verify nonce |
| 20 |
if (!wp_verify_nonce($_POST['nonce'] ?? '', 'king_addons_mailchimp_nonce')) { |
| 21 |
return; |
| 22 |
} |
| 23 |
|
| 24 |
// Retrieve API key from settings |
| 25 |
$api_key = get_option('king_addons_mailchimp_api_key', ''); |
| 26 |
// Parse list ID |
| 27 |
$list_id = sanitize_text_field(wp_unslash($_POST['listId'] ?? '')); |
| 28 |
|
| 29 |
// Parse form fields |
| 30 |
parse_str($_POST['fields'] ?? '', $fields); |
| 31 |
|
| 32 |
// Prepare data |
| 33 |
$email = sanitize_text_field($fields['king_addons_mailchimp_email'] ?? ''); |
| 34 |
$merge_fields = [ |
| 35 |
'FNAME' => sanitize_text_field($fields['king_addons_mailchimp_firstname'] ?? ''), |
| 36 |
'LNAME' => sanitize_text_field($fields['king_addons_mailchimp_lastname'] ?? ''), |
| 37 |
'PHONE' => sanitize_text_field($fields['king_addons_mailchimp_phone_number'] ?? ''), |
| 38 |
]; |
| 39 |
|
| 40 |
// Build Mailchimp API endpoint |
| 41 |
$api_url = sprintf( |
| 42 |
'https://%s.api.mailchimp.com/3.0/lists/%s/members/%s', |
| 43 |
explode('-', $api_key)[1], |
| 44 |
$list_id, |
| 45 |
wp_hash(strtolower($email)) |
| 46 |
); |
| 47 |
|
| 48 |
// Set up request args |
| 49 |
$api_args = [ |
| 50 |
'method' => 'PUT', |
| 51 |
'headers' => [ |
| 52 |
'Content-Type' => 'application/json', |
| 53 |
'Authorization' => 'apikey ' . $api_key, |
| 54 |
], |
| 55 |
'body' => json_encode([ |
| 56 |
'email_address' => $email, |
| 57 |
'status' => 'subscribed', |
| 58 |
'merge_fields' => $merge_fields, |
| 59 |
]), |
| 60 |
]; |
| 61 |
|
| 62 |
// Send request |
| 63 |
$response = wp_remote_post($api_url, $api_args); |
| 64 |
|
| 65 |
// Check response |
| 66 |
if (!is_wp_error($response)) { |
| 67 |
$body = json_decode(wp_remote_retrieve_body($response)); |
| 68 |
|
| 69 |
if (!empty($body)) { |
| 70 |
if (isset($body->status) && $body->status === 'subscribed') { |
| 71 |
wp_send_json(['status' => 'subscribed']); |
| 72 |
} else { |
| 73 |
// Security fix: Sanitize title from remote API response to prevent XSS |
| 74 |
wp_send_json(['status' => esc_html($body->title ?? '')]); |
| 75 |
} |
| 76 |
} |
| 77 |
} |
| 78 |
} |
| 79 |
} |
| 80 |
|
| 81 |
new MailChimp_Ajax(); |