Building a Robust Subscription System with Java Spring Boot and Conductor
Tags: subscription, springboot, java, orchestration
Published: 2023-06-01 06:04:08

When managing subscriptions, manually handling the renewal process is daunting for an organization. **What if you forget your renewal?** It can definitely impact your organization resulting in service disruptions and financial penalties.

You might have already heard of several instances where organizations forget their domain renewal, resulting in service outages that cost them millions.

Automating your subscription renewal process is the only way to overcome such scenarios. An orchestration engine like Orkes Conductor can be leveraged to automate your subscription workflows. Orkes Conductor is an app-building platform built over Netflix Conductor.

In this blog, let’s look at how to build a sample subscription application for managing monthly subscriptions using Conductor and Java Spring Boot 2.

## Monthly Subscription Workflow: Explained

Suppose the business logic for your monthly subscription workflow is as follows:

1. Trigger a subscription workflow that includes a trial period. The trial period consists of sending a welcome mail and a waiting period until the trial ends.
2. Once the trial ends, it starts the billing process that should recur every billing period.
3. At the end of the number of specified billing periods, the workflow ends and notifies the user.
4. The user should be able to cancel the subscription at any point during either the trial or billing period.
5. A way to notify the users before the trial starts, when billing commences, and when the subscription is completed/canceled.

Let’s visualize the workflow:

![Workflow handling monthly subscriptions](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z9jvohtrgfaejfeendv9.png)

[View in Playground](https://play.orkes.io/workflowDef/monthly_subscription_workflow_with_trial)

You need to provide the following input parameters while running the workflow.

- **userId**
- **userEmail**
- **billingAmount**
- **billingPeriod**

Let’s see how the workflow progress:

- The workflow begins with a [fork-join](https://orkes.io/content/reference-docs/operators/fork-join) task that lets you run a specified list of tasks in parallel.

In this example, we have two forks. The first fork handles the subscription flow, including the trial and actual subscription process. The second fork waits for a signal if the user is canceling. Either fork can complete and end the workflow.

- In the first fork, when a user subscribes, the trial period begins. An email is sent to the user regarding the trial commencement. This is implemented using a [worker task (SIMPLE task)](https://orkes.io/content/reference-docs/operators/worker-task), where you can configure the email subject, & email content. The email ID and username will be invoked from the workflow input.

```json
{
           "name": "send-subscription-demo-email",
           "taskReferenceName": "send_welcome_email",
           "inputParameters": {
             "emailSubject": "Welcome to the subscription!",
             "emailContent": "Some email content welcoming user to subscription",
             "userEmail": "${workflow.input.userEmail}",
             "userId": "${workflow.input.userId}"
           },
           "type": "SIMPLE",
},
```

- It is followed by a [wait](https://orkes.io/content/reference-docs/operators/wait) task that can be configured to wait as per your trial period. In this example, we have configured it to wait until 10 seconds.
- Once the wait period is over, the subscription begins, and an email regarding this is sent using the same task definition we defined above.
- Then the subscription begins and is looped until completion using the [do-while](https://orkes.io/content/reference-docs/operators/do-while) task.

### Now, what if the user cancels the subscription?

The second fork waits for the signal if the user cancels. To pass the signal, we have leveraged Webhook in this example. A [webhook](https://orkes.io/content/reference-docs/system-tasks/wait-for-webhook#creating-webhook) is configured with the following parameters:

![Webhook for invoking subscription workflow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g8wa76ed1223ltbgrwxv.png)

- Under the field **Workflows To Receive Webhook Event**, we have chosen the monthly subscription workflow.
- Conductor has out-of-box support for the majority of providers. Since we are using the cURL command to send signals to webhook, we have chosen the **Source Platform** as **Custom**.
- The webhook is configured to expect a header called “**subscriptionflow**” with the value “**subscription-flow-header-unique-value**”.
- On saving the webhook initially, the URL would be _Unverified_, and when the first event comes from the webhook with header values configured, the URL would be verified.

For this example, we have already created a [webhook](https://play.orkes.io/configure-webhook/ba70ba33-1a19-449e-98c2-d4581fcd9aad) in Playground.

In the **WAIT_FOR_WEBHOOK** task in the workflow definition, the input matches are defined as:

```json
"inputParameters": {
             "matches": {
               "$['event']['userId']": "${workflow.input.userId}"
             }
},
```
Hence the sample webhook invocation using cURL looks like this:

```shell
curl -H "Content-Type:application/json" -H "Accept:application/json"      -H 'subscriptionflow: subscription-flow-header-unique-value'         -X POST 'https://play.orkes.io/webhook/ba70ba33-1a19-449e-98c2-d4581fcd9aad'      -d '{"event": {"userId" : "user-id-1"}}'
```

It includes the headers keys and value (same as configured in the webhook), the webhook URL & the input parameter “userId”, which should be the same as the workflow input you’ve provided.

You can use the webhook we created in Playground to run this example. In case you are using another custom webhook, be sure to replace the webhook URL while invoking. Under [application.properties](https://github.com/conductor-sdk/orkes-java-springboot2-subscription-example/blob/main/src/main/resources/application.properties) in your spring boot project, too, you need to update the webhook URL.

## Running Spring Boot App

The code used to define this application is available on Github here: [https://github.com/conductor-sdk/orkes-java-springboot2-subscription-example](https://github.com/conductor-sdk/orkes-java-springboot2-subscription-example)

To run this app locally:

1. Clone the spring boot project locally on your system.
2. Replace the [application.properties](https://github.com/conductor-sdk/orkes-java-springboot2-subscription-example/blob/main/src/main/resources/application.properties) file with the access keys. Check out this guide on how to [generate access keys from Playground](https://orkes.io/content/how-to-videos/access-key-and-secret).

```json
orkes.access.key=your_key_id
orkes.access.secret=your_key_secret
orkes.conductor.server.url=https://play.orkes.io/api.
```

You also need to provide [permissions for the application to access the workflow and tasks](https://orkes.io/content/access-control-and-security/applications#adding-permissions).

**Note**: If you are running Conductor locally, replace orkes.conductor.server.url with your Conductor server URL.

Run your Spring Boot application from the root project folder using the following command:

```
mvn spring-boot:run
```
This application has a controller that is exposed in [SubscriptionApiController.java](https://github.com/conductor-sdk/orkes-java-springboot2-subscription-example/blob/main/src/main/java/io/orkes/example/subscription/controller/SubscriptionApiController.java) and has the following API methods:

1. **/startSubscription** : When invoked, it will trigger a workflow that handles subscriptions.
2. **/cancelSubscription** : When invoked, it will call a webhook API into Conductor to signal that the subscription has ended.

## Run Subscription Workflow in Playground

Now you’ve got an understanding of the subscription workflow. Since you have configured and run your Spring Boot app, let’s run the workflow now!

{% embed https://www.youtube.com/watch?v=c6ExCnzJo-U %}

1. From Playground, click [Run Workflow](https://play.orkes.io/runWorkflow) from the left menu.
2. Choose the workflow **monthly_subscription_workflow_with_trial**, provide the input parameters, and run the workflow.

```json
{
 "userId": "",
"userEmail": "",
"billingPeriods": "",
 "billingAmount": ""
 }
```

A successful execution looks like this in case if the user hasn’t canceled:

![Successful execution for subscription workflow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xg9dfvfer5xjqcgpfkvv.jpg)

If the subscription is canceled by the user (a signal is received via Webhook), the execution looks like this:

![Successful execution for subscription workflow when user cancels](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/voic9ykk0t8tfo08z0o8.jpg)

## Summing Up

We built a visualized flow that can manage subscriptions effectively and even included handling a trial period! 🥂

Try building the application from scratch, and [reach out to us for any queries](https://app.slack.com/client/T02KG20GJ1Z/C02KJ820XPW).

Meanwhile, explore other Conductor features through [Orkes Playground](https://play.orkes.io/), a free dedicated developer sandbox for you to try out Conductor in real-time.

If you enjoy building applications with Conductor, don’t forget to give us a star on our [Conductor](https://github.com/conductor-oss/conductor) repo. ⭐⭐⭐