What are webhooks?
A webhook is a means of proactively informing one system when there is a change or event in another one. At Mainstay, webhooks allow a partner to receive notifications of escalations to an external API (in addition to email).
Configuration
To configure a new webhook, visit https://app.mainstay.com/settings/api-tokens (Settings > Mainstay API). This table shows a list of all configured webhooks.
- Name - a custom name given to this configuration
- Enable - a boolean toggle that sets whether to send data to this webhook URL
- URL - the web address of the external system that is expecting data
- Event Type - the kind of event that would be sent to this URL; at present, this is only Escalations
- Revoke Access - remove this configuration
Creating a Configuration
- Click Create New to configure a webhook.
- Enter a custom Name for this configuration and the exact URL that will receive the data.
- Click Create Shared Secret
- Copy this Shared Secret to a safe place. This is used for verifying that data received at this URL was sent from Mainstay.
- To enable or disable this configuration, click the toggle in the Enabled column.
Removing a Configuration
- Click Revoke Access to pull up a confirmation screen.
- Click Yes, Revoke to permanently delete this configuration.
- Note that it is not possible to edit a configuration. If you need to change the Name or URL, or if you need to reset the Shared Secret, simply delete the existing configuration and create a new one.
Escalations Rules
To configure an escalation rule, visit https://app.mainstay.com/settings/escalation (Settings > Email Forwarding & Escalations). See the support article on Email Forwarding & Escalations to learn more about manual and automatic escalations.
If the webhooks feature is available on your account - regardless of whether you have any enabled configurations - you will see an informational banner above both the Manual Forwarding Suggestions and Automatic Escalation Rules tables:
You will also be able to configure rules without an email recipient - the field becomes optional:
All escalation events will send to all enabled webhook configurations. Even if there is an email recipient, an escalation event will still be sent to your webhook configurations.
You can also have campaign Script escalations and responses to Script questions escalate to webhooks if you so choose:
Conversations
Escalation events that send data to webhooks will appear on the Conversations page, just like email escalations.
If the data failed to send, a status will be shown.
Escalations Event Payload
Here is an example of an automatic escalation sent to a webhook URL as a POST request:
{
"topic_schema_version": "2.0",
"topic": "escalation.triggered",
"event_id": "afe4be18-bfbe-4967-b9cd-f42d534f4862",
"event_time": "2022-05-27T17:55:22.054895Z",
"attempts": 1,
"data": {
"escalation_id": "xzzWPnuiewF4cJW5C",
"contact_id": "5e41985fe64395007d593825",
"message_id": "85564b211327403ca2e67bf9f0cac5f5",
"escalated_message": "test from James M die",
"institution_id": "productTest",
"occurred_at": "2022-05-27T17:55:13.126751Z",
"non_english_translation": null,
"escalation_type": "sensitiveMatch",
"conversation_link": "https://app.mainstay.com/conversations/5e41985fe64395007d593825",
"contact_information": {
"mainstay_id": "5e41985fe64395007d593825",
"first_name": "James",
"last_name": "Mayr",
"preferred_name": "Jimbo",
"email": "james@mainstay.com",
"phone": "5553141592",
"enrollment_id": "abc",
"crm_id": "xyz",
"custom_fields": {
"favoritecolor": "blue"
},
"latest_chat_history": [],
"logs": [
{
"incoming": true,
"message_body": "test from James M die"
},
{
"incoming": false,
"message_body": "You said die and I'm programed to treat that language seriously. If there's an emergency, call 911"
}
]
}
}
}
Note that event_id and event_time refer to Mainstay's attempt to send this payload to the webhook URL, while data.escalation_id and data.occurred_at refer to the escalation event itself - in this case, the bot recognizing that the incoming message contained the sensitive word "die".
Creating A Webhook Endpoint
A webhook endpoint is an HTTP or HTTPS endpoint on your server with a URL. Note that once your new webhook endpoint is publicly accessible, it must be HTTPS.
Set up an HTTP endpoint on your local machine which will do the jobs of verifying the incoming POST request signatures, consuming the request payload, and returning a response to Mainstay.
The incoming request payload has the headers and schema as detailed above.
The webhook URL should send return a response with one of the following shapes back to Mainstay.
Successful requests:
{"statusCode": 200, "body": {"message": str}}
Failed requests:
400 - Bad request
{"statusCode": 400, "body": {"error": str}}
500 - Something else went wrong
{"statusCode": 500, "body": {"error": str}}
Verifying webhook signatures
Every webhook request from Mainstay is signed with the shared secret you got when you created the subscription. Check the signature before trusting a request. A valid signature confirms that Mainstay sent the request and that nobody changed it on the way.
Request format
Mainstay sends an HTTPS POST to your endpoint with these headers:
Header |
Example |
Description |
|---|---|---|
Mainstay-Signature |
v1=bdee0dc41375… |
Signature version, =, then a hex-encoded HMAC-SHA256 digest |
Mainstay-Timestamp |
1793805479 |
When the request was signed, in Unix time (seconds) |
Content-Type |
application/json |
|
User-Agent |
Mainstay-Webhooks/1.0 |
|
How to verify
Read the raw request body. Use the bytes exactly as they arrived, before any JSON parsing. If you parse and re-serialize the body, spacing and key order can change and the check will fail. In Express, for example, use
express.raw()with type "application/json" on the webhook route rather thanexpress.json().Build the signed string. Join the Mainstay-Timestamp value, a period (.) and the raw body:
<Mainstay-Timestamp>.<raw request body>Compute the expected signature. Run HMAC-SHA256 over that string, using your shared secret as the key, and hex-encode the result. Use the secret exactly as shown to you, as text. Don't hex-decode it first.
Compare signatures. Strip the "
v1=" prefix fromMainstay-Signatureand compare the rest to your result with a constant-time comparison, such ashmac.compare_digestin Python orcrypto.timingSafeEqualin Node.js.Check the timestamp. Reject the request if Mainstay-Timestamp is more than 5 minutes from your current time. This protects against replayed requests.
If either check fails, respond with 401 and don't process the event.
Example (Python)
import hashlib
import hmac
import time
TOLERANCE_SECONDS = 300
def is_valid_mainstay_request(raw_body: bytes, headers, shared_secret: str) -> bool:
timestamp = headers.get("Mainstay-Timestamp", "")
signature = headers.get("Mainstay-Signature", "")
version, _, received = signature.partition("=")
if version != "v1" or not timestamp.isdigit():
return False
if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
return False
signed = timestamp.encode() + b"." + raw_body
expected = hmac.new(shared_secret.encode(), signed, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, received)
Example (Node.js)
const crypto = require("crypto");
function isValidMainstayRequest(rawBody, headers, sharedSecret) {
const timestamp = headers["mainstay-timestamp"] || "";
const [version, received = ""] = (headers["mainstay-signature"] || "").split("=");
if (version !== "v1" || !/^\d+$/.test(timestamp)) return false;
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false;
const expected = crypto
.createHmac("sha256", sharedSecret)
.update(timestamp + "." + rawBody)
.digest("hex");
return (
expected.length === received.length &&
crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(received))
);
}
Responding, retries and duplicates
Respond with a
2xxstatus within 20 seconds. Do any slow processing after you respond.If Mainstay gets an error status, a timeout or a connection failure, it retries after about 1 minute and then after about 10 minutes. That's 3 attempts in total.
Each retry is signed fresh: it gets a new
Mainstay-TimestampandMainstay-Signature, and the body's "attempts" value goes up by one. Retries still pass the 5-minute timestamp check.event_idandevent_timestay the same on every attempt of an event. Useevent_idto drop events you've already processed.Redirects aren't followed. Register the final URL of your endpoint.
Keep your secret safe
The shared secret is shown only once, when you create the subscription. Store it like a password. If it leaks, delete the subscription and create a new one to get a new secret.
Comments
0 comments
Article is closed for comments.