SimplyBook (Session Auth)#

This example will walk you through creating a Developer App that uses Session Auth and has a single visible trigger that looks for new data. To make the example real, we'll be implementing the SimplyBook API.

Quick Preparation Checklist#

If you plan to follow along, it is recommended you set up everything beforehand and keep these resources open and ready for quick access.

Create the App#

To get started, go to the Developer Platform and click the "Create App" button. You'll be asked to provide a title and a brief description.

Create App screen

After you submit, you should find yourself with a fresh App like this:

Screenshot of empty dev app

Setting up authentication#

We'll start by defining how Zapier should authenticate with SimplyBook. From the above screen, click the "Get Started" button in the authentication section.

Get Started button

On Step 1 you will want to choose Session Auth since that is what SimplyBook uses.

Selecting Session Auth

You should then find yourself on Step 2 with a couple of pre-generated authentication fields. These are the fields that users will be presented with when they add a SimplyBook account to Zapier.

Screenshot of generated authentication fields

Looking at the documentation, there’s a companyLogin we’ll need, so let’s add that by clicking on “Add Another Authentication Field” on the top left of the list of fields.

Screenshot of adding Company Login

After adding that, we have all fields we need. Sorting them (clicking the arrow buttons to the right) is a good idea, for an improved UX.

Screenshot of all authentication fields

After clicking Next, we’re at the final step for setting up the authentication schema plainly. Here we’ll want to define how authentication goes through, which, according to the documentation, is in the header.

NOTE: Sometimes the UI will not show anything here. Just save and in the app dashboard click “Manage Authentication Settings”, select “Session Auth” and you can get the screen below.

Screenshot of auth mapping

Authentication variables are added automatically with their key capitalised, if in the header, or unchanged if in the query string.

For SimplyBook we’ll need custom headers, so we’ll need more custom scripting later.

At this point, we have the authentication setup and are ready to make our test trigger.

Setting up a test trigger#

In order to verify the authentication users provide, we need to build a test trigger. The test trigger is simply an API call to an endpoint that requires authentication and is guaranteed to always return some data. This allows Zapier to verify that the authentication information a user provides is valid. For SimplyBook, we'll use the /admin endpoint as the test call (using the getCompanyInfo() method).

NOTE: Usually there’s a /me or /user endpoint you can use, in most APIs.

From your App, click the "Add Your First Test Trigger" button.

Create trigger button

The first form you see allows you to define some of the meta information about the trigger. Since this is a test trigger that will not be useful beyond verifying authentication, we can put something short and leave the "Hide" checkbox checked.

Step 1 of adding a trigger

Click next to proceed to Step 2, Trigger Fields. Trigger fields add extra information for the trigger which you can use in the URL or in Scripting. We're actually going to skip over this step because our trigger does not require any additional info. Hit next to get to Step 3, where we define how our trigger will fetch data from SimplyBook.

Here, according to the documentation,, here is what we will need to fill out:

Step 3 of adding a trigger

Click save to proceed to Step 4. Typically in this step you would copy and paste an example JSON representation of a response in the text area. Since this test trigger will be hidden from actual use in the Zapier UI, we'll skip this step, so just click save.

At this point, we have defined our test trigger and are almost ready to try it out!

Defining how authentication really works#

Now we need to jump into Scripting and create our own get_session_info method.

Also a “generic” add_custom_headers method to inject in all TRIGGER_KEY_pre_poll (and similarly for any other actions or searches we could have) our custom headers.

Click the “Edit Code” button.

Edit Code button

According to SimplyBook’s documentation, the authentication needs to be a POST request to https://user-api.simplybook.me/login, with a JSON body, like:

{
  "jsonrpc": "2.0",
  "method": "getUserToken",
  "params": [
    "companyLogin",
    "username",
    "password"
  ],
  "id": 1
}

That means we should make Scripting look like:

'use strict';

var Zap = {
    get_session_info: function(bundle) {
        var user_token,
            request_data,
            token_request_payload,
            token_response,
            parsed_response;

        // Build Request Body
        request_data = {
            jsonrpc: '2.0',
            method: 'getUserToken',
            params: [
                bundle.auth_fields.company,
                bundle.auth_fields.username,
                bundle.auth_fields.password
            ],
            id: 1
        };

        // Assemble the meta data for our key swap request
        token_request_payload = {
            method: 'POST',
            url: 'https://user-api.simplybook.me/login',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            data: z.JSON.stringify(request_data)
        };

        // Fire off the key exchange request.
        token_response = z.request(token_request_payload);
        parsed_response = z.JSON.parse(token_response.content);

        // Handle errors (ideally we'd look in the response status_code)
        if (parsed_response.error) {
            throw new HaltedException('Error: ' + parsed_response.error.message);
        }

        // Extract the `user_token` from the returned JSON.
        if (parsed_response.result) {
            user_token = parsed_response.result;
        } else {
            throw new HaltedException('Invalid Login Credentials!');
        }

        // Now we get the user_token!
        return { 'user_token': user_token };
    },

    // Add custom headers to a bundle
    add_custom_headers: function(bundle) {
        bundle.request.method = 'POST';
        bundle.request.headers['X-Company-Login'] = bundle.auth_fields.company;
        bundle.request.headers['X-User-Token'] = bundle.auth_fields.user_token;

        // Delete unnecessary auto-added fields
        delete bundle.request.headers.company;
        delete bundle.request.headers.username;
        delete bundle.request.headers.password;

        return bundle;
    },

    // Modify the request details before checking auth
    auth_test_pre_poll: function(bundle) {
        bundle = this.add_custom_headers(bundle);

        // Build Request Body
        var request_data = {
            jsonrpc: '2.0',
            method: 'getCompanyInfo',
            params: [],
            id: 1
        };

        bundle.request.data = z.JSON.stringify(request_data);

        return bundle.request;
    },

    // Check if there's an invalid session
    auth_test_post_poll: function(bundle) {
        var parsed_response = z.JSON.parse(bundle.response.content);

        // Handle errors (ideally we'd look in the response status_code)
        if (parsed_response.error) {
            throw new InvalidSessionException();
        }

        return parsed_response.result;
    }
};

Don’t forget to Save (top right button)!

Testing what we have built so far (authentication)#

Now is a good time to go and see if we have the authentication field and test trigger setup properly. To test them, you can go to your connected accounts and click the connect account dropdown.

Connect account dropdown

After you select the SimplyBook Example App, you will get this form:

Screenshot of authentication field

As you can see, the form contains the authentication fields we set up. Fill out the form and click continue. At this point, Zapier will make an API call to the auth trigger. If everything is setup correctly, you should get a success message and the account should be added:

Example of successfully adding a SimplyBook account

You can check the requests and what they have in your app’s Monitoring tab.

App’s Monitoring Tab

Now that we have working authentication, we are ready to create our first visible trigger!

Creating a visible trigger#

A useful trigger would be to get all existing bookings.

Looking through the documentation we can find a getBookingsZaper() method in the /admin endpoint. Let’s use that.

We’ll start by clicking to add a new trigger.

Add New Trigger button

Here’s what we’d fill in for the first step:

Add New Trigger: Step 1

Click “Save & Next”. Since there are no fields/params for this trigger, we can skip step 2 as well. Click “Next”

Here’s what we’ll need in Step 3:

Add New Trigger: Step 3

Click “Save & Next”. In this last step we’ll add a sample object. This won’t usually be shown to the user in the UI, unless they skip the test step:

{
    "id": "1",
    "record_date": "2016-05-10 20:25:01",
    "start_date": "20160511T090000",
    "end_date": "20160511T100000",
    "unit_id": "1",
    "text": "Test Text",
    "client": "Test Client",
    "unit": "Test Unit",
    "event": "Test Event",
    "event_id": "1",
    "is_confirm": "1",
    "client_id": "1",
    "client_phone": "1111111111",
    "client_email": "test@example.com",
    "offset": "0",
    "comment": "",
    "code": "test"
}

Feel free to mark special fields as important and create better labels (we’ll automatically figure that out if you don’t set anything)

Add New Trigger: Step 4

Click save and we are done here.

Now we just need to use Scripting to customise (add pre_poll and post_poll for this new trigger).

Basically Scripting should become this:

'use strict';

var Zap = {
    get_session_info: function(bundle) {
        var user_token,
            request_data,
            token_request_payload,
            token_response,
            parsed_response;

        // Build Request Body
        request_data = {
            jsonrpc: '2.0',
            method: 'getUserToken',
            params: [
                bundle.auth_fields.company,
                bundle.auth_fields.username,
                bundle.auth_fields.password
            ],
            id: 1
        };

        // Assemble the meta data for our key swap request
        token_request_payload = {
            method: 'POST',
            url: 'https://user-api.simplybook.me/login',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            data: z.JSON.stringify(request_data)
        };

        // Fire off the key exchange request.
        token_response = z.request(token_request_payload);
        parsed_response = z.JSON.parse(token_response.content);

        // Handle errors (ideally we'd look in the response status_code)
        if (parsed_response.error) {
            throw new HaltedException('Error: ' + parsed_response.error.message);
        }

        // Extract the `user_token` from the returned JSON.
        if (parsed_response.result) {
            user_token = parsed_response.result;
        } else {
            throw new HaltedException('Invalid Login Credentials!');
        }

        // Now we get the user_token!
        return { 'user_token': user_token };
    },

    // Add custom headers to a bundle
    add_custom_headers: function(bundle) {
        bundle.request.method = 'POST';
        bundle.request.headers['X-Company-Login'] = bundle.auth_fields.company;
        bundle.request.headers['X-User-Token'] = bundle.auth_fields.user_token;

        // Delete unnecessary auto-added fields
        delete bundle.request.headers.company;
        delete bundle.request.headers.username;
        delete bundle.request.headers.password;

        return bundle;
    },

    // Modify the request details before checking auth
    auth_test_pre_poll: function(bundle) {
        bundle = this.add_custom_headers(bundle);

        // Build Request Body
        var request_data = {
            jsonrpc: '2.0',
            method: 'getCompanyInfo',
            params: [],
            id: 1
        };

        bundle.request.data = z.JSON.stringify(request_data);

        return bundle.request;
    },

    // Check if there's an invalid session
    auth_test_post_poll: function(bundle) {
        var parsed_response = z.JSON.parse(bundle.response.content);

        // Handle errors (ideally we'd look in the response status_code)
        if (parsed_response.error) {
            throw new InvalidSessionException();
        }

        return parsed_response.result;
    },

    // Modify the request details before getting bookings
    new_booking_pre_poll: function(bundle) {
        bundle = this.add_custom_headers(bundle);

        // Build Request Body
        var request_data = {
            jsonrpc: '2.0',
            method: 'getBookingsZapier',
            params: [],
            id: 1
        };

        bundle.request.data = z.JSON.stringify(request_data);

        return bundle.request;
    },

    // Check if there's an invalid session
    new_booking_post_poll: function(bundle) {
        var parsed_response = z.JSON.parse(bundle.response.content);

        // Handle errors (ideally we'd look in the response status_code)
        if (parsed_response.error) {
            throw new InvalidSessionException();
        }

        return parsed_response.result;
    }
};

At this point, we have a visible trigger that we are ready to test.

Testing the trigger#

Now that we have built out the basics of our App, it is time to try it out and see if it works. Go to your dashboard and click the “Make a Zap!” button.

On the first step of the Zap Editor you should be able to see the SimplyBook app and select it’s single visible trigger

Step 1 Zap Editor

Now log into SimplyBook and create a new booking, if you don’t have any yet.

After that, you should be able to see it in your Zap.

Step 2 Zap Editor

As an action, you can use anything we like. Sending a direct message to slack tends to work really well.

Step 3 Zap Editor

You should now be able to login to Slack and see the new booking.

New Booking in Slack

Congratulations! You have a working SimplyBook application that:

  • Uses Session Auth to authenticate.
  • Has a polling trigger to test authentication credentials.
  • Has a visible polling trigger.

Be sure to check out our other examples for more details on doing other interesting things with Zapier's developer platform!

↑ Was this documentation useful? Yes No
Get Help