php - Populate Contact Form 7 Posted Data with API Response

one text

Solution:

What it sounds like you want to do is first update the mail body with a string replacement, rather than using some hidden variable. With that, you can do something like this in your contact form mail tab. Where {{api_response}} will be replaced by whatever you define in the function Kiri_cf7_api_sender

/** Contact Form 7 Mail Tab in Editor **/
Dear [your-name],

This is the email body...

{{api_response}}

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."

So now for the function Kiri_cf7_api_sender

add_action( 'wpcf7_before_send_mail', 'Kiri_cf7_api_sender' );
function Kiri_cf7_api_sender( $contact_form ) {

    if ( 'Quote_form' === $contact_form->title ) {
        $submission = WPCF7_Submission::get_instance();

        if ( $submission ) {
            $posted_data = $submission->get_posted_data();

            $name    = $posted_data['your-name'];
            $surname = $posted_data['your-name2'];
            $phone   = $posted_data['tel-922'];
            $urltest = $posted_data['dynamichidden-739']; // Not sure if this should be a form field, or just some kind of option field.
            
            if ( strpos( $urltest, '?phone' ) !== false ) {
                $url = 'api string';

            } elseif ( strpos( $urltest, '?email' ) !== false ) {
                $url = 'api string';

            } else {
                $url = 'api string';

                $response = wp_remote_post( $url );
                $body     = wp_remote_retrieve_body( $response );

            }
        }
        // Get the email tab from the contact form.
        $mail = $contact_form->prop( 'mail' );
        // Retreive the mail body, and string replace our placeholder with the field from the API Response.
        // Whatever the api response is within the $body - if you have to json decode or whatever to get it.
        $mail['body'] = str_replace( '{{api_response}}', $body['field'] , $mail['body'] );
        // Update the email with the replaced text, before sending.
        $contact_form->set_properties( array( 'mail' => $mail ) );
        // Push a response to the event listener wpcf7mailsent.
        $submission->add_result_props( array( 'my_api_response' => $body ) );

    }
}

This should at least send the email, and allow you to add the API response to your email.

It also pushes an response to the javascript event wpcf7mailsent which can be found by.

<script type="text/javascript">
    document.addEventListener('wpcf7mailsent', function (event) {
        console.log(event.detail.my_api_response);
    }, false);
</script>

Source