mailchimp integration on a custom footer

I want the user to be able to opt-in to a MailChimp newsletter within a custom footer, which one. of our clients has asked for. The client also uses MailChimp so we therefore cannot use anything like contactform-7 etc

The two images below will help explain. The user will type in their email address and will submit the email to subscribe to the newsletter. I repeat this is in a custom footer and I am trying to do this from a child theme

I tried following the MailChimp api documentation for adding a member to an existing list https://mailchimp.com/developer/api/marketing/list-members/ . This didn't work. It caused the site to crash

I have seen some code here which has been useful since it allows me to pass information from my JS file to my functions.php file https://artisansweb.net/mailchimp-integration-in-wordpress-without-using-a-plugin/

However, I keep receiving the same error when I type in an email that passes the regex 'Something went wrong, please try again'

I have checked the network tab on chrome and the email, a security token and the correct action are all showing - so information is being passed from JS to php. It also (weirdly) is showing a 200 code after submitting. However, there are no new subscribers showing on MailChimp and the error message above is showing (which if you look below is the default case in the subscribe_user_to_mailchimp function)

How can I resolve this?

Code is below:

functions.php

// enqueue js for footer (subscribing to newsletter)
  wp_register_script('kingster-script-child-footer', get_template_directory_uri() . '-child/js/footer.js', array('jquery', 'jquery-effects-core'));

  // Localize the script with new data
  $script_array = array(
    'ajaxurl' = admin_url('admin-ajax.php'),
    'security' = wp_create_nonce(subscribe_user),
  );
  wp_localize_script( 'kingster-script-child-footer', 'aw', $script_array );

  // Enqueued script with localized data.
  wp_enqueue_script( 'kingster-script-child-footer' );

  add_action('wp_ajax_subscribe_user', 'subscribe_user_to_mailchimp');
  add_action('wp_ajax_nopriv_subscribe_user', 'subscribe_user_to_mailchimp');
   
  function subscribe_user_to_mailchimp() {
      check_ajax_referer('subscribe_user', 'security');
      $email = $_POST['email'];
      $audience_id = '12905';
      $api_key = 'xxxxxxxxxxxxxxxxxxx-us17';
      $data_center = substr($api_key,strpos($api_key,'-')+1);
      $url = 'https://'. $data_center .'.api.mailchimp.com/3.0/lists/'. $audience_id .'/members';
      $auth = base64_encode( 'user:' . $api_key );
      $arr_data = json_encode(array( 
          'email_address' = $email, 
          'status' = 'subscribed' //pass 'subscribed' or 'pending'
      ));
   
      $response = wp_remote_post( $url, array(
              'method' = 'POST',
              'headers' = array(
                  'Content-Type' = 'application/json',
                  'Authorization' = Basic $auth
              ),
              'body' = $arr_data,
          )
      );
   
      if ( is_wp_error( $response ) ) {
         $error_message = $response-get_error_message();
         echo Something went wrong: $error_message;
      } else {
          $status_code = wp_remote_retrieve_response_code( $response );
          switch ($status_code) {
              case '200':
                  echo $status_code;
                  break;
              case '400':
                  $api_response = json_decode( wp_remote_retrieve_body( $response ), true );
                  echo $api_response['title'];
                  break;
              default:
                  echo 'Something went wrong. Please try again.';
                  break;
          }
      }
      wp_die();
  }

js/footer.js

jQuery(document).ready(function($) {
    var subscribeButton = $('#subscribe-newsletter-button');
    var subscribeInput = $('#subscribe-newsletter-form-input')
    
    $(subscribeButton).click(function() {
         var email = $(subscribeInput).val()
         if(isEmail(email)) {
            var data = {
                'action': 'subscribe_user',
                'email': email,
                'security': aw.security
            };
      
            $.post(aw.ajaxurl, data, function(response) {
                if (response == 200) {
                    alert('You have subscribed successfully.');
                } else {
                    alert(response);
                }
            });
        } else {
            alert('This is not a valid email');
        }
    });
})

function isEmail(email) {
    var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return regex.test(email);
}

edit: I printed the error message and got this in the response:

(
    [headers] = Requests_Utility_CaseInsensitiveDictionary Object
        (
            [data:protected] = Array
                (
                    [server] = openresty
                    [content-type] = application/problem+json; charset=utf-8
                    [content-length] = 197
                    [x-request-id] = 75f70c65-afc6-42f8-806f-2ecb7080071d
                    [link] = https://us17.api.mailchimp.com/schema/3.0/Definitions/ProblemDetailDocument.json; rel=describedBy
                    [content-encoding] = gzip
                    [vary] = Accept-Encoding
                    [date] = Tue, 25 Aug 2020 09:58:36 GMT
                )

        )

    [body] = {type:http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/,title:Resource Not Found,status:404,detail:The requested resource could not be found.,instance:75f70c65-afc6-42f8-806f-2ecb7080071d}
    [response] = Array
        (
            [code] = 404
            [message] = Not Found
        )

    [cookies] = Array
        (
        )

    [filename] = 
    [http_response] = WP_HTTP_Requests_Response Object
        (
            [response:protected] = Requests_Response Object
                (
                    [body] = {type:http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/,title:Resource Not Found,status:404,detail:The requested resource could not be found.,instance:75f70c65-afc6-42f8-806f-2ecb7080071d}
                    [raw] = HTTP/1.1 404 Not Found
Server: openresty
Content-Type: application/problem+json; charset=utf-8
Content-Length: 197
X-Request-Id: 75f70c65-afc6-42f8-806f-2ecb7080071d
Link: https://us17.api.mailchimp.com/schema/3.0/Definitions/ProblemDetailDocument.json; rel=describedBy
Content-Encoding: gzip
Vary: Accept-Encoding
Date: Tue, 25 Aug 2020 09:58:36 GMT
Connection: close

{type:http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/,title:Resource Not Found,status:404,detail:The requested resource could not be found.,instance:75f70c65-afc6-42f8-806f-2ecb7080071d}
                    [headers] = Requests_Response_Headers Object
                        (
                            [data:protected] = Array
                                (
                                    [server] = Array
                                        (
                                            [0] = openresty
                                        )

                                    [content-type] = Array
                                        (
                                            [0] = application/problem+json; charset=utf-8
                                        )

                                    [content-length] = Array
                                        (
                                            [0] = 197
                                        )

                                    [x-request-id] = Array
                                        (
                                            [0] = 75f70c65-afc6-42f8-806f-2ecb7080071d
                                        )

                                    [link] = Array
                                        (
                                            [0] = https://us17.api.mailchimp.com/schema/3.0/Definitions/ProblemDetailDocument.json; rel=describedBy
                                        )

                                    [content-encoding] = Array
                                        (
                                            [0] = gzip
                                        )

                                    [vary] = Array
                                        (
                                            [0] = Accept-Encoding
                                        )

                                    [date] = Array
                                        (
                                            [0] = Tue, 25 Aug 2020 09:58:36 GMT
                                        )

                                )

                        )

                    [status_code] = 404
                    [protocol_version] = 1.1
                    [success] = 
                    [redirects] = 0
                    [url] = https://us17.api.mailchimp.com/3.0/lists/12905/members
                    [history] = Array
                        (
                        )

                    [cookies] = Requests_Cookie_Jar Object
                        (
                            [cookies:protected] = Array
                                (
                                )

                        )

                )

            [filename:protected] = 
            [data] = 
            [headers] = 
            [status] = 
        )

)

Topic plugin-mailchimp ajax email api customization Wordpress

Category Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.