Contact from 7 API integration + data layer

65 views Asked by At

I'm working on integrating Contact Form 7 with an API, which is functioning as expected. However, the challenge arises with the API returning a dynamic "gatewayID" that I need to push to Google Tag Manager through the data layer. The issue I'm facing is the data layer itself is not being transmitted at all. I'm struggling to identify the cause of this issue and would appreciate any advice on how to ensure the gatewayID is correctly sent to the data layer for Google Tag Manager to receive.

/* Function to send contact form 7 data to API */
add_action('wpcf7_before_send_mail', 'send_post_after_cf7');
function send_post_after_cf7($contact_form) {
    $submission = WPCF7_Submission::get_instance();

    if ($submission) {
        $posted_data = $submission->get_posted_data();
        //get form ID, id = post id of cf7
        $form_id = $contact_form->id();
        //global values contain all forms
        $phone = $posted_data['tel'];
        $zip = $posted_data['zip'];
        $referer_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'N/A';
        $current_date_time = date('Y-m-d H:i:s');
        $newsletter = isset( $posted_data['newsletter'] ) ? true : false;

        //form6
        if ($form_id == '2152452'){
        //get form data
                $email = $posted_data['your-email'];
                $name = $posted_data['your-name'];
                $source = "formcontact";
                $fullName = sanitize_text_field($posted_data['your-name']);

        //get API url
        $api_url = 'https://api.xxxx.com/my-api/form6';
                
        $body = array(
                    'email' => $email,
                    'phone' => $phone, 
                    'zip' => $zip,
                    'source' => $source,
                    "firstName" => $fullName,
                    "sourceUrl" => $referer_url,
                    "gdpr_date" => $current_date_time, 
                    "newsletter" => $newsletter
                );
        } 

        $args = array(
            'method' => 'POST',
            'headers' => array(
                'Content-Type' => 'application/json',
            ),
            'body' => json_encode( $body ),
        );

        $body_json = json_encode($body);
        $response = wp_remote_post($api_url, array(
            'method' => 'POST',
            'headers' => array('Content-Type' => 'application/json; charset=utf-8'),
            'body' => json_encode($body),
            'data_format' => 'body',
        ));

        if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) == 200) {
            $body = wp_remote_retrieve_body($response);
            $data = json_decode($body);
            if (isset($data->gatewayID)) {
                $gatewayID = $data->gatewayID;

                add_action('wp_footer', function() use ($gatewayID, $form_id) {
                    $dataLayerContent = [
                        'event' => 'formSubmissionSuccess',
                        'gatewayID' => $gatewayID,
                    ];
                    if ($form_id == '2152452') {
                        $dataLayerContent['form_type'] = 'formcontact';
                        if (isset($posted_data['tel'])) {
                            $dataLayerContent['phone'] = $posted_data['tel'];
                        }
                        if (isset($posted_data['your-email'])) {
                            $dataLayerContent['email'] = $posted_data['your-email'];
                        }
                        if (isset($posted_data['your-name'])) {
                            $dataLayerContent['name'] = $posted_data['your-name'];
                        }
                        if (isset($posted_data['zip'])) {
                            $dataLayerContent['ZIP'] = $posted_data['zip'];
                        }
                    }
            $jsonContent = json_encode($dataLayerContent);
                    
            error_log("Data Layer content: " . $jsonContent);

            echo "<script type='text/javascript'>
                window.dataLayer = window.dataLayer || [];
                 window.dataLayer.push($jsonContent);
            </script>";
                    

                });
             $response_body = wp_remote_retrieve_body($response);
               error_log("API request successful, sent data to CRM: $body_json, response: $response_body, Data Layer content: " . json_encode($jsonContent));
            }
        }
    }
}
1

There are 1 answers

0
Howard E On

To push items to the front end, you need to push your data to the DOM. You can do this with the CF7 DOM Events.

First, use $submission->add_result_props() to push your event.

/* Function to send contact form 7 data to API */
add_action( 'wpcf7_before_send_mail', 'send_post_after_cf7' );
function send_post_after_cf7( $contact_form ) {
    $submission = WPCF7_Submission::get_instance();

    if ( $submission ) {
        $posted_data = $submission->get_posted_data();
        // get form ID, id = post id of cf7
        $form_id = $contact_form->id();
        // global values contain all forms
        $phone             = $posted_data['tel'];
        $zip               = $posted_data['zip'];
        $referer_url       = isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : 'N/A';
        $current_date_time = date( 'Y-m-d H:i:s' );
        $newsletter        = isset( $posted_data['newsletter'] ) ? true : false;

        // form6
        if ( $form_id == '2152452' ) {
            // get form data
            $email    = $posted_data['your-email'];
            $name     = $posted_data['your-name'];
            $source   = 'formcontact';
            $fullName = sanitize_text_field( $posted_data['your-name'] );

            // get API url
            $api_url = 'https://api.xxxx.com/my-api/form6';

            $body = array(
                'email'      => $email,
                'phone'      => $phone,
                'zip'        => $zip,
                'source'     => $source,
                'firstName'  => $fullName,
                'sourceUrl'  => $referer_url,
                'gdpr_date'  => $current_date_time,
                'newsletter' => $newsletter,
            );
        }

        $args = array(
            'method'  => 'POST',
            'headers' => array(
                'Content-Type' => 'application/json',
            ),
            'body'    => json_encode( $body ),
        );

        $body_json = json_encode( $body );
        $response  = wp_remote_post(
            $api_url,
            array(
                'method'      => 'POST',
                'headers'     => array( 'Content-Type' => 'application/json; charset=utf-8' ),
                'body'        => json_encode( $body ),
                'data_format' => 'body',
            )
        );

        if ( ! is_wp_error( $response ) && wp_remote_retrieve_response_code( $response ) == 200 ) {
            $body = wp_remote_retrieve_body( $response );
            $data = json_decode( $body );
            if ( isset( $data->gatewayID ) ) {
                $gatewayID = $data->gatewayID;
                $submission->add_result_props(
                    array(
                        'myCustomResponse' => array(
                            'gatewayID' => $gatewayID,
                            'apiResponse' => $data,
                        ),
                    
                    ),
                );
            }
        }
    }
}

Then you can retrieve the data using the DOM Event from CF7 - The custom event will land in apiResponse

let wpcf7Elm = document.querySelector( '.wpcf7' );
 
wpcf7Elm.addEventListener( 'wpcf7submit', function( event ) {
  console.log(event.detail.apiResponse.myCustomResponse);
}, false );

From there, you should be able to create an event in GTAG.