Aaron Fryer

Hooking up your gravity form to dotmailer.

This is part of a series of tutorials about things I have learnt on the job and that I feel are worth sharing back out to the community.

This is part of a series of tutorials about things I have learnt on the job and that I feel are worth sharing back out to the community.

So you built your website in Wordpress and now you need to hookup those contact us forms to your dotmailer account. Luckily gravity forms has a neat little function 'gform_post_submission' that allows us to call our own function when the form is submitted and that dotmailer has a REST API that we can use to send our data to.

To get started you will need to do is either create a new file for this function or open the file that will house our new function. Then you will need to add this:

    add_action('gform_post_submission_1', 'process_contact_form', 10, 2);

    /* Change gform_post_submission_1 to the ID of the gravity form you want to add this behaviour to e.g. gform_post_submission_5

    If you wanted it to apply to all forms simply put this in instead gform_post_submission */

What this will do is add our new action hook to the submission of the gravity form with the ID of 1. When the form is submitted the function will be executed, cool right?

Next step is to create our new function:

    function process_contact_form($entry, $form)
    {

    }

Now you are wondering what the $entry and $form is, they are:

$entry -> The entries in the form $form -> the form that sent it

The next step is to get your API login and secret from dotmailer, the instructions on how to do that are on this page: https://developer.dotmailer.com/docs/getting-started-with-the-api

Now add your API login details to the script, like so:

    //API username
    $username = "your-api-username@apiconnector.com";

    //API password
    $password = "your-api-password";

Now you need to find out the API endpoint URIs that will need to utilise and add them into your script.

    //The endpoint for sending Emails
    $urlEmail = "https://your_regoin_id-api.dotmailer.com/v2/email";

    //this is ID of the address book
    $addressBook = "your-addressbook-id";

    //The endpoint for the address book
    $urlContacts = "https://your_regoin_id-api.dotmailer.com/v2/address-books/". $addressBook ."/contacts";

In this example we are going to be sending confirmation emails to our users and adding them to a mailing list. We will be adding them to an address book, to add them to the address book we need to know the ID of the address book. This can be found by going to the page of the address book and getting the number for the value of 'i' from the query string in the address bar.

After this step I recommend getting the entries into human readable variables but well documented code that highlights the data that each entry contains will work as well.

    //user data
    $subject = $entry['1'];
    $fName = $entry['4'];
    $sName = $entry['5'];
    $email = $entry['2'];
    $address = $entry['6'];
    $postcode = $entry['7'];
    $telephone = $entry['3'];
    $message = $entry['8'];

Now we can get to the fun part of writing our logic to process our data and then send it off to dotmailer. Lets create a function for processing our form data to be sent in an email.

    function prepare_mail()
    {

    }

This function will prepare our email ready to be sent to the API, so lets assemble our data and organise what we want our email to contain.

    function prepare_mail($subject, $fName, $sName, $email, $address, $postcode, $telephone, $message)
    {
        $emailSubject = "About your " . $subject;
        $recipients = array($email);
        $email_content = "Thank you " . $fName . " " . $sName . ", Our email content. Your enquiry was:" . $message;
    }

At this stage we have prepared our variables ready for the email. Please note that the $recipients is an array object that the dotmailer API will require. Next lets create our email object that we will send to dotmailer.

    $rawBody = array(
        'toAddresses' => $recipients,
        'subject' => $emailSubject,
        'fromAddress' => 'your companies email address',
        'htmlContent' => $email_content
    );

    $body = json_encode($rawBody);  
    return $body;

This section of code creates an array of the email data based on the API specification found here: https://developer.dotmailer.com/docs/send-transactional-email

Once we have created our array of email data we run 'json_encode()' on it to create a JSON object which we return to the 'process_contact_form' function. Then we add this like of code to the 'process_contact_form' function.

    //We prepare our body content
    $emailBody = prepare_mail($subject, $fName, $sName, $email, $address, $postcode, $telephone, $message);

Next we create our function that will send our data to the API and to make this function reusable we will be supplying the destination URI and the body as variables.


    function send_data($username, $password, $url, $body)
    {
        //set the headers for authentication + JSON
        $headers = array(
            'Content-Type' => 'application/json',
            'Authorization' => 'Basic ' . base64_encode( $username . ':' . $password )
        );

        $request_data = array(
            'headers' => $headers,
            'body' => $body
        );
        $sent = wp_remote_post($url, $request_data);
    }

This function sets our headers, it is important to set our 'Content-Type' to 'application/json' as not setting it will give you an 'ERROR_CONTENT_TYPE_IS_NOT_SUPPORTED' error from the API. Dotmailer API will require the API username and password to be sent via Basic Auth and so we will need to 'base64_encode' our username and passsword.

Next we will need to construct our request so we will create and array with our headers and body, once we have constructed our request we will send it via the Wordpress 'wp_remote_post()' function with our URL and the request data. We will now add the function call to our 'process_contact_form' function:

    //We send the email to the end user
    send_data($username, $password, $urlEmail, $emailBody);

Now if we take a look at the documentation of the API for adding a person to an address book here: https://developer.dotmailer.com/docs/add-contact-to-address-book

You will not that to send our form data we need to send it in a 'Key' => 'Value' pair. So in the interest readability and reusability we will place this into a seperate function.

    function create_mail_datafields($subject, $fName, $sName, $address, $postcode, $telephone, $message)
    {
        $datafields = array(
            array(
                'Key' => 'FIRSTNAME',
                'Value' =>$fName
            ),
            array(
                'Key' => 'LASTNAME',
                'Value' => $sName
            ),
            array(
                'Key' => 'FULLNAME',
                'Value' => $fName . " " . $sName
            ),
            array(
                'Key' => 'ADDRESS',
                'Value' => $address
            ),
            array(
                'Key' => 'POSTCODE',
                'Value' => $postcode
            ),
            array(
                'Key' => 'TELEPHONE',
                'Value' => $telephone
            ),
            array(
                'Key' => 'ENQUIRYTYPE',
                'Value' => $subject
            ),
            array(
                'Key' => 'ENQUIRY',
                'Value' => $message
            ));

        return $datafields;
    }

This function creates an array of arrays (tongue twister :P ) with each array consisting of a 'Key' and 'Value', then we return that array but we do not create a JSON object at this stage. We then grab the data in the main function:

    //We prepare the datafields to add to the maillist
    $datafields = create_mail_datafields($subject, $fName, $sName, $address, $postcode, $telephone, $message);

The Next and final stage involves preparing our contact to send to the API and then send the data. Lets start by adding our final function to our script.

    function prepare_mailist($email, $datafields)
    {
        $rawBody = array(
            'email' => $email,
            'optInType' => 'Unknown',
            'emailType' => 'PlainText',
            'dataFields' => $datafields
        );

        $body = json_encode($rawBody);  

        return $body;
    }

This function we add our email and our datalist to this array and create a JSON object out of it. This is similar to our previous function labeled 'prepare_mail' function. We now add these lines to our main function:

     //We prepare the contact to be sent to our addressbook
    $contactBody = prepare_mailist($email, $datafields);

    //We add the user to the mailing list
    send_data($username, $password, $urlContacts, $contactBody);

Our script is now complete and now should look like this:

    add_action('gform_post_submission_1', 'process_contact_form', 10, 2);

    function process_contact_form($entry, $form)
    {

        //API username
        $username = "your-api-username@apiconnector.com";

        //API password
        $password = "your-api-password";

        //The endpoint for sending Emails
        $urlEmail = "https://your_regoin_id-api.dotmailer.com/v2/email";

        //this is ID of the address book
        $addressBook = "your-addressbook-id";

        //The endpoint for the address book
        $urlContacts = "https://r1-api.dotmailer.com/v2/address-books/". $addressBook ."/contacts" ;

        //user data
        $subject = $entry['1'];
        $fName = $entry['4'];
        $sName = $entry['5'];
        $email = $entry['2'];
        $address = $entry['6'];
        $postcode = $entry['7'];
        $telephone = $entry['3'];
        $message = $entry['8'];

        //We prepare our body content
        $emailBody = prepare_mail($subject, $fName, $sName, $email, $address, $postcode, $telephone, $message);

        //We send the email to the end user
        send_data($username, $password, $urlEmail, $emailBody);

        //We prepare the datafields to add to the maillist
        $datafields = create_mail_datafields($subject, $fName, $sName, $address, $postcode, $telephone, $message);

        //We prepare the contact to be sent to addressbook
        $contactBody = prepare_mailist($email, $datafields);

        //We add the user to the mailing list
        send_data($username, $password, $urlContacts, $contactBody);
    }

    function prepare_mail($subject, $fName, $sName, $email, $address, $postcode, $telephone, $message) 
    {
        $emailSubject = "About your " . $subject;
        $recipients = array($email);
        $email_content = "Thank you " . $fName . " " . $sName . ", Our email content. Your enquiry was:" . $message;

        $rawBody = array(
            'toAddresses' => $recipients,
            'subject' => $emailSubject,
            'fromAddress' => 'your companies email address',
            'htmlContent' => $email_content
        );

        $body = json_encode($rawBody);  
        return $body;
    }

    function send_data($username, $password, $url, $body)
    {
        //set the headers for authentication + JSON
        $headers = array(
            'Content-Type' => 'application/json',
            'Authorization' => 'Basic ' . base64_encode( $username . ':' . $password )
        );

        $auth_request_data = array(
            'headers' => $headers,
            'body' => $body
        );
        $sent = wp_remote_post($url, $auth_request_data);
    }

    function create_mail_datafields($subject, $fName, $sName, $address, $postcode, $telephone, $message)
    {
        $datafields = array(
            array(
                'Key' => 'FIRSTNAME',
                'Value' =>$fName
            ),
            array(
                'Key' => 'LASTNAME',
                'Value' => $sName
            ),
            array(
                'Key' => 'FULLNAME',
                'Value' => $fName . " " . $sName
            ),
            array(
                'Key' => 'ADDRESS',
                'Value' => $address
            ),
            array(
                'Key' => 'POSTCODE',
                'Value' => $postcode
            ),
            array(
                'Key' => 'TELEPHONE',
                'Value' => $telephone
            ),
            array(
                'Key' => 'ENQUIRYTYPE',
                'Value' => $subject
            ),
            array(
                'Key' => 'ENQUIRY',
                'Value' => $message
            ));

        return $datafields;
    }

    function prepare_mailist($email, $datafields)
    {
        $rawBody = array(
            'email' => $email,
            'optInType' => 'Unknown',
            'emailType' => 'PlainText',
            'dataFields' => $datafields
        );

        $body = json_encode($rawBody);  

        return $body;
    }

Note that custom contact fields will need to be added to the dotmailer address book.

Now that we have finished you can sit back and enjoy PiƱa Coladas and getting caught in the rain. I hope you found this useful.

Posted in Coding, Tutorials, Blog on Sep 28, 2016