Integrating your contact form with external services

For many online businesses, the contact form is one piece of a larger marketing and customer management system involving multiple services. You might be sending support requests into HelpScout, or adding interested readers to your MailChimp mailing list, or creating a new lead in your CRM.

Popular services might have add-on plugins that integrate with your form. For instance, WPForms has MailChimp and Aweber add-ons. But what if you need to build your own integration? It is surprisingly easy.

Connecting to a Custom CRM

Over the past five years I’ve created multiple CRMs for myself. I started with TwentyTen CRM, then Genesis CRM, and now I’m using a custom (non-WordPress) CRM that Jared Atchison and I co-developed. I use it to analyze lead sources, keep notes during calls with prospective clients, manage projects, and track key metrics like profitability and time spent on change requests.

When I switched my contact form over to WPForms, it only took a few minutes to connect my CRM. You can do the same with other form plugins like Gravity Forms, but the filter names and field data structure will be different (like this).

Place the following in your core functionality plugin:

<?php
/**
* Integrate WPForms with CRM
*
* @author Bill Erickson
* @link http://www.billerickson.net/contact-form-integration/
*
* @param array $fields
* @param array $entry
* @param array $form_data
* @param int $entry_id
*/
function be_crm_connector( $fields, $entry, $form_data, $entry_id ) {
$api_url = 'http://example.com';
$body = array(
'secret' => '',
'name' => $fields['1']['value'],
'email' => $fields['2']['value'],
'phone' => $fields['3']['value'],
'url' => $fields['4']['value'],
'referral' => $fields['5']['value'],
'referral_other' => $fields['6']['value'],
'services' => $fields['7']['value'],
'date' => date( 'Y-m-d' ),
'inquiry' => $fields['8']['value'],
'status' => '1',
);
$request = wp_remote_post( $api_url, array( 'body' => $body ) );
// Simple error handling
if ( is_wp_error( $request ) ) {
$msg = "There was an error trying to push a lead to the CRM.\n";
$msg .= 'Error returned: ' . $error = $request->get_error_message() . "\n\n";
$msg .= "The lead below may need to be added to the CRM manually.\n";
$msg .= $body['name'] . ' ' . $body['email'];
wp_mail( get_bloginfo( 'admin_email' ), 'CRM Connector Error', $msg );
}
}
add_action( 'wpforms_process_complete_5702', 'be_crm_connector', 10, 4 );
view raw crm-connector.php hosted with ❤ by GitHub

This function is hooked to wpforms_process_complete_5702. This runs when the form with an ID of 5702 has fully processed, saved the entry, and sent out the notifications. Change the ‘5702’ to match your form’s ID, or use wpforms_process_complete to run on all forms. The Form ID can be found in WPForms > All Forms:

wpforms-listing

I’ve defined the $api_url for my CRM, which is where this form data will be sent. I then place all the relevant fields in $body.

The $fields variable is an array of all the form fields, indexed by Field ID. When editing a field, you can see the ID listed by the field type at the top of the “Field Options” panel. In the screenshot below, see the Name (ID #1):

wpforms-edit-field

The ‘value’ parameter holds the fully formatted version of each field entry. For instance, if you’re using the name field that has “First Name” and “Last Name” inputs, the ‘value’ will contain the combined name. You could also access just the first and last name using $fields['1']['first'] and $fields['1']['last'].

After putting together the message, I send it using wp_remote_post() to the API URL. It is received by my CRM, and added to the database. If you’re curious, the API looks like this. If there’s an error with the request, I create a message describing the error and send it as an email to myself.

Summary

With a high quality form plugin like WPForms, it’s simple to send your form submissions to any API.

form intermediate wordpress

Receive New Posts by Email

Comments

  1. Bill,

    Nice post! I haven’t used WPForms yet, but it sounds like it’s a good plugin. Do you still use Gravity Forms, or has WPForms provided a suitable replacement?

    Also, I’m a little sad there isn’t a link on “now I’m using a custom (non-WordPress) CRM that Jared Atchison and I co-developed.” That sounds intriguing. I have yet to find a full CRM that works for me, mainly relying on FreshBooks and notes (ugh).

    Cheers,
    Joshua

    1. I’ve only used it on a few projects since it’s so new, but I’ve been happy with it. For what most of my clients need – a standard contact form – it’s definitely a suitable replacement. Even the free WPForms Lite will work for them since most don’t need any of the add-ons.

      Gravity Forms is still my go-to plugin for more complicated integrations, like a form that generates a draft post in a custom post type, mapping fields to meta, etc.

      The reason we haven’t posted about the non-WordPress CRM is that we’re rebuilding it AGAIN. We originally built it off of WordPress to simplify the database structure and make it faster to query. With thousands of posts (contact form submissions) and dozens post meta fields, the WordPress based ones became very sluggish.

      But in the process we were constantly “reinventing the wheel” – rebuilding core WP functionality like user authentication, sanitization/escaping, inserting content into the database, transients…

      Now we’re building a new version that’s a WordPress plugin but uses a separate table for the entries. Jared actually modeled it on his work with WPForms, which stores the entries in a separate table for performance reasons as well (Forms are a CPT though).

      I think Jared has both versions of the CRM running, and I’m on the old one. I’ve been meaning to switch over and finish up some work on it (missing a few reports) but we’ve both been busy.

      We also have a Share Count Plugin that will be launching soon, so keep your eyes out for a post about that.

      1. I think I mentioned at Pressnomics that I finally broke down and bought a CRM/project management tool last month because I didn’t have time to continue supporting our home-grown one. (We went with Insightly.) I’m so happy we finally made that change, but the annoying thing about switching platforms is that we have to transfer all the data over. Bill, when you have switched between CRMs are you doing manual data entry of old records or do you have a script that transfers things from one system to another? I’ve been thinking I might build something that uses WP API to import old data into Insightly, but I haven’t had time.

        Are you beta testing the Share Count plugin? Would love to have a look, if so.

        1. Since my previous CRM was WordPress-based and installed on the same server as my new CRM, I created a WordPress template to export leads from WordPress to the new DB.

          I grabbed 500 posts at a time, structured all the fields like my new CRM wants them, then inserted them into the new CRM’s database. Finally I mark those posts as ‘exported’ using post meta so that the next time I refresh this page it doesn’t import duplicates.

        2. Amber, I’m considering Insightly for a client. BUT it seems the only email marketing system they integrate with is MailChimp or Emma. Love GetResponse, but I may be stuck with the monkey. What are you using? His site is WP using ContactForm7 and Contact Form DB with it.

          Bill, I may be contacting you for a quote on custom integration. GetResponse plugin works well, but I want to also use Insightly, because it’s so user-friendly.

          1. One option is to use WPForms => Zapier => Insightly.

            Zapier is a service that lets you connect 500+ services without any coding. Instead of WPForms writing an addon for every email marketing and CRM tool, they created a Zapier addon so now you can connect your form to any of Zapier’s supported services, including Insightly.

  2. Bill,
    I am very interested in your WordPress CRM … having searched far and wide for a useful WP CRM I think I can safely say; there are none out there.
    Please consider making your CRM available one way or the other 🙂

    1. The new WordPress-based one will be publicly available when we finish it.

      But there’s a very good chance my CRM won’t work perfectly for you. What I think is more important is you build your own CRM so that it does what you need, and can grow with you. Every few months I’m adding new reports to it to collect different type of data. For instance, in my recent post How long does it take to build a website, I added a report to analyze the modification period of past projects.

      If you’re a WordPress developer, the simplest thing you can do is build a CRM on WordPress so you can customize it. Set up a separate WordPress install (crm.yoursite.com), use the code detailed above to send your contact form data to it, and write a simple API that takes that data and generates a WordPress post based on it. Add all your relevant fields as post meta, and create template pages for the different reports you want. Both TwentyTen CRM and Genesis CRM can provide guidance for this.

  3. Thanks! Very useful. How can i sent to 1 field of crm values of 3 fields from Gravity Forms?
    I mean this row ‘clientaddress’ => $entry[‘3’], I need t osend somethin like this
    ‘clientaddress’ => $entry[‘3, 4, 5’],

    1. Like this: 'clientaddress' => $entry['3'] . $entry['4'] . $entry['5'],

      Although if you’re using WPForms, you’ll want to change that to $entry['3']['value'] etc

  4. Hi Bill,

    I have a question that I’m hoping is simple enough you can help me answer. I’ve got an HTML code block in my form that asks for and the retrieves the user’s geolocation using HTML5 (like this http://www.w3schools.com/html/html5_geolocation.asp ). This is working great so far, it returns the coordinates and the accuracy in the div. However I’m struggling to save that data off in the form somewhere. Can you point me to something that will help me understand how to set the field values so that the lat/long can be saved off in entry?

    Trying to build a web app where a user can request a pickup at their exact location, the WPForms geolocation add on isn’t good enough.

    1. I think the best approach here is to create a new field type. That way the field data is actually saved with the entry. Here’s an example from a recent project I worked on.

      The init() method is where you define the basic field settings (name, type, icon, order…). The field_options() method lets you define the available options in the left sidebar when editing a field. field_preview() is what’s shown in the form builder, and field_display() is what’s displayed in the actual form.

      Depending on what data is provided by the input field, you may want to use the wpforms_process_filter filter to modify the form data before it’s saved.

      I recommend including this in a core functionality plugin. At the top of the code snippet I show what you can put in your CF plugin – using wpforms_loaded action to load your code after WPForms has loaded.

      For more guidance, take a look at how WPForms builds its fields in /includes/fields, and /pro/includes/fields. You might also try asking the question on the WPForms support forum – I know Jared is always happy to help developers extend WPForms.

      For more examples of building new field types,

  5. Thank you for this, we are using contact form 7 and are rrying to integrate to an existing restful api service. In yor example, how would you handle a json response from the remote server, and send the user to a page formatted with this data that was returned ?

    Latsly would you recommend WPforms over contact form 7 ?

    1. I had to check with the authoritative source on this – Jared Atchison, the developer of WPForms.

      Use a very high priority on your function that’s hooked to wpforms_process_complete, like this: add_action( 'wpforms_process_complete', 'be_my_integration', 100, 4 );

      That way it’s the last thing to run, after WPForms has done all its processing, saving and emailing. Use wp_redirect( $uri ); exit; to redirec the user based on the data in your json response.

  6. Bill your blog post has gotten me the closest to where I need to be with my current client. I am not quite there yet. I followed your instruction created the core-functionality plugin placed the coding into the plugin. My issue is I am trying to create a form for a utility broker that needs a response from the external api. I figured I could use most of this method until the response from the external api part. How do I go about finishing this?

  7. Bill Erickson, Good morning.
    First of all, sorry for my English.
    I’m not a pro in coding, I’m a newbie really, taking the first steps, but I’m really curious in how the APIs world works, and how to send data from wordpress forms to an external data base, and then I land here.
    I took a look to your API code, but I don’t know whats in the inc/init.php file, can you show it? it´s possible? how to conect and to fill the data base?

    Sorry again if I bother you, and thanks for your time.

    1. Where do you see inc/init.php referenced? I don’t see it mentioned anywhere so am not sure what you’re referring to.

  8. Bill,

    Sorry for bringing up an old post, but what if there are some basic authentication requirements? How would I send the data via API?

Leave a comment