Trigger Workflow from API

It is a unified API to trigger workflow and doesn't require user creation before hand to trigger notification. Recommended for platforms transitioning their existing notifications to SuprSend.
If you are using our frontend SDKs to configure notifications and passing events and user properties from third-party data platforms like Segment, then event-based trigger would be a better choice.

📘

Available in SDK version >= 1.10.0


Sample Payload

const {Suprsend, WorkflowTriggerRequest} = require("@suprsend/node-sdk");

const supr_client = new Suprsend("_workspace_key_", "_workspace_secret_");

const workflow_payload = {
    "workflow": "_workflow_slug_",
    "actor": {
      "distinct_id": "0fxxx8f74-xxxx-41c5-8752-xxxcb6911fb08",
      "name":"actor_1"
    },
    "recipients": [
      {
        "distinct_id": "0gxxx9f14-xxxx-23c5-1902-xxxcb6912ab09",
        "$email":["[email protected]"],
        "name":"recipient_1"
      }
    ],
    "data":{
      "first_name": "User",
      "invoice_amount": "$5000",
      "invoice_id":"Invoice-1234"
    }
}

// create workflow instance
const wf = new WorkflowTriggerRequest(workflow_payload, {tenant_id: "tenant_id1", idempotency_key: "_unique_request_identifier"})

const response = supr_client.workflows.trigger(wf); // trigger workflow 
response.then(res => console.log("response", res));
PropertyTypeDescription
workflowstringSlug of designed workflow on SuprSend dashboard. You'll get the slug from workflow settings.
recipientsarray of string / array of objectsList of users who need to be notified. You can add upto 100 recipients in a workflow trigger. You can either pass recipients as an array of distinct_ID (if user is pre-synced in SuprSend database) or define recipient information inline.
actor (Optional)string / objectIncludes distinct_id and properties of the user who performed the action. You can use it for cross-user notifications where you need to include actor properties in notification template. Actor properties can be added as $actor.<prop>.
dataobjectvariable data required to render dynamic template content or workflow properties such as dynamic delay or channel override in send node.
tenant_id (Optional)stringtrigger workflow for specific tenant/brand.
idempotency_key (Optional)stringunique identifier of the request. We'll be returning idempotency_key in our outbound webhook response. You can use it to map notification statuses and replies in your system.

Response

Once your request is accepted, you can check the status of your request in the SuprSend Logs.

{
  success: true,
  status: 'success',
  status_code: 202,
  message: '{"status":"success"}'
}

Sending notification to multiple users

Recipients in workflow call is an array of distinct_ids or recipient objects. You can pass upto 100 recipients in a single workflow trigger. SuprSend will internally convert it into multiple workflow triggers, one for each recipient in the array.

"recipients": ["distinct_id1","distinct_id2"]

---- OR ------

"recipients": [
  {
    "distinct_id": "id1",
    "$email":["[email protected]"],
    "name":"recipient_1"
  },
  {
    "distinct_id": "id1",
    "$email":["[email protected]"],
    "name":"recipient_2"
  }
]

📘

Use lists to broadcast to a large list of users

We recommend you to use lists and broadcast to send notifications to a user list larger than 1000 users. This approach allows bulk processing, resulting in significantly faster delivery compared to individual workflow calls. Sending individual workflows to a large set of users may introduce delays in your notification queue.


Identifying recipients inline

One of the benefits of using direct workflow trigger is that you can identify recipients inline. You can include recipient channel information, their channel preferences, and their user properties along with the workflow trigger. Upon triggering the workflow, the recipient will be automatically created in the SuprSend database in the background. This facilitates dynamic synchronization of your user data within SuprSend and eliminates the need for any migration efforts on your end to start sending notifications from SuprSend. You can also use recipient properties in your template as $recipient.<property>.

This is how the complete recipient object with look like

"recipients": [{
  "distinct_id": "0gxxx9f14-xxxx-23c5-1902-xxxcb6912ab09",
  "$email":["[email protected]"], // email communication channel
  "$sms":["+15555555555"], // sms communication channel
  "$channels":["email","inbox"],
  "$preferred_language":"en",
  "custom_prop1":"value_1", // custom property
  "custom_prop2": "value_2", // custom property
}]
PropertyTypeDescription
distinct_idstringUnique identifier of the user to be notified.
communication channels ($email, $sms etc).array of string / objectsThe communication channels info provided will be updated to user profile in the background. For this workflow, only channel values specified for this recipient will be used for sending notification instead of all channel values present in User profile.
$channelsarray of stringBy default, notifications will be sent to all channels defined in the workflow delivery nodes. However, if you have a scenario where user has specific channel preference for a notification (e.g., they only want to receive payment reminders via email), you can include that preference in the workflow payload. This will ensure that notifications are sent only to the channels specified in the this. Supported channel: email, sms, whatsapp, androidpush, iospush, slack, webpush, ms_teams.

You can always use our in-build preference APIs to maintain user notification preferences. Preferences defined within SuprSend will automatically apply with workflow trigger.
$preferred_languagestringIf you want to send notification in user's preferred language, you can set it by passing language code in this method.
*objectYou can pass other user properties to render dynamic template content. These properties will also be set in user profile and can be used in the template as $recipient.<property>.

Communication Channels of recipient

"$email":["[email protected]"],

"$whatsapp":["+15555555555"],

"$sms":["+15555555555"],

"$androidpush": [{"token": "__android_push_token__", "provider": "fcm", "device_id": ""}],

"$iospush":[{"token": "__ios_push_token__", "provider": "apns", "device_id": ""}],

// slack using email
"$slack": [{
  "email": "[email protected]",
  "access_token": "xoxb-XXXXXXXX"
}]  

// slack using member_id
"$slack": [{
  "user_id": "U/WXXXXXXXX",
  "access_token": "xoxb-XXXXXX"
}] 

// slack channel
"$slack": [{
  "channel": "CXXXXXXXX",
  "access_token": "xoxb-XXXXXX"
}]

// slack incoming webhook
"$slack": [{
  "incoming_webhook": {
    "url": "https://hooks.slack.com/services/TXXXXXXXXX/BXXXXXXXX/XXXXXXXXXXXXXXXXXXX"
  }
}]

// MS teams user or channel using conversation_id
"$ms_teams": [{
  "tenant_id": "c1981ab2-9aaf-xxxx-xxxx",
  "service_url": "https://smba.trafficmanager.net/amer",
  "conversation_id": "19:c1524d7c-a06f-456f-8abe-xxxx"
}] 

// MS teams user using user_id
"$ms_teams": [{
  "tenant_id": "c1981ab2-9aaf-xxxx-xxxx",
  "service_url": "https://smba.trafficmanager.net/amer",
  "user_id": "29:1nsLcmJ2RKtYH6Cxxxx-xxxx"
}]

// MS teams incoming webhook
"$ms_teams": [{
  "incoming_webhook": {
    "url": "https://wnk1z.webhook.office.com/webhookb2/XXXXXXXXX"
  }
}] 

Sending cross-user notifications

In scenarios where you need to notify a group of users based on another user's action, such as sending a notification to the document owner when someone comments on it, you can specify the actor in your workflow call. This allows you to use actor's name or other properties in your notification template. Actor properties can be included in the template as $actor.<property>.

//handlebar template
Hi {{$recipient.name}}, {{$actor.name}} added {{length comments}} new comments on the {{doc_name}}.

// rendered content with Sample Data
Hi recipient_1, actor_1 added 2 new comments on the annual IT report.
{
  "workflow": "new_comment",
  "actor": {
    "distinct_id": "0fxxx8f74-xxxx-41c5-8752-xxxcb6911fb08",
    "name":"actor_1"
  },
  "recipients": [
    {
      "distinct_id": "0gxxx9f14-xxxx-23c5-1902-xxxcb6912ab09",
      "$email":["[email protected]"],
      "name":"recipient_1"
    }
  ],
  "data":{
    "doc_name": "annual IT report",
    "date": "2024-01-01",
    "comments":["change the date","rest looks good"]
  }
}

Sending notification to anonymous user

You can send notifications to anonymous users by passing "is_transient": true in your recipient object. This approach is recommended for scenarios where you need to send notifications to unregistered users without creating them in the SuprSend platform. The same way, you can pass "is_transient": true in your actor object to use actor properties in template without creating user profile.

const workflow_payload = {
    "workflow": "_workflow_slug_",
    "actor": {
      "is_transient": true, // for anonymous actor
      "name":"actor_1"
    },
    "recipients": [
      {
        "is_transient": true, // for anonymous recipient
        "$email":["[email protected]"],
        "name":"recipient_1"
      }
    ],
    "data":{
      "first_name": "User",
      "invoice_amount": "$5000",
      "invoice_id":"Invoice-1234"
    }
}

Multi-tenant notifications

For cases where you want to send notifications to your enterprise customers end users, pass the tenant_id in your workflow instance. You can use this to dynamically manage tenant level notification customizations. This includes the ability to customize template design or content and route notifications via tenant vendors.

const workflow = new WorkflowTriggerRequest(workflow_body, {tenant_id: "tenant_id1"})

Idempotent requests

SuprSend supports idempotency to ensure that requests can be retried safely without duplicate processing. If Suprsend receives and processes a request with an idempotency_key, it will skip processing requests with same idempotency_key for next 24 hours. Idempotency key should be uniquely generated for each request (max 255 characters allowed). Spaces in start and end of the key will be trimmed. Here are some common approaches for generating idempotency keys:

  • Generate a random UUID for each request.
  • Construct the idempotency key by combining relevant information about the request. This can include parameters, identifiers, or specific contextual details that are meaningful within your application. For example, you could concatenate the user ID, action, and timestamp to form an idempotency key like user147-new-comment-1687437670
  • Request-specific Identifier: If your request already contains a unique identifier, such as an order ID or a job ID, you can use that identifier directly as the idempotency key.
const workflow = new WorkflowTriggerRequest(workflow_body, {idempotency_key: "_unique_request_identifier"})

Bulk API for triggering multiple workflows

Bulk API allows you to send multiple workflow requests in a single call. Use .append() and workflows.bulk_trigger_instance() to add however-many-records to call in bulk.

const {Suprsend, WorkflowTriggerRequest} = require("@suprsend/node-sdk");

const supr_client = new Suprsend("_workspace_key_", "_workspace_secret_");

const wf1 = new WorkflowTriggerRequest(wf_body1, {tenant_id: "tenant_id1", idempotency_key: "_unique_identifier_of_the_request_"}) // workflow1 instance
const wf2 = new WorkflowTriggerRequest(body2)  // workflow2 instance

const bulk_ins = supr_client.workflows.bulk_trigger_instance() // create bulk instance

bulk_ins.append(wf1,wf2)  // add workflows instances to bulk instance

const response = bulk_ins.trigger(); // trigger workflows 
response.then(res => console.log("response", res));

Response

{
  status: "success/fail/partial",
  total: 10,
  success: 10,
  failure: 0,
  failed_records: [{"record": {...}, "error": "error_str", "code": "<status_code>"}],
  warnings: []
}

Add attachment (in email)

To add one or more attachments to a notification (viz. Email), call wf_instance.add_attachment() for each file with local path or remote attachment url. Ensure that file path is valid, and public(for remote url) otherwise it will raise error.

const wf_instance = new WorkflowTriggerRequest(wf_body);

wf_instance.add_attachment("/home/user/billing.pdf");
wf_instance.add_attachment("https://www.adobe.com/sample_file.pdf");

🚧

A single workflow instance size (including attachment) must not exceed 100KB (100 x 1024 bytes).


Dynamic workflow trigger

You can trigger workflow from node SDK by using supr_client.trigger_workflow method. Import Workflow class before calling this method

const { Workflow } = require("@suprsend/node-sdk")

// Prepare Workflow body
const workflow_body = {
  "name": "workflow_name",
  "template": "template_slug",
  "notification_category": "notification_category", //notification category transactional/promotional/system
  "delay": "time_delay",  // time delay after which the first notification will be sent
  "trigger_at": "date string in ISO 8601", // to trigger scheduled notifications

  "users": [
    {
      "distinct_id": "distinct_id", // unique identifier of the user
      // if $channels is present, communication will be triggered on mentioned channels only.
      // "$channels": ["email"],

      // User communication channel can be added as [optional]:
      // "$email":["[email protected]"],
      // "$whatsapp":["+15555555555"],
      // "$sms":["+15555555555"],
      // "$androidpush": [{"token": "__android_push_token__", "provider": "fcm", "device_id": ""}],  
      // "$iospush":[{"token": "__ios_push_token__", "provider": "apns", "device_id": ""}],
      // "$slack": {
      //"email": "[email protected]",
      //"access_token": "xoxb-XXXXXXXX"
      //}   --- slack using email

      // "$slack": {
      // "user_id": "U/WXXXXXXXX",
      // "access_token": "xoxb-XXXXXX"
      //} --- slack using member_id

      //"$slack": {
      //"channel": "CXXXXXXXX",
      //"access_token": "xoxb-XXXXXX"
      //} --- slack channel

      //"$slack": {
      //"incoming_webhook": {
      //"url": "https://hooks.slack.com/services/TXXXXXXXXX/BXXXXXXXX/XXXXXXXXXXXXXXXXXXX"
      //}
      //} --- slack incoming webhook

      // "$ms_teams": {
      //"tenant_id": "c1981ab2-9aaf-xxxx-xxxx",
      //"service_url": "https://smba.trafficmanager.net/amer",
      //"conversation_id": "19:c1524d7c-a06f-456f-8abe-xxxx"
      //} --- MS teams user or channel using conversation_id

      // "$ms_teams": {
      //"tenant_id": "c1981ab2-9aaf-xxxx-xxxx",
      //"service_url": "https://smba.trafficmanager.net/amer",
      //"user_id": "29:1nsLcmJ2RKtYH6Cxxxx-xxxx"
      //} --- MS teams user using user_id

      // "$ms_teams": {
      //  "incoming_webhook": {
      //  "url": "https://wnk1z.webhook.office.com/webhookb2/XXXXXXXXX"
      // }
      //} --- MS teams incoming webhook

    }
  ],

  // delivery instruction [optional]. how should notifications be sent, and whats the success metric
  "delivery": {
    "smart": <boolean_value>,
    "success": "success_metric",
    "time_to_live": "TTL duration", // will be applicable for smart = TRUE
    "mandatory_channels": [] // list of mandatory channels e.g ["email"], will be applicable for smart = TRUE
},
      // data can be any json
      "data": {
        "key":"value",
          "nested_key": {
            "nested_key1": "some_value_1",
              "nested_key2": {
                "nested_key3": "some_value_3",
              },
          }
      }
} 

const wf = new Workflow(workflow_body, {brand_id="default", idempotency_key="__uniq_request_id__"})
// Trigger workflow
const response = supr_client.trigger_workflow(wf); // returns promise
response.then((res) => console.log("response", res));


For configuring a workflow from backend, you can pass following properties in your method

ParameterDescriptionFormatObligation
nameIt is the unique name of the workflow. You can see workflow-related analytics on the workflow page (how many notifications were sent, delivered, clicked or interacted). The workflow name should be easily identifiable for your reference at a later stagetextMandatory
templateIt is the unique slug name of the template created on SuprSend platform. You can get this slug name by clicking on the clipboard icon next to the Template name on SuprSend templates page.
It is the same for all channels
slug nameMandatory
notification_categoryYou can understand more about them in the Notification Category documentationsystem / transactional / promotionalMandatory
delayWorkflow will be halted for the time mentioned in delay, and become active once the delay period is over.XXdXXhXXmXXs or if its number (n) then delay is in seconds (n)Optional
trigger_atTrigger workflow on a specific date-timedate string in ISO 8601
eg. "2021-08-27T20:14:51.643Z"
Optional
usersArray object of target users.

Atleast 1 user mandatory.

distinct_id for each user mandatory

Channel information is non-mandatory (If you have already sent channel information via backend or Frontend SDK (on app or website))

Notification will be sent to only the channels defined in workflow if channel information is added
"users":
[
{
"distinct_id": "value",
"$channels": [],
channel_information_dict #(optional)
],
Mandatory
deliverydelivery instructions for the workflow. You can set Smart Delivery preference by setting "smart":true

By default, delivery instruction will be "delivery": {
"smart": false,
"success": "seen"
}
delivery: {
"smart": True/False,
"success": "delivered/seen/interaction/",
"time_to_live": "",
"mandatory_channels": [] # list of mandatory channels e.g gation",

}
Optional
dataJSON.
To replace the variables in the template. Templates use handlebarsjs(doc:hadlebarsjs-guide) language
"data":
{ "key": {
"key": "value",
"key": "value"
}
},
Optional
brand_idBrand_id of the tenant to trigger notification on behalf of your tenantsstringOptional
idempotency_keyunique key in the request call for idempotent requestsstringOptional

👍

+CountryCode Required for SMS and Whatsapp

For setting $sms and $whatsapp, +<countrycode> is mandatory to send along with phone number. Eg: +1 for US


2878

To find the template slug name on SuprSend platform, click on the clipboard icon on Templates page.
Templates > Template Details Page




Response structure

// Response structure
{
    "success": true, // if true, request was accepted.
    "status": "success",
    "status_code": 202,  // http status code
    "message": "Accepted",
}

{
    "success": false, // error will be present in message
    "status": "fail",
    "status": 400, // http status code
    "message": "error message",
}

Once your request is accepted, you can check the status of your request in the ' SuprSend Logs' section.


Bulk API for triggering multiple workflows.

Bulk API allows you to send multiple workflow requests in a single call. There isn't any limit on number-of-records that can be added to bulk_workflows instance. Use .append() on bulk_workflows instance to add however-many-records to call in bulk.

const { Workflow } = require("@suprsend/node-sdk")

const bulk_ins = supr_client.bulk_workflows.new_instance()

// one or more workflow instances
const workflow1 = new Workflow({...}) // body must be a proper workflow request json/dict
const workflow2 = new Workflow({...}) // body must be a proper workflow request json/dict

// --- use .append on bulk instance to add one or more records
bulk_ins.append(workflow1)
bulk_ins.append(workflow2)
// OR
bulk_ins.append(workflow1, workflow2)

// -------
const response = bulk_ins.trigger()
response.then((res) => console.log("response", res));


Response

// Response structure
{
  status: "success",
  total: 10, // number of records sent in bulk
  success: 10, // number of records succeeded
  failure: 0, // number of records failed
  failed_records: [],
  warnings: []
}

{
  status: "fail",
  total: 10, // number of records sent in bulk
  success: 0, // number of records succeeded
  failure: 10, // number of records failed
  failed_records: [{"record": {...}, "error": "error_str", "code": 500}],
  warnings: []
}

{
  status: "partial",
  total: 10, // number of records sent in bulk
  success: 6, // number of records succeeded
  failure: 4, // number of records failed
  failed_records: [{"record": {...}, "error": "error_str", "code": 500}],
  warnings: []
}