|
1
|
--- |
|
2
|
products: |
|
3
|
- order |
|
4
|
- payment |
|
5
|
- cart |
|
6
|
- customer |
|
7
|
--- |
|
8
|
|
|
9
|
import { Github, PlaySolid, EllipsisHorizontal } from "@medusajs/icons" |
|
10
|
import { Prerequisites, InlineIcon } from "docs-ui" |
|
11
|
|
|
12
|
export const metadata = { |
|
13
|
title: `Subscriptions Recipe`, |
|
14
|
} |
|
15
|
|
|
16
|
# {metadata.title} |
|
17
|
|
|
18
|
In this guide, you'll learn how to support subscription purchases with Medusa. |
|
19
|
|
|
20
|
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. |
|
21
|
|
|
22
|
In this guide, you'll customize Medusa to implement subscription-based purchases with the following features: |
|
23
|
|
|
24
|
1. Subscription-based purchases for a specified interval (monthly or yearly) and period. |
|
25
|
2. Customize the admin dashboard to view subscriptions and associated orders. |
|
26
|
3. Automatic renewal of the subscription. |
|
27
|
4. Automatic subscription expiration tracking. |
|
28
|
5. Allow customers to view and cancel their subscriptions. |
|
29
|
|
|
30
|
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. |
|
31
|
|
|
32
|
<Note> |
|
33
|
|
|
34
|
This guide provides an example of an approach to implement subscriptions. You're free to choose a different approach using the Medusa Framework. |
|
35
|
|
|
36
|
</Note> |
|
37
|
|
|
38
|
<CardList items={[ |
|
39
|
{ |
|
40
|
href: "https://github.com/medusajs/examples/tree/main/subscription", |
|
41
|
title: "Subscription Example Repository", |
|
42
|
text: "Find the full code for this recipe example in this repository.", |
|
43
|
icon: Github, |
|
44
|
}, |
|
45
|
{ |
|
46
|
href: "https://res.cloudinary.com/dza7lstvk/raw/upload/v1721125608/OpenApi/Subscriptions_OpenApi_b371x4.yml", |
|
47
|
title: "OpenApi Specs for Postman", |
|
48
|
text: "Import this OpenApi Specs file into tools like Postman.", |
|
49
|
icon: PlaySolid, |
|
50
|
}, |
|
51
|
]} /> |
|
52
|
|
|
53
|
--- |
|
54
|
|
|
55
|
## Step 1: Install a Medusa Application |
|
56
|
|
|
57
|
<Prerequisites items={[ |
|
58
|
{ |
|
59
|
text: "Node.js v20.19.0+ or v22.12.0+", |
|
60
|
link: "https://nodejs.org/en/download" |
|
61
|
}, |
|
62
|
{ |
|
63
|
text: "Git CLI tool", |
|
64
|
link: "https://git-scm.com/downloads" |
|
65
|
}, |
|
66
|
{ |
|
67
|
text: "PostgreSQL", |
|
68
|
link: "https://www.postgresql.org/download/" |
|
69
|
} |
|
70
|
]} /> |
|
71
|
|
|
72
|
Start by installing the Medusa application on your machine with the following command: |
|
73
|
|
|
74
|
```bash npx2yarnExec |
|
75
|
npx create-medusa-app@latest |
|
76
|
``` |
|
77
|
|
|
78
|
You'll first be asked for the project's name. Then, when you're asked whether you want to install the Next.js Starter Storefront, choose `Y` for yes. |
|
79
|
|
|
80
|
the installation process will start, which will install the Medusa application as a monorepository in a directory with your project's name. The backend is installed in the `apps/backend` directory, and the Next.js Starter Storefront is installed in the `apps/storefront` directory. |
|
81
|
|
|
82
|
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. |
|
83
|
|
|
84
|
Afterwards, you can log in with the new user and explore the dashboard. The Next.js Starter Storefront is also running at `http://localhost:8000`. |
|
85
|
|
|
86
|
<Note title="Ran into Errors?"> |
|
87
|
|
|
88
|
Check out the [troubleshooting guides](../../../../troubleshooting/create-medusa-app-errors/page.mdx) for help. |
|
89
|
|
|
90
|
</Note> |
|
91
|
|
|
92
|
<Note> |
|
93
|
|
|
94
|
In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project. |
|
95
|
|
|
96
|
</Note> |
|
97
|
|
|
98
|
--- |
|
99
|
|
|
100
|
## Step 2: Configure Stripe Module Provider |
|
101
|
|
|
102
|
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](../../../../commerce-modules/payment/payment-provider/stripe/page.mdx) in your Medusa application. |
|
103
|
|
|
104
|
<Prerequisites items={[ |
|
105
|
{ |
|
106
|
text: "Stripe account", |
|
107
|
link: "https://stripe.com/" |
|
108
|
}, |
|
109
|
{ |
|
110
|
text: "Stripe Secret API Key", |
|
111
|
link: "https://support.stripe.com/questions/locate-api-keys-in-the-dashboard" |
|
112
|
}, |
|
113
|
]} /> |
|
114
|
|
|
115
|
To add the Stripe Module Provider to the Medusa configurations, add the following to the `medusa-config.ts` file: |
|
116
|
|
|
117
|
```ts title="medusa-config.ts" |
|
118
|
module.exports = defineConfig({ |
|
119
|
// ... |
|
120
|
modules: [ |
|
121
|
{ |
|
122
|
resolve: "@medusajs/medusa/payment", |
|
123
|
options: { |
|
124
|
providers: [ |
|
125
|
{ |
|
126
|
resolve: "@medusajs/medusa/payment-stripe", |
|
127
|
id: "stripe", |
|
128
|
options: { |
|
129
|
apiKey: process.env.STRIPE_API_KEY, |
|
130
|
}, |
|
131
|
}, |
|
132
|
], |
|
133
|
}, |
|
134
|
}, |
|
135
|
], |
|
136
|
}) |
|
137
|
``` |
|
138
|
|
|
139
|
The Medusa configurations accept a `modules` property to add modules to your application. You'll learn more about modules in the next section. |
|
140
|
|
|
141
|
You add the Stripe Module Provider to the [Payment Module](../../../../commerce-modules/payment/page.mdx)'s options. Learn more about these options in the [Payment Module's options documentation](../../../../commerce-modules/payment/module-options/page.mdx). |
|
142
|
|
|
143
|
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: |
|
144
|
|
|
145
|
```plain |
|
146
|
STRIPE_API_KEY=sk_test_51J... |
|
147
|
``` |
|
148
|
|
|
149
|
Where `sk_test_51J...` is your Stripe Secret API Key. |
|
150
|
|
|
151
|
<Note> |
|
152
|
|
|
153
|
Learn more about other Stripe options and configurations in the [Stripe Module Provider documentation](../../../../commerce-modules/payment/payment-provider/stripe/page.mdx). |
|
154
|
|
|
155
|
</Note> |
|
156
|
|
|
157
|
### Enable Stripe in Regions |
|
158
|
|
|
159
|
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. |
|
160
|
|
|
161
|
To do that, start the Medusa application: |
|
162
|
|
|
163
|
```bash npm2yarn |
|
164
|
npm run dev |
|
165
|
``` |
|
166
|
|
|
167
|
Then, open the dashboard at `localhost:9000/app`. After you log in: |
|
168
|
|
|
169
|
1. Go to Settings -> Regions. |
|
170
|
2. Click on a region to edit. |
|
171
|
3. Click on the <InlineIcon Icon={EllipsisHorizontal} alt="three-dots" /> icon at the top right of the first section. |
|
172
|
4. In the side window that opens, edit the region's payment provider to choose "Stripe (STRIPE)". |
|
173
|
5. Once you're done, click the Save button. |
|
174
|
|
|
175
|
 |
|
176
|
|
|
177
|
--- |
|
178
|
|
|
179
|
## Step 3: Create Subscription Module |
|
180
|
|
|
181
|
Medusa creates commerce features in modules. For example, product features and data models are created in the Product Module. |
|
182
|
|
|
183
|
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. |
|
184
|
|
|
185
|
So, you'll create a subscription module that holds the data models related to a subscription and allows you to manage them. |
|
186
|
|
|
187
|
Create the directory `src/modules/subscription`. |
|
188
|
|
|
189
|
### Create Data Models |
|
190
|
|
|
191
|
Create the file `src/modules/subscription/models/subscription.ts` with the following content: |
|
192
|
|
|
193
|
export const subscriptionHighlights = [ |
|
194
|
["8", "interval", "Whether the subscription is renewed monthly or yearly."], |
|
195
|
["9", "period", "How many months/years before a new order is created for the subscription."], |
|
196
|
["10", "subscription_date", "When the subscription was created."], |
|
197
|
["11", "last_order_date", "When the last time a new order was created for the subscription"], |
|
198
|
["12", "next_order_date", "When the subscription’s next order should be created."], |
|
199
|
["12", "nullable", "In case the subscription doesn’t have a next date or has expired."], |
|
200
|
["13", "expiration_date", "When the subscription expires."], |
|
201
|
["14", "metadata", "Any additional data can be held in this property."] |
|
202
|
] |
|
203
|
|
|
204
|
```ts title="src/modules/subscription/models/subscription.ts" highlights={subscriptionHighlights} |
|
205
|
import { model } from "@medusajs/framework/utils" |
|
206
|
import { SubscriptionInterval, SubscriptionStatus } from "../types" |
|
207
|
|
|
208
|
const Subscription = model.define("subscription", { |
|
209
|
id: model.id().primaryKey(), |
|
210
|
status: model.enum(SubscriptionStatus) |
|
211
|
.default(SubscriptionStatus.ACTIVE), |
|
212
|
interval: model.enum(SubscriptionInterval), |
|
213
|
period: model.number(), |
|
214
|
subscription_date: model.dateTime(), |
|
215
|
last_order_date: model.dateTime(), |
|
216
|
next_order_date: model.dateTime().index().nullable(), |
|
217
|
expiration_date: model.dateTime().index(), |
|
218
|
metadata: model.json().nullable(), |
|
219
|
}) |
|
220
|
|
|
221
|
export default Subscription |
|
222
|
``` |
|
223
|
|
|
224
|
This creates a `Subscription` data model that holds a subscription’s details, including: |
|
225
|
|
|
226
|
- `interval`: indicates whether the subscription is renewed monthly or yearly. |
|
227
|
- `period`: a number indicating how many months/years before a new order is created for the subscription. For example, if `period` is `3` and `interval` is `monthly`, then a new order is created every three months. |
|
228
|
- `subscription_date`: when the subscription was created. |
|
229
|
- `last_order_date`: when the last time a new order was created for the subscription. |
|
230
|
- `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. |
|
231
|
- `expiration_date`: when the subscription expires. |
|
232
|
- `metadata`: any additional data can be held in this JSON property. |
|
233
|
|
|
234
|
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: |
|
235
|
|
|
236
|
```ts title="src/modules/subscription/types/index.ts" |
|
237
|
export enum SubscriptionStatus { |
|
238
|
ACTIVE = "active", |
|
239
|
CANCELED = "canceled", |
|
240
|
EXPIRED = "expired", |
|
241
|
FAILED = "failed" |
|
242
|
} |
|
243
|
|
|
244
|
export enum SubscriptionInterval { |
|
245
|
MONTHLY = "monthly", |
|
246
|
YEARLY = "yearly" |
|
247
|
} |
|
248
|
``` |
|
249
|
|
|
250
|
### Create Main Service |
|
251
|
|
|
252
|
Create the module’s main service in the file `src/modules/subscription/service.ts` with the following content: |
|
253
|
|
|
254
|
```ts title="src/modules/subscription/service.ts" |
|
255
|
import { MedusaService } from "@medusajs/framework/utils" |
|
256
|
import Subscription from "./models/subscription" |
|
257
|
|
|
258
|
class SubscriptionModuleService extends MedusaService({ |
|
259
|
Subscription, |
|
260
|
}) { |
|
261
|
} |
|
262
|
|
|
263
|
export default SubscriptionModuleService |
|
264
|
``` |
|
265
|
|
|
266
|
The main service extends the service factory to provide data-management features on the `Subscription` data model. |
|
267
|
|
|
268
|
### Create Module Definition File |
|
269
|
|
|
270
|
Create the file `src/modules/subscription/index.ts` that holds the module’s definition: |
|
271
|
|
|
272
|
```ts title="src/modules/subscription/index.ts" |
|
273
|
import { Module } from "@medusajs/framework/utils" |
|
274
|
import SubscriptionModuleService from "./service" |
|
275
|
|
|
276
|
export const SUBSCRIPTION_MODULE = "subscriptionModuleService" |
|
277
|
|
|
278
|
export default Module(SUBSCRIPTION_MODULE, { |
|
279
|
service: SubscriptionModuleService, |
|
280
|
}) |
|
281
|
``` |
|
282
|
|
|
283
|
This sets the module’s name to `subscriptionModuleService` and its main service to `SubscriptionModuleService`. |
|
284
|
|
|
285
|
### Register Module in Medusa’s Configuration |
|
286
|
|
|
287
|
Finally, add the module into `medusa-config.ts`: |
|
288
|
|
|
289
|
```ts title="medusa-config.ts" |
|
290
|
module.exports = defineConfig({ |
|
291
|
// ... |
|
292
|
modules: [ |
|
293
|
// ... |
|
294
|
{ |
|
295
|
resolve: "./src/modules/subscription", |
|
296
|
}, |
|
297
|
], |
|
298
|
}) |
|
299
|
``` |
|
300
|
|
|
301
|
### Further Read |
|
302
|
|
|
303
|
- [How to Create a Module](!docs!/learn/fundamentals/modules) |
|
304
|
- [How to Create a Data Model](!docs!/learn/fundamentals/modules#1-create-data-model) |
|
305
|
- [Learn more about the service factory](!docs!/learn/fundamentals/modules/service-factory). |
|
306
|
|
|
307
|
--- |
|
308
|
|
|
309
|
## Step 4: Define Links |
|
310
|
|
|
311
|
Modules are isolated in Medusa, making them reusable, replaceable, and integrable in your application without side effects. |
|
312
|
|
|
313
|
So, you can't have relations between data models in modules. Instead, you define a link between them. |
|
314
|
|
|
315
|
Links are relations between data models of different modules that maintain the isolation between the modules. |
|
316
|
|
|
317
|
In this step, you’ll define links between the Subscription Module’s `Subscription` data model and the data models of Medusa’s Commerce Modules: |
|
318
|
|
|
319
|
1. Link between the `Subscription` data model and the Cart Module's `Cart` model. |
|
320
|
2. Link between the `Subscription` data model and the Customer Module's `Customer` model. |
|
321
|
3. Link between the `Subscription` data model and the Order Module's `Order` model. |
|
322
|
|
|
323
|
### Define a Link to Cart |
|
324
|
|
|
325
|
To link a subscription to the cart used to make the purchase, create the file `src/links/subscription-cart.ts` with the following content: |
|
326
|
|
|
327
|
```ts title="src/links/subscription-cart.ts" |
|
328
|
import { defineLink } from "@medusajs/framework/utils" |
|
329
|
import SubscriptionModule from "../modules/subscription" |
|
330
|
import CartModule from "@medusajs/medusa/cart" |
|
331
|
|
|
332
|
export default defineLink( |
|
333
|
SubscriptionModule.linkable.subscription, |
|
334
|
CartModule.linkable.cart |
|
335
|
) |
|
336
|
``` |
|
337
|
|
|
338
|
This defines a link between the `Subscription` data model and the Cart Module’s `Cart` data model. |
|
339
|
|
|
340
|
<Note title="Tip"> |
|
341
|
|
|
342
|
When you create a new order for the subscription, you’ll retrieve the linked cart and use the same shipping and payment details the customer supplied when the purchase was made. |
|
343
|
|
|
344
|
</Note> |
|
345
|
|
|
346
|
### Define a Link to Customer |
|
347
|
|
|
348
|
To link a subscription to the customer who purchased it, create the file `src/links/subscription-customer.ts` with the following content: |
|
349
|
|
|
350
|
```ts title="src/links/subscription-customer.ts" |
|
351
|
import { defineLink } from "@medusajs/framework/utils" |
|
352
|
import SubscriptionModule from "../modules/subscription" |
|
353
|
import CustomerModule from "@medusajs/medusa/customer" |
|
354
|
|
|
355
|
export default defineLink( |
|
356
|
{ |
|
357
|
linkable: SubscriptionModule.linkable.subscription.id, |
|
358
|
isList: true, |
|
359
|
}, |
|
360
|
CustomerModule.linkable.customer |
|
361
|
) |
|
362
|
``` |
|
363
|
|
|
364
|
This defines a list link to the `Subscription` data model, since a customer may have multiple subscriptions. |
|
365
|
|
|
366
|
### Define a Link to Order |
|
367
|
|
|
368
|
To link a subscription to the orders created for it, create the file `src/links/subscription-order.ts` with the following content: |
|
369
|
|
|
370
|
```ts title="src/links/subscription-order.ts" |
|
371
|
import { defineLink } from "@medusajs/framework/utils" |
|
372
|
import SubscriptionModule from "../modules/subscription" |
|
373
|
import OrderModule from "@medusajs/medusa/order" |
|
374
|
|
|
375
|
export default defineLink( |
|
376
|
SubscriptionModule.linkable.subscription, |
|
377
|
{ |
|
378
|
linkable: OrderModule.linkable.order.id, |
|
379
|
isList: true, |
|
380
|
} |
|
381
|
) |
|
382
|
``` |
|
383
|
|
|
384
|
This defines a list link to the `Order` data model since a subscription has multiple orders. |
|
385
|
|
|
386
|
### Further Reads |
|
387
|
|
|
388
|
- [How to Define a Link](!docs!/learn/fundamentals/module-links) |
|
389
|
|
|
390
|
--- |
|
391
|
|
|
392
|
## Step 5: Run Migrations |
|
393
|
|
|
394
|
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: |
|
395
|
|
|
396
|
```bash npx2yarn |
|
397
|
npx medusa db:generate subscriptionModuleService |
|
398
|
``` |
|
399
|
|
|
400
|
This generates a migration in the `src/modules/subscriptions/migrations` directory. |
|
401
|
|
|
402
|
Then, to reflect the migration and links in the database, run the following command: |
|
403
|
|
|
404
|
```bash npx2yarn |
|
405
|
npx medusa db:migrate |
|
406
|
``` |
|
407
|
|
|
408
|
--- |
|
409
|
|
|
410
|
## Step 6: Override createSubscriptions Method in Service |
|
411
|
|
|
412
|
Since the Subscription Module’s main service extends the service factory, it has a generic `createSubscriptions` method that creates one or more subscriptions. |
|
413
|
|
|
414
|
In this step, you’ll override it to add custom logic to the subscription creation that sets its date properties. |
|
415
|
|
|
416
|
### Install moment Library |
|
417
|
|
|
418
|
Before you start, install the [Moment.js library](https://momentjs.com/) to help manipulate and format dates with the following command: |
|
419
|
|
|
420
|
```bash npm2yarn |
|
421
|
npm install moment |
|
422
|
``` |
|
423
|
|
|
424
|
### Add getNextOrderDate Method |
|
425
|
|
|
426
|
In `src/modules/subscription/service.ts`, add the following method to `SubscriptionModuleService`: |
|
427
|
|
|
428
|
export const getNextOrderDateHighlights = [ |
|
429
|
["31", "isAfter", "If the calculated next day is after the expiration date, `null` is returned instead."] |
|
430
|
] |
|
431
|
|
|
432
|
```ts title="src/modules/subscription/service.ts" highlights={getNextOrderDateHighlights} |
|
433
|
// ... |
|
434
|
import moment from "moment" |
|
435
|
import { |
|
436
|
CreateSubscriptionData, |
|
437
|
SubscriptionData, |
|
438
|
SubscriptionInterval, |
|
439
|
} from "./types" |
|
440
|
|
|
441
|
class SubscriptionModuleService extends MedusaService({ |
|
442
|
Subscription, |
|
443
|
}) { |
|
444
|
getNextOrderDate({ |
|
445
|
last_order_date, |
|
446
|
expiration_date, |
|
447
|
interval, |
|
448
|
period, |
|
449
|
}: { |
|
450
|
last_order_date: Date |
|
451
|
expiration_date: Date |
|
452
|
interval: SubscriptionInterval, |
|
453
|
period: number |
|
454
|
}): Date | null { |
|
455
|
const nextOrderDate = moment(last_order_date) |
|
456
|
.add( |
|
457
|
period, |
|
458
|
interval === SubscriptionInterval.MONTHLY ? |
|
459
|
"month" : "year" |
|
460
|
) |
|
461
|
const expirationMomentDate = moment(expiration_date) |
|
462
|
|
|
463
|
return nextOrderDate.isAfter(expirationMomentDate) ? |
|
464
|
null : nextOrderDate.toDate() |
|
465
|
} |
|
466
|
} |
|
467
|
``` |
|
468
|
|
|
469
|
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. |
|
470
|
|
|
471
|
If the next order date, calculated from the last order date, exceeds the expiration date, `null` is returned. |
|
472
|
|
|
473
|
### Add getExpirationDate Method |
|
474
|
|
|
475
|
In the same file, add the following method to `SubscriptionModuleService`: |
|
476
|
|
|
477
|
```ts title="src/modules/subscription/service.ts" |
|
478
|
class SubscriptionModuleService extends MedusaService({ |
|
479
|
Subscription, |
|
480
|
}) { |
|
481
|
// ... |
|
482
|
getExpirationDate({ |
|
483
|
subscription_date, |
|
484
|
interval, |
|
485
|
period, |
|
486
|
}: { |
|
487
|
subscription_date: Date, |
|
488
|
interval: SubscriptionInterval, |
|
489
|
period: number |
|
490
|
}) { |
|
491
|
return moment(subscription_date) |
|
492
|
.add( |
|
493
|
period, |
|
494
|
interval === SubscriptionInterval.MONTHLY ? |
|
495
|
"month" : "year" |
|
496
|
).toDate() |
|
497
|
} |
|
498
|
} |
|
499
|
``` |
|
500
|
|
|
501
|
The `getExpirationDate` method accepts a subscription’s date, interval, and period to calculate and return its expiration date. |
|
502
|
|
|
503
|
### Override the createSubscriptions Method |
|
504
|
|
|
505
|
Before overriding the `createSubscriptions` method, add the following types to `src/modules/subscription/types/index.ts`: |
|
506
|
|
|
507
|
```ts title="src/modules/subscription/types/index.ts" |
|
508
|
import { InferTypeOf } from "@medusajs/framework/types" |
|
509
|
import Subscription from "../models/subscription" |
|
510
|
|
|
511
|
// ... |
|
512
|
|
|
513
|
export type CreateSubscriptionData = { |
|
514
|
interval: SubscriptionInterval |
|
515
|
period: number |
|
516
|
status?: SubscriptionStatus |
|
517
|
subscription_date?: Date |
|
518
|
metadata?: Record<string, unknown> |
|
519
|
} |
|
520
|
|
|
521
|
export type SubscriptionData = InferTypeOf<typeof Subscription> |
|
522
|
``` |
|
523
|
|
|
524
|
<Note title="Tip"> |
|
525
|
|
|
526
|
Since the `Subscription` data model is a variable, use `InferTypeOf` to infer its type. |
|
527
|
|
|
528
|
</Note> |
|
529
|
|
|
530
|
Then, in `src/modules/subscription/service.ts`, add the following to override the `createSubscriptions` method: |
|
531
|
|
|
532
|
```ts title="src/modules/subscription/service.ts" |
|
533
|
class SubscriptionModuleService extends MedusaService({ |
|
534
|
Subscription, |
|
535
|
}) { |
|
536
|
// ... |
|
537
|
|
|
538
|
// @ts-expect-error |
|
539
|
async createSubscriptions( |
|
540
|
data: CreateSubscriptionData | CreateSubscriptionData[] |
|
541
|
): Promise<SubscriptionData[]> { |
|
542
|
const input = Array.isArray(data) ? data : [data] |
|
543
|
|
|
544
|
const subscriptions = await Promise.all( |
|
545
|
input.map(async (subscription) => { |
|
546
|
const subscriptionDate = subscription.subscription_date || new Date() |
|
547
|
const expirationDate = this.getExpirationDate({ |
|
548
|
subscription_date: subscriptionDate, |
|
549
|
interval: subscription.interval, |
|
550
|
period: subscription.period, |
|
551
|
}) |
|
552
|
|
|
553
|
return await super.createSubscriptions({ |
|
554
|
...subscription, |
|
555
|
subscription_date: subscriptionDate, |
|
556
|
last_order_date: subscriptionDate, |
|
557
|
next_order_date: this.getNextOrderDate({ |
|
558
|
last_order_date: subscriptionDate, |
|
559
|
expiration_date: expirationDate, |
|
560
|
interval: subscription.interval, |
|
561
|
period: subscription.period, |
|
562
|
}), |
|
563
|
expiration_date: expirationDate, |
|
564
|
}) |
|
565
|
}) |
|
566
|
) |
|
567
|
|
|
568
|
return subscriptions |
|
569
|
} |
|
570
|
} |
|
571
|
``` |
|
572
|
|
|
573
|
The `createSubscriptions` calculates for each subscription the expiration and next order dates using the methods created earlier. It creates and returns the subscriptions. |
|
574
|
|
|
575
|
This method is used in the next step. |
|
576
|
|
|
577
|
--- |
|
578
|
|
|
579
|
## Step 7: Create Subscription Workflow |
|
580
|
|
|
581
|
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. |
|
582
|
|
|
583
|
In this step, you’ll create the workflow that you’ll execute when a customer purchases a subscription. |
|
584
|
|
|
585
|
The workflow accepts a cart’s ID, and it has three steps: |
|
586
|
|
|
587
|
1. Create the order from the cart. |
|
588
|
2. Create a subscription. |
|
589
|
3. Link the subscription to the order, cart, and customer. |
|
590
|
|
|
591
|
Medusa provides the first and last steps in the `@medusajs/medusa/core-flows` package, so you only need to implement the second step. |
|
592
|
|
|
593
|
### Create a Subscription Step (Second Step) |
|
594
|
|
|
595
|
Create the file `src/workflows/create-subscription/steps/create-subscription.ts` with the following content: |
|
596
|
|
|
597
|
export const createSubscriptionsHighlights = [ |
|
598
|
["28", "linkDefs", "An array of links to be created later."], |
|
599
|
["30", "createSubscriptions", "Create the subscription."], |
|
600
|
["33", "main_order_id", "Store the ID of the order created for the subscription purchase."], |
|
601
|
["43", "subscription", "Pass the subscription to the compensation function."] |
|
602
|
] |
|
603
|
|
|
604
|
```ts title="src/workflows/create-subscription/steps/create-subscription.ts" highlights={createSubscriptionsHighlights} collapsibleLines="1-7" expandMoreLabel="Show Imports" |
|
605
|
import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk" |
|
606
|
import { Modules } from "@medusajs/framework/utils" |
|
607
|
import { LinkDefinition } from "@medusajs/framework/types" |
|
608
|
import { SubscriptionInterval } from "../../../modules/subscription/types" |
|
609
|
import SubscriptionModuleService from "../../../modules/subscription/service" |
|
610
|
import { SUBSCRIPTION_MODULE } from "../../../modules/subscription" |
|
611
|
|
|
612
|
type StepInput = { |
|
613
|
cart_id: string |
|
614
|
order_id: string |
|
615
|
customer_id?: string |
|
616
|
subscription_data: { |
|
617
|
interval: SubscriptionInterval |
|
618
|
period: number |
|
619
|
} |
|
620
|
} |
|
621
|
|
|
622
|
const createSubscriptionStep = createStep( |
|
623
|
"create-subscription", |
|
624
|
async ({ |
|
625
|
cart_id, |
|
626
|
order_id, |
|
627
|
customer_id, |
|
628
|
subscription_data, |
|
629
|
}: StepInput, { container }) => { |
|
630
|
const subscriptionModuleService: SubscriptionModuleService = |
|
631
|
container.resolve(SUBSCRIPTION_MODULE) |
|
632
|
const linkDefs: LinkDefinition[] = [] |
|
633
|
|
|
634
|
const subscription = await subscriptionModuleService.createSubscriptions({ |
|
635
|
...subscription_data, |
|
636
|
metadata: { |
|
637
|
main_order_id: order_id, |
|
638
|
}, |
|
639
|
}) |
|
640
|
|
|
641
|
// TODO add links |
|
642
|
|
|
643
|
return new StepResponse({ |
|
644
|
subscription: subscription[0], |
|
645
|
linkDefs, |
|
646
|
}, { |
|
647
|
subscription: subscription[0], |
|
648
|
}) |
|
649
|
}, async (data, { container }) => { |
|
650
|
// TODO implement compensation |
|
651
|
} |
|
652
|
) |
|
653
|
|
|
654
|
export default createSubscriptionStep |
|
655
|
``` |
|
656
|
|
|
657
|
This step receives the IDs of the cart, order, and customer, along with the subscription’s details. |
|
658
|
|
|
659
|
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. |
|
660
|
|
|
661
|
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: |
|
662
|
|
|
663
|
export const createSubscriptionsLinkHighlights = [ |
|
664
|
["1", "push", "Link the subscription to the order."], |
|
665
|
["10", "push", "Link the subscription to the cart."], |
|
666
|
["20", "push", "Link the subscription the cart's customer, if available."] |
|
667
|
] |
|
668
|
|
|
669
|
```ts title="src/workflows/create-subscription/steps/create-subscription.ts" highlights={createSubscriptionsLinkHighlights} |
|
670
|
linkDefs.push({ |
|
671
|
[SUBSCRIPTION_MODULE]: { |
|
672
|
"subscription_id": subscription[0].id, |
|
673
|
}, |
|
674
|
[Modules.ORDER]: { |
|
675
|
"order_id": order_id, |
|
676
|
}, |
|
677
|
}) |
|
678
|
|
|
679
|
linkDefs.push({ |
|
680
|
[SUBSCRIPTION_MODULE]: { |
|
681
|
"subscription_id": subscription[0].id, |
|
682
|
}, |
|
683
|
[Modules.CART]: { |
|
684
|
"cart_id": cart_id, |
|
685
|
}, |
|
686
|
}) |
|
687
|
|
|
688
|
if (customer_id) { |
|
689
|
linkDefs.push({ |
|
690
|
[SUBSCRIPTION_MODULE]: { |
|
691
|
"subscription_id": subscription[0].id, |
|
692
|
}, |
|
693
|
[Modules.CUSTOMER]: { |
|
694
|
"customer_id": customer_id, |
|
695
|
}, |
|
696
|
}) |
|
697
|
} |
|
698
|
``` |
|
699
|
|
|
700
|
This adds links between: |
|
701
|
|
|
702
|
1. The subscription and the order. |
|
703
|
2. The subscription and the cart. |
|
704
|
3. The subscription and the customer, if a customer is associated with the cart. |
|
705
|
|
|
706
|
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: |
|
707
|
|
|
708
|
```ts title="src/workflows/create-subscription/steps/create-subscription.ts" |
|
709
|
if (!data) { |
|
710
|
return |
|
711
|
} |
|
712
|
const subscriptionModuleService: SubscriptionModuleService = |
|
713
|
container.resolve(SUBSCRIPTION_MODULE) |
|
714
|
|
|
715
|
await subscriptionModuleService.cancelSubscriptions(data.subscription.id) |
|
716
|
``` |
|
717
|
|
|
718
|
The compensation function receives the subscription as a parameter. It cancels the subscription. |
|
719
|
|
|
720
|
### Create Workflow |
|
721
|
|
|
722
|
Create the file `src/workflows/create-subscription/index.ts` with the following content: |
|
723
|
|
|
724
|
export const createSubscriptionWorkflowHighlights = [ |
|
725
|
["29", "acquireLockStep", "Acquire a lock on the cart to prevent race conditions."], |
|
726
|
["34", "completeCartWorkflow", "Complete the cart and create the order."], |
|
727
|
["40", "useQueryGraphStep", "Retrieve the order's details."], |
|
728
|
["95", "useQueryGraphStep", "Retrieve any existing subscription links for the order."], |
|
729
|
["101", "when", "Check if a subscription already exists for the order."], |
|
730
|
["108", "createSubscriptionStep", "Create the subscription."], |
|
731
|
["115", "createRemoteLinkStep", "Create the links returned by the previous step."], |
|
732
|
["120", "releaseLockStep", "Release the lock on the cart."] |
|
733
|
] |
|
734
|
|
|
735
|
```ts title="src/workflows/create-subscription/index.ts" highlights={createSubscriptionWorkflowHighlights} collapsibleLines="1-13" expandMoreLabel="Show Imports" |
|
736
|
import { |
|
737
|
createWorkflow, |
|
738
|
WorkflowResponse, |
|
739
|
useQueryGraphStep, |
|
740
|
acquireLockStep, |
|
741
|
releaseLockStep, |
|
742
|
} from "@medusajs/framework/workflows-sdk" |
|
743
|
import { |
|
744
|
createRemoteLinkStep, |
|
745
|
completeCartWorkflow, |
|
746
|
useQueryGraphStep, |
|
747
|
} from "@medusajs/medusa/core-flows" |
|
748
|
import { |
|
749
|
SubscriptionInterval, |
|
750
|
} from "../../modules/subscription/types" |
|
751
|
import createSubscriptionStep from "./steps/create-subscription" |
|
752
|
|
|
753
|
type WorkflowInput = { |
|
754
|
cart_id: string, |
|
755
|
subscription_data: { |
|
756
|
interval: SubscriptionInterval |
|
757
|
period: number |
|
758
|
} |
|
759
|
} |
|
760
|
|
|
761
|
const createSubscriptionWorkflow = createWorkflow( |
|
762
|
"create-subscription", |
|
763
|
(input: WorkflowInput) => { |
|
764
|
acquireLockStep({ |
|
765
|
key: input.cart_id, |
|
766
|
timeout: 2, |
|
767
|
ttl: 10, |
|
768
|
}) |
|
769
|
const { id } = completeCartWorkflow.runAsStep({ |
|
770
|
input: { |
|
771
|
id: input.cart_id, |
|
772
|
}, |
|
773
|
}) |
|
774
|
|
|
775
|
const { data: orders } = useQueryGraphStep({ |
|
776
|
entity: "order", |
|
777
|
fields: [ |
|
778
|
"id", |
|
779
|
"status", |
|
780
|
"summary", |
|
781
|
"currency_code", |
|
782
|
"customer_id", |
|
783
|
"display_id", |
|
784
|
"region_id", |
|
785
|
"email", |
|
786
|
"total", |
|
787
|
"subtotal", |
|
788
|
"tax_total", |
|
789
|
"discount_total", |
|
790
|
"discount_subtotal", |
|
791
|
"discount_tax_total", |
|
792
|
"original_total", |
|
793
|
"original_tax_total", |
|
794
|
"item_total", |
|
795
|
"item_subtotal", |
|
796
|
"item_tax_total", |
|
797
|
"original_item_total", |
|
798
|
"original_item_subtotal", |
|
799
|
"original_item_tax_total", |
|
800
|
"shipping_total", |
|
801
|
"shipping_subtotal", |
|
802
|
"shipping_tax_total", |
|
803
|
"original_shipping_tax_total", |
|
804
|
"original_shipping_subtotal", |
|
805
|
"original_shipping_total", |
|
806
|
"created_at", |
|
807
|
"updated_at", |
|
808
|
"credit_lines.*", |
|
809
|
"items.*", |
|
810
|
"items.tax_lines.*", |
|
811
|
"items.adjustments.*", |
|
812
|
"items.detail.*", |
|
813
|
"items.variant.*", |
|
814
|
"items.variant.product.*", |
|
815
|
"shipping_address.*", |
|
816
|
"billing_address.*", |
|
817
|
"shipping_methods.*", |
|
818
|
"shipping_methods.tax_lines.*", |
|
819
|
"shipping_methods.adjustments.*", |
|
820
|
"payment_collections.*", |
|
821
|
], |
|
822
|
filters: { |
|
823
|
id, |
|
824
|
}, |
|
825
|
options: { |
|
826
|
throwIfKeyNotFound: true, |
|
827
|
}, |
|
828
|
}) |
|
829
|
|
|
830
|
const { data: existingLinks } = useQueryGraphStep({ |
|
831
|
entity: subscriptionOrderLink.entryPoint, |
|
832
|
fields: ["subscription.id"], |
|
833
|
filters: { order_id: orders[0].id }, |
|
834
|
}).config({ name: "retrieve-existing-links" }) |
|
835
|
|
|
836
|
const subscription = when( |
|
837
|
"create-subscription-condition", |
|
838
|
{ existingLinks }, |
|
839
|
(data) => data.existingLinks.length === 0 |
|
840
|
) |
|
841
|
.then(() => { |
|
842
|
|
|
843
|
const { subscription, linkDefs } = createSubscriptionStep({ |
|
844
|
cart_id: input.cart_id, |
|
845
|
order_id: orders[0].id, |
|
846
|
customer_id: orders[0].customer_id!, |
|
847
|
subscription_data: input.subscription_data, |
|
848
|
}) |
|
849
|
|
|
850
|
createRemoteLinkStep(linkDefs) |
|
851
|
|
|
852
|
return subscription |
|
853
|
}) |
|
854
|
|
|
855
|
releaseLockStep({ |
|
856
|
key: input.cart_id, |
|
857
|
}) |
|
858
|
|
|
859
|
return new WorkflowResponse({ |
|
860
|
subscription: subscription, |
|
861
|
order: orders[0], |
|
862
|
}) |
|
863
|
} |
|
864
|
) |
|
865
|
|
|
866
|
export default createSubscriptionWorkflow |
|
867
|
``` |
|
868
|
|
|
869
|
This workflow accepts the cart’s ID, along with the subscription details. It executes the following steps: |
|
870
|
|
|
871
|
1. [acquireLockStep](/references/medusa-workflows/steps/acquireLockStep) to acquire a lock on the cart to prevent race conditions. |
|
872
|
2. [completeCartWorkflow](/references/medusa-workflows/completeCartWorkflow) that completes a cart and creates an order. |
|
873
|
3. [useQueryGraphStep](/references/helper-steps/useQueryGraphStep) to retrieve the order's details. [Query](!docs!/learn/fundamentals/query) is a tool that allows you to retrieve data across modules. |
|
874
|
4. [useQueryGraphStep](/references/helper-steps/useQueryGraphStep) again to check if a subscription already exists for the order. This is necessary to ensure idempotency in case the workflow is retried. |
|
875
|
5. Use `when` to check if a subscription already exists for the order. If not, it executes the next steps: |
|
876
|
1. `createSubscriptionStep`, which is the step you created previously. |
|
877
|
2. `createRemoteLinkStep` which accepts links to create. These links are in the `linkDefs` array returned by the previous step. |
|
878
|
6. [releaseLockStep](/references/medusa-workflows/steps/releaseLockStep) to release the lock on the cart. |
|
879
|
|
|
880
|
The workflow returns the created subscription and order. |
|
881
|
|
|
882
|
### Further Reads |
|
883
|
|
|
884
|
- [How to Create a Workflow](!docs!/learn/fundamentals/workflows) |
|
885
|
- [Learn more about the compensation function](!docs!/learn/fundamentals/workflows/compensation-function) |
|
886
|
- [How to use Link](!docs!/learn/fundamentals/module-links/link) |
|
887
|
|
|
888
|
--- |
|
889
|
|
|
890
|
## Step 8: Custom Complete Cart API Route |
|
891
|
|
|
892
|
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. |
|
893
|
|
|
894
|
An [API Route](!docs!/learn/fundamentals/api-routes) is an endpoint that exposes commerce features to external applications and clients, such as storefronts. |
|
895
|
|
|
896
|
In this step, you’ll create a custom API route similar to the [Complete Cart API route](!api!/store/carts/complete-cart) that uses the workflow you previously created to complete the customer's purchase and create a subscription. |
|
897
|
|
|
898
|
Create the file `src/api/store/carts/[id]/subscribe/route.ts` with the following content: |
|
899
|
|
|
900
|
export const completeCartHighlights = [ |
|
901
|
["18", "graph", "Retrieve the cart to retrieve the subscription details from the `metadata`."], |
|
902
|
["30", "", "If the subscription data isn't set in the cart's `metadata`, throw an error"], |
|
903
|
["37", "createSubscriptionWorkflow", "Execute the workflow created in the previous step."] |
|
904
|
] |
|
905
|
|
|
906
|
```ts title="src/api/store/carts/[id]/subscribe/route.ts" highlights={completeCartHighlights} collapsibleLines="1-10" expandMoreLabel="Show Imports" |
|
907
|
import { |
|
908
|
MedusaRequest, |
|
909
|
MedusaResponse, |
|
910
|
} from "@medusajs/framework/http" |
|
911
|
import { |
|
912
|
ContainerRegistrationKeys, |
|
913
|
MedusaError, |
|
914
|
} from "@medusajs/framework/utils" |
|
915
|
import createSubscriptionWorkflow from "../../../../../workflows/create-subscription" |
|
916
|
import { SubscriptionInterval } from "../../../../../modules/subscription/types" |
|
917
|
|
|
918
|
export const POST = async ( |
|
919
|
req: MedusaRequest, |
|
920
|
res: MedusaResponse |
|
921
|
) => { |
|
922
|
const query = req.scope.resolve(ContainerRegistrationKeys.QUERY) |
|
923
|
|
|
924
|
const { data: [cart] } = await query.graph({ |
|
925
|
entity: "cart", |
|
926
|
fields: [ |
|
927
|
"metadata", |
|
928
|
], |
|
929
|
filters: { |
|
930
|
id: [req.params.id], |
|
931
|
}, |
|
932
|
}) |
|
933
|
|
|
934
|
const { metadata } = cart |
|
935
|
|
|
936
|
if (!metadata?.subscription_interval || !metadata.subscription_period) { |
|
937
|
throw new MedusaError( |
|
938
|
MedusaError.Types.INVALID_DATA, |
|
939
|
"Please set the subscription's interval and period first." |
|
940
|
) |
|
941
|
} |
|
942
|
|
|
943
|
const { result } = await createSubscriptionWorkflow( |
|
944
|
req.scope |
|
945
|
).run({ |
|
946
|
input: { |
|
947
|
cart_id: req.params.id, |
|
948
|
subscription_data: { |
|
949
|
interval: metadata.subscription_interval as SubscriptionInterval, |
|
950
|
period: metadata.subscription_period as number, |
|
951
|
}, |
|
952
|
}, |
|
953
|
}) |
|
954
|
|
|
955
|
res.json({ |
|
956
|
type: "order", |
|
957
|
order: result.order, |
|
958
|
}) |
|
959
|
} |
|
960
|
``` |
|
961
|
|
|
962
|
Since the file exports a `POST` function, you're exposing a `POST` API route at `/store/carts/[id]/subscribe`. |
|
963
|
|
|
964
|
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. |
|
965
|
|
|
966
|
Then, you use the `createSubscriptionWorkflow` you created to create the order, and return the created order in the response. |
|
967
|
|
|
968
|
In the next step, you'll customize the Next.js Starter Storefront, allowing you to test out the subscription feature. |
|
969
|
|
|
970
|
### Further Reads |
|
971
|
|
|
972
|
- [How to Create an API Route](!docs!/learn/fundamentals/api-routes) |
|
973
|
|
|
974
|
--- |
|
975
|
|
|
976
|
## Intermission: Payment Flow Overview |
|
977
|
|
|
978
|
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](../../../../storefront-development/checkout/payment/page.mdx) for more details. |
|
979
|
|
|
980
|
By default, the checkout flow requires you to create a [payment collection](../../../../commerce-modules/payment/payment-collection/page.mdx), then a [payment session](../../../../commerce-modules/payment/payment-session/page.mdx) 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. |
|
981
|
|
|
982
|
 |
|
983
|
|
|
984
|
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](!api!/store/payment-collections/initialize-payment-session), 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. |
|
985
|
|
|
986
|
<Note title="Tip"> |
|
987
|
|
|
988
|
If you're using a custom payment provider, you can handle that additional data in the [initiatePayment method](/references/payment/provider#initiatepayment) of your provider's service. |
|
989
|
|
|
990
|
</Note> |
|
991
|
|
|
992
|
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](../../../../commerce-modules/payment/account-holder/page.mdx) documentation. |
|
993
|
|
|
994
|
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. |
|
995
|
|
|
996
|
--- |
|
997
|
|
|
998
|
## Step 9: Add Subscriptions to Next.js Starter Storefront |
|
999
|
|
|
1000
|
In this step, you'll customize the checkout flow in the [Next.js Starter storefront](../../../../nextjs-starter/page.mdx), which you installed in the first step, to: |
|
1001
|
|
|
1002
|
1. Add a subscription step to the checkout flow. |
|
1003
|
2. Pass the additional data that Stripe requires to later capture the payment when the subscription renews, as explained in the [Payment Flow Overview](#intermission-payment-flow-overview). |
|
1004
|
3. Change the complete cart action to use the custom API route you created in the previous step. |
|
1005
|
|
|
1006
|
### Add Subscription Step |
|
1007
|
|
|
1008
|
Start by adding the function to update the subscription data in the cart. Add to the file `src/lib/data/cart.ts` the following: |
|
1009
|
|
|
1010
|
```ts title="src/lib/data/cart.ts" badgeLabel="Storefront" badgeColor="orange" |
|
1011
|
export enum SubscriptionInterval { |
|
1012
|
MONTHLY = "monthly", |
|
1013
|
YEARLY = "yearly" |
|
1014
|
} |
|
1015
|
|
|
1016
|
export async function updateSubscriptionData( |
|
1017
|
subscription_interval: SubscriptionInterval, |
|
1018
|
subscription_period: number |
|
1019
|
) { |
|
1020
|
const cartId = getCartId() |
|
1021
|
|
|
1022
|
if (!cartId) { |
|
1023
|
throw new Error("No existing cart found when placing an order") |
|
1024
|
} |
|
1025
|
|
|
1026
|
await updateCart({ |
|
1027
|
metadata: { |
|
1028
|
subscription_interval, |
|
1029
|
subscription_period, |
|
1030
|
}, |
|
1031
|
}) |
|
1032
|
revalidateTag("cart") |
|
1033
|
} |
|
1034
|
``` |
|
1035
|
|
|
1036
|
This updates the cart's `metadata` with the subscription details. |
|
1037
|
|
|
1038
|
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: |
|
1039
|
|
|
1040
|
```tsx title="src/modules/checkout/components/subscriptions/index.tsx" badgeLabel="Storefront" badgeColor="orange" collapsibleLines="1-12" expandMoreLabel="Show Imports" |
|
1041
|
"use client" |
|
1042
|
|
|
1043
|
import { Button, clx, Heading, Text } from "@medusajs/ui" |
|
1044
|
import { CheckCircleSolid } from "@medusajs/icons" |
|
1045
|
import { usePathname, useRouter, useSearchParams } from "next/navigation" |
|
1046
|
import { useCallback, useState } from "react" |
|
1047
|
import Divider from "../../../common/components/divider" |
|
1048
|
import Input from "../../../common/components/input" |
|
1049
|
import NativeSelect from "../../../common/components/native-select" |
|
1050
|
import { capitalize } from "lodash" |
|
1051
|
import { updateSubscriptionData } from "../../../../lib/data/cart" |
|
1052
|
|
|
1053
|
export enum SubscriptionInterval { |
|
1054
|
MONTHLY = "monthly", |
|
1055
|
YEARLY = "yearly" |
|
1056
|
} |
|
1057
|
|
|
1058
|
const SubscriptionForm = () => { |
|
1059
|
const [interval, setInterval] = useState<SubscriptionInterval>( |
|
1060
|
SubscriptionInterval.MONTHLY |
|
1061
|
) |
|
1062
|
const [period, setPeriod] = useState(1) |
|
1063
|
const [isLoading, setIsLoading] = useState(false) |
|
1064
|
|
|
1065
|
const searchParams = useSearchParams() |
|
1066
|
const router = useRouter() |
|
1067
|
const pathname = usePathname() |
|
1068
|
|
|
1069
|
const isOpen = searchParams.get("step") === "subscription" |
|
1070
|
|
|
1071
|
const createQueryString = useCallback( |
|
1072
|
(name: string, value: string) => { |
|
1073
|
const params = new URLSearchParams(searchParams) |
|
1074
|
params.set(name, value) |
|
1075
|
|
|
1076
|
return params.toString() |
|
1077
|
}, |
|
1078
|
[searchParams] |
|
1079
|
) |
|
1080
|
|
|
1081
|
const handleEdit = () => { |
|
1082
|
router.push(pathname + "?" + createQueryString("step", "subscription"), { |
|
1083
|
scroll: false, |
|
1084
|
}) |
|
1085
|
} |
|
1086
|
|
|
1087
|
const handleSubmit = async () => { |
|
1088
|
setIsLoading(true) |
|
1089
|
|
|
1090
|
updateSubscriptionData(interval, period) |
|
1091
|
.then(() => { |
|
1092
|
setIsLoading(false) |
|
1093
|
router.push(pathname + "?step=delivery", { scroll: false }) |
|
1094
|
}) |
|
1095
|
} |
|
1096
|
|
|
1097
|
return ( |
|
1098
|
<div className="bg-white"> |
|
1099
|
<div className="flex flex-row items-center justify-between mb-6"> |
|
1100
|
<Heading |
|
1101
|
level="h2" |
|
1102
|
className={clx( |
|
1103
|
"flex flex-row text-3xl-regular gap-x-2 items-baseline", |
|
1104
|
{ |
|
1105
|
"opacity-50 pointer-events-none select-none": |
|
1106
|
!isOpen, |
|
1107
|
} |
|
1108
|
)} |
|
1109
|
> |
|
1110
|
Subscription Details |
|
1111
|
{!isOpen && <CheckCircleSolid />} |
|
1112
|
</Heading> |
|
1113
|
{!isOpen && ( |
|
1114
|
<Text> |
|
1115
|
<button |
|
1116
|
onClick={handleEdit} |
|
1117
|
className="text-ui-fg-interactive hover:text-ui-fg-interactive-hover" |
|
1118
|
data-testid="edit-payment-button" |
|
1119
|
> |
|
1120
|
Edit |
|
1121
|
</button> |
|
1122
|
</Text> |
|
1123
|
)} |
|
1124
|
</div> |
|
1125
|
<div> |
|
1126
|
<div className={isOpen ? "block" : "hidden"}> |
|
1127
|
<div className="flex flex-col gap-4"> |
|
1128
|
<NativeSelect |
|
1129
|
placeholder="Interval" |
|
1130
|
value={interval} |
|
1131
|
onChange={(e) => |
|
1132
|
setInterval(e.target.value as SubscriptionInterval) |
|
1133
|
} |
|
1134
|
required |
|
1135
|
autoComplete="interval" |
|
1136
|
> |
|
1137
|
{Object.values(SubscriptionInterval).map( |
|
1138
|
(intervalOption, index) => ( |
|
1139
|
<option key={index} value={intervalOption}> |
|
1140
|
{capitalize(intervalOption)} |
|
1141
|
</option> |
|
1142
|
) |
|
1143
|
)} |
|
1144
|
</NativeSelect> |
|
1145
|
<Input |
|
1146
|
label="Period" |
|
1147
|
name="period" |
|
1148
|
autoComplete="period" |
|
1149
|
value={period} |
|
1150
|
onChange={(e) => |
|
1151
|
setPeriod(parseInt(e.target.value)) |
|
1152
|
} |
|
1153
|
required |
|
1154
|
type="number" |
|
1155
|
/> |
|
1156
|
</div> |
|
1157
|
|
|
1158
|
<Button |
|
1159
|
size="large" |
|
1160
|
className="mt-6" |
|
1161
|
onClick={handleSubmit} |
|
1162
|
isLoading={isLoading} |
|
1163
|
disabled={!interval || !period} |
|
1164
|
> |
|
1165
|
Continue to delivery |
|
1166
|
</Button> |
|
1167
|
</div> |
|
1168
|
</div> |
|
1169
|
<Divider className="mt-8" /> |
|
1170
|
</div> |
|
1171
|
) |
|
1172
|
} |
|
1173
|
|
|
1174
|
export default SubscriptionForm |
|
1175
|
``` |
|
1176
|
|
|
1177
|
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. |
|
1178
|
|
|
1179
|
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: |
|
1180
|
|
|
1181
|
```ts title="src/lib/data/cart.ts" badgeLabel="Storefront" badgeColor="orange" |
|
1182
|
export async function setAddresses(currentState: unknown, formData: FormData) { |
|
1183
|
// ... |
|
1184
|
redirect( |
|
1185
|
`/${formData.get("shipping_address.country_code")}/checkout?step=subscription` |
|
1186
|
) |
|
1187
|
} |
|
1188
|
``` |
|
1189
|
|
|
1190
|
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: |
|
1191
|
|
|
1192
|
```tsx title="src/modules/checkout/templates/checkout-form/index.tsx" badgeLabel="Storefront" badgeColor="orange" |
|
1193
|
// other imports... |
|
1194
|
import SubscriptionForm from "@modules/checkout/components/subscriptions" |
|
1195
|
import { Suspense } from "react" |
|
1196
|
|
|
1197
|
export default async function CheckoutForm({ |
|
1198
|
cart, |
|
1199
|
customer, |
|
1200
|
}: { |
|
1201
|
cart: HttpTypes.StoreCart | null |
|
1202
|
customer: HttpTypes.StoreCustomer | null |
|
1203
|
}) { |
|
1204
|
// ... |
|
1205
|
|
|
1206
|
return ( |
|
1207
|
<div> |
|
1208
|
{/* ... */} |
|
1209
|
{/* After Addresses, before Shipping */} |
|
1210
|
<div> |
|
1211
|
<Suspense fallback={<></>}> |
|
1212
|
<SubscriptionForm /> |
|
1213
|
</Suspense> |
|
1214
|
</div> |
|
1215
|
{/* ... */} |
|
1216
|
</div> |
|
1217
|
) |
|
1218
|
} |
|
1219
|
``` |
|
1220
|
|
|
1221
|
<Note> |
|
1222
|
|
|
1223
|
In Next.js 15, any component that uses `useSearchParams()` must be wrapped in a `<Suspense>` boundary to enable static prerendering. Without the `<Suspense>` boundary, the build fails with: `useSearchParams() should be wrapped in a suspense boundary`. |
|
1224
|
|
|
1225
|
</Note> |
|
1226
|
|
|
1227
|
### Pass Additional Data to Payment Provider |
|
1228
|
|
|
1229
|
As explained in the [Payment Flow Overview](#intermission-payment-flow-overview), you need to pass additional data to the payment provider to support subscriptions. |
|
1230
|
|
|
1231
|
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](https://docs.stripe.com/payments/payment-intents#future-usage). |
|
1232
|
|
|
1233
|
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: |
|
1234
|
|
|
1235
|
```tsx title="src/modules/checkout/components/payment/index.tsx" badgeLabel="Storefront" badgeColor="orange" |
|
1236
|
await initiatePaymentSession(cart, { |
|
1237
|
provider_id: method, |
|
1238
|
data: { |
|
1239
|
setup_future_usage: "off_session", |
|
1240
|
}, |
|
1241
|
}) |
|
1242
|
``` |
|
1243
|
|
|
1244
|
If you're integrating with a custom payment provider, you can instead pass the required data for that provider in the `data` object. |
|
1245
|
|
|
1246
|
The payment method can now be used later to capture the payment when the subscription renews. |
|
1247
|
|
|
1248
|
### Change Complete Cart Action |
|
1249
|
|
|
1250
|
Finally, you need to change the complete cart action to use the custom API route you created in the previous step. |
|
1251
|
|
|
1252
|
In `src/lib/data/cart.ts`, find the `placeOrder` function and change the `await sdk.store.cart.complete` call to the following: |
|
1253
|
|
|
1254
|
```ts title="src/lib/data/cart.ts" badgeLabel="Storefront" badgeColor="orange" |
|
1255
|
const cartRes = await sdk.client.fetch<{ |
|
1256
|
type: "cart" |
|
1257
|
cart: HttpTypes.StoreCart |
|
1258
|
} | { |
|
1259
|
type: "order" |
|
1260
|
order: HttpTypes.StoreOrder |
|
1261
|
}>( |
|
1262
|
`/store/carts/${id}/subscribe`, |
|
1263
|
{ |
|
1264
|
method: "POST", |
|
1265
|
headers, |
|
1266
|
} |
|
1267
|
) |
|
1268
|
``` |
|
1269
|
|
|
1270
|
You change the request to send a `POST` request to the `/store/carts/[id]/subscribe` endpoint you created earlier. You can keep the rest of the `placeOrder` function as is. |
|
1271
|
|
|
1272
|
### Test Cart Completion and Subscription Creation |
|
1273
|
|
|
1274
|
To test out the cart completion flow: |
|
1275
|
|
|
1276
|
1. In the `apps/backend` directory, run the following command to start the application: |
|
1277
|
|
|
1278
|
```bash npm2yarn |
|
1279
|
npm run dev |
|
1280
|
``` |
|
1281
|
|
|
1282
|
2. In the `apps/storefront` directory, run the following command to start the storefront: |
|
1283
|
|
|
1284
|
```bash npm2yarn |
|
1285
|
npm run dev |
|
1286
|
``` |
|
1287
|
|
|
1288
|
3. 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. |
|
1289
|
|
|
1290
|
--- |
|
1291
|
|
|
1292
|
## Step 10: Add Admin API Routes for Subscription |
|
1293
|
|
|
1294
|
In this step, you’ll add two API routes for admin users: |
|
1295
|
|
|
1296
|
1. One to list all subscriptions. |
|
1297
|
2. One to retrieve a subscription. |
|
1298
|
|
|
1299
|
### List Subscriptions Admin API Route |
|
1300
|
|
|
1301
|
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](!docs!/learn/fundamentals/query) to paginate the retrieved data. |
|
1302
|
|
|
1303
|
You'll start with the API route. To create it, create the file `src/api/admin/subscriptions/route.ts` with the following content: |
|
1304
|
|
|
1305
|
export const listSubscriptionsAdminHighlight = [ |
|
1306
|
["16", "graph", "Retrieve the subscriptions with their orders and customer."] |
|
1307
|
] |
|
1308
|
|
|
1309
|
```ts title="src/api/admin/subscriptions/route.ts" highlights={listSubscriptionsAdminHighlight} |
|
1310
|
import { |
|
1311
|
AuthenticatedMedusaRequest, |
|
1312
|
MedusaResponse, |
|
1313
|
} from "@medusajs/framework" |
|
1314
|
import { ContainerRegistrationKeys } from "@medusajs/framework/utils" |
|
1315
|
|
|
1316
|
export const GET = async ( |
|
1317
|
req: AuthenticatedMedusaRequest, |
|
1318
|
res: MedusaResponse |
|
1319
|
) => { |
|
1320
|
const query = req.scope.resolve(ContainerRegistrationKeys.QUERY) |
|
1321
|
|
|
1322
|
const { |
|
1323
|
data: subscriptions, |
|
1324
|
metadata: { count, take, skip } = {}, |
|
1325
|
} = await query.graph({ |
|
1326
|
entity: "subscription", |
|
1327
|
...req.queryConfig, |
|
1328
|
}) |
|
1329
|
|
|
1330
|
res.json({ |
|
1331
|
subscriptions, |
|
1332
|
count, |
|
1333
|
limit: take, |
|
1334
|
offset: skip, |
|
1335
|
}) |
|
1336
|
} |
|
1337
|
``` |
|
1338
|
|
|
1339
|
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. |
|
1340
|
|
|
1341
|
Then, you return the subscriptions, along with the: |
|
1342
|
|
|
1343
|
- `count`: The total number of subscriptions. |
|
1344
|
- `limit`: The maximum number of subscriptions returned. |
|
1345
|
- `offset`: The number of subscriptions skipped before retrieving the subscriptions. |
|
1346
|
|
|
1347
|
These fields are useful for clients to paginate the subscriptions. |
|
1348
|
|
|
1349
|
### Add Query Configuration Middleware |
|
1350
|
|
|
1351
|
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](!docs!/learn/fundamentals/api-routes/middlewares) to the route. |
|
1352
|
|
|
1353
|
To add a middleware, create the file `src/api/middlewares.ts` with the following content: |
|
1354
|
|
|
1355
|
```ts title="src/api/middlewares.ts" |
|
1356
|
import { |
|
1357
|
validateAndTransformQuery, |
|
1358
|
defineMiddlewares, |
|
1359
|
} from "@medusajs/framework/http" |
|
1360
|
import { createFindParams } from "@medusajs/medusa/api/utils/validators" |
|
1361
|
|
|
1362
|
export const GetCustomSchema = createFindParams() |
|
1363
|
|
|
1364
|
export default defineMiddlewares({ |
|
1365
|
routes: [ |
|
1366
|
{ |
|
1367
|
matcher: "/admin/subscriptions", |
|
1368
|
method: "GET", |
|
1369
|
middlewares: [ |
|
1370
|
validateAndTransformQuery( |
|
1371
|
GetCustomSchema, |
|
1372
|
{ |
|
1373
|
defaults: [ |
|
1374
|
"id", |
|
1375
|
"subscription_date", |
|
1376
|
"expiration_date", |
|
1377
|
"status", |
|
1378
|
"metadata.*", |
|
1379
|
"orders.*", |
|
1380
|
"customer.*", |
|
1381
|
], |
|
1382
|
isList: true, |
|
1383
|
} |
|
1384
|
), |
|
1385
|
], |
|
1386
|
}, |
|
1387
|
], |
|
1388
|
}) |
|
1389
|
``` |
|
1390
|
|
|
1391
|
You add the `validateAndTransformQuery` middleware to `GET` requests sent to routes starting with `/admin/subscriptions`. This middleware accepts the following parameters: |
|
1392
|
|
|
1393
|
- A validation schema indicating which query parameters are accepted. You create the schema with [Zod](https://zod.dev/). Medusa has a createFindParams utility that generates a Zod schema accepting four query parameters: |
|
1394
|
- `fields`: The fields and relations to retrieve in the returned resources. |
|
1395
|
- `offset`: The number of items to skip before retrieving the returned items. |
|
1396
|
- `limit`: The maximum number of items to return. |
|
1397
|
- `order`: The fields to order the returned items by in ascending or descending order. |
|
1398
|
- A Query configuration object. It accepts the following properties: |
|
1399
|
- `defaults`: An array of default fields and relations to retrieve in each resource. |
|
1400
|
- `isList`: A boolean indicating whether a list of items are returned in the response. |
|
1401
|
|
|
1402
|
The middleware combines your default configurations with the query parameters in the request to determine the fields to retrieve and the pagination settings. |
|
1403
|
|
|
1404
|
Refer to the [Request Query Configuration](!docs!/learn/fundamentals/query#request-query-configurations) documentation to learn more about this middleware and the query configurations. |
|
1405
|
|
|
1406
|
### Get Subscription Admin API Route |
|
1407
|
|
|
1408
|
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: |
|
1409
|
|
|
1410
|
export const getSubscriptionsAdminHighlight = [ |
|
1411
|
["13", "graph", "Retrieve the subscription with its orders and customer."] |
|
1412
|
] |
|
1413
|
|
|
1414
|
```ts title="src/api/admin/subscriptions/[id]/route.ts" highlights={getSubscriptionsAdminHighlight} |
|
1415
|
import { |
|
1416
|
AuthenticatedMedusaRequest, |
|
1417
|
MedusaResponse, |
|
1418
|
} from "@medusajs/framework" |
|
1419
|
import { ContainerRegistrationKeys } from "@medusajs/framework/utils" |
|
1420
|
|
|
1421
|
export const GET = async ( |
|
1422
|
req: AuthenticatedMedusaRequest, |
|
1423
|
res: MedusaResponse |
|
1424
|
) => { |
|
1425
|
const query = req.scope.resolve(ContainerRegistrationKeys.QUERY) |
|
1426
|
|
|
1427
|
const { data: [subscription] } = await query.graph({ |
|
1428
|
entity: "subscription", |
|
1429
|
fields: [ |
|
1430
|
"*", |
|
1431
|
"orders.*", |
|
1432
|
"customer.*", |
|
1433
|
], |
|
1434
|
filters: { |
|
1435
|
id: [req.params.id], |
|
1436
|
}, |
|
1437
|
}) |
|
1438
|
|
|
1439
|
res.json({ |
|
1440
|
subscription, |
|
1441
|
}) |
|
1442
|
} |
|
1443
|
``` |
|
1444
|
|
|
1445
|
This adds a `GET` API route at `/admin/subscriptions/[id]`, where `[id]` is the ID of the subscription to retrieve. |
|
1446
|
|
|
1447
|
In the route handler, you retrieve a subscription by its ID using Query and return it in the response. |
|
1448
|
|
|
1449
|
<Note title="Tip"> |
|
1450
|
|
|
1451
|
You can also use Query configuration as explained for the previous route. |
|
1452
|
|
|
1453
|
</Note> |
|
1454
|
|
|
1455
|
In the next section, you’ll extend the Medusa Admin and use these API routes to show the subscriptions. |
|
1456
|
|
|
1457
|
--- |
|
1458
|
|
|
1459
|
## Step 11: Extend Admin |
|
1460
|
|
|
1461
|
The Medusa Admin is customizable, allowing you to inject widgets into existing pages or add UI routes to create new pages. |
|
1462
|
|
|
1463
|
In this step, you’ll add two UI routes: |
|
1464
|
|
|
1465
|
1. One to view all subscriptions. |
|
1466
|
2. One to view a single subscription. |
|
1467
|
|
|
1468
|
### Create Types File |
|
1469
|
|
|
1470
|
Before creating the UI routes, create the file `src/admin/types/index.ts` that holds types used by the UI routes: |
|
1471
|
|
|
1472
|
```ts title="src/admin/types/index.ts" |
|
1473
|
import { |
|
1474
|
OrderDTO, |
|
1475
|
CustomerDTO, |
|
1476
|
} from "@medusajs/framework/types" |
|
1477
|
|
|
1478
|
export enum SubscriptionStatus { |
|
1479
|
ACTIVE = "active", |
|
1480
|
CANCELED = "canceled", |
|
1481
|
EXPIRED = "expired", |
|
1482
|
FAILED = "failed" |
|
1483
|
} |
|
1484
|
|
|
1485
|
export enum SubscriptionInterval { |
|
1486
|
MONTHLY = "monthly", |
|
1487
|
YEARLY = "yearly" |
|
1488
|
} |
|
1489
|
|
|
1490
|
export type SubscriptionData = { |
|
1491
|
id: string |
|
1492
|
status: SubscriptionStatus |
|
1493
|
interval: SubscriptionInterval |
|
1494
|
subscription_date: string |
|
1495
|
last_order_date: string |
|
1496
|
next_order_date: string | null |
|
1497
|
expiration_date: string |
|
1498
|
metadata: Record<string, unknown> | null |
|
1499
|
orders?: OrderDTO[] |
|
1500
|
customer?: CustomerDTO |
|
1501
|
} |
|
1502
|
|
|
1503
|
``` |
|
1504
|
|
|
1505
|
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. |
|
1506
|
|
|
1507
|
### Configure JS SDK |
|
1508
|
|
|
1509
|
Medusa provides a [JS SDK](../../../../js-sdk/page.mdx) that facilitates sending requests to the server. You can use this SDK in any JavaScript client-side application, including your admin customizations. |
|
1510
|
|
|
1511
|
To configure the JS SDK, create the file `src/admin/lib/sdk.ts` with the following content: |
|
1512
|
|
|
1513
|
```ts title="src/admin/lib/sdk.ts" |
|
1514
|
import Medusa from "@medusajs/js-sdk" |
|
1515
|
|
|
1516
|
export const sdk = new Medusa({ |
|
1517
|
baseUrl: import.meta.env.VITE_BACKEND_URL || "/", |
|
1518
|
debug: import.meta.env.DEV, |
|
1519
|
auth: { |
|
1520
|
type: "session", |
|
1521
|
}, |
|
1522
|
}) |
|
1523
|
``` |
|
1524
|
|
|
1525
|
This initializes the SDK, setting the following options: |
|
1526
|
|
|
1527
|
- `baseUrl`: The URL of the Medusa server. You use the Vite environment variable `VITE_BACKEND_URL`. |
|
1528
|
- `debug`: A boolean indicating whether to log debug information. You use the Vite environment variable `DEV`. |
|
1529
|
- `auth`: An object indicating the authentication type. You use the session authentication type, which is the recommended approach for admin customizations. |
|
1530
|
|
|
1531
|
Learn more about other customizations in the [JS SDK documentation](../../../../js-sdk/page.mdx). |
|
1532
|
|
|
1533
|
### Create Subscriptions List UI Route |
|
1534
|
|
|
1535
|
You'll now create the subscriptions list UI route. Since you'll show the subscriptions in a table, you'll use the [DataTable component](!ui!/components/data-table) from Medusa UI. It facilitates displaying data in a tabular format with sorting, filtering, and pagination. |
|
1536
|
|
|
1537
|
Start by creating the file `src/admin/routes/subscriptions/page.tsx` with the following content: |
|
1538
|
|
|
1539
|
export const list1Highlights = [ |
|
1540
|
["10", "getBadgeColor", "Get the color to be used for the status's badge."], |
|
1541
|
["23", "getStatusTitle", "Capitalize the status for the text shown in the status's badge."], |
|
1542
|
["28", "columnHelper", "Prepare the column creation utility."], |
|
1543
|
["30", "columns", "Define the columns for the data table."], |
|
1544
|
["64", "SubscriptionsPage", "Define the component that shows the UI route's content."], |
|
1545
|
["68", "config", "Export configurations to show the UI route in the sidebar."] |
|
1546
|
] |
|
1547
|
|
|
1548
|
```tsx title="src/admin/routes/subscriptions/page.tsx" highlights={list1Highlights} collapsibleLines="1-9" expandMoreLabel="Show Imports" |
|
1549
|
import { defineRouteConfig } from "@medusajs/admin-sdk" |
|
1550
|
import { ClockSolid } from "@medusajs/icons" |
|
1551
|
import { Container, Heading, Badge, createDataTableColumnHelper, useDataTable, DataTablePaginationState, DataTable } from "@medusajs/ui" |
|
1552
|
import { useMemo, useState } from "react" |
|
1553
|
import { SubscriptionData, SubscriptionStatus } from "../../types" |
|
1554
|
import { useQuery } from "@tanstack/react-query" |
|
1555
|
import { sdk } from "../../lib/sdk" |
|
1556
|
import { useNavigate } from "react-router-dom" |
|
1557
|
|
|
1558
|
const getBadgeColor = (status: SubscriptionStatus) => { |
|
1559
|
switch(status) { |
|
1560
|
case SubscriptionStatus.CANCELED: |
|
1561
|
return "orange" |
|
1562
|
case SubscriptionStatus.FAILED: |
|
1563
|
return "red" |
|
1564
|
case SubscriptionStatus.EXPIRED: |
|
1565
|
return "grey" |
|
1566
|
default: |
|
1567
|
return "green" |
|
1568
|
} |
|
1569
|
} |
|
1570
|
|
|
1571
|
const getStatusTitle = (status: SubscriptionStatus) => { |
|
1572
|
return status.charAt(0).toUpperCase() + |
|
1573
|
status.substring(1) |
|
1574
|
} |
|
1575
|
|
|
1576
|
const columnHelper = createDataTableColumnHelper<SubscriptionData>() |
|
1577
|
|
|
1578
|
const columns = [ |
|
1579
|
columnHelper.accessor("id", { |
|
1580
|
header: "#", |
|
1581
|
}), |
|
1582
|
columnHelper.accessor("metadata.main_order_id", { |
|
1583
|
header: "Main Order", |
|
1584
|
}), |
|
1585
|
columnHelper.accessor("customer.email", { |
|
1586
|
header: "Customer", |
|
1587
|
}), |
|
1588
|
columnHelper.accessor("subscription_date", { |
|
1589
|
header: "Subscription Date", |
|
1590
|
cell: ({ getValue }) => { |
|
1591
|
return getValue().toLocaleString() |
|
1592
|
}, |
|
1593
|
}), |
|
1594
|
columnHelper.accessor("expiration_date", { |
|
1595
|
header: "Expiry Date", |
|
1596
|
cell: ({ getValue }) => { |
|
1597
|
return getValue().toLocaleString() |
|
1598
|
}, |
|
1599
|
}), |
|
1600
|
columnHelper.accessor("status", { |
|
1601
|
header: "Status", |
|
1602
|
cell: ({ getValue }) => { |
|
1603
|
return ( |
|
1604
|
<Badge color={getBadgeColor(getValue())}> |
|
1605
|
{getStatusTitle(getValue())} |
|
1606
|
</Badge> |
|
1607
|
) |
|
1608
|
}, |
|
1609
|
}), |
|
1610
|
] |
|
1611
|
|
|
1612
|
const SubscriptionsPage = () => { |
|
1613
|
// TODO add implementation |
|
1614
|
} |
|
1615
|
|
|
1616
|
export const config = defineRouteConfig({ |
|
1617
|
label: "Subscriptions", |
|
1618
|
icon: ClockSolid, |
|
1619
|
}) |
|
1620
|
|
|
1621
|
export default SubscriptionsPage |
|
1622
|
``` |
|
1623
|
|
|
1624
|
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. |
|
1625
|
|
|
1626
|
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. |
|
1627
|
|
|
1628
|
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. |
|
1629
|
|
|
1630
|
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. |
|
1631
|
|
|
1632
|
In the `SubscriptionsPage` component, you'll fetch the subscriptions and show them in a data table. So, replace the `SubscriptionsPage` component with the following: |
|
1633
|
|
|
1634
|
```tsx title="src/admin/routes/subscriptions/page.tsx" |
|
1635
|
const SubscriptionsPage = () => { |
|
1636
|
const navigate = useNavigate() |
|
1637
|
const [pagination, setPagination] = useState<DataTablePaginationState>({ |
|
1638
|
pageSize: 4, |
|
1639
|
pageIndex: 0, |
|
1640
|
}) |
|
1641
|
|
|
1642
|
const query = useMemo(() => { |
|
1643
|
return new URLSearchParams({ |
|
1644
|
limit: `${pagination.pageSize}`, |
|
1645
|
offset: `${pagination.pageIndex * pagination.pageSize}`, |
|
1646
|
}) |
|
1647
|
}, [pagination]) |
|
1648
|
|
|
1649
|
const { data, isLoading } = useQuery<{ |
|
1650
|
subscriptions: SubscriptionData[], |
|
1651
|
count: number |
|
1652
|
}>({ |
|
1653
|
queryFn: () => sdk.client.fetch(`/admin/subscriptions?${query.toString()}`), |
|
1654
|
queryKey: ["subscriptions", query.toString()], |
|
1655
|
}) |
|
1656
|
|
|
1657
|
const table = useDataTable({ |
|
1658
|
columns, |
|
1659
|
data: data?.subscriptions || [], |
|
1660
|
getRowId: (subscription) => subscription.id, |
|
1661
|
rowCount: data?.count || 0, |
|
1662
|
isLoading, |
|
1663
|
pagination: { |
|
1664
|
state: pagination, |
|
1665
|
onPaginationChange: setPagination, |
|
1666
|
}, |
|
1667
|
onRowClick(event, row) { |
|
1668
|
navigate(`/subscriptions/${row.id}`) |
|
1669
|
}, |
|
1670
|
}) |
|
1671
|
|
|
1672
|
|
|
1673
|
return ( |
|
1674
|
<Container> |
|
1675
|
<DataTable instance={table}> |
|
1676
|
<DataTable.Toolbar> |
|
1677
|
<Heading level="h1">Subscriptions</Heading> |
|
1678
|
</DataTable.Toolbar> |
|
1679
|
<DataTable.Table /> |
|
1680
|
{/** This component will render the pagination controls **/} |
|
1681
|
<DataTable.Pagination /> |
|
1682
|
</DataTable> |
|
1683
|
</Container> |
|
1684
|
) |
|
1685
|
} |
|
1686
|
``` |
|
1687
|
|
|
1688
|
In the component, you first initialize a `pagination` state variable of type `DataTablePaginationState`. This is necessary for the table to manage pagination. |
|
1689
|
|
|
1690
|
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. |
|
1691
|
|
|
1692
|
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. |
|
1693
|
|
|
1694
|
Finally, you render the data table with the subscriptions data, along with the pagination controls. |
|
1695
|
|
|
1696
|
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. |
|
1697
|
|
|
1698
|
### Create a Single Subscription UI Route |
|
1699
|
|
|
1700
|
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: |
|
1701
|
|
|
1702
|
```tsx title="src/admin/routes/subscriptions/[id]/page.tsx" |
|
1703
|
import { |
|
1704
|
Container, |
|
1705
|
Heading, |
|
1706
|
Table, |
|
1707
|
} from "@medusajs/ui" |
|
1708
|
import { useParams, Link } from "react-router-dom" |
|
1709
|
import { SubscriptionData } from "../../../types/index.js" |
|
1710
|
import { useQuery } from "@tanstack/react-query" |
|
1711
|
import { sdk } from "../../../lib/sdk.js" |
|
1712
|
|
|
1713
|
const SubscriptionPage = () => { |
|
1714
|
const { id } = useParams() |
|
1715
|
const { data, isLoading } = useQuery<{ |
|
1716
|
subscription: SubscriptionData |
|
1717
|
}>({ |
|
1718
|
queryFn: () => sdk.client.fetch(`/admin/subscriptions/${id}`), |
|
1719
|
queryKey: ["subscription", id], |
|
1720
|
}) |
|
1721
|
|
|
1722
|
return ( |
|
1723
|
<Container> |
|
1724
|
{isLoading && <span>Loading...</span>} |
|
1725
|
{data?.subscription && ( |
|
1726
|
<> |
|
1727
|
<Heading level="h1">Orders of Subscription #{data.subscription.id}</Heading> |
|
1728
|
<Table> |
|
1729
|
<Table.Header> |
|
1730
|
<Table.Row> |
|
1731
|
<Table.HeaderCell>#</Table.HeaderCell> |
|
1732
|
<Table.HeaderCell>Date</Table.HeaderCell> |
|
1733
|
<Table.HeaderCell>View Order</Table.HeaderCell> |
|
1734
|
</Table.Row> |
|
1735
|
</Table.Header> |
|
1736
|
<Table.Body> |
|
1737
|
{data.subscription.orders?.map((order) => ( |
|
1738
|
<Table.Row key={order.id}> |
|
1739
|
<Table.Cell>{order.id}</Table.Cell> |
|
1740
|
<Table.Cell>{(new Date(order.created_at)).toDateString()}</Table.Cell> |
|
1741
|
<Table.Cell> |
|
1742
|
<Link to={`/orders/${order.id}`}> |
|
1743
|
View Order |
|
1744
|
</Link> |
|
1745
|
</Table.Cell> |
|
1746
|
</Table.Row> |
|
1747
|
))} |
|
1748
|
</Table.Body> |
|
1749
|
</Table> |
|
1750
|
</> |
|
1751
|
)} |
|
1752
|
</Container> |
|
1753
|
) |
|
1754
|
} |
|
1755
|
|
|
1756
|
export default SubscriptionPage |
|
1757
|
``` |
|
1758
|
|
|
1759
|
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. |
|
1760
|
|
|
1761
|
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. |
|
1762
|
|
|
1763
|
### Test the UI Routes |
|
1764
|
|
|
1765
|
To test the UI routes, run the Medusa application and go to `http://localhost:9000/app`. |
|
1766
|
|
|
1767
|
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. |
|
1768
|
|
|
1769
|
To view a subscription’s details, click on its row, which opens the subscription details page. This page contains the subscription’s orders. |
|
1770
|
|
|
1771
|
### Further Reads |
|
1772
|
|
|
1773
|
- [How to Create UI Routes](!docs!/learn/fundamentals/admin/ui-routes) |
|
1774
|
- [DataTable component](!ui!/components/data-table) |
|
1775
|
|
|
1776
|
--- |
|
1777
|
|
|
1778
|
## Step 12: Create New Subscription Orders Workflow |
|
1779
|
|
|
1780
|
In this step, you’ll create a workflow to create a new subscription order. Later, you’ll execute this workflow in a scheduled job. |
|
1781
|
|
|
1782
|
The workflow has eight steps: |
|
1783
|
|
|
1784
|
```mermaid |
|
1785
|
graph TD |
|
1786
|
useQueryGraphStep["Retrieve Cart (useQueryGraphStep by Medusa)"] --> createPaymentCollectionStep["createPaymentCollectionStep (Medusa)"] |
|
1787
|
createPaymentCollectionStep["createPaymentCollectionStep (Medusa)"] --> getPaymentMethodStep |
|
1788
|
getPaymentMethodStep --> createPaymentSessionsWorkflow["createPaymentSessionsWorkflow (Medusa)"] |
|
1789
|
createPaymentSessionsWorkflow["createPaymentSessionsWorkflow (Medusa)"] --> authorizePaymentSessionStep["authorizePaymentSessionStep (Medusa)"] |
|
1790
|
authorizePaymentSessionStep["authorizePaymentSessionStep (Medusa)"] --> createSubscriptionOrderStep |
|
1791
|
createSubscriptionOrderStep --> createRemoteLinkStep["Create Links (createRemoteLinkStep by Medusa)"] |
|
1792
|
createRemoteLinkStep["Create Links (createRemoteLinkStep by Medusa)"] --> capturePaymentStep["capturePaymentStep (Medusa)"] |
|
1793
|
capturePaymentStep["capturePaymentStep (Medusa)"] --> updateSubscriptionStep |
|
1794
|
``` |
|
1795
|
|
|
1796
|
1. Retrieve the subscription’s linked cart. Medusa provides a `useQueryGraphStep` in the `@medusajs/medusa/core-flows` package that can be used as a step. |
|
1797
|
2. Create a payment collection for the new order. Medusa provides a `createPaymentCollectionsStep` in the `@medusajs/medusa/core-flows` package that you can use. |
|
1798
|
3. Get the customer's saved payment method. This payment method will be used to charge the customer. |
|
1799
|
4. 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. |
|
1800
|
5. Authorize the payment session. Medusa also provides the `authorizePaymentSessionStep` in the `@medusajs/medusa/core-flows` package, which can be used. |
|
1801
|
6. Create the subscription’s new order. |
|
1802
|
7. Create links between the subscription and the order using the `createRemoteLinkStep` provided in the `@medusajs/medusa/core-flows` package. |
|
1803
|
8. Capture the order’s payment using the `capturePaymentStep` provided by Medusa in the `@medusajs/medusa/core-flows` package. |
|
1804
|
9. Update the subscription’s `last_order_date` and `next_order_date` properties. |
|
1805
|
|
|
1806
|
You’ll only implement the third, sixth, and ninth steps. |
|
1807
|
|
|
1808
|
### Create getPaymentMethodStep (Third Step) |
|
1809
|
|
|
1810
|
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](#intermission-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](../../../../commerce-modules/payment/account-holder/page.mdx), allowing you to retrieve it later and re-capture the payment. |
|
1811
|
|
|
1812
|
To create the step, create the file `src/workflows/create-subscription-order/steps/get-payment-method.ts` with the following content: |
|
1813
|
|
|
1814
|
```tsx title="src/workflows/create-subscription-order/steps/get-payment-method.ts" |
|
1815
|
import { MedusaError, Modules } from "@medusajs/framework/utils" |
|
1816
|
import { AccountHolderDTO, CustomerDTO, PaymentMethodDTO } from "@medusajs/framework/types" |
|
1817
|
import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk" |
|
1818
|
|
|
1819
|
export interface GetPaymentMethodStepInput { |
|
1820
|
customer?: CustomerDTO & { |
|
1821
|
account_holders: AccountHolderDTO[] |
|
1822
|
} |
|
1823
|
} |
|
1824
|
|
|
1825
|
// Since we know we are using Stripe, we can get the correct creation date from their data. |
|
1826
|
const getLatestPaymentMethod = (paymentMethods: PaymentMethodDTO[]) => { |
|
1827
|
return paymentMethods.sort( |
|
1828
|
(a, b) => |
|
1829
|
((b.data?.created as number) ?? 0) - ((a.data?.created as number) ?? 0) |
|
1830
|
)[0] |
|
1831
|
} |
|
1832
|
|
|
1833
|
export const getPaymentMethodStep = createStep( |
|
1834
|
"get-payment-method", |
|
1835
|
async ({ customer }: GetPaymentMethodStepInput, { container }) => { |
|
1836
|
// TODO implement step |
|
1837
|
} |
|
1838
|
) |
|
1839
|
``` |
|
1840
|
|
|
1841
|
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. |
|
1842
|
|
|
1843
|
Then, you create the `getPaymentMethodStep` that receives the customer's data and account holders as an input. |
|
1844
|
|
|
1845
|
Next, you'll add the implementation of the step. Replace `getPaymentMethodStep` with the following: |
|
1846
|
|
|
1847
|
```tsx title="src/workflows/create-subscription-order/steps/get-payment-method.ts" |
|
1848
|
export const getPaymentMethodStep = createStep( |
|
1849
|
"get-payment-method", |
|
1850
|
async ({ customer }: GetPaymentMethodStepInput, { container }) => { |
|
1851
|
const paymentModuleService = container.resolve(Modules.PAYMENT) |
|
1852
|
|
|
1853
|
const providerId = "pp_stripe_stripe" |
|
1854
|
const accountHolder = customer?.account_holders?.find( |
|
1855
|
(ah) => ah.provider_id === providerId |
|
1856
|
) |
|
1857
|
|
|
1858
|
if (!accountHolder) { |
|
1859
|
throw new MedusaError( |
|
1860
|
MedusaError.Types.INVALID_DATA, |
|
1861
|
"No account holder found for the customer while retrieving payment method" |
|
1862
|
) |
|
1863
|
} |
|
1864
|
|
|
1865
|
const paymentMethods = await paymentModuleService.listPaymentMethods( |
|
1866
|
{ |
|
1867
|
// you can change to other payment provider |
|
1868
|
provider_id: providerId, |
|
1869
|
context: { |
|
1870
|
account_holder: accountHolder, |
|
1871
|
}, |
|
1872
|
} |
|
1873
|
) |
|
1874
|
|
|
1875
|
if (!paymentMethods.length) { |
|
1876
|
throw new MedusaError( |
|
1877
|
MedusaError.Types.INVALID_DATA, |
|
1878
|
"At least one saved payment method is required for performing a payment" |
|
1879
|
) |
|
1880
|
} |
|
1881
|
|
|
1882
|
const paymentMethodToUse = getLatestPaymentMethod(paymentMethods) |
|
1883
|
|
|
1884
|
return new StepResponse( |
|
1885
|
paymentMethodToUse, |
|
1886
|
accountHolder |
|
1887
|
) |
|
1888
|
} |
|
1889
|
) |
|
1890
|
``` |
|
1891
|
|
|
1892
|
In the step, you first find the account holder for the Stripe payment provider from the customer's `account_holders` list, and throw an error if none is found. Then, you list the customer's payment methods using the Payment Module service's `listPaymentMethods` method. If you're using a different payment provider, adjust the `provider_id` value. |
|
1893
|
|
|
1894
|
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. |
|
1895
|
|
|
1896
|
### Create createSubscriptionOrderStep (Sixth Step) |
|
1897
|
|
|
1898
|
Create the file `src/workflows/create-subscription-order/steps/create-subscription-order.ts` with the following content: |
|
1899
|
|
|
1900
|
export const createSubscriptionOrderStep1Highlights = [ |
|
1901
|
["21", "getOrderData", "Format the order's input data from the cart."], |
|
1902
|
["31", "linkDefs", "An array of links to be created."], |
|
1903
|
["33", "createOrderWorkflow", "Use Medusa's workflow to create the order."], |
|
1904
|
["45", "order", "Pass the order to the compensation function."] |
|
1905
|
] |
|
1906
|
|
|
1907
|
```ts title="src/workflows/create-subscription-order/steps/create-subscription-order.ts" highlights={createSubscriptionOrderStep1Highlights} collapsibleLines="1-14" expandMoreLabel="Show Imports" |
|
1908
|
import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk" |
|
1909
|
import { |
|
1910
|
CartWorkflowDTO, |
|
1911
|
PaymentCollectionDTO, |
|
1912
|
IOrderModuleService, |
|
1913
|
LinkDefinition, |
|
1914
|
} from "@medusajs/framework/types" |
|
1915
|
import { |
|
1916
|
Modules, |
|
1917
|
} from "@medusajs/framework/utils" |
|
1918
|
import { createOrderWorkflow } from "@medusajs/medusa/core-flows" |
|
1919
|
import { SubscriptionData } from "../../../modules/subscription/types" |
|
1920
|
import { SUBSCRIPTION_MODULE } from "../../../modules/subscription" |
|
1921
|
|
|
1922
|
export type CreateSubscriptionOrderStepInput = { |
|
1923
|
subscription: SubscriptionData |
|
1924
|
cart: CartWorkflowDTO |
|
1925
|
payment_collection: PaymentCollectionDTO |
|
1926
|
} |
|
1927
|
|
|
1928
|
function getOrderData(cart: CartWorkflowDTO) { |
|
1929
|
// TODO format order's data |
|
1930
|
} |
|
1931
|
|
|
1932
|
const createSubscriptionOrderStep = createStep( |
|
1933
|
"create-subscription-order", |
|
1934
|
async ({ |
|
1935
|
subscription, cart, payment_collection, |
|
1936
|
}: CreateSubscriptionOrderStepInput, |
|
1937
|
{ container, context }) => { |
|
1938
|
const linkDefs: LinkDefinition[] = [] |
|
1939
|
|
|
1940
|
const { result: order } = await createOrderWorkflow(container) |
|
1941
|
.run({ |
|
1942
|
input: getOrderData(cart), |
|
1943
|
context, |
|
1944
|
}) |
|
1945
|
|
|
1946
|
// TODO add links to linkDefs |
|
1947
|
|
|
1948
|
return new StepResponse({ |
|
1949
|
order, |
|
1950
|
linkDefs, |
|
1951
|
}, { |
|
1952
|
order, |
|
1953
|
}) |
|
1954
|
}, |
|
1955
|
async (data, { container }) => { |
|
1956
|
// TODO add compensation function |
|
1957
|
} |
|
1958
|
) |
|
1959
|
|
|
1960
|
export default createSubscriptionOrderStep |
|
1961
|
``` |
|
1962
|
|
|
1963
|
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. |
|
1964
|
|
|
1965
|
In this step, you use a `getOrderData` function to format the order’s input data. |
|
1966
|
|
|
1967
|
Replace the `getOrderData` function definition with the following: |
|
1968
|
|
|
1969
|
```ts title="src/workflows/create-subscription-order/steps/create-subscription-order.ts" |
|
1970
|
function getOrderData(cart: CartWorkflowDTO) { |
|
1971
|
return { |
|
1972
|
region_id: cart.region_id, |
|
1973
|
customer_id: cart.customer_id, |
|
1974
|
sales_channel_id: cart.sales_channel_id, |
|
1975
|
email: cart.email, |
|
1976
|
currency_code: cart.currency_code, |
|
1977
|
shipping_address: { |
|
1978
|
...cart.shipping_address, |
|
1979
|
id: null, |
|
1980
|
}, |
|
1981
|
billing_address: { |
|
1982
|
...cart.billing_address, |
|
1983
|
id: null, |
|
1984
|
}, |
|
1985
|
items: cart.items, |
|
1986
|
shipping_methods: cart.shipping_methods?.map((method) => ({ |
|
1987
|
name: method.name, |
|
1988
|
amount: method.amount, |
|
1989
|
is_tax_inclusive: method.is_tax_inclusive, |
|
1990
|
shipping_option_id: method.shipping_option_id, |
|
1991
|
data: method.data, |
|
1992
|
tax_lines: method.tax_lines?.map((taxLine) => ({ |
|
1993
|
description: taxLine.description, |
|
1994
|
tax_rate_id: taxLine.tax_rate_id, |
|
1995
|
code: taxLine.code, |
|
1996
|
rate: taxLine.rate, |
|
1997
|
provider_id: taxLine.provider_id, |
|
1998
|
})), |
|
1999
|
adjustments: method.adjustments?.map((adjustment) => ({ |
|
2000
|
code: adjustment.code, |
|
2001
|
amount: adjustment.amount, |
|
2002
|
description: adjustment.description, |
|
2003
|
promotion_id: adjustment.promotion_id, |
|
2004
|
provider_id: adjustment.provider_id, |
|
2005
|
})), |
|
2006
|
})), |
|
2007
|
} |
|
2008
|
} |
|
2009
|
``` |
|
2010
|
|
|
2011
|
This formats the order’s data using the cart originally used to make the subscription purchase. |
|
2012
|
|
|
2013
|
Next, to add links to the returned `linkDefs` array, replace the `TODO` in the step with the following: |
|
2014
|
|
|
2015
|
export const createSubscriptionOrderStep2Highlights = [ |
|
2016
|
["2", "", "Add a link to be created between the order and the payment collection."], |
|
2017
|
["10", "", "Add a link to be created between the subscription and the order."] |
|
2018
|
] |
|
2019
|
|
|
2020
|
```ts title="src/workflows/create-subscription-order/steps/create-subscription-order.ts" highlights={createSubscriptionOrderStep2Highlights} |
|
2021
|
linkDefs.push({ |
|
2022
|
[Modules.ORDER]: { |
|
2023
|
order_id: order.id, |
|
2024
|
}, |
|
2025
|
[Modules.PAYMENT]: { |
|
2026
|
payment_collection_id: payment_collection.id, |
|
2027
|
}, |
|
2028
|
}, |
|
2029
|
{ |
|
2030
|
[SUBSCRIPTION_MODULE]: { |
|
2031
|
subscription_id: subscription.id, |
|
2032
|
}, |
|
2033
|
[Modules.ORDER]: { |
|
2034
|
order_id: order.id, |
|
2035
|
}, |
|
2036
|
}) |
|
2037
|
``` |
|
2038
|
|
|
2039
|
This adds links to be created into the `linkDefs` array between the new order and payment collection, and the new order and its subscription. |
|
2040
|
|
|
2041
|
Finally, replace the `TODO` in the compensation function to cancel the order in case of an error: |
|
2042
|
|
|
2043
|
```ts title="src/workflows/create-subscription-order/steps/create-subscription-order.ts" |
|
2044
|
if (!data) { |
|
2045
|
return |
|
2046
|
} |
|
2047
|
const orderModuleService: IOrderModuleService = container.resolve( |
|
2048
|
Modules.ORDER |
|
2049
|
) |
|
2050
|
|
|
2051
|
await orderModuleService.cancel(data.order.id) |
|
2052
|
``` |
|
2053
|
|
|
2054
|
### Create updateSubscriptionStep (Ninth Step) |
|
2055
|
|
|
2056
|
Before creating the seventh step, add in `src/modules/subscription/service.ts` the following new method: |
|
2057
|
|
|
2058
|
```ts title="src/modules/subscription/service.ts" |
|
2059
|
class SubscriptionModuleService extends MedusaService({ |
|
2060
|
Subscription, |
|
2061
|
}) { |
|
2062
|
// ... |
|
2063
|
async recordNewSubscriptionOrder(id: string) { |
|
2064
|
const subscription = await this.retrieveSubscription(id) |
|
2065
|
|
|
2066
|
const orderDate = new Date() |
|
2067
|
|
|
2068
|
return await this.updateSubscriptions({ |
|
2069
|
id, |
|
2070
|
last_order_date: orderDate, |
|
2071
|
next_order_date: this.getNextOrderDate({ |
|
2072
|
last_order_date: orderDate, |
|
2073
|
expiration_date: subscription.expiration_date, |
|
2074
|
interval: subscription.interval, |
|
2075
|
period: subscription.period, |
|
2076
|
}), |
|
2077
|
}) |
|
2078
|
} |
|
2079
|
} |
|
2080
|
``` |
|
2081
|
|
|
2082
|
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. |
|
2083
|
|
|
2084
|
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: |
|
2085
|
|
|
2086
|
export const updateSubscriptionStepHighlights = [ |
|
2087
|
["22", "prevSubscriptionData", "Retrieve the old subscription data to pass it to the compensation function."], |
|
2088
|
["28", "recordNewSubscriptionOrder", "Update the subscription's `last_order_date` and `next_order_date`."], |
|
2089
|
["35", "prev_data", "Pass the old subscription data to the compensation function."] |
|
2090
|
] |
|
2091
|
|
|
2092
|
```ts title="src/workflows/create-subscription-order/steps/update-subscription.ts" highlights={updateSubscriptionStepHighlights} collapsibleLines="1-9" expandMoreLabel="Show Imports" |
|
2093
|
import { |
|
2094
|
createStep, |
|
2095
|
StepResponse, |
|
2096
|
} from "@medusajs/framework/workflows-sdk" |
|
2097
|
import { |
|
2098
|
SUBSCRIPTION_MODULE, |
|
2099
|
} from "../../../modules/subscription" |
|
2100
|
import SubscriptionModuleService from "../../../modules/subscription/service" |
|
2101
|
|
|
2102
|
type StepInput = { |
|
2103
|
subscription_id: string |
|
2104
|
} |
|
2105
|
|
|
2106
|
const updateSubscriptionStep = createStep( |
|
2107
|
"update-subscription", |
|
2108
|
async ({ subscription_id }: StepInput, { container }) => { |
|
2109
|
const subscriptionModuleService: SubscriptionModuleService = |
|
2110
|
container.resolve( |
|
2111
|
SUBSCRIPTION_MODULE |
|
2112
|
) |
|
2113
|
|
|
2114
|
const prevSubscriptionData = await subscriptionModuleService |
|
2115
|
.retrieveSubscription( |
|
2116
|
subscription_id |
|
2117
|
) |
|
2118
|
|
|
2119
|
const subscription = await subscriptionModuleService |
|
2120
|
.recordNewSubscriptionOrder( |
|
2121
|
subscription_id |
|
2122
|
) |
|
2123
|
|
|
2124
|
return new StepResponse({ |
|
2125
|
subscription, |
|
2126
|
}, { |
|
2127
|
prev_data: prevSubscriptionData, |
|
2128
|
}) |
|
2129
|
}, |
|
2130
|
async ({ |
|
2131
|
data, |
|
2132
|
}, { container }) => { |
|
2133
|
// TODO add compensation |
|
2134
|
} |
|
2135
|
) |
|
2136
|
|
|
2137
|
export default updateSubscriptionStep |
|
2138
|
``` |
|
2139
|
|
|
2140
|
This creates the `updateSubscriptionStep` that updates the subscriber using the `recordNewSubscriptionOrder` method of the Subscription Module’s main service. It returns the updated subscription. |
|
2141
|
|
|
2142
|
Before updating the subscription, the step retrieves the old data and passes it to the compensation function to undo the changes on the subscription. |
|
2143
|
|
|
2144
|
So, replace the `TODO` in the compensation function with the following: |
|
2145
|
|
|
2146
|
```ts title="src/workflows/create-subscription-order/steps/update-subscription.ts" |
|
2147
|
if (!data) { |
|
2148
|
return |
|
2149
|
} |
|
2150
|
const subscriptionModuleService: SubscriptionModuleService = |
|
2151
|
container.resolve( |
|
2152
|
SUBSCRIPTION_MODULE |
|
2153
|
) |
|
2154
|
|
|
2155
|
await subscriptionModuleService.updateSubscriptions({ |
|
2156
|
id: data.prev_data.id, |
|
2157
|
last_order_date: data.prev_data.last_order_date, |
|
2158
|
next_order_date: data.prev_data.next_order_date, |
|
2159
|
}) |
|
2160
|
``` |
|
2161
|
|
|
2162
|
This updates the subscription’s `last_order_date` and `next_order_date` properties to the values before the update. |
|
2163
|
|
|
2164
|
### Create Workflow |
|
2165
|
|
|
2166
|
Finally, create the file `src/workflows/create-subscription-order/index.ts` with the following content: |
|
2167
|
|
|
2168
|
export const createSubscriptionOrderWorkflowHighlights = [ |
|
2169
|
["31", "useQueryGraphStep", "Retrieve the cart linked to the subscription."], |
|
2170
|
["68", "createPaymentCollectionsStep", "Create a payment collection using the same information in the cart."], |
|
2171
|
["72", "getPaymentMethodStep", "Get the customer's saved payment method."], |
|
2172
|
["85", "data", "Pass data required by Stripe to capture the payment."], |
|
2173
|
["94", "createPaymentSessionsWorkflow", "Create a payment session in the payment collection from the previous step."], |
|
2174
|
["98", "authorizePaymentSessionStep", "Authorize the payment session created from the first step."], |
|
2175
|
["103", "createSubscriptionOrderStep", "Create the new order for the subscription."], |
|
2176
|
["109", "createRemoteLinkStep", "Create links returned by the previous step."], |
|
2177
|
["111", "capturePaymentStep", "Capture the order’s payment."], |
|
2178
|
["116", "updateSubscriptionStep", "Update the subscription’s `last_order_date` and `next_order_date`."] |
|
2179
|
] |
|
2180
|
|
|
2181
|
```ts title="src/workflows/create-subscription-order/index.ts" highlights={createSubscriptionOrderWorkflowHighlights} collapsibleLines="1-23" expandMoreLabel="Show Imports" |
|
2182
|
import { createWorkflow, transform, WorkflowResponse } from "@medusajs/framework/workflows-sdk" |
|
2183
|
import { |
|
2184
|
useQueryGraphStep, |
|
2185
|
createPaymentSessionsWorkflow, |
|
2186
|
createRemoteLinkStep, |
|
2187
|
capturePaymentStep, |
|
2188
|
} from "@medusajs/medusa/core-flows" |
|
2189
|
import { |
|
2190
|
SubscriptionData, |
|
2191
|
} from "../../modules/subscription/types" |
|
2192
|
import { |
|
2193
|
authorizePaymentSessionStep, |
|
2194
|
createPaymentCollectionsStep, |
|
2195
|
} from "@medusajs/medusa/core-flows" |
|
2196
|
import createSubscriptionOrderStep, { |
|
2197
|
CreateSubscriptionOrderStepInput, |
|
2198
|
} from "./steps/create-subscription-order" |
|
2199
|
import updateSubscriptionStep from "./steps/update-subscription" |
|
2200
|
import { |
|
2201
|
getPaymentMethodStep, |
|
2202
|
GetPaymentMethodStepInput, |
|
2203
|
} from "./steps/get-payment-method" |
|
2204
|
|
|
2205
|
type WorkflowInput = { |
|
2206
|
subscription: SubscriptionData |
|
2207
|
} |
|
2208
|
|
|
2209
|
const createSubscriptionOrderWorkflow = createWorkflow( |
|
2210
|
"create-subscription-order", |
|
2211
|
(input: WorkflowInput) => { |
|
2212
|
const { data: subscriptions } = useQueryGraphStep({ |
|
2213
|
entity: "subscription", |
|
2214
|
fields: [ |
|
2215
|
"*", |
|
2216
|
"cart.*", |
|
2217
|
"cart.items.*", |
|
2218
|
"cart.items.tax_lines.*", |
|
2219
|
"cart.items.adjustments.*", |
|
2220
|
"cart.shipping_address.*", |
|
2221
|
"cart.billing_address.*", |
|
2222
|
"cart.shipping_methods.*", |
|
2223
|
"cart.shipping_methods.tax_lines.*", |
|
2224
|
"cart.shipping_methods.adjustments.*", |
|
2225
|
"cart.payment_collection.*", |
|
2226
|
"cart.payment_collection.payment_sessions.*", |
|
2227
|
"cart.customer.*", |
|
2228
|
"cart.customer.account_holders.*", |
|
2229
|
], |
|
2230
|
filters: { |
|
2231
|
id: input.subscription.id, |
|
2232
|
}, |
|
2233
|
options: { |
|
2234
|
throwIfKeyNotFound: true, |
|
2235
|
}, |
|
2236
|
}) |
|
2237
|
|
|
2238
|
const paymentCollectionData = transform({ |
|
2239
|
subscriptions, |
|
2240
|
}, (data) => { |
|
2241
|
const cart = data.subscriptions[0].cart |
|
2242
|
return { |
|
2243
|
currency_code: cart?.currency_code || "", |
|
2244
|
amount: cart?.payment_collection?.amount || 0, |
|
2245
|
metadata: cart?.payment_collection?.metadata || undefined, |
|
2246
|
} |
|
2247
|
}) |
|
2248
|
|
|
2249
|
const payment_collection = createPaymentCollectionsStep([ |
|
2250
|
paymentCollectionData, |
|
2251
|
])[0] |
|
2252
|
|
|
2253
|
const defaultPaymentMethod = getPaymentMethodStep({ |
|
2254
|
customer: subscriptions[0].cart.customer, |
|
2255
|
}) |
|
2256
|
|
|
2257
|
const paymentSessionData = transform({ |
|
2258
|
payment_collection, |
|
2259
|
subscriptions, |
|
2260
|
defaultPaymentMethod, |
|
2261
|
}, (data) => { |
|
2262
|
return { |
|
2263
|
payment_collection_id: data.payment_collection.id, |
|
2264
|
provider_id: "pp_stripe_stripe", |
|
2265
|
customer_id: data.subscriptions[0].cart?.customer?.id, |
|
2266
|
data: { |
|
2267
|
payment_method: data.defaultPaymentMethod.id, |
|
2268
|
off_session: true, |
|
2269
|
confirm: true, |
|
2270
|
capture_method: "automatic", |
|
2271
|
}, |
|
2272
|
} |
|
2273
|
}) |
|
2274
|
|
|
2275
|
const paymentSession = createPaymentSessionsWorkflow.runAsStep({ |
|
2276
|
input: paymentSessionData, |
|
2277
|
}) |
|
2278
|
|
|
2279
|
const payment = authorizePaymentSessionStep({ |
|
2280
|
id: paymentSession.id, |
|
2281
|
context: paymentSession.context, |
|
2282
|
}) |
|
2283
|
|
|
2284
|
const { order, linkDefs } = createSubscriptionOrderStep({ |
|
2285
|
subscription: input.subscription, |
|
2286
|
cart: carts[0], |
|
2287
|
payment_collection, |
|
2288
|
} as unknown as CreateSubscriptionOrderStepInput) |
|
2289
|
|
|
2290
|
createRemoteLinkStep(linkDefs) |
|
2291
|
|
|
2292
|
capturePaymentStep({ |
|
2293
|
payment_id: payment.id, |
|
2294
|
amount: payment.amount, |
|
2295
|
}) |
|
2296
|
|
|
2297
|
updateSubscriptionStep({ |
|
2298
|
subscription_id: input.subscription.id, |
|
2299
|
}) |
|
2300
|
|
|
2301
|
return new WorkflowResponse({ |
|
2302
|
order, |
|
2303
|
}) |
|
2304
|
} |
|
2305
|
) |
|
2306
|
|
|
2307
|
export default createSubscriptionOrderWorkflow |
|
2308
|
``` |
|
2309
|
|
|
2310
|
The workflow runs the following steps: |
|
2311
|
|
|
2312
|
1. `useQueryGraphStep` to retrieve the details of the cart linked to the subscription. |
|
2313
|
2. `createPaymentCollectionsStep` to create a payment collection using the same information in the cart. |
|
2314
|
3. `getPaymentMethodStep` to get the customer's saved payment method. |
|
2315
|
4. `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](!docs!/learn/fundamentals/workflows/variable-manipulation) from the Workflows SDK. |
|
2316
|
- Since you're capturing the payment with Stripe, you must pass in the payment session's `data` object the following properties: |
|
2317
|
- `payment_method`: the ID of the payment method saved in Stripe. |
|
2318
|
- `off_session`: `true` to indicate that the payment is [off-session](https://docs.stripe.com/payments/payment-intents#future-usage). |
|
2319
|
- `confirm`: `true` to confirm the payment. |
|
2320
|
- `capture_method`: `automatic` to automatically capture the payment. |
|
2321
|
- If you're using a payment provider other than Stripe, you'll need to adjust the `provider_id` value and the `data` object properties depending on what the provider expects. |
|
2322
|
5. `authorizePaymentSessionStep` to authorize the payment session created from the first step. |
|
2323
|
6. `createSubscriptionOrderStep` to create the new order for the subscription. |
|
2324
|
7. `createRemoteLinkStep` to create links returned by the previous step. |
|
2325
|
8. `capturePaymentStep` to capture the order’s payment. |
|
2326
|
9. `updateSubscriptionStep` to update the subscription’s `last_order_date` and `next_order_date`. |
|
2327
|
|
|
2328
|
<Note title="Tip"> |
|
2329
|
|
|
2330
|
A workflow's constructor function has some constraints in implementation, which is why you need to use `transform` for data manipulation. Learn more about these constraints in [this documentation](!docs!/learn/fundamentals/workflows/constructor-constraints). |
|
2331
|
|
|
2332
|
</Note> |
|
2333
|
|
|
2334
|
In the next step, you’ll execute the workflow in a scheduled job. |
|
2335
|
|
|
2336
|
### Further Reads |
|
2337
|
|
|
2338
|
- [Payment Module](../../../../commerce-modules/payment/page.mdx) |
|
2339
|
|
|
2340
|
--- |
|
2341
|
|
|
2342
|
## Step 13: Create New Subscription Orders Scheduled Job |
|
2343
|
|
|
2344
|
A scheduled job is an asynchronous function executed at a specified interval pattern. Use scheduled jobs to execute a task at a regular interval. |
|
2345
|
|
|
2346
|
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. |
|
2347
|
|
|
2348
|
Create the file `src/jobs/create-subscription-orders.ts` with the following content: |
|
2349
|
|
|
2350
|
export const createSubscriptionOrdersJob1Highlights = [ |
|
2351
|
["18", "page", "The current page number"], |
|
2352
|
["19", "limit", "The number of subscriptions per page."], |
|
2353
|
["20", "pagesCount", "The total number of pages."], |
|
2354
|
["23", "beginningToday", "Get the date for today at `00:00:00`."], |
|
2355
|
["29", "endToday", "Get the date for today at `23:59:59`."], |
|
2356
|
["39", "$gte", "The `next_order_date` must be greater than or equal to `beginningToday`."], |
|
2357
|
["40", "$lte", "The `next_order_date` must be less than or equal to `endToday`."], |
|
2358
|
] |
|
2359
|
|
|
2360
|
```ts title="src/jobs/create-subscription-orders.ts" highlights={createSubscriptionOrdersJob1Highlights} collapsibleLines="1-8" expandMoreLabel="Show Imports" |
|
2361
|
import { MedusaContainer } from "@medusajs/framework/types" |
|
2362
|
import SubscriptionModuleService from "../modules/subscription/service" |
|
2363
|
import { SUBSCRIPTION_MODULE } from "../modules/subscription" |
|
2364
|
import moment from "moment" |
|
2365
|
import createSubscriptionOrderWorkflow from "../workflows/create-subscription-order" |
|
2366
|
import { SubscriptionStatus } from "../modules/subscription/types" |
|
2367
|
import { ContainerRegistrationKeys } from "@medusajs/framework/utils" |
|
2368
|
|
|
2369
|
export default async function createSubscriptionOrdersJob( |
|
2370
|
container: MedusaContainer |
|
2371
|
) { |
|
2372
|
const subscriptionModuleService: SubscriptionModuleService = |
|
2373
|
container.resolve(SUBSCRIPTION_MODULE) |
|
2374
|
const logger = container.resolve( |
|
2375
|
ContainerRegistrationKeys.LOGGER |
|
2376
|
) |
|
2377
|
|
|
2378
|
let page = 0 |
|
2379
|
const limit = 20 |
|
2380
|
let pagesCount = 0 |
|
2381
|
|
|
2382
|
do { |
|
2383
|
const beginningToday = moment(new Date()).set({ |
|
2384
|
second: 0, |
|
2385
|
minute: 0, |
|
2386
|
hour: 0, |
|
2387
|
}) |
|
2388
|
.toDate() |
|
2389
|
const endToday = moment(new Date()).set({ |
|
2390
|
second: 59, |
|
2391
|
minute: 59, |
|
2392
|
hour: 23, |
|
2393
|
}) |
|
2394
|
.toDate() |
|
2395
|
|
|
2396
|
const [subscriptions, count] = await subscriptionModuleService |
|
2397
|
.listAndCountSubscriptions({ |
|
2398
|
next_order_date: { |
|
2399
|
$gte: beginningToday, |
|
2400
|
$lte: endToday, |
|
2401
|
}, |
|
2402
|
status: SubscriptionStatus.ACTIVE, |
|
2403
|
}, { |
|
2404
|
skip: page * limit, |
|
2405
|
take: limit, |
|
2406
|
}) |
|
2407
|
|
|
2408
|
// TODO create orders for subscriptions |
|
2409
|
|
|
2410
|
if (!pagesCount) { |
|
2411
|
pagesCount = count / limit |
|
2412
|
} |
|
2413
|
|
|
2414
|
page++ |
|
2415
|
} while (page < pagesCount - 1) |
|
2416
|
} |
|
2417
|
|
|
2418
|
export const config = { |
|
2419
|
name: "create-subscription-orders", |
|
2420
|
schedule: "0 0 * * *", // Every day at midnight |
|
2421
|
} |
|
2422
|
``` |
|
2423
|
|
|
2424
|
This creates a scheduled job that runs once a day. |
|
2425
|
|
|
2426
|
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. |
|
2427
|
|
|
2428
|
To create orders for the subscriptions returned, replace the `TODO` with the following: |
|
2429
|
|
|
2430
|
```ts title="src/jobs/create-subscription-orders.ts" |
|
2431
|
await Promise.all( |
|
2432
|
subscriptions.map(async (subscription) => { |
|
2433
|
try { |
|
2434
|
const { result } = await createSubscriptionOrderWorkflow(container) |
|
2435
|
.run({ |
|
2436
|
input: { |
|
2437
|
subscription, |
|
2438
|
}, |
|
2439
|
}) |
|
2440
|
|
|
2441
|
logger.info(`Created new order ${ |
|
2442
|
result.order.id |
|
2443
|
} for subscription ${subscription.id}`) |
|
2444
|
} catch (e) { |
|
2445
|
logger.error( |
|
2446
|
`Error creating a new order for subscription ${subscription.id}`, |
|
2447
|
e |
|
2448
|
) |
|
2449
|
} |
|
2450
|
}) |
|
2451
|
) |
|
2452
|
``` |
|
2453
|
|
|
2454
|
This loops over the returned subscriptions and executes the `createSubscriptionOrderWorkflow` from the previous step to create the order. |
|
2455
|
|
|
2456
|
### Further Reads |
|
2457
|
|
|
2458
|
- [How to Create a Scheduled Job](!docs!/learn/fundamentals/scheduled-jobs) |
|
2459
|
|
|
2460
|
--- |
|
2461
|
|
|
2462
|
## Step 14: Expire Subscriptions Scheduled Job |
|
2463
|
|
|
2464
|
In this step, you’ll create a scheduled job that finds subscriptions whose `expiration_date` is the current date and marks them as expired. |
|
2465
|
|
|
2466
|
Before creating the scheduled job, add in `src/modules/subscription/service.ts` a new method: |
|
2467
|
|
|
2468
|
```ts title="src/modules/subscription/service.ts" |
|
2469
|
class SubscriptionModuleService extends MedusaService({ |
|
2470
|
Subscription, |
|
2471
|
}) { |
|
2472
|
// ... |
|
2473
|
async expireSubscription(id: string | string[]): Promise<SubscriptionData[]> { |
|
2474
|
const input = Array.isArray(id) ? id : [id] |
|
2475
|
|
|
2476
|
return await this.updateSubscriptions({ |
|
2477
|
selector: { |
|
2478
|
id: input, |
|
2479
|
}, |
|
2480
|
data: { |
|
2481
|
next_order_date: null, |
|
2482
|
status: SubscriptionStatus.EXPIRED, |
|
2483
|
}, |
|
2484
|
}) |
|
2485
|
} |
|
2486
|
} |
|
2487
|
``` |
|
2488
|
|
|
2489
|
The `expireSubscription` updates the following properties of the specified subscriptions: |
|
2490
|
|
|
2491
|
1. Set `next_order_date` to `null` as there are no more orders. |
|
2492
|
2. Set the `status` to `expired`. |
|
2493
|
|
|
2494
|
Then, create the file `src/jobs/expire-subscription-orders.ts` with the following content: |
|
2495
|
|
|
2496
|
export const expireSubscriptionOrdersJobHighlights = [ |
|
2497
|
["17", "page", "The current page number"], |
|
2498
|
["18", "limit", "The number of subscriptions per page."], |
|
2499
|
["19", "pagesCount", "The total number of pages."], |
|
2500
|
["22", "beginningToday", "Get the date for today at `00:00:00`."], |
|
2501
|
["28", "endToday", "Get the date for today at `23:59:59`."], |
|
2502
|
["38", "$gte", "The `expiration_date` must be greater than or equal to `beginningToday`."], |
|
2503
|
["39", "$lte", "The `expiration_date` must be less than or equal to `endToday`."], |
|
2504
|
["49", "expireSubscription", "Set the subscriptions as expired."] |
|
2505
|
] |
|
2506
|
|
|
2507
|
```ts title="src/jobs/expire-subscription-orders.ts" highlights={expireSubscriptionOrdersJobHighlights} collapsibleLines="1-7" expandMoreLabel="Show Imports" |
|
2508
|
import { MedusaContainer } from "@medusajs/framework/types" |
|
2509
|
import SubscriptionModuleService from "../modules/subscription/service" |
|
2510
|
import { SUBSCRIPTION_MODULE } from "../modules/subscription" |
|
2511
|
import moment from "moment" |
|
2512
|
import { SubscriptionStatus } from "../modules/subscription/types" |
|
2513
|
import { ContainerRegistrationKeys } from "@medusajs/framework/utils" |
|
2514
|
|
|
2515
|
export default async function expireSubscriptionOrdersJob( |
|
2516
|
container: MedusaContainer |
|
2517
|
) { |
|
2518
|
const subscriptionModuleService: SubscriptionModuleService = |
|
2519
|
container.resolve(SUBSCRIPTION_MODULE) |
|
2520
|
const logger = container.resolve( |
|
2521
|
ContainerRegistrationKeys.LOGGER |
|
2522
|
) |
|
2523
|
|
|
2524
|
let page = 0 |
|
2525
|
const limit = 20 |
|
2526
|
let pagesCount = 0 |
|
2527
|
|
|
2528
|
do { |
|
2529
|
const beginningToday = moment(new Date()).set({ |
|
2530
|
second: 0, |
|
2531
|
minute: 0, |
|
2532
|
hour: 0, |
|
2533
|
}) |
|
2534
|
.toDate() |
|
2535
|
const endToday = moment(new Date()).set({ |
|
2536
|
second: 59, |
|
2537
|
minute: 59, |
|
2538
|
hour: 23, |
|
2539
|
}) |
|
2540
|
.toDate() |
|
2541
|
|
|
2542
|
const [subscriptions, count] = await subscriptionModuleService |
|
2543
|
.listAndCountSubscriptions({ |
|
2544
|
expiration_date: { |
|
2545
|
$gte: beginningToday, |
|
2546
|
$lte: endToday, |
|
2547
|
}, |
|
2548
|
status: SubscriptionStatus.ACTIVE, |
|
2549
|
}, { |
|
2550
|
skip: page * limit, |
|
2551
|
take: limit, |
|
2552
|
}) |
|
2553
|
|
|
2554
|
const subscriptionIds = subscriptions.map((subscription) => subscription.id) |
|
2555
|
|
|
2556
|
await subscriptionModuleService.expireSubscription(subscriptionIds) |
|
2557
|
|
|
2558
|
logger.log(`Expired ${subscriptionIds}.`) |
|
2559
|
|
|
2560
|
if (!pagesCount) { |
|
2561
|
pagesCount = count / limit |
|
2562
|
} |
|
2563
|
|
|
2564
|
page++ |
|
2565
|
} while (page < pagesCount - 1) |
|
2566
|
} |
|
2567
|
|
|
2568
|
export const config = { |
|
2569
|
name: "expire-subscriptions", |
|
2570
|
schedule: "0 0 * * *", // Every day at midnight |
|
2571
|
} |
|
2572
|
``` |
|
2573
|
|
|
2574
|
This scheduled job runs once a day. |
|
2575
|
|
|
2576
|
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. |
|
2577
|
|
|
2578
|
You also implement pagination in case there are more than `20` expired subscriptions. |
|
2579
|
|
|
2580
|
--- |
|
2581
|
|
|
2582
|
## Step 15: Add Customer API Routes |
|
2583
|
|
|
2584
|
In this step, you’ll add two API routes for authenticated customers: |
|
2585
|
|
|
2586
|
1. View their list of subscriptions. |
|
2587
|
2. Cancel a subscription. |
|
2588
|
|
|
2589
|
### Create Subscriptions List API Route |
|
2590
|
|
|
2591
|
Create the file `src/api/store/customers/me/subscriptions/route.ts` with the following content: |
|
2592
|
|
|
2593
|
```ts title="src/api/store/customers/me/subscriptions/route.ts" |
|
2594
|
import { |
|
2595
|
AuthenticatedMedusaRequest, |
|
2596
|
MedusaResponse, |
|
2597
|
} from "@medusajs/framework/http" |
|
2598
|
import { ContainerRegistrationKeys } from "@medusajs/framework/utils" |
|
2599
|
|
|
2600
|
export const GET = async ( |
|
2601
|
req: AuthenticatedMedusaRequest, |
|
2602
|
res: MedusaResponse |
|
2603
|
) => { |
|
2604
|
const query = req.scope.resolve(ContainerRegistrationKeys.QUERY) |
|
2605
|
|
|
2606
|
const { data: [customer] } = await query.graph({ |
|
2607
|
entity: "customer", |
|
2608
|
fields: [ |
|
2609
|
"subscriptions.*", |
|
2610
|
], |
|
2611
|
filters: { |
|
2612
|
id: [req.auth_context.actor_id], |
|
2613
|
}, |
|
2614
|
}) |
|
2615
|
|
|
2616
|
res.json({ |
|
2617
|
subscriptions: customer.subscriptions, |
|
2618
|
}) |
|
2619
|
} |
|
2620
|
``` |
|
2621
|
|
|
2622
|
This adds an API route at `/store/customers/me/subscriptions`. |
|
2623
|
|
|
2624
|
In the route handler, you retrieve the authenticated customer’s subscriptions using Query and return them in the response. |
|
2625
|
|
|
2626
|
### Cancel Subscription API Route |
|
2627
|
|
|
2628
|
Before creating this API route, add in `src/modules/subscription/service.ts` the following new method: |
|
2629
|
|
|
2630
|
```ts title="src/modules/subscription/service.ts" |
|
2631
|
class SubscriptionModuleService extends MedusaService({ |
|
2632
|
Subscription, |
|
2633
|
}) { |
|
2634
|
// ... |
|
2635
|
|
|
2636
|
async cancelSubscriptions( |
|
2637
|
id: string | string[]): Promise<SubscriptionData[]> { |
|
2638
|
const input = Array.isArray(id) ? id : [id] |
|
2639
|
|
|
2640
|
return await this.updateSubscriptions({ |
|
2641
|
selector: { |
|
2642
|
id: input, |
|
2643
|
}, |
|
2644
|
data: { |
|
2645
|
next_order_date: null, |
|
2646
|
status: SubscriptionStatus.CANCELED, |
|
2647
|
}, |
|
2648
|
}) |
|
2649
|
} |
|
2650
|
} |
|
2651
|
``` |
|
2652
|
|
|
2653
|
The `cancelSubscriptions` method updates the specified subscribers to set their `next_order_date` to `null` and their status to `canceled`. |
|
2654
|
|
|
2655
|
Then, create the file `src/api/store/customers/me/subscriptions/[id]/route.ts` with the following content: |
|
2656
|
|
|
2657
|
{/* eslint-disable @medusajs/no-service-mutations-in-api-route */} |
|
2658
|
|
|
2659
|
```ts title="src/api/store/customers/me/subscriptions/[id]/route.ts" |
|
2660
|
import { |
|
2661
|
AuthenticatedMedusaRequest, |
|
2662
|
MedusaResponse, |
|
2663
|
} from "@medusajs/framework/http" |
|
2664
|
import SubscriptionModuleService from "../../../../../../modules/subscription/service" |
|
2665
|
import { |
|
2666
|
SUBSCRIPTION_MODULE, |
|
2667
|
} from "../../../../../../modules/subscription" |
|
2668
|
|
|
2669
|
export const POST = async ( |
|
2670
|
req: AuthenticatedMedusaRequest, |
|
2671
|
res: MedusaResponse |
|
2672
|
) => { |
|
2673
|
const subscriptionModuleService: SubscriptionModuleService = |
|
2674
|
req.scope.resolve(SUBSCRIPTION_MODULE) |
|
2675
|
|
|
2676
|
const subscription = await subscriptionModuleService.cancelSubscriptions( |
|
2677
|
req.params.id |
|
2678
|
) |
|
2679
|
|
|
2680
|
res.json({ |
|
2681
|
subscription, |
|
2682
|
}) |
|
2683
|
} |
|
2684
|
``` |
|
2685
|
|
|
2686
|
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. |
|
2687
|
|
|
2688
|
### Test it Out |
|
2689
|
|
|
2690
|
To test out the above API routes, first, log in as a customer with the following request: |
|
2691
|
|
|
2692
|
```bash |
|
2693
|
curl -X POST 'http://localhost:9000/auth/customer/emailpass' \ |
|
2694
|
-H 'Content-Type: application/json' \ |
|
2695
|
--data-raw '{ |
|
2696
|
"email": "customer@gmail.com", |
|
2697
|
"password": "supersecret" |
|
2698
|
}' |
|
2699
|
``` |
|
2700
|
|
|
2701
|
Make sure to replace the `email` and `password` with the correct credentials. |
|
2702
|
|
|
2703
|
<Note> |
|
2704
|
|
|
2705
|
If you don’t have a customer account, create one either using the Next.js Starter storefront or by following [this guide](../../../../storefront-development/customers/register/page.mdx). |
|
2706
|
|
|
2707
|
</Note> |
|
2708
|
|
|
2709
|
Then, send a `GET` request to `/store/customers/me/subscriptions` to retrieve the customer’s subscriptions: |
|
2710
|
|
|
2711
|
```bash |
|
2712
|
curl 'http://localhost:9000/store/customers/me/subscriptions' \ |
|
2713
|
-H 'Authorization: Bearer {token}' \ |
|
2714
|
-H 'x-publishable-api-key: {your_publishable_api_key}' |
|
2715
|
``` |
|
2716
|
|
|
2717
|
Where `{token}` is the token retrieved from the previous request. |
|
2718
|
|
|
2719
|
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: |
|
2720
|
|
|
2721
|
```bash |
|
2722
|
curl -X POST 'http://localhost:9000/store/customers/me/subscriptions/01J2VB8TVC14K29FREQ2DRS6NA' \ |
|
2723
|
-H 'Authorization: Bearer {token}' \ |
|
2724
|
-H 'x-publishable-api-key: {your_publishable_api_key}' |
|
2725
|
``` |
|
2726
|
|
|
2727
|
--- |
|
2728
|
|
|
2729
|
## Next Steps |
|
2730
|
|
|
2731
|
The next steps of this example depend on your use case. This section provides some insight into implementing them. |
|
2732
|
|
|
2733
|
### Use Existing Features |
|
2734
|
|
|
2735
|
To manage the orders created for a subscription, or other functionalities, use Medusa’s existing [Admin API routes](!api!/admin). |
|
2736
|
|
|
2737
|
### Link Subscriptions to Other Data Models |
|
2738
|
|
|
2739
|
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](#step-4-define-links). |
|
2740
|
|
|
2741
|
For example, you can link a subscription to a promotion to offer a subscription-specific discount. |
|
2742
|
|
|
2743
|
### Storefront Development |
|
2744
|
|
|
2745
|
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](../../../../storefront-development/page.mdx) section. |