Subscriptions Recipe
In this guide, you'll learn how to support subscription purchases with Medusa.
When you install a Medusa application, you get a fully-fledged commerce platform with support for customizations. While Medusa doesn't provide subscription-based purchases natively, it provides the framework to support you in implementing this feature.
In this guide, you'll customize Medusa to implement subscription-based purchases with the following features:
- Subscription-based purchases for a specified interval (monthly or yearly) and period.
- Customize the admin dashboard to view subscriptions and associated orders.
- Automatic renewal of the subscription.
- Automatic subscription expiration tracking.
- Allow customers to view and cancel their subscriptions.
This guide uses Stripe as an example to capture the subscription payments. You're free to use a different payment provider or implement your payment logic instead.
Step 1: Install a Medusa Application#
Start by installing the Medusa application on your machine with the following command:
You'll first be asked for the project's name. Then, when you're asked whether you want to install the Next.js storefront, choose Y
for yes.
Afterwards, the installation process will start, which will install the Medusa application in a directory with your project's name, and the Next.js storefront in a directory with the {project-name}-storefront
name.
Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credentials and submit the form.
Afterwards, you can log in with the new user and explore the dashboard. The Next.js storefront is also running at http://localhost:8000
.
Step 2: Configure Stripe Module Provider#
As mentioned in the introduction, you'll use Stripe as the payment provider for the subscription payments. In this step, you'll configure the Stripe Module Provider in your Medusa application.
To add the Stripe Module Provider to the Medusa configurations, add the following to the medusa-config.ts
file:
The Medusa configurations accept a modules
property to add modules to your application. You'll learn more about modules in the next section.
You add the Stripe Module Provider to the Payment Module's options. Learn more about these options in the Payment Module's options documentation.
You also pass an apiKey
option to the Stripe Module Provider and set its value to an environment variable. So, add the following to your .env
file:
Where sk_test_51J...
is your Stripe Secret API Key.
Enable Stripe in Regions#
To allow customers to use Stripe during checkout, you must enable it in at least one region. Customers can only choose from payment providers available in their region. You can enable the payment provider in the Medusa Admin dashboard.
To do that, start the Medusa application:
Then, open the dashboard at localhost:9000/app
. After you log in:
- Go to Settings -> Regions.
- Click on a region to edit.
- Click on the icon at the top right of the first section.
- In the side window that opens, edit the region's payment provider to choose "Stripe (STRIPE)".
- Once you're done, click the Save button.
Step 3: Create Subscription Module#
Medusa creates commerce features in modules. For example, product features and data models are created in the Product Module.
You also create custom commerce data models and features in custom modules. They're integrated into the Medusa application similar to Medusa's modules without side effects.
So, you'll create a subscription module that holds the data models related to a subscription and allows you to manage them.
Create the directory src/modules/subscription
.
Create Data Models#
Create the file src/modules/subscription/models/subscription.ts
with the following content:
1import { model } from "@medusajs/framework/utils"2import { SubscriptionInterval, SubscriptionStatus } from "../types"3 4const Subscription = model.define("subscription", {5 id: model.id().primaryKey(),6 status: model.enum(SubscriptionStatus)7 .default(SubscriptionStatus.ACTIVE),8 interval: model.enum(SubscriptionInterval),9 period: model.number(),10 subscription_date: model.dateTime(),11 last_order_date: model.dateTime(),12 next_order_date: model.dateTime().index().nullable(),13 expiration_date: model.dateTime().index(),14 metadata: model.json().nullable(),15})16 17export default Subscription
This creates a Subscription
data model that holds a subscription’s details, including:
interval
: indicates whether the subscription is renewed monthly or yearly.period
: a number indicating how many months/years before a new order is created for the subscription. For example, ifperiod
is3
andinterval
ismonthly
, then a new order is created every three months.subscription_date
: when the subscription was created.last_order_date
: when the last time a new order was created for the subscription.next_order_date
: when the subscription’s next order should be created. This property is nullable in case the subscription doesn’t have a next date or has expired.expiration_date
: when the subscription expires.metadata
: any additional data can be held in this JSON property.
Notice that the data models use enums defined in another file. So, create the file src/modules/subscription/types/index.ts
with the following content:
Create Main Service#
Create the module’s main service in the file src/modules/subscription/service.ts
with the following content:
The main service extends the service factory to provide data-management features on the Subscription
data model.
Create Module Definition File#
Create the file src/modules/subscription/index.ts
that holds the module’s definition:
This sets the module’s name to subscriptionModuleService
and its main service to SubscriptionModuleService
.
Register Module in Medusa’s Configuration#
Finally, add the module into medusa-config.ts
:
Further Read#
Step 4: Define Links#
Modules are isolated in Medusa, making them reusable, replaceable, and integrable in your application without side effects.
So, you can't have relations between data models in modules. Instead, you define a link between them.
Links are relations between data models of different modules that maintain the isolation between the modules.
In this step, you’ll define links between the Subscription Module’s Subscription
data model and the data models of Medusa’s commerce modules:
- Link between the
Subscription
data model and the Cart Module'sCart
model. - Link between the
Subscription
data model and the Customer Module'sCustomer
model. - Link between the
Subscription
data model and the Order Module'sOrder
model.
Define a Link to Cart#
To link a subscription to the cart used to make the purchase, create the file src/links/subscription-cart.ts
with the following content:
This defines a link between the Subscription
data model and the Cart Module’s Cart
data model.
Define a Link to Customer#
To link a subscription to the customer who purchased it, create the file src/links/subscription-customer.ts
with the following content:
1import { defineLink } from "@medusajs/framework/utils"2import SubscriptionModule from "../modules/subscription"3import CustomerModule from "@medusajs/medusa/customer"4 5export default defineLink(6 {7 linkable: SubscriptionModule.linkable.subscription,8 isList: true,9 },10 CustomerModule.linkable.customer11)
This defines a list link to the Subscription
data model, since a customer may have multiple subscriptions.
Define a Link to Order#
To link a subscription to the orders created for it, create the file src/links/subscription-order.ts
with the following content:
1import { defineLink } from "@medusajs/framework/utils"2import SubscriptionModule from "../modules/subscription"3import OrderModule from "@medusajs/medusa/order"4 5export default defineLink(6 SubscriptionModule.linkable.subscription,7 {8 linkable: OrderModule.linkable.order,9 isList: true,10 }11)
This defines a list link to the Order
data model since a subscription has multiple orders.
Further Reads#
Step 5: Run Migrations#
To create a table for the Subscription
data model in the database, start by generating the migrations for the Subscription Module with the following command:
This generates a migration in the src/modules/subscriptions/migrations
directory.
Then, to reflect the migration and links in the database, run the following command:
Step 6: Override createSubscriptions Method in Service#
Since the Subscription Module’s main service extends the service factory, it has a generic createSubscriptions
method that creates one or more subscriptions.
In this step, you’ll override it to add custom logic to the subscription creation that sets its date properties.
Install moment Library#
Before you start, install the Moment.js library to help manipulate and format dates with the following command:
Add getNextOrderDate Method#
In src/modules/subscription/service.ts
, add the following method to SubscriptionModuleService
:
1// ...2import moment from "moment"3import { 4 CreateSubscriptionData, 5 SubscriptionData, 6 SubscriptionInterval,7} from "./types"8 9class SubscriptionModuleService extends MedusaService({10 Subscription,11}) {12 getNextOrderDate({13 last_order_date,14 expiration_date,15 interval,16 period,17 }: {18 last_order_date: Date19 expiration_date: Date20 interval: SubscriptionInterval,21 period: number22 }): Date | null {23 const nextOrderDate = moment(last_order_date)24 .add(25 period, 26 interval === SubscriptionInterval.MONTHLY ? 27 "month" : "year"28 )29 const expirationMomentDate = moment(expiration_date)30 31 return nextOrderDate.isAfter(expirationMomentDate) ? 32 null : nextOrderDate.toDate()33 }34}
This method accepts a subscription’s last order date, expiration date, interval, and period, and uses them to calculate and return the next order date.
If the next order date, calculated from the last order date, exceeds the expiration date, null
is returned.
Add getExpirationDate Method#
In the same file, add the following method to SubscriptionModuleService
:
1class SubscriptionModuleService extends MedusaService({2 Subscription,3}) {4 // ...5 getExpirationDate({6 subscription_date,7 interval,8 period,9 }: {10 subscription_date: Date,11 interval: SubscriptionInterval,12 period: number13 }) {14 return moment(subscription_date)15 .add(16 period,17 interval === SubscriptionInterval.MONTHLY ?18 "month" : "year"19 ).toDate()20 }21}
The getExpirationDate
method accepts a subscription’s date, interval, and period to calculate and return its expiration date.
Override the createSubscriptions Method#
Before overriding the createSubscriptions
method, add the following types to src/modules/subscription/types/index.ts
:
1import { InferTypeOf } from "@medusajs/framework/types"2import Subscription from "../models/subscription"3 4// ...5 6export type CreateSubscriptionData = {7 interval: SubscriptionInterval8 period: number9 status?: SubscriptionStatus10 subscription_date?: Date11 metadata?: Record<string, unknown>12}13 14export type SubscriptionData = InferTypeOf<typeof Subscription>
Subscription
data model is a variable, use InferTypeOf
to infer its type.Then, in src/modules/subscription/service.ts
, add the following to override the createSubscriptions
method:
1class SubscriptionModuleService extends MedusaService({2 Subscription,3}) {4 // ...5 6 // @ts-expect-error7 async createSubscriptions(8 data: CreateSubscriptionData | CreateSubscriptionData[]9 ): Promise<SubscriptionData[]> {10 const input = Array.isArray(data) ? data : [data]11 12 const subscriptions = await Promise.all(13 input.map(async (subscription) => {14 const subscriptionDate = subscription.subscription_date || new Date()15 const expirationDate = this.getExpirationDate({16 subscription_date: subscriptionDate,17 interval: subscription.interval,18 period: subscription.period,19 })20 21 return await super.createSubscriptions({22 ...subscription,23 subscription_date: subscriptionDate,24 last_order_date: subscriptionDate,25 next_order_date: this.getNextOrderDate({26 last_order_date: subscriptionDate,27 expiration_date: expirationDate,28 interval: subscription.interval,29 period: subscription.period,30 }),31 expiration_date: expirationDate,32 })33 })34 )35 36 return subscriptions37 }38}
The createSubscriptions
calculates for each subscription the expiration and next order dates using the methods created earlier. It creates and returns the subscriptions.
This method is used in the next step.
Step 7: Create Subscription Workflow#
To implement and expose a feature that manipulates data, you create a workflow that uses services to implement the functionality, then create an API route that executes that workflow.
In this step, you’ll create the workflow that you’ll execute when a customer purchases a subscription.
The workflow accepts a cart’s ID, and it has three steps:
- Create the order from the cart.
- Create a subscription.
- Link the subscription to the order, cart, and customer.
Medusa provides the first and last steps in the @medusajs/medusa/core-flows
package, so you only need to implement the second step.
Create a Subscription Step (Second Step)#
Create the file src/workflows/create-subscription/steps/create-subscription.ts
with the following content:
6import { SUBSCRIPTION_MODULE } from "../../../modules/subscription"7 8type StepInput = {9 cart_id: string10 order_id: string11 customer_id?: string12 subscription_data: {13 interval: SubscriptionInterval14 period: number15 }16}17 18const createSubscriptionStep = createStep(19 "create-subscription",20 async ({ 21 cart_id, 22 order_id, 23 customer_id,24 subscription_data,25 }: StepInput, { container }) => {26 const subscriptionModuleService: SubscriptionModuleService = 27 container.resolve(SUBSCRIPTION_MODULE)28 const linkDefs: LinkDefinition[] = []29 30 const subscription = await subscriptionModuleService.createSubscriptions({31 ...subscription_data,32 metadata: {33 main_order_id: order_id,34 },35 })36 37 // TODO add links38 39 return new StepResponse({40 subscription: subscription[0],41 linkDefs,42 }, {43 subscription: subscription[0],44 })45 }, async ({ subscription }, { container }) => {46 // TODO implement compensation47 }48)49 50export default createSubscriptionStep
This step receives the IDs of the cart, order, and customer, along with the subscription’s details.
In this step, you use the createSubscriptions
method to create the subscription. In the metadata
property, you set the ID of the order created on purchase.
The step returns the created subscription as well as an array of links to create. To add the links to be created in the returned array, replace the first TODO
with the following:
1linkDefs.push({2 [SUBSCRIPTION_MODULE]: {3 "subscription_id": subscription[0].id,4 },5 [Modules.ORDER]: {6 "order_id": order_id,7 },8})9 10linkDefs.push({11 [SUBSCRIPTION_MODULE]: {12 "subscription_id": subscription[0].id,13 },14 [Modules.CART]: {15 "cart_id": cart_id,16 },17})18 19if (customer_id) {20 linkDefs.push({21 [SUBSCRIPTION_MODULE]: {22 "subscription_id": subscription[0].id,23 },24 [Modules.CUSTOMER]: {25 "customer_id": customer_id,26 },27 })28}
This adds links between:
- The subscription and the order.
- The subscription and the cart.
- The subscription and the customer, if a customer is associated with the cart.
The step also has a compensation function to undo the step’s changes if an error occurs. So, replace the second TODO
with the following:
The compensation function receives the subscription as a parameter. It cancels the subscription.
Create Workflow#
Create the file src/workflows/create-subscription/index.ts
with the following content:
12} from "../../modules/subscription/types"13import createSubscriptionStep from "./steps/create-subscription"14 15type WorkflowInput = {16 cart_id: string,17 subscription_data: {18 interval: SubscriptionInterval19 period: number20 }21}22 23const createSubscriptionWorkflow = createWorkflow(24 "create-subscription",25 (input: WorkflowInput) => {26 const { id } = completeCartWorkflow.runAsStep({27 input: {28 id: input.cart_id,29 },30 })31 32 const { data: orders } = useQueryGraphStep({33 entity: "order",34 fields: [35 "id",36 "status",37 "summary",38 "currency_code",39 "customer_id",40 "display_id",41 "region_id",42 "email",43 "total",44 "subtotal",45 "tax_total",46 "discount_total",47 "discount_subtotal",48 "discount_tax_total",49 "original_total",50 "original_tax_total",51 "item_total",52 "item_subtotal",53 "item_tax_total",54 "original_item_total",55 "original_item_subtotal",56 "original_item_tax_total",57 "shipping_total",58 "shipping_subtotal",59 "shipping_tax_total",60 "original_shipping_tax_total",61 "original_shipping_subtotal",62 "original_shipping_total",63 "created_at",64 "updated_at",65 "credit_lines.*",66 "items.*",67 "items.tax_lines.*",68 "items.adjustments.*",69 "items.detail.*",70 "items.variant.*",71 "items.variant.product.*",72 "shipping_address.*",73 "billing_address.*",74 "shipping_methods.*",75 "shipping_methods.tax_lines.*",76 "shipping_methods.adjustments.*",77 "payment_collections.*",78 ],79 filters: {80 id,81 },82 options: {83 throwIfKeyNotFound: true,84 },85 })86 87 const { subscription, linkDefs } = createSubscriptionStep({88 cart_id: input.cart_id,89 order_id: orders[0].id,90 customer_id: orders[0].customer_id,91 subscription_data: input.subscription_data,92 })93 94 createRemoteLinkStep(linkDefs)95 96 return new WorkflowResponse({97 subscription: subscription,98 order: orders[0],99 })100 }101)102 103export default createSubscriptionWorkflow
This workflow accepts the cart’s ID, along with the subscription details. It executes the following steps:
completeCartWorkflow
from@medusajs/medusa/core-flows
that completes a cart and creates an order.useQueryGraphStep
from@medusajs/medusa/core-flows
to retrieve the order's details. Query is a tool that allows you to retrieve data across modules.createSubscriptionStep
, which is the step you created previously.createRemoteLinkStep
from@medusajs/medusa/core-flows
, which accepts links to create. These links are in thelinkDefs
array returned by the previous step.
The workflow returns the created subscription and order.
Further Reads#
Step 8: Custom Complete Cart API Route#
To create a subscription when a customer completes their purchase, you need to expose an endpoint that executes the subscription workflow. To do that, you'll create an API route.
An API Route is an endpoint that exposes commerce features to external applications and clients, such as storefronts.
In this step, you’ll create a custom API route similar to the Complete Cart API route that uses the workflow you previously created to complete the customer's purchase and create a subscription.
Create the file src/api/store/carts/[id]/subscribe/route.ts
with the following content:
9import createSubscriptionWorkflow from "../../../../../workflows/create-subscription"10 11export const POST = async (12 req: MedusaRequest,13 res: MedusaResponse14) => {15 const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)16 17 const { data: [cart] } = await query.graph({18 entity: "cart",19 fields: [20 "metadata",21 ],22 filters: {23 id: [req.params.id],24 },25 })26 27 const { metadata } = cart28 29 if (!metadata?.subscription_interval || !metadata.subscription_period) {30 throw new MedusaError(31 MedusaError.Types.INVALID_DATA,32 "Please set the subscription's interval and period first."33 )34 }35 36 const { result } = await createSubscriptionWorkflow(37 req.scope38 ).run({39 input: {40 cart_id: req.params.id,41 subscription_data: {42 interval: metadata.subscription_interval,43 period: metadata.subscription_period,44 },45 },46 })47 48 res.json({49 type: "order",50 ...result,51 })52}
Since the file exports a POST
function, you're exposing a POST
API route at /store/carts/[id]/subscribe
.
In the route handler function, you retrieve the cart to access it's metadata
property. If the subscription details aren't stored there, you throw an error.
Then, you use the createSubscriptionWorkflow
you created to create the order, and return the created order and subscription in the response.
In the next step, you'll customize the Next.js storefront, allowing you to test out the subscription feature.
Further Reads#
Intermission: Payment Flow Overview#
Before continuing with the customizations, you must understand the payment changes you need to make to support subscriptions. In this guide, you'll get a general overview, but you can refer to the Payment in Storefront documentation for more details.
By default, the checkout flow requires you to create a payment collection, then a payment session in that collection. When you create the payment session, that subsequently performs the necessary action to initialize the payment in the payment provider. For example, it creates a payment intent in Stripe.
To support subscriptions, you need to support capturing the payment each time the subscription renews. When creating the payment session using the Initialize Payment Session API route, you must pass the data that your payment provider requires to support capturing the payment again in the future. You can pass the data that the provider requires in the data
property.
When you create the payment session, Medusa creates an account holder for the customer. An account holder represents a customer's saved payment information, including saved methods, in a third-party provider and may hold data from that provider. Learn more in the Account Holder documentation.
The account holder allows you to retrieve the saved payment method and use it to capture the payment when the subscription renews. You'll see how this works later when you implement the logic to renew the subscription.
Step 9: Add Subscriptions to Next.js Storefront#
In this step, you'll customize the checkout flow in the Next.js Starter storefront, which you installed in the first step, to:
- Add a subscription step to the checkout flow.
- Pass the additional data that Stripe requires to later capture the payment when the subscription renews, as explained in the Payment Flow Overview.
Add Subscription Step#
Start by adding the function to update the subscription data in the cart. Add to the file src/lib/data/cart.ts
the following:
1export enum SubscriptionInterval {2 MONTHLY = "monthly",3 YEARLY = "yearly"4}5 6export async function updateSubscriptionData(7 subscription_interval: SubscriptionInterval,8 subscription_period: number9) {10 const cartId = getCartId()11 12 if (!cartId) {13 throw new Error("No existing cart found when placing an order")14 }15 16 await updateCart({17 metadata: {18 subscription_interval,19 subscription_period,20 },21 })22 revalidateTag("cart")23}
This updates the cart's metadata
with the subscription details.
Then, you'll add the subscription form that shows as part of the checkout to select the subscription interval and period. Create the file src/modules/checkout/components/subscriptions/index.tsx
with the following content:
11import { updateSubscriptionData } from "../../../../lib/data/cart"12 13export enum SubscriptionInterval {14 MONTHLY = "monthly",15 YEARLY = "yearly"16}17 18const SubscriptionForm = () => {19 const [interval, setInterval] = useState<SubscriptionInterval>(20 SubscriptionInterval.MONTHLY21 )22 const [period, setPeriod] = useState(1)23 const [isLoading, setIsLoading] = useState(false)24 25 const searchParams = useSearchParams()26 const router = useRouter()27 const pathname = usePathname()28 29 const isOpen = searchParams.get("step") === "subscription"30 31 const createQueryString = useCallback(32 (name: string, value: string) => {33 const params = new URLSearchParams(searchParams)34 params.set(name, value)35 36 return params.toString()37 },38 [searchParams]39 )40 41 const handleEdit = () => {42 router.push(pathname + "?" + createQueryString("step", "subscription"), {43 scroll: false,44 })45 }46 47 const handleSubmit = async () => {48 setIsLoading(true)49 50 updateSubscriptionData(interval, period)51 .then(() => {52 setIsLoading(false)53 router.push(pathname + "?step=delivery", { scroll: false })54 })55 }56 57 return (58 <div className="bg-white">59 <div className="flex flex-row items-center justify-between mb-6">60 <Heading61 level="h2"62 className={clx(63 "flex flex-row text-3xl-regular gap-x-2 items-baseline",64 {65 "opacity-50 pointer-events-none select-none":66 !isOpen,67 }68 )}69 >70 Subscription Details71 {!isOpen && <CheckCircleSolid />}72 </Heading>73 {!isOpen && (74 <Text>75 <button76 onClick={handleEdit}77 className="text-ui-fg-interactive hover:text-ui-fg-interactive-hover"78 data-testid="edit-payment-button"79 >80 Edit81 </button>82 </Text>83 )}84 </div>85 <div>86 <div className={isOpen ? "block" : "hidden"}>87 <div className="flex flex-col gap-4">88 <NativeSelect 89 placeholder="Interval" 90 value={interval} 91 onChange={(e) => 92 setInterval(e.target.value as SubscriptionInterval)93 }94 required95 autoComplete="interval"96 >97 {Object.values(SubscriptionInterval).map(98 (intervalOption, index) => (99 <option key={index} value={intervalOption}>100 {capitalize(intervalOption)}101 </option>102 )103 )}104 </NativeSelect>105 <Input106 label="Period"107 name="period"108 autoComplete="period"109 value={period}110 onChange={(e) => 111 setPeriod(parseInt(e.target.value))112 }113 required114 type="number"115 />116 </div>117 118 <Button119 size="large"120 className="mt-6"121 onClick={handleSubmit}122 isLoading={isLoading}123 disabled={!interval || !period}124 >125 Continue to delivery126 </Button>127 </div>128 </div>129 <Divider className="mt-8" />130 </div>131 )132}133 134export default SubscriptionForm
This adds a component that displays a form to choose the subscription's interval and period during checkout. When the customer submits the form, you use the updateSubscriptionData
function that sends a request to the Medusa application to update the cart with the subscription details.
Next, you want the subscription step to show after the address step. So, change the last line of the setAddresses
function in src/lib/data/cart.ts
to redirect to the subscription step once the customer enters their address:
And to show the subscription form during checkout, add the SubscriptionForm
in src/modules/checkout/templates/checkout-form/index.tsx
after the Addresses
wrapper component:
1// other imports...2import SubscriptionForm from "@modules/checkout/components/subscriptions"3 4export default async function CheckoutForm({5 cart,6 customer,7}: {8 cart: HttpTypes.StoreCart | null9 customer: HttpTypes.StoreCustomer | null10}) {11 // ...12 13 return (14 <div>15 {/* ... */}16 {/* After Addresses, before Shipping */}17 <div>18 <SubscriptionForm />19 </div>20 {/* ... */}21 </div>22 )23}
Pass Additional Data to Payment Provider#
As explained in the Payment Flow Overview, you need to pass additional data to the payment provider to support subscriptions.
For Stripe, you need to pass the setup_future_usage
property in the data
object when you create the payment session. This property allows you to capture the payment in the future, as explained in Stripe's documentation.
To pass this data, you'll make changes in the src/modules/checkout/components/payment/index.tsx
file. In this file, the initiatePaymentSession
is used in two places. In each of them, pass the data
property as follows:
If you're integrating with a custom payment provider, you can instead pass the required data for that provider in the data
object.
The payment method can now be used later to capture the payment when the subscription renews.
Test Cart Completion and Subscription Creation#
To test out the cart completion flow:
- In the Medusa application's directory, run the following command to start the application:
- In the Next.js Starter's directory, run the following command to start the storefront:
- Add a product to the cart and place an order. During checkout, you'll see a Subscription Details step to fill out the interval and period.
Step 10: Add Admin API Routes for Subscription#
In this step, you’ll add two API routes for admin users:
- One to list all subscriptions.
- One to retrieve a subscription.
List Subscriptions Admin API Route#
The list subscriptions API route should allow clients to retrieve subscriptions with pagination. An API route can be configured to accept pagination fields, such as limit
and offset
, then use them with Query to paginate the retrieved data.
You'll start with the API route. To create it, create the file src/api/admin/subscriptions/route.ts
with the following content:
1import { 2 AuthenticatedMedusaRequest, 3 MedusaResponse,4} from "@medusajs/framework"5import { ContainerRegistrationKeys } from "@medusajs/framework/utils"6 7export const GET = async (8 req: AuthenticatedMedusaRequest,9 res: MedusaResponse10) => {11 const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)12 13 const { 14 data: subscriptions,15 metadata: { count, take, skip },16 } = await query.graph({17 entity: "subscription",18 ...req.queryConfig,19 })20 21 res.json({22 subscriptions,23 count,24 limit: take,25 offset: skip,26 })27}
This adds a GET
API route at /admin/subscriptions
. In the route handler, you use Query to retrieve the subscriptions. Notice that you pass the req.queryConfig
object to the query.graph
method. This object contains the pagination fields, such as limit
and offset
, which are combined from the configurations you'll add in the middleware, and the optional query parameters in the request.
Then, you return the subscriptions, along with the:
count
: The total number of subscriptions.limit
: The maximum number of subscriptions returned.offset
: The number of subscriptions skipped before retrieving the subscriptions.
These fields are useful for clients to paginate the subscriptions.
Add Query Configuration Middleware#
To configure the pagination and retrieved fields within the route handler, and to allow passing query parameters that change these configurations in the request, you need to add the validateAndTransformQuery
middleware to the route.
To add a middleware, create the file src/api/middlewares.ts
with the following content:
1import { 2 validateAndTransformQuery,3 defineMiddlewares,4} from "@medusajs/framework/http"5import { createFindParams } from "@medusajs/medusa/api/utils/validators"6 7export const GetCustomSchema = createFindParams()8 9export default defineMiddlewares({10 routes: [11 {12 matcher: "/admin/subscriptions",13 method: "GET",14 middlewares: [15 validateAndTransformQuery(16 GetCustomSchema,17 {18 defaults: [19 "id",20 "subscription_date",21 "expiration_date",22 "status",23 "metadata.*",24 "orders.*",25 "customer.*",26 ],27 isList: true,28 }29 ),30 ],31 },32 ],33})
You add the validateAndTransformQuery
middleware to GET
requests sent to routes starting with /admin/subscriptions
. This middleware accepts the following parameters:
- A validation schema indicating which query parameters are accepted. You create the schema with Zod. Medusa has a createFindParams utility that generates a Zod schema accepting four query parameters:
fields
: The fields and relations to retrieve in the returned resources.offset
: The number of items to skip before retrieving the returned items.limit
: The maximum number of items to return.order
: The fields to order the returned items by in ascending or descending order.
- A Query configuration object. It accepts the following properties:
defaults
: An array of default fields and relations to retrieve in each resource.isList
: A boolean indicating whether a list of items are returned in the response.
The middleware combines your default configurations with the query parameters in the request to determine the fields to retrieve and the pagination settings.
Refer to the Request Query Configuration documentation to learn more about this middleware and the query configurations.
Get Subscription Admin API Route#
Next, you'll add the API route to retrieve a single subscription. So, create the file src/api/admin/subscriptions/[id]/route.ts
with the following content:
1import { 2 AuthenticatedMedusaRequest, 3 MedusaResponse,4} from "@medusajs/framework"5import { ContainerRegistrationKeys } from "@medusajs/framework/utils"6 7export const GET = async (8 req: AuthenticatedMedusaRequest,9 res: MedusaResponse10) => {11 const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)12 13 const { data: [subscription] } = await query.graph({14 entity: "subscription",15 fields: [16 "*",17 "orders.*",18 "customer.*",19 ],20 filters: {21 id: [req.params.id],22 },23 })24 25 res.json({26 subscription,27 })28}
This adds a GET
API route at /admin/subscriptions/[id]
, where [id]
is the ID of the subscription to retrieve.
In the route handler, you retrieve a subscription by its ID using Query and return it in the response.
In the next section, you’ll extend the Medusa Admin and use these API routes to show the subscriptions.
Step 11: Extend Admin#
The Medusa Admin is customizable, allowing you to inject widgets into existing pages or add UI routes to create new pages.
In this step, you’ll add two UI routes:
- One to view all subscriptions.
- One to view a single subscription.
Create Types File#
Before creating the UI routes, create the file src/admin/types/index.ts
that holds types used by the UI routes:
1import { 2 OrderDTO,3 CustomerDTO,4} from "@medusajs/framework/types"5 6export enum SubscriptionStatus {7 ACTIVE = "active",8 CANCELED = "canceled",9 EXPIRED = "expired",10 FAILED = "failed"11}12 13export enum SubscriptionInterval {14 MONTHLY = "monthly",15 YEARLY = "yearly"16}17 18export type SubscriptionData = {19 id: string20 status: SubscriptionStatus21 interval: SubscriptionInterval22 subscription_date: string23 last_order_date: string24 next_order_date: string | null25 expiration_date: string26 metadata: Record<string, unknown> | null27 orders?: OrderDTO[]28 customer?: CustomerDTO29}
You define types for the subscription status and interval, as well as a SubscriptionData
type that represents the subscription data. The SubscriptionData
type includes the subscription's ID, status, interval, dates, metadata, and related orders and customer. You'll use these types for the subscriptions retrieved from the server.
Configure JS SDK#
Medusa provides a JS SDK that facilitates sending requests to the server. You can use this SDK in any JavaScript client-side application, including your admin customizations.
To configure the JS SDK, create the file src/admin/lib/sdk.ts
with the following content:
This initializes the SDK, setting the following options:
baseUrl
: The URL of the Medusa server. You use the Vite environment variableVITE_BACKEND_URL
.debug
: A boolean indicating whether to log debug information. You use the Vite environment variableDEV
.auth
: An object indicating the authentication type. You use the session authentication type, which is the recommended approach for admin customizations.
Learn more about other customizations in the JS SDK documentation.
Create Subscriptions List UI Route#
You'll now create the subscriptions list UI route. Since you'll show the subscriptions in a table, you'll use the DataTable component from Medusa UI. It facilitates displaying data in a tabular format with sorting, filtering, and pagination.
Start by creating the file src/admin/routes/subscriptions/page.tsx
with the following content:
8import { useNavigate } from "react-router-dom"9 10const getBadgeColor = (status: SubscriptionStatus) => {11 switch(status) {12 case SubscriptionStatus.CANCELED:13 return "orange"14 case SubscriptionStatus.FAILED:15 return "red"16 case SubscriptionStatus.EXPIRED:17 return "grey"18 default:19 return "green"20 }21}22 23const getStatusTitle = (status: SubscriptionStatus) => {24 return status.charAt(0).toUpperCase() + 25 status.substring(1)26}27 28const columnHelper = createDataTableColumnHelper<SubscriptionData>()29 30const columns = [31 columnHelper.accessor("id", {32 header: "#",33 }),34 columnHelper.accessor("metadata.main_order_id", {35 header: "Main Order",36 }),37 columnHelper.accessor("customer.email", {38 header: "Customer",39 }),40 columnHelper.accessor("subscription_date", {41 header: "Subscription Date",42 cell: ({ getValue }) => {43 return getValue().toLocaleString()44 },45 }),46 columnHelper.accessor("expiration_date", {47 header: "Expiry Date",48 cell: ({ getValue }) => {49 return getValue().toLocaleString()50 },51 }),52 columnHelper.accessor("status", {53 header: "Status",54 cell: ({ getValue }) => {55 return (56 <Badge color={getBadgeColor(getValue())}>57 {getStatusTitle(getValue())}58 </Badge>59 )60 },61 }),62]63 64const SubscriptionsPage = () => {65 // TODO add implementation66}67 68export const config = defineRouteConfig({69 label: "Subscriptions",70 icon: ClockSolid,71})72 73export default SubscriptionsPage
First, you define two helper functions: getBadgeColor
to get the color for the status badge, and getStatusTitle
to capitalize the status for the badge text.
Then, you use the createDataTableColumnHelper
utility to create a column helper. This utility simplifies defining columns for the data table. You define the columns for the data table using the helper, specifying the accessor, header, and cell for each column.
The UI route file must export a React component, SubscriptionsPage
, that shows the content of the UI route. You'll implement this component in a bit.
Finally, you can export the route configuration using the defineRouteConfig
function, which shows the UI route in the sidebar with the specified label and icon.
In the SubscriptionsPage
component, you'll fetch the subscriptions and show them in a data table. So, replace the SubscriptionsPage
component with the following:
1const SubscriptionsPage = () => {2 const navigate = useNavigate()3 const [pagination, setPagination] = useState<DataTablePaginationState>({4 pageSize: 4,5 pageIndex: 0,6 })7 8 const query = useMemo(() => {9 return new URLSearchParams({10 limit: `${pagination.pageSize}`,11 offset: `${pagination.pageIndex * pagination.pageSize}`,12 })13 }, [pagination])14 15 const { data, isLoading } = useQuery<{16 subscriptions: SubscriptionData[],17 count: number18 }>({19 queryFn: () => sdk.client.fetch(`/admin/subscriptions?${query.toString()}`),20 queryKey: ["subscriptions", query.toString()],21 })22 23 const table = useDataTable({24 columns,25 data: data?.subscriptions || [],26 getRowId: (subscription) => subscription.id,27 rowCount: data?.count || 0,28 isLoading,29 pagination: {30 state: pagination,31 onPaginationChange: setPagination,32 },33 onRowClick(event, row) {34 navigate(`/subscriptions/${row.id}`)35 },36 })37 38 39 return (40 <Container>41 <DataTable instance={table}>42 <DataTable.Toolbar>43 <Heading level="h1">Subscriptions</Heading>44 </DataTable.Toolbar>45 <DataTable.Table />46 {/** This component will render the pagination controls **/}47 <DataTable.Pagination />48 </DataTable>49 </Container>50 )51}
In the component, you first initialize a pagination
state variable of type DataTablePaginationState
. This is necessary for the table to manage pagination.
Then, you use the useQuery
hook from the @tanstack/react-query
package to fetch the subscriptions. In the query function, you use the JS SDK to send a request to the /admin/subscriptions
API route with the pagination query parameters.
Next, you use the useDataTable
hook to create a data table instance. You pass the columns, subscriptions data, row count, loading state, and pagination settings to the hook. You also navigate to the subscription details page when a row is clicked.
Finally, you render the data table with the subscriptions data, along with the pagination controls.
The subscriptions UI route will now show a table of subscriptions, and when you click on the ID of any of them, you can view its individual page that you'll create next.
Create a Single Subscription UI Route#
To create the UI route or page that shows the details of a single subscription, create the file src/admin/routes/subscriptions/[id]/page.tsx
with the following content:
1import { 2 Container,3 Heading,4 Table,5} from "@medusajs/ui"6import { useParams, Link } from "react-router-dom"7import { SubscriptionData } from "../../../types/index.js"8import { useQuery } from "@tanstack/react-query"9import { sdk } from "../../../lib/sdk.js"10 11const SubscriptionPage = () => {12 const { id } = useParams()13 const { data, isLoading } = useQuery<{14 subscription: SubscriptionData15 }>({16 queryFn: () => sdk.client.fetch(`/admin/subscriptions/${id}`),17 queryKey: ["subscription", id],18 })19 20 return (21 <Container>22 {isLoading && <span>Loading...</span>}23 {data?.subscription && (24 <>25 <Heading level="h1">Orders of Subscription #{data.subscription.id}</Heading>26 <Table>27 <Table.Header>28 <Table.Row>29 <Table.HeaderCell>#</Table.HeaderCell>30 <Table.HeaderCell>Date</Table.HeaderCell>31 <Table.HeaderCell>View Order</Table.HeaderCell>32 </Table.Row>33 </Table.Header>34 <Table.Body>35 {data.subscription.orders?.map((order) => (36 <Table.Row key={order.id}>37 <Table.Cell>{order.id}</Table.Cell>38 <Table.Cell>{(new Date(order.created_at)).toDateString()}</Table.Cell>39 <Table.Cell>40 <Link to={`/orders/${order.id}`}>41 View Order42 </Link>43 </Table.Cell>44 </Table.Row>45 ))}46 </Table.Body>47 </Table>48 </>49 )}50 </Container>51 )52}53 54export default SubscriptionPage
This creates the React component used to display a subscription’s details page. Again, you use the useQuery
hook to fetch the subscription data using the JS SDK. You pass the subscription ID from the route parameters to the hook.
Then, you render the subscription’s orders in a table. For each order, you show the ID, date, and a link to view the order.
Test the UI Routes#
To test the UI routes, run the Medusa application and go to http://localhost:9000/app
.
After you log-in, you’ll find a new sidebar item “Subscriptions”. Once you click on it, you’ll see the list of subscription purchases.
To view a subscription’s details, click on its row, which opens the subscription details page. This page contains the subscription’s orders.
Further Reads#
Step 12: Create New Subscription Orders Workflow#
In this step, you’ll create a workflow to create a new subscription order. Later, you’ll execute this workflow in a scheduled job.
The workflow has eight steps:
- Retrieve the subscription’s linked cart. Medusa provides a
useQueryGraphStep
in the@medusajs/medusa/core-flows
package that can be used as a step. - Create a payment collection for the new order. Medusa provides a
createPaymentCollectionsStep
in the@medusajs/medusa/core-flows
package that you can use. - Get the customer's saved payment method. This payment method will be used to charge the customer.
- Create payment sessions in the payment collection. Medusa provides a
createPaymentSessionsWorkflow
in the@medusajs/medusa/core-flows
package that can be used as a step. - Authorize the payment session. Medusa also provides the
authorizePaymentSessionStep
in the@medusajs/medusa/core-flows
package, which can be used. - Create the subscription’s new order.
- Create links between the subscription and the order using the
createRemoteLinkStep
provided in the@medusajs/medusa/core-flows
package. - Capture the order’s payment using the
capturePaymentStep
provided by Medusa in the@medusajs/medusa/core-flows
package. - Update the subscription’s
last_order_date
andnext_order_date
properties.
You’ll only implement the third, sixth, and ninth steps.
Create getPaymentMethodStep (Third Step)#
To charge the customer using their payment method saved in Stripe, you need to retrieve that payment method. As explained in the Payment Flow Overview, you customized the storefront to pass the setup_future_usage
option to Stripe. So, the payment method was saved in Stripe and linked to the customer's account holder, allowing you to retrieve it later and re-capture the payment.
To create the step, create the file src/workflows/create-subscription-order/steps/get-payment-method.ts
with the following content:
1import { MedusaError, Modules } from "@medusajs/framework/utils"2import { AccountHolderDTO, CustomerDTO, PaymentMethodDTO } from "@medusajs/framework/types"3import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"4 5export interface GetPaymentMethodStepInput {6 customer: CustomerDTO & {7 account_holder: AccountHolderDTO8 }9}10 11// Since we know we are using Stripe, we can get the correct creation date from their data.12const getLatestPaymentMethod = (paymentMethods: PaymentMethodDTO[]) => {13 return paymentMethods.sort(14 (a, b) =>15 ((b.data?.created as number) ?? 0) - ((a.data?.created as number) ?? 0)16 )[0]17}18 19export const getPaymentMethodStep = createStep(20 "get-payment-method",21 async ({ customer }: GetPaymentMethodStepInput, { container }) => {22 // TODO implement step23 }24)
You create a getLatestPaymentMethod
function that receives an array of payment methods and returns the latest one based on the created
date in the data
field. This is based off of Stripe's payment method data, so if you're using a different payment provider, you may need to adjust this function.
Then, you create the getPaymentMethodStep
that receives the customer's data and account holder as an input.
Next, you'll add the implemenation of the step. Replace getPaymentMethodStep
with the following:
1export const getPaymentMethodStep = createStep(2 "get-payment-method",3 async ({ customer }: GetPaymentMethodStepInput, { container }) => {4 const paymentModuleService = container.resolve(Modules.PAYMENT)5 6 if (!customer.account_holder) {7 throw new MedusaError(8 MedusaError.Types.INVALID_DATA,9 "No account holder found for the customer while retrieving payment method"10 )11 }12 13 const paymentMethods = await paymentModuleService.listPaymentMethods(14 {15 // you can change to other payment provider16 provider_id: "pp_stripe_stripe",17 context: {18 account_holder: customer.account_holder,19 },20 }21 )22 23 if (!paymentMethods.length) {24 throw new MedusaError(25 MedusaError.Types.INVALID_DATA,26 "At least one saved payment method is required for performing a payment"27 )28 }29 30 const paymentMethodToUse = getLatestPaymentMethod(paymentMethods)31 32 return new StepResponse(33 paymentMethodToUse,34 customer.account_holder35 )36 }37)
In the step, you first check that the customer has an account holder, and throw an error otherwise. Then, you list the customer's payment methods using the Payment Module service's listPaymentMethods
method. You filter the payment methods to retrieve only the ones from the Stripe provider. So, if you're using a different payment provider, you may need to adjust the provider_id
value.
If the customer doesn't have any payment methods, you throw an error. Otherwise, you return the latest payment method found using the getLatestPaymentMethod
function.
Create createSubscriptionOrderStep (Sixth Step)#
Create the file src/workflows/create-subscription-order/steps/create-subscription-order.ts
with the following content:
13import { SUBSCRIPTION_MODULE } from "../../../modules/subscription"14 15type StepInput = {16 subscription: SubscriptionData17 cart: CartWorkflowDTO18 payment_collection: PaymentCollectionDTO19}20 21function getOrderData(cart: CartWorkflowDTO) {22 // TODO format order's data23}24 25const createSubscriptionOrderStep = createStep(26 "create-subscription-order",27 async ({ 28 subscription, cart, payment_collection,29 }: StepInput, 30 { container, context }) => {31 const linkDefs: LinkDefinition[] = []32 33 const { result: order } = await createOrderWorkflow(container)34 .run({35 input: getOrderData(cart),36 context,37 })38 39 // TODO add links to linkDefs40 41 return new StepResponse({42 order,43 linkDefs,44 }, {45 order,46 })47 },48 async ({ order }, { container }) => {49 // TODO add compensation function50 }51)52 53export default createSubscriptionOrderStep
This creates a createSubscriptionOrderStep
that uses the createOrdersWorkflow
, which Medusa provides in the @medusajs/medusa/core-flows
package. The step returns the created order and an array of links to be created.
In this step, you use a getOrderData
function to format the order’s input data.
Replace the getOrderData
function definition with the following:
1function getOrderData(cart: CartWorkflowDTO) {2 return {3 region_id: cart.region_id,4 customer_id: cart.customer_id,5 sales_channel_id: cart.sales_channel_id,6 email: cart.email,7 currency_code: cart.currency_code,8 shipping_address: {9 ...cart.shipping_address,10 id: null,11 },12 billing_address: {13 ...cart.billing_address,14 id: null,15 },16 items: cart.items,17 shipping_methods: cart.shipping_methods.map((method) => ({18 name: method.name,19 amount: method.amount,20 is_tax_inclusive: method.is_tax_inclusive,21 shipping_option_id: method.shipping_option_id,22 data: method.data,23 tax_lines: method.tax_lines.map((taxLine) => ({24 description: taxLine.description,25 tax_rate_id: taxLine.tax_rate_id,26 code: taxLine.code,27 rate: taxLine.rate,28 provider_id: taxLine.provider_id,29 })),30 adjustments: method.adjustments.map((adjustment) => ({31 code: adjustment.code,32 amount: adjustment.amount,33 description: adjustment.description,34 promotion_id: adjustment.promotion_id,35 provider_id: adjustment.provider_id,36 })),37 })),38 }39}
This formats the order’s data using the cart originally used to make the subscription purchase.
Next, to add links to the returned linkDefs
array, replace the TODO
in the step with the following:
1linkDefs.push({2 [Modules.ORDER]: {3 order_id: order.id,4 },5 [Modules.PAYMENT]: {6 payment_collection_id: payment_collection.id,7 },8},9{10 [SUBSCRIPTION_MODULE]: {11 subscription_id: subscription.id,12 },13 [Modules.ORDER]: {14 order_id: order.id,15 },16})
This adds links to be created into the linkDefs
array between the new order and payment collection, and the new order and its subscription.
Finally, replace the TODO
in the compensation function to cancel the order in case of an error:
Create updateSubscriptionStep (Ninth Step)#
Before creating the seventh step, add in src/modules/subscription/service.ts
the following new method:
1class SubscriptionModuleService extends MedusaService({2 Subscription,3}) {4 // ...5 async recordNewSubscriptionOrder(id: string) {6 const subscription = await this.retrieveSubscription(id)7 8 const orderDate = new Date()9 10 return await this.updateSubscriptions({11 id,12 last_order_date: orderDate,13 next_order_date: this.getNextOrderDate({14 last_order_date: orderDate,15 expiration_date: subscription.expiration_date,16 interval: subscription.interval,17 period: subscription.period,18 }),19 })20 }21}
The recordNewSubscriptionOrder
method updates a subscription’s last_order_date
with the current date and calculates the next order date using the getNextOrderDate
method added previously.
Then, to create the step that updates a subscription after its order is created, create the file src/workflows/create-subscription-order/steps/update-subscription.ts
with the following content:
8import SubscriptionModuleService from "../../../modules/subscription/service"9 10type StepInput = {11 subscription_id: string12}13 14const updateSubscriptionStep = createStep(15 "update-subscription",16 async ({ subscription_id }: StepInput, { container }) => {17 const subscriptionModuleService: SubscriptionModuleService = 18 container.resolve(19 SUBSCRIPTION_MODULE20 )21 22 const prevSubscriptionData = await subscriptionModuleService23 .retrieveSubscription(24 subscription_id25 )26 27 const subscription = await subscriptionModuleService28 .recordNewSubscriptionOrder(29 subscription_id30 )31 32 return new StepResponse({33 subscription,34 }, {35 prev_data: prevSubscriptionData,36 })37 },38 async ({ 39 prev_data,40 }, { container }) => {41 // TODO add compensation42 }43)44 45export default updateSubscriptionStep
This creates the updateSubscriptionStep
that updates the subscriber using the recordNewSubscriptionOrder
method of the Subscription Module’s main service. It returns the updated subscription.
Before updating the subscription, the step retrieves the old data and passes it to the compensation function to undo the changes on the subscription.
So, replace the TODO
in the compensation function with the following:
1const subscriptionModuleService: SubscriptionModuleService = 2 container.resolve(3 SUBSCRIPTION_MODULE4 )5 6await subscriptionModuleService.updateSubscriptions({7 id: prev_data.id,8 last_order_date: prev_data.last_order_date,9 next_order_date: prev_data.next_order_date,10})
This updates the subscription’s last_order_date
and next_order_date
properties to the values before the update.
Create Workflow#
Finally, create the file src/workflows/create-subscription-order/index.ts
with the following content:
17import { getPaymentMethodStep } from "./steps/get-payment-method"18 19type WorkflowInput = {20 subscription: SubscriptionData21}22 23const createSubscriptionOrderWorkflow = createWorkflow(24 "create-subscription-order",25 (input: WorkflowInput) => {26 const { data: subscriptions } = useQueryGraphStep({27 entity: "subscription",28 fields: [29 "*",30 "cart.*",31 "cart.items.*",32 "cart.items.tax_lines.*",33 "cart.items.adjustments.*",34 "cart.shipping_address.*",35 "cart.billing_address.*",36 "cart.shipping_methods.*",37 "cart.shipping_methods.tax_lines.*",38 "cart.shipping_methods.adjustments.*",39 "cart.payment_collection.*",40 "cart.payment_collection.payment_sessions.*",41 "cart.customer.*",42 "cart.customer.account_holder.*",43 ],44 filters: {45 id: input.subscription.id,46 },47 options: {48 throwIfKeyNotFound: true,49 },50 })51 52 const paymentCollectionData = transform({53 subscriptions,54 }, (data) => {55 const cart = data.subscriptions[0].cart56 return {57 currency_code: cart.currency_code,58 amount: cart.payment_collection.amount,59 metadata: cart.payment_collection.metadata,60 }61 })62 63 const payment_collection = createPaymentCollectionsStep([64 paymentCollectionData,65 ])[0]66 67 const defaultPaymentMethod = getPaymentMethodStep({68 customer: subscriptions[0].cart.customer,69 })70 71 const paymentSessionData = transform({72 payment_collection,73 subscriptions,74 defaultPaymentMethod,75 }, (data) => {76 return {77 payment_collection_id: data.payment_collection.id,78 provider_id: "pp_stripe_stripe",79 customer_id: data.subscriptions[0].cart.customer.id,80 data: {81 payment_method: data.defaultPaymentMethod.id,82 off_session: true,83 confirm: true,84 capture_method: "automatic",85 },86 }87 })88 89 const paymentSession = createPaymentSessionsWorkflow.runAsStep({90 input: paymentSessionData,91 })92 93 const payment = authorizePaymentSessionStep({94 id: paymentSession.id,95 context: paymentSession.context,96 })97 98 const { order, linkDefs } = createSubscriptionOrderStep({99 subscription: input.subscription,100 cart: carts[0],101 payment_collection,102 })103 104 createRemoteLinkStep(linkDefs)105 106 capturePaymentStep({107 payment_id: payment.id,108 amount: payment.amount,109 })110 111 updateSubscriptionStep({112 subscription_id: input.subscription.id,113 })114 115 return new WorkflowResponse({116 order,117 })118 }119)120 121export default createSubscriptionOrderWorkflow
The workflow runs the following steps:
useQueryGraphStep
to retrieve the details of the cart linked to the subscription.createPaymentCollectionsStep
to create a payment collection using the same information in the cart.getPaymentMethodStep
to get the customer's saved payment method.createPaymentSessionsWorkflow
to create a payment session in the payment collection from the previous step. You prepare the data to create the payment session using transform from the Workflows SDK.- Since you're capturing the payment with Stripe, you must pass in the payment session's
data
object the following properties:payment_method
: the ID of the payment method saved in Stripe.off_session
:true
to indicate that the payment is off-session.confirm
:true
to confirm the payment.capture_method
:automatic
to automatically capture the payment.
- If you're using a payment provider other than Stripe, you'll need to adjust the
provider_id
value and thedata
object properties depending on what the provider expects.
- Since you're capturing the payment with Stripe, you must pass in the payment session's
authorizePaymentSessionStep
to authorize the payment session created from the first step.createSubscriptionOrderStep
to create the new order for the subscription.createRemoteLinkStep
to create links returned by the previous step.capturePaymentStep
to capture the order’s payment.updateSubscriptionStep
to update the subscription’slast_order_date
andnext_order_date
.
transform
for data manipulation. Learn more about these constraints in this documentation.In the next step, you’ll execute the workflow in a scheduled job.
Further Reads#
Step 13: Create New Subscription Orders Scheduled Job#
A scheduled job is an asynchronous function executed at a specified interval pattern. Use scheduled jobs to execute a task at a regular interval.
In this step, you’ll create a scheduled job that runs once a day. It finds all subscriptions whose next_order_date
property is the current date and uses the workflow from the previous step to create an order for them.
Create the file src/jobs/create-subscription-orders.ts
with the following content:
6import { SubscriptionStatus } from "../modules/subscription/types"7 8export default async function createSubscriptionOrdersJob(9 container: MedusaContainer10) {11 const subscriptionModuleService: SubscriptionModuleService =12 container.resolve(SUBSCRIPTION_MODULE)13 const logger = container.resolve("logger")14 15 let page = 016 const limit = 2017 let pagesCount = 018 19 do {20 const beginningToday = moment(new Date()).set({21 second: 0,22 minute: 0,23 hour: 0,24 })25 .toDate()26 const endToday = moment(new Date()).set({27 second: 59,28 minute: 59,29 hour: 23,30 })31 .toDate()32 33 const [subscriptions, count] = await subscriptionModuleService34 .listAndCountSubscriptions({35 next_order_date: {36 $gte: beginningToday,37 $lte: endToday,38 },39 status: SubscriptionStatus.ACTIVE,40 }, {41 skip: page * limit,42 take: limit,43 }) 44 45 // TODO create orders for subscriptions46 47 if (!pagesCount) {48 pagesCount = count / limit49 }50 51 page++52 } while (page < pagesCount - 1)53}54 55export const config = {56 name: "create-subscription-orders",57 schedule: "0 0 * * *", // Every day at midnight58}
This creates a scheduled job that runs once a day.
In the scheduled job, you retrieve subscriptions whose next_order_date
is between the beginning and end of today, and whose status
is active
. You also support paginating the subscriptions in case there are more than 20
matching those filters.
To create orders for the subscriptions returned, replace the TODO
with the following:
1await Promise.all(2 subscriptions.map(async (subscription) => {3 try {4 const { result } = await createSubscriptionOrderWorkflow(container)5 .run({6 input: {7 subscription,8 },9 })10 11 logger.info(`Created new order ${12 result.order.id13 } for subscription ${subscription.id}`)14 } catch (e) {15 logger.error(16 `Error creating a new order for subscription ${subscription.id}`,17 e18 )19 }20 })21)
This loops over the returned subscriptions and executes the createSubscriptionOrderWorkflow
from the previous step to create the order.
Further Reads#
Step 14: Expire Subscriptions Scheduled Job#
In this step, you’ll create a scheduled job that finds subscriptions whose expiration_date
is the current date and marks them as expired.
Before creating the scheduled job, add in src/modules/subscription/service.ts
a new method:
1class SubscriptionModuleService extends MedusaService({2 Subscription,3}) {4 // ...5 async expireSubscription(id: string | string[]): Promise<SubscriptionData[]> {6 const input = Array.isArray(id) ? id : [id]7 8 return await this.updateSubscriptions({9 selector: {10 id: input,11 },12 data: {13 next_order_date: null,14 status: SubscriptionStatus.EXPIRED,15 },16 })17 }18}
The expireSubscription
updates the following properties of the specified subscriptions:
- Set
next_order_date
tonull
as there are no more orders. - Set the
status
toexpired
.
Then, create the file src/jobs/expire-subscription-orders.ts
with the following content:
5import { SubscriptionStatus } from "../modules/subscription/types"6 7export default async function expireSubscriptionOrdersJob(8 container: MedusaContainer9) {10 const subscriptionModuleService: SubscriptionModuleService =11 container.resolve(SUBSCRIPTION_MODULE)12 const logger = container.resolve("logger")13 14 let page = 015 const limit = 2016 let pagesCount = 017 18 do {19 const beginningToday = moment(new Date()).set({20 second: 0,21 minute: 0,22 hour: 0,23 })24 .toDate()25 const endToday = moment(new Date()).set({26 second: 59,27 minute: 59,28 hour: 23,29 })30 .toDate()31 32 const [subscriptions, count] = await subscriptionModuleService33 .listAndCountSubscriptions({34 expiration_date: {35 $gte: beginningToday,36 $lte: endToday,37 },38 status: SubscriptionStatus.ACTIVE,39 }, {40 skip: page * limit,41 take: limit,42 }) 43 44 const subscriptionIds = subscriptions.map((subscription) => subscription.id)45 46 await subscriptionModuleService.expireSubscription(subscriptionIds)47 48 logger.log(`Expired ${subscriptionIds}.`)49 50 if (!pagesCount) {51 pagesCount = count / limit52 }53 54 page++55 } while (page < pagesCount - 1)56}57 58export const config = {59 name: "expire-subscriptions",60 schedule: "0 0 * * *", // Every day at midnight61}
This scheduled job runs once a day.
In the scheduled job, you find all subscriptions whose expiration_date
is between the beginning and end of today and their status is active
. Then, you use the expireSubscription
method to expire those subscriptions.
You also implement pagination in case there are more than 20
expired subscriptions.
Step 15: Add Customer API Routes#
In this step, you’ll add two API routes for authenticated customers:
- View their list of subscriptions.
- Cancel a subscription.
Create Subscriptions List API Route#
Create the file src/api/store/customers/me/subscriptions/route.ts
with the following content:
1import { 2 AuthenticatedMedusaRequest, 3 MedusaResponse,4} from "@medusajs/framework/http"5import { ContainerRegistrationKeys } from "@medusajs/framework/utils"6 7export const GET = async (8 req: AuthenticatedMedusaRequest,9 res: MedusaResponse10) => {11 const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)12 13 const { data: [customer] } = await query.graph({14 entity: "customer",15 fields: [16 "subscriptions.*",17 ],18 filters: {19 id: [req.auth_context.actor_id],20 },21 })22 23 res.json({24 subscriptions: customer.subscriptions,25 })26}
This adds an API route at /store/customers/me/subscriptions
.
In the route handler, you retrieve the authenticated customer’s subscriptions using Query and return them in the response.
Cancel Subscription API Route#
Before creating this API route, add in src/modules/subscription/service.ts
the following new method:
1class SubscriptionModuleService extends MedusaService({2 Subscription,3}) {4 // ...5 6 async cancelSubscriptions(7 id: string | string[]): Promise<SubscriptionData[]> {8 const input = Array.isArray(id) ? id : [id]9 10 return await this.updateSubscriptions({11 selector: {12 id: input,13 },14 data: {15 next_order_date: null,16 status: SubscriptionStatus.CANCELED,17 },18 })19 }20}
The cancelSubscriptions
method updates the specified subscribers to set their next_order_date
to null
and their status to canceled
.
Then, create the file src/api/store/customers/me/subscriptions/[id]/route.ts
with the following content:
1import { 2 AuthenticatedMedusaRequest, 3 MedusaResponse,4} from "@medusajs/framework/http"5import SubscriptionModuleService from "../../../../../../modules/subscription/service"6import { 7 SUBSCRIPTION_MODULE,8} from "../../../../../../modules/subscription"9 10export const POST = async (11 req: AuthenticatedMedusaRequest,12 res: MedusaResponse13) => {14 const subscriptionModuleService: SubscriptionModuleService =15 req.scope.resolve(SUBSCRIPTION_MODULE)16 17 const subscription = await subscriptionModuleService.cancelSubscriptions(18 req.params.id19 )20 21 res.json({22 subscription,23 })24}
This adds an API route at /store/customers/me/subscriptions/[id]
. In the route handler, you use the cancelSubscriptions
method added above to cancel the subscription whose ID is passed as a path parameter.
Test it Out#
To test out the above API routes, first, log in as a customer with the following request:
Make sure to replace the email
and password
with the correct credentials.
Then, send a GET
request to /store/customers/me/subscriptions
to retrieve the customer’s subscriptions:
Where {token}
is the token retrieved from the previous request.
To cancel a subscription, send a POST
request to /store/customers/me/subscriptions/[id]
, replacing the [id]
with the ID of the subscription to cancel:
Next Steps#
The next steps of this example depend on your use case. This section provides some insight into implementing them.
Use Existing Features#
To manage the orders created for a subscription, or other functionalities, use Medusa’s existing Admin API routes.
Link Subscriptions to Other Data Models#
If your use case requires a subscription to have relations to other existing data models, you can create links to them, similar to step four.
For example, you can link a subscription to a promotion to offer a subscription-specific discount.
Storefront Development#
Medusa provides a Next.js Starter storefront that you can customize to your use case. You can also create a custom storefront. To learn how visit the Storefront Development section.