Manage Subscriptions and Surveys With User Actions

On this page

In this tutorial, you build the User Actions for a paid news site called PiedPiper. A temporal Subscribe Action gives a reader one month of access, sends a welcome email, and notifies a mock Intercom. When the subscription ends, FusionAuth sends a goodbye email and notifies PiedPiper, and PiedPiper applies a Ban Action to stop the reader from logging in. An instantaneous Survey Action records the reader's feedback and notifies a mock Slack.

For the terms and the types of Actions, see User Actions.

The following diagram shows the flow you build:

SlackIntercomFusionAuthPiedPiperUser AgentSlackIntercomFusionAuthPiedPiperUser AgentLaterPay for a one-month subscriptionApply subscription ActionSend welcome emailSend subscription notificationSubscription expiresSend goodbye emailSend expiry notificationApply prevent login ActionComplete customer survey formApply survey ActionSend survey notificationRetrieve all Actions for the User
SlackIntercomFusionAuthPiedPiperUser AgentSlackIntercomFusionAuthPiedPiperUser AgentLaterPay for a one-month subscriptionApply subscription ActionSend welcome emailSend subscription notificationSubscription expiresSend goodbye emailSend expiry notificationApply prevent login ActionComplete customer survey formApply survey ActionSend survey notificationRetrieve all Actions for the User

PiedPiper applies subscription and survey Actions, and FusionAuth sends emails and webhooks to Intercom and Slack.

Prerequisites#

  • Node.js.
  • curl.
  • FusionAuth running on your computer, with the Admin UI at http://localhost:9011/admin. For instructions, see Install Locally. The online FusionAuth sandbox doesn't work for this tutorial, because FusionAuth must reach mock services on your computer.

Set Up Email#

FusionAuth sends the tutorial's emails to MailDev, a mock SMTP server.

  1. In a new terminal, start MailDev, and leave the terminal open until you finish the tutorial:

    $ npm install maildev && npx maildev -v
    
  2. Browse to http://localhost:1080/ to watch emails arrive.

  3. When FusionAuth runs in Docker, let FusionAuth reach services on your computer. Docker 18 or later on macOS and Windows, and Docker 20 or later on Linux, support host.docker.internal. In the FusionAuth docker-compose.yml file, add the following to the fusionauth service, at the same level as volumes:

    extra_hosts:
      - "host.docker.internal:host-gateway"
    

    Then restart FusionAuth. The restart can reset your FusionAuth database:

    $ docker compose down && docker compose up
    
  4. In the Admin UI, go to Tenants and edit the Default Tenant with .

  5. On the Email tab, set Port to 1025. Set Host to host.docker.internal when FusionAuth runs in Docker, or to localhost otherwise.

    The tenant Email tab with the SMTP host and port highlighted.
    The tenant Email tab with the SMTP host and port highlighted.
  6. Click Send test email , and confirm that the email arrives in MailDev:

    The test email in the MailDev inbox.
    The test email in the MailDev inbox.
  7. Save the Tenant with .

Create the Application, Users, and API Key#

The tutorial sets fixed Ids, because later commands use the Ids. Outside a tutorial, you can leave Ids blank and let FusionAuth generate them.

  1. Go to Applications and add an Application with . Set Id to e9fdb985-9173-4e01-9d73-ac2d60d1dc8e and Name to PiedPiper.

  2. On the Roles tab, add the following Roles with Add Roles :

    • Name admin, with Super Role turned on.
    • Name customer.
    The Add Application form with the admin and customer roles.
    The Add Application form with the admin and customer roles.
  3. On the OAuth tab, set Authorized redirect URLs to http://localhost:3000/oauth-redirect and Logout URL to http://localhost:3000/logout. To add a redirect URL, type the URL, then click the popup that appears. Record the Client secret.

    The Add Application OAuth tab with the client secret, redirect URL and logout URL highlighted.
    The Add Application OAuth tab with the client secret, redirect URL and logout URL highlighted.
  4. Save the Application with .

  5. Go to Users and add the administrator, who applies Actions, with . Set Email to admin@example.com, turn off Send email to set up password, and set the password to password. Set Languages to Esperanto: type the language, then click the popup that appears. The administrator plays the support agent in the survey, and the language decides how the survey event shows the Option. Save the user.

  6. On the administrator's Registrations tab, add the following Registrations with Add registration :

    • Application PiedPiper, with the admin Role.
    • Application FusionAuth, with the GlobalAdmin Role.
    An administrator registered to the Pied Piper and FusionAuth applications.
    An administrator registered to the Pied Piper and FusionAuth applications.
  7. Add the subscriber, who receives Actions. Set Email to reader@example.com, turn off Send email to set up password, and set the password to password. Set Languages to Esperanto, and save the user.

  8. On the subscriber's Registrations tab, add a Registration for PiedPiper with the customer Role.

    A user registered to the Pied Piper application.
    A user registered to the Pied Piper application.
  9. Record the User Id of both users.

  10. Go to Settings -> API Keys and add an API key with . Set Id to cbf34b5f-cb45-4c97-9b7c-5fda3ad8f08c and Key to FTQkSoanK7ObbNjOoU69WDVclfTx8L_zfEJbdR8M0xu-jKotV0iQZiQh. Leave every endpoint toggle off, which gives the key access to every API, and save the key.

    The Add API Key form with an Id and key entered.
    The Add API Key form with an Id and key entered.
Caution

The tutorial's API key can call every API. In production, give each key only the endpoints that the key needs. For more information, see Managing API Keys.

Create the Subscription Actions#

The subscription needs email templates, Reasons, webhooks, and Actions. Reasons are optional. Reasons help when one Action has several causes, such as a free trial, a competition prize, or a payment.

  1. Go to Customizations -> Email Templates and add an email template with . Set the following fields, then save the template:

    • Id: ae080fe4-5650-484f-807b-c692e218353d
    • Name and Default Subject: Welcome
    • Default HTML on the HTML Template tab, and Default Text on the Text Template tab: Welcome to PiedPiper. Your subscription is valid for one month of reading.
    The Add Email Template form for the Welcome template.
    The Add Email Template form for the Welcome template.
  2. Add a second email template:

    • Id: 1671beff-78ed-420d-9e13-46b4d7d5c00d
    • Name and Default Subject: Goodbye
    • Default HTML and Default Text: Your subscription has expired and you may no longer read the news. Goodbye.

    The templates in this tutorial use fixed text. Real templates usually use variables, such as the user's name. For more information, see Email Templates.

  3. Go to Settings -> User Actions and click Reasons :

    The User Actions page with the Reasons button highlighted.
    The User Actions page with the Reasons button highlighted.
  4. Add the following Reasons with , and save each one:

    • Id ae080fe4-5650-484f-807b-c692e218353d, Text Paid Subscription, and Code PS.
    • Id 28b0dd40-3a65-48ae-8eb3-4d63d253180a, Text Expired Subscription, and Code ES.
    The Reasons page with the two subscription reasons.
    The Reasons page with the two subscription reasons.
  5. Go to Settings -> Webhooks and add the webhook that notifies Intercom about new subscribers. Set Id to 55934340-3c92-410a-b361-40fb324ed412 and URL to http://host.docker.internal:3000/intercom, make sure that the user.action event is on, and save the webhook. Use localhost instead of host.docker.internal when FusionAuth doesn't run in Docker.

    The Add Webhook form for the Intercom webhook.
    The Add Webhook form for the Intercom webhook.
  6. Add the webhook that notifies PiedPiper when a subscription ends. Set Id to fa76b458-e0a0-438a-a5c8-26ca487e473e and URL to http://host.docker.internal:3000/expire, make sure that the user.action event is on, and save the webhook.

  7. Go to Tenants , edit the Default Tenant, and open the Webhooks tab. The tab lists both webhooks as enabled. Turn on the user.action event, and save the Tenant. For more information about webhook settings, see Events and Webhooks.

  8. Go to Settings -> User Actions and add the subscription Action with :

    • Id: 38bf18dd-6cbc-453d-a438-ddafe0daa1b0
    • Name: Subscribe
    • Make action time-based: on
    • On the Email tab, turn on Email user when action is taken. Set Start template to Welcome, and set Modify template, Cancel template, and End template to Goodbye.

    The tutorial never modifies or cancels a subscription, so FusionAuth never sends the modify and cancel emails. The Admin UI still requires a template for every state when Email user when action is taken is on. Save the Action.

    The Add User Action form for the Subscribe action.
    The Add User Action form for the Subscribe action.
  9. Add the Action that stops a reader from logging in after the subscription ends. Set Id to b96a0548-e87c-42dd-887c-31294ca10c8b and Name to Ban, turn on Make action time-based and Prevent login during action, and save the Action. The Ban Action sends no email and no webhook.

You can also create these objects with the API or a client library. For an example, see Using User Actions on the FusionAuth blog.

Create the Survey Action#

The survey uses an instantaneous Action with an Option for each answer. Each Option has an Esperanto translation, so support agents who read Esperanto see feedback in their language.

  1. Add an email template that thanks the reader for the survey:

    • Id: 9006bb3c-b13b-4238-b858-d7a97e054a8d
    • Name and Default Subject: Thanks
    • Default HTML and Default Text: Thank you for your survey feedback. It helps us improve. If your experience was negative we'll contact you shortly.
  2. Add a webhook for the mock Slack. Set Id to d86e097a-f23f-459b-80c5-8b47bae182ee and URL to http://host.docker.internal:3000/slack, make sure that the user.action event is on, and save the webhook.

  3. Go to Settings -> User Actions and add an Action. Set Id to 8e6d80df-74bb-4cb8-9caa-c9a2dafc6e57 and Name to Survey, and leave Make action time-based, Notify users when action is taken, and the Email tab settings off.

  4. On the Options tab, add the following Options with Add option . For each Option, click Add localization , set Locale to Esperanto and Text to the translation, and click Submit :

    Name Esperanto
    Good Bona
    Neutral Meza
    Bad Malbona
  5. Save the Action:

    The Survey user action with its three options.
    The Survey user action with its three options.

Run the Example App#

The example app plays PiedPiper, Intercom, and Slack.

  1. Clone the example app and install the dependencies:

    $ git clone https://github.com/FusionAuth/fusionauth-example-user-actions-guide.git
    $ cd fusionauth-example-user-actions-guide
    $ npm install
    
  2. Copy .env.sample to .env.

  3. In .env, set CLIENT_ID to e9fdb985-9173-4e01-9d73-ac2d60d1dc8e, and set CLIENT_SECRET to the client secret you recorded.

  4. In .env, set API_KEY to FTQkSoanK7ObbNjOoU69WDVclfTx8L_zfEJbdR8M0xu-jKotV0iQZiQh.

  5. Start the app:

    $ npm run start
    

You don't need to change the code. The app calls the FusionAuth API with the TypeScript client library, configured from the API_KEY and BASE_URL environment variables:

const client = require('@fusionauth/typescript-client');
const apikey = process.env.API_KEY;
const fusionAuthURL = process.env.BASE_URL;

The /intercom route stands in for Intercom, which starts onboarding for new subscribers. The route prints each webhook to the console:

app.post('/intercom', function(req, res) {
  console.log('Incoming Request to Intercom:');
  console.log(req.body);
  console.log('');
  res.sendStatus(200);
});

The /slack route stands in for Slack in the same way. Administrators who watch Slack can contact a reader right away when the survey answer is Bad:

app.post('/slack', function(req, res) {
  console.log('Incoming Request to Slack:');
  console.log(req.body);
  console.log('');
  res.sendStatus(200);
});

FusionAuth calls the /expire route when a subscription ends. The route applies the Ban Action, which prevents login:

app.post('/expire', async function(req, res) {
  console.log('Incoming Request to PiedPiper Expiry:');
  console.log(req.body);
  console.log('');
  if (req.body.event.action === 'Subscribe' && req.body.event.phase === 'end') {
    try {
      const request = {
        action: {
          actioneeUserId: req.body.event.actioneeUserId,
          actionerUserId: req.body.event.actionerUserId,
          applicationIds: ['e9fdb985-9173-4e01-9d73-ac2d60d1dc8e'],
          emailUser: false,
          expiry: 8223372036854775806, // the end of time
          notifyUser: false,
          reasonId: '28b0dd40-3a65-48ae-8eb3-4d63d253180a', // subscription expired reason
          userActionId: 'b96a0548-e87c-42dd-887c-31294ca10c8b' //ban action
        },
        broadcast: false
      };
      const fusion = new client.FusionAuthClient(apikey, fusionAuthURL);
      const clientResponse = await fusion.actionUser(request);
      if (!clientResponse.wasSuccessful)
        throw Error(clientResponse);
      console.info('User banned successfully');
    }
    catch (e) {
      console.error('Error handling expiry: ');
      console.dir(e, { depth: null });
    }
  }
  res.sendStatus(200);
});

Test the Subscription#

  1. Apply the subscription Action from a new terminal. Your app would apply the Action after the reader pays. Replace actioneeUserId with the subscriber's Id and actionerUserId with the administrator's Id. To see the subscription end quickly, set expiry to one minute from now. The expiry is a moment in time in milliseconds, not a duration.

    On Linux or macOS, the shell computes the expiry:

    $ curl -i --location --request POST 'http://localhost:9011/api/user/action' \
      --header 'Authorization: FTQkSoanK7ObbNjOoU69WDVclfTx8L_zfEJbdR8M0xu-jKotV0iQZiQh' \
      --header 'Content-Type: application/json' \
      --data-raw '{
        "broadcast": true,
        "action": {
          "actioneeUserId": "9af67e9a-8332-4c06-971c-463b6710c340",
          "actionerUserId": "ac2f073d-c063-4a7b-ab76-812f44ed7f55",
          "comment": "Paid for the news",
          "emailUser": true,
          "expiry": '"$(($(date +%s) * 1000 + 60000))"',
          "userActionId": "38bf18dd-6cbc-453d-a438-ddafe0daa1b0",
          "reasonId": "ae080fe4-5650-484f-807b-c692e218353d"
        }
      }'
    

    Copy the Milliseconds value from the FusionAuth Date-Time tool, add 60000, and use the result as expiry:

    $ curl -i --location --request POST 'http://localhost:9011/api/user/action' \
      --header 'Authorization: FTQkSoanK7ObbNjOoU69WDVclfTx8L_zfEJbdR8M0xu-jKotV0iQZiQh' \
      --header 'Content-Type: application/json' \
      --data-raw '{
        "broadcast": true,
        "action": {
          "actioneeUserId": "9af67e9a-8332-4c06-971c-463b6710c340",
          "actionerUserId": "ac2f073d-c063-4a7b-ab76-812f44ed7f55",
          "comment": "Paid for the news",
          "emailUser": true,
          "expiry": 1690288205000,
          "userActionId": "38bf18dd-6cbc-453d-a438-ddafe0daa1b0",
          "reasonId": "ae080fe4-5650-484f-807b-c692e218353d"
        }
      }'
    

    FusionAuth returns a 200 status code and the Action instance:

    Example JSON Response
    {
      "action": {
        "actioneeUserId": "223515c6-6be5-4027-ac4f-4ebdcded2af9",
        "actionerUserId": "a1b4962f-0480-437c-9bb1-856fa2acabed",
        "applicationIds": [],
        "comment": "Paid for the news",
        "emailUserOnEnd": true,
        "endEventSent": false,
        "expiry": 1690204666927,
        "id": "ad07e697-1583-4c2e-922e-8038945b3c09",
        "insertInstant": 1690204662349,
        "localizedName": "Subscribe",
        "name": "Subscribe",
        "notifyUserOnEnd": false,
        "userActionId": "38bf18dd-6cbc-453d-a438-ddafe0daa1b0",
        "reason": "Paid Subscription",
        "localizedReason": "Paid Subscription",
        "reasonCode": "PS"
      }
    }
    
  2. In the terminal that runs PiedPiper, read the webhooks. Every Action calls every webhook that listens for user.action, so each route receives the event and must check action, reasonCode, and phase. The start of the subscription sends the following event:

    Example Webhook Event
    event: {
        action: 'Subscribe',
        actionId: '32754f74-d92c-4829-ab8b-704825baf1ef',
        actioneeUserId: '9af67e9a-8332-4c06-971c-463b6710c340',
        actionerUserId: 'ac2f073d-c063-4a7b-ab76-812f44ed7f55',
        applicationIds: [],
        comment: 'Paid for the news',
        createInstant: 1690282558415,
        emailedUser: true,
        expiry: 1690282574000,
        id: '5dba9944-ce71-4ce0-b18f-c44723e7394b',
        info: { ipAddress: '172.28.0.1' },
        localizedAction: 'Subscribe',
        localizedDuration: '15 seconds',
        notifyUser: false,
        phase: 'start',
        tenantId: '8891ecad-ae5c-3d5d-1f4e-3e95f8583b78',
        type: 'user.action'
      }
    
  3. After one minute, confirm that PiedPiper received both the start event and the end event.

  4. In MailDev, confirm that the welcome and goodbye emails arrived. When the emails are missing, check that the Tenant email settings use port 1025 and the right host.

    The welcome and goodbye emails in the MailDev inbox.
    The welcome and goodbye emails in the MailDev inbox.
  5. In the PiedPiper terminal, look for User banned successfully. The message means that the /expire route received the end event, matched req.body.event.action === 'Subscribe' && req.body.event.phase === 'end', and applied the Ban Action.

  6. Log in to http://localhost:3000 as reader@example.com. FusionAuth refuses the login:

    The login page showing that the account is locked.
    The login page showing that the account is locked.

To delete an Action instance while you experiment, send the instance Id from the response:

$ curl -i --location --request DELETE 'http://localhost:9011/api/user/action/3cc31d87-25b9-4528-970a-2b177508afe1' \
  --header 'Authorization: FTQkSoanK7ObbNjOoU69WDVclfTx8L_zfEJbdR8M0xu-jKotV0iQZiQh' \
  --header 'Content-Type: application/json' \
  --data-raw '{"action": {"actionerUserId": "ac2f073d-c063-4a7b-ab76-812f44ed7f55"}}'

Test the Survey#

In the survey, the reader rates a support agent, so the reader is the Actioner and the agent is the Actionee. The survey Action is instantaneous, so the request has no expiry.

  1. Apply the survey Action. Replace actioneeUserId with the administrator's Id and actionerUserId with the subscriber's Id:

    $ curl -i --location --request POST 'http://localhost:9011/api/user/action' \
      --header 'Authorization: FTQkSoanK7ObbNjOoU69WDVclfTx8L_zfEJbdR8M0xu-jKotV0iQZiQh' \
      --header 'Content-Type: application/json' \
      --data-raw '{
        "broadcast": true,
        "action": {
          "actioneeUserId": "ac2f073d-c063-4a7b-ab76-812f44ed7f55",
          "actionerUserId": "9af67e9a-8332-4c06-971c-463b6710c340",
          "applicationIds": ["e9fdb985-9173-4e01-9d73-ac2d60d1dc8e"],
          "comment": "Could not find my horoscope in the newspaper :( Agent did not help me.",
          "emailUser": false,
          "userActionId": "8e6d80df-74bb-4cb8-9caa-c9a2dafc6e57",
          "option": "Bad"
        }
      }'
    

    The option field holds the Option name, Bad, as a string. To keep code working when you rename Options, see Name Options for Code.

  2. In the PiedPiper terminal, find the event that the mock Slack received:

    Example Webhook Event
    {
      event: {
        action: 'Survey',
        actionId: 'ef9e753f-ecc0-468b-8160-dcb25dbb4d91',
        actioneeUserId: 'ac2f073d-c063-4a7b-ab76-812f44ed7f55',
        actionerUserId: '9af67e9a-8332-4c06-971c-463b6710c340',
        applicationIds: [ 'e9fdb985-9173-4e01-9d73-ac2d60d1dc8e' ],
        comment: 'Could not find my horoscope in the newspaper :(',
        createInstant: 1690291936476,
        emailedUser: false,
        id: 'be3470aa-0dfd-408e-a286-6d3c16a9af1f',
        info: { ipAddress: '172.28.0.1' },
        localizedAction: 'Survey',
        localizedOption: 'Malbona',
        notifyUser: false,
        option: 'Bad',
        tenantId: '8891ecad-ae5c-3d5d-1f4e-3e95f8583b78',
        type: 'user.action'
      }
    }
    

    The event shows localizedOption in the preferred language of the Actionee. The Actionee is the administrator, whose language is Esperanto, so the event shows Malbona. For an Actionee without a matching localization, the event shows the Option name.

  3. Retrieve every Action instance for the subscriber to build an audit trail. Replace the Id with the subscriber's Id:

    $ curl -i --location --request GET 'http://localhost:9011/api/user/action?userId=9af67e9a-8332-4c06-971c-463b6710c340' \
      --header 'Authorization: FTQkSoanK7ObbNjOoU69WDVclfTx8L_zfEJbdR8M0xu-jKotV0iQZiQh'
    

    For the response fields, see Retrieve a Previously Taken Action.