|
1
|
--- |
|
2
|
sidebar_label: "Integrate Slack" |
|
3
|
tags: |
|
4
|
- server |
|
5
|
- tutorial |
|
6
|
- notification |
|
7
|
products: |
|
8
|
- order |
|
9
|
--- |
|
10
|
|
|
11
|
import { Card, Prerequisites, Details, WorkflowDiagram } from "docs-ui" |
|
12
|
import { Github, PlaySolid } from "@medusajs/icons" |
|
13
|
|
|
14
|
export const metadata = { |
|
15
|
title: `Integrate Slack (Notification) with Medusa`, |
|
16
|
} |
|
17
|
|
|
18
|
# {metadata.title} |
|
19
|
|
|
20
|
In this tutorial, you'll learn how to integrate Slack with Medusa to receive notifications about created orders. |
|
21
|
|
|
22
|
When you install a Medusa application, you get a fully-fledged commerce platform with a Framework for customization. Medusa's architecture facilitates integrating third-party services to customize Medusa's infrastructure for your business needs. |
|
23
|
|
|
24
|
Medusa's [Notification Module](../../../infrastructure-modules/notification/page.mdx) allows you to customize Medusa's infrastructure to send notifications using the third-party provider that fits your business needs, such as [Slack](https://slack.com/). |
|
25
|
|
|
26
|
In this tutorial, you'll integrate Slack with Medusa to receive notifications about created orders. |
|
27
|
|
|
28
|
## Summary |
|
29
|
|
|
30
|
By following this tutorial, you'll learn how to: |
|
31
|
|
|
32
|
- Install and set up Medusa. |
|
33
|
- Integrate Slack with Medusa. |
|
34
|
- Handle Medusa's `order.placed` event to send notifications to Slack. |
|
35
|
|
|
36
|
You can follow this tutorial whether you're new to Medusa or an advanced Medusa developer. |
|
37
|
|
|
38
|
 |
|
39
|
|
|
40
|
<Card |
|
41
|
title="Example Repository" |
|
42
|
text="Find the full code of the guide in this repository." |
|
43
|
href="https://github.com/medusajs/examples/tree/main/slack-integration" |
|
44
|
icon={Github} |
|
45
|
/> |
|
46
|
|
|
47
|
--- |
|
48
|
|
|
49
|
## Step 1: Install a Medusa Application |
|
50
|
|
|
51
|
<Prerequisites items={[ |
|
52
|
{ |
|
53
|
text: "Node.js v20.19.0+ or v22.12.0+", |
|
54
|
link: "https://nodejs.org/en/download" |
|
55
|
}, |
|
56
|
{ |
|
57
|
text: "Git CLI tool", |
|
58
|
link: "https://git-scm.com/downloads" |
|
59
|
}, |
|
60
|
{ |
|
61
|
text: "PostgreSQL", |
|
62
|
link: "https://www.postgresql.org/download/" |
|
63
|
} |
|
64
|
]} /> |
|
65
|
|
|
66
|
Start by installing the Medusa application on your machine with the following command: |
|
67
|
|
|
68
|
```bash |
|
69
|
npx create-medusa-app@latest |
|
70
|
``` |
|
71
|
|
|
72
|
First, you'll be asked for the project's name. Then, when prompted about installing the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx), choose "Yes." |
|
73
|
|
|
74
|
Afterwards, 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. |
|
75
|
|
|
76
|
Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credentials and submit the form. Afterwards, you can log in with the new user and explore the dashboard. |
|
77
|
|
|
78
|
<Note title="Ran into Errors?"> |
|
79
|
|
|
80
|
Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help. |
|
81
|
|
|
82
|
</Note> |
|
83
|
|
|
84
|
<Note> |
|
85
|
|
|
86
|
In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project. |
|
87
|
|
|
88
|
</Note> |
|
89
|
|
|
90
|
--- |
|
91
|
|
|
92
|
## Step 2: Create Slack Module Provider |
|
93
|
|
|
94
|
To integrate third-party services into Medusa, you create a custom [module](!docs!/learn/fundamentals/modules). A module is a reusable package with functionalities related to a single feature or domain. |
|
95
|
|
|
96
|
Medusa's [Notification Module](../../../infrastructure-modules/notification/page.mdx) provides an interface to send notifications in your Medusa application. It delegates the actual sending of notifications to the underlying provider, such as Slack. |
|
97
|
|
|
98
|
In this step, you'll integrate Slack as a Notification Module Provider. Later, you'll use it to send a notification when an order is created. |
|
99
|
|
|
100
|
<Note> |
|
101
|
|
|
102
|
Refer to the [Modules](!docs!/learn/fundamentals/modules) documentation to learn more about modules in Medusa. |
|
103
|
|
|
104
|
</Note> |
|
105
|
|
|
106
|
### a. Install Axios |
|
107
|
|
|
108
|
To send requests to Slack, you'll use the [Axios](https://axios-http.com/) library. So, run the following command to install it in your Medusa application: |
|
109
|
|
|
110
|
```bash npm2yarn |
|
111
|
npm install axios |
|
112
|
``` |
|
113
|
|
|
114
|
You'll use Axios in the module's service. |
|
115
|
|
|
116
|
### b. Create Module Directory |
|
117
|
|
|
118
|
A module is created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/slack`. |
|
119
|
|
|
120
|
### c. Create Slack Module's Service |
|
121
|
|
|
122
|
A module has a service that contains its logic. For Notification Module Providers, the service implements the logic to send notifications with a third-party service. |
|
123
|
|
|
124
|
To create the service of the Slack Notification Module Provider, create the file `src/modules/slack/service.ts` with the following content: |
|
125
|
|
|
126
|
export const serviceHighlights = [ |
|
127
|
["6", "webhook_url", "The Slack webhook URL to send notifications to."], |
|
128
|
["7", "admin_url", "The URL of the Medusa Admin dashboard, used to add links in the notifications."], |
|
129
|
["13", "identifier", "The unique identifier for the module provider."], |
|
130
|
] |
|
131
|
|
|
132
|
```ts title="src/modules/slack/service.ts" highlights={serviceHighlights} |
|
133
|
import { |
|
134
|
AbstractNotificationProviderService, |
|
135
|
} from "@medusajs/framework/utils" |
|
136
|
|
|
137
|
type Options = { |
|
138
|
webhook_url: string |
|
139
|
admin_url: string |
|
140
|
} |
|
141
|
|
|
142
|
type InjectedDependencies = {} |
|
143
|
|
|
144
|
class SlackNotificationProviderService extends AbstractNotificationProviderService { |
|
145
|
static identifier = "slack" |
|
146
|
protected options: Options |
|
147
|
|
|
148
|
constructor(container: InjectedDependencies, options: Options) { |
|
149
|
super() |
|
150
|
this.options = options |
|
151
|
} |
|
152
|
} |
|
153
|
``` |
|
154
|
|
|
155
|
A Notification Module Provider's service must extend the `AbstractNotificationProviderService` class. You'll implement its methods in a bit. |
|
156
|
|
|
157
|
The service must also have an `identifier` static property, which is a unique identifier for the module. This identifier is used when registering the module in the [Medusa container](!docs!/learn/fundamentals/medusa-container). |
|
158
|
|
|
159
|
The service's constructor receives two parameters: |
|
160
|
|
|
161
|
- `container`: The [module's container](!docs!/learn/fundamentals/modules/container) that contains Framework resources available to the module. You don't need to access any resources for this provider. |
|
162
|
- `options`: Options that are passed to the module provider when it's registered in Medusa's configurations. You define the following options: |
|
163
|
- `webhook_url`: The Slack webhook URL to send notifications to. |
|
164
|
- `admin_url`: The URL of the Medusa Admin dashboard, which you'll use to add links in the notifications. |
|
165
|
|
|
166
|
<Note> |
|
167
|
|
|
168
|
You'll learn how to set these options when you [add the module provider to Medusa's configurations](#g-add-module-provider-to-medusas-configurations). |
|
169
|
|
|
170
|
</Note> |
|
171
|
|
|
172
|
In the constructor, you set the `options` property to the passed options. |
|
173
|
|
|
174
|
In the next sections, you'll implement the methods of the `AbstractNotificationProviderService` class. |
|
175
|
|
|
176
|
<Note> |
|
177
|
|
|
178
|
Refer to the [Create Notification Module Provider](/references/notification-provider-module) guide for detailed information about the methods. |
|
179
|
|
|
180
|
</Note> |
|
181
|
|
|
182
|
### d. Implement validateOptions Method |
|
183
|
|
|
184
|
The `validateOptions` method is used to validate the options passed to the module provider. If the method throws an error, the Medusa application won't start. |
|
185
|
|
|
186
|
So, add the `validateOptions` method to the `SlackNotificationProviderService` class: |
|
187
|
|
|
188
|
```ts title="src/modules/slack/service.ts" |
|
189
|
// other imports... |
|
190
|
import { |
|
191
|
MedusaError, |
|
192
|
} from "@medusajs/framework/utils" |
|
193
|
|
|
194
|
class SlackNotificationProviderService extends AbstractNotificationProviderService { |
|
195
|
// ... |
|
196
|
static validateOptions(options: Record<any, any>): void | never { |
|
197
|
if (!options.webhook_url) { |
|
198
|
throw new MedusaError( |
|
199
|
MedusaError.Types.INVALID_ARGUMENT, |
|
200
|
"Webhook URL is required" |
|
201
|
) |
|
202
|
} |
|
203
|
if (!options.admin_url) { |
|
204
|
throw new MedusaError( |
|
205
|
MedusaError.Types.INVALID_ARGUMENT, |
|
206
|
"Admin URL is required" |
|
207
|
) |
|
208
|
} |
|
209
|
} |
|
210
|
} |
|
211
|
``` |
|
212
|
|
|
213
|
The `validateOptions` method receives the options passed to the module provider as a parameter. |
|
214
|
|
|
215
|
In the method, you throw an error if any of the options are not set. |
|
216
|
|
|
217
|
### e. Implement send Method |
|
218
|
|
|
219
|
When the Medusa application needs to send a notification through a channel (such as Slack), it calls the `send` method of the channel's module provider. |
|
220
|
|
|
221
|
You'll first add helper methods that you'll use in the `send` method. Then, you'll implement the `send` method itself. |
|
222
|
|
|
223
|
#### getDisplayAmount Method |
|
224
|
|
|
225
|
The first method you'll add is a method to format amounts for displaying them in notifications. So, add the `getDisplayAmount` method to the `SlackNotificationProviderService` class: |
|
226
|
|
|
227
|
```ts title="src/modules/slack/service.ts" |
|
228
|
class SlackNotificationProviderService extends AbstractNotificationProviderService { |
|
229
|
// ... |
|
230
|
private async getDisplayAmount(amount: number, currencyCode: string) { |
|
231
|
return Intl.NumberFormat("en-US", { |
|
232
|
style: "currency", |
|
233
|
currency: currencyCode, |
|
234
|
}).format(amount) |
|
235
|
} |
|
236
|
} |
|
237
|
``` |
|
238
|
|
|
239
|
The `getDisplayAmount` method receives an amount and a currency code and returns the formatted amount as a string. |
|
240
|
|
|
241
|
#### sendOrderNotification Method |
|
242
|
|
|
243
|
Next, you'll add a method to format a Slack message for created orders. So, add the `sendOrderNotification` method to the `SlackNotificationProviderService` class: |
|
244
|
|
|
245
|
export const sendOrderNotificationHighlights = [ |
|
246
|
["12", "order", "The order to send a notification for."], |
|
247
|
["20", "blocks", "Format the slack message as blocks."], |
|
248
|
["96", "axios", "Send the formatted message to Slack using Axios."], |
|
249
|
] |
|
250
|
|
|
251
|
```ts title="src/modules/slack/service.ts" highlights={sendOrderNotificationHighlights} |
|
252
|
// other imports... |
|
253
|
import { |
|
254
|
OrderDTO, |
|
255
|
ProviderSendNotificationDTO, |
|
256
|
ProviderSendNotificationResultsDTO, |
|
257
|
} from "@medusajs/framework/types" |
|
258
|
import axios from "axios" |
|
259
|
|
|
260
|
class SlackNotificationProviderService extends AbstractNotificationProviderService { |
|
261
|
// ... |
|
262
|
async sendOrderNotification(notification: ProviderSendNotificationDTO) { |
|
263
|
const order = notification.data?.order as OrderDTO |
|
264
|
if (!order) { |
|
265
|
throw new MedusaError( |
|
266
|
MedusaError.Types.NOT_FOUND, |
|
267
|
"Order not found" |
|
268
|
) |
|
269
|
} |
|
270
|
const shippingAddress = order.shipping_address |
|
271
|
const blocks: Record<string, unknown>[] = [ |
|
272
|
{ |
|
273
|
type: "section", |
|
274
|
text: { |
|
275
|
type: "mrkdwn", |
|
276
|
text: `Order *<${this.options.admin_url}/orders/${order.id}|#${order.display_id}>* has been created.`, |
|
277
|
}, |
|
278
|
}, |
|
279
|
] |
|
280
|
|
|
281
|
if (shippingAddress) { |
|
282
|
blocks.push({ |
|
283
|
type: "section", |
|
284
|
text: { |
|
285
|
type: "mrkdwn", |
|
286
|
text: `*Customer*\n${shippingAddress.first_name} ${ |
|
287
|
shippingAddress.last_name |
|
288
|
}\n${order.email}\n*Destination*\n${ |
|
289
|
shippingAddress.address_1 |
|
290
|
}\n${ |
|
291
|
shippingAddress.city |
|
292
|
}, ${(shippingAddress.country_code as string).toUpperCase()}`, |
|
293
|
}, |
|
294
|
}) |
|
295
|
} |
|
296
|
|
|
297
|
blocks.push( |
|
298
|
{ |
|
299
|
type: "section", |
|
300
|
text: { |
|
301
|
type: "mrkdwn", |
|
302
|
text: `*Subtotal*\t${await this.getDisplayAmount(order.subtotal as number, order.currency_code)}\n*Shipping*\t${ |
|
303
|
await this.getDisplayAmount(order.shipping_total as number, order.currency_code) |
|
304
|
}\n*Discount Total*\t${await this.getDisplayAmount( |
|
305
|
order.discount_total as number, |
|
306
|
order.currency_code |
|
307
|
)}\n*Tax*\t${await this.getDisplayAmount(order.tax_total as number, order.currency_code)}\n*Total*\t${ |
|
308
|
await this.getDisplayAmount(order.total as number, order.currency_code) |
|
309
|
}`, |
|
310
|
}, |
|
311
|
}, |
|
312
|
{ |
|
313
|
type: "divider", |
|
314
|
} |
|
315
|
) |
|
316
|
|
|
317
|
await Promise.all( |
|
318
|
order.items?.map(async (item) => { |
|
319
|
const line: Record<string, unknown> = { |
|
320
|
type: "section", |
|
321
|
text: { |
|
322
|
type: "mrkdwn", |
|
323
|
text: `*${item.title}*\n${item.quantity} x ${await this.getDisplayAmount( |
|
324
|
item.unit_price as number, |
|
325
|
order.currency_code |
|
326
|
)}`, |
|
327
|
}, |
|
328
|
} |
|
329
|
|
|
330
|
if (item.thumbnail) { |
|
331
|
const url = item.thumbnail |
|
332
|
|
|
333
|
line.accessory = { |
|
334
|
type: "image", |
|
335
|
alt_text: "Item", |
|
336
|
image_url: url, |
|
337
|
} |
|
338
|
} |
|
339
|
|
|
340
|
blocks.push(line) |
|
341
|
blocks.push({ |
|
342
|
type: "divider", |
|
343
|
}) |
|
344
|
}) || [] |
|
345
|
) |
|
346
|
|
|
347
|
await axios.post(this.options.webhook_url, { |
|
348
|
text: `Order ${order.display_id} was created`, |
|
349
|
blocks, |
|
350
|
}) |
|
351
|
|
|
352
|
return { |
|
353
|
id: order.id, |
|
354
|
} |
|
355
|
} |
|
356
|
} |
|
357
|
``` |
|
358
|
|
|
359
|
The `sendOrderNotification` method receives a `ProviderSendNotificationDTO` object, which is the object passed to the `send` method that you'll implement next. The object has a `data` property that contains the order data. |
|
360
|
|
|
361
|
In the method, you format the Slack message to show the order's ID, customer information, shipping address, order items, and total amounts. You also add a link to the order's details page in the Medusa Admin dashboard. |
|
362
|
|
|
363
|
Finally, you send the formatted message to Slack using the `axios.post` method with the configured webhook URL. |
|
364
|
|
|
365
|
#### send Method |
|
366
|
|
|
367
|
You can now implement the `send` method, which is the method that Medusa calls to send notifications using the provider. Add the `send` method to the `SlackNotificationProviderService` class: |
|
368
|
|
|
369
|
```ts title="src/modules/slack/service.ts" |
|
370
|
class SlackNotificationProviderService extends AbstractNotificationProviderService { |
|
371
|
// ... |
|
372
|
async send( |
|
373
|
notification: ProviderSendNotificationDTO |
|
374
|
): Promise<ProviderSendNotificationResultsDTO> { |
|
375
|
const { template } = notification |
|
376
|
|
|
377
|
switch (template) { |
|
378
|
case "order-created": |
|
379
|
return this.sendOrderNotification(notification) |
|
380
|
default: |
|
381
|
throw new MedusaError( |
|
382
|
MedusaError.Types.NOT_FOUND, |
|
383
|
`Template ${template} not supported` |
|
384
|
) |
|
385
|
} |
|
386
|
} |
|
387
|
} |
|
388
|
``` |
|
389
|
|
|
390
|
The `send` method receives a `ProviderSendNotificationDTO` object, which contains the notification data and the template to use for sending the notification. |
|
391
|
|
|
392
|
<Note> |
|
393
|
|
|
394
|
The method receives other parameters, which you can find in the [Create Notification Module Provider](/references/notification-provider-module#send) guide. |
|
395
|
|
|
396
|
</Note> |
|
397
|
|
|
398
|
In the method, you check the `template` property of the notification object. If it's `order-created`, you call the `sendOrderNotification` method to send the notification. Otherwise, you throw an error indicating that the template is not supported. |
|
399
|
|
|
400
|
### f. Export Module Definition |
|
401
|
|
|
402
|
You've now finished implementing the necessary methods for the Slack Notification Module Provider. |
|
403
|
|
|
404
|
The final piece to a module is its definition, which you export in an `index.ts` file at the module's root directory. This definition tells Medusa the module's details, including its service. |
|
405
|
|
|
406
|
To create the module's definition, create the file `src/modules/slack/index.ts` with the following content: |
|
407
|
|
|
408
|
```ts title="src/modules/slack/index.ts" |
|
409
|
import SlackNotificationProvider from "./service" |
|
410
|
import { |
|
411
|
ModuleProvider, |
|
412
|
Modules, |
|
413
|
} from "@medusajs/framework/utils" |
|
414
|
|
|
415
|
export default ModuleProvider(Modules.NOTIFICATION, { |
|
416
|
services: [SlackNotificationProvider], |
|
417
|
}) |
|
418
|
``` |
|
419
|
|
|
420
|
You use `ModuleProvider` from the Modules SDK to create the module provider's definition. It accepts two parameters: |
|
421
|
|
|
422
|
1. The name of the module that this provider belongs to, which is `Modules.NOTIFICATION` in this case. |
|
423
|
2. An object with a required property `services` indicating the Module Provider's services. |
|
424
|
|
|
425
|
### g. Add Module Provider to Medusa's Configurations |
|
426
|
|
|
427
|
Once you finish building the module, add it to Medusa's configurations to start using it. |
|
428
|
|
|
429
|
In `medusa-config.ts`, add a `modules` property: |
|
430
|
|
|
431
|
export const configHighlights = [ |
|
432
|
["10", "id", "The ID of the module provider, used to register it."], |
|
433
|
["12", "channels", "The channels that this provider is used to send notifications."], |
|
434
|
["13", "webhook_url", "The Slack webhook URL to send notifications to."], |
|
435
|
["14", "admin_url", "The URL of the Medusa Admin dashboard, used to add links in the notifications."] |
|
436
|
] |
|
437
|
|
|
438
|
```ts title="medusa-config.ts" highlights={configHighlights} |
|
439
|
module.exports = defineConfig({ |
|
440
|
// ... |
|
441
|
modules: [ |
|
442
|
{ |
|
443
|
resolve: "@medusajs/medusa/notification", |
|
444
|
options: { |
|
445
|
providers: [ |
|
446
|
{ |
|
447
|
resolve: "./src/modules/slack", |
|
448
|
id: "slack", |
|
449
|
options: { |
|
450
|
channels: ["slack"], |
|
451
|
webhook_url: process.env.SLACK_WEBHOOK_URL, |
|
452
|
admin_url: process.env.SLACK_ADMIN_URL, |
|
453
|
}, |
|
454
|
}, |
|
455
|
], |
|
456
|
}, |
|
457
|
}, |
|
458
|
], |
|
459
|
}) |
|
460
|
``` |
|
461
|
|
|
462
|
To pass a Notification Module Provider to the Notification Module, you add the `modules` property to the Medusa configuration and pass the Notification Module in its value. |
|
463
|
|
|
464
|
The Notification Module accepts a `providers` option, which is an array of Notification Module Providers to register. |
|
465
|
|
|
466
|
To register the Slack Notification Module Provider, you add an object to the `providers` array with the following properties: |
|
467
|
|
|
468
|
- `resolve`: The NPM package or path to the module provider. In this case, it's the path to the `src/modules/slack` directory. |
|
469
|
- `id`: The ID of the module provider. The Notification Module Provider is then registered with the ID `np_{identifier}_{id}`, where: |
|
470
|
- `{identifier}`: The identifier static property defined in the Module Provider's service, which is `slack` in this case. |
|
471
|
- `{id}`: The ID set in this configuration, which is also `slack` in this case. |
|
472
|
- `options`: The options to pass to the module provider. These are the options you defined in the `Options` interface of the module provider's service. |
|
473
|
- You must also set a `channel` option that indicates the channel this provider is used to send notifications. |
|
474
|
|
|
475
|
### h. Set Options as Environment Variables |
|
476
|
|
|
477
|
Next, you'll set the options you passed to the Slack Notification Module Provider as environment variables. |
|
478
|
|
|
479
|
To set the webhook URL, you need to create a Slack application and configure a webhook URL. To do that: |
|
480
|
|
|
481
|
1. Go to your [Slack Apps](https://api.slack.com/apps) page. |
|
482
|
2. Click the "Create New App" button. |
|
483
|
|
|
484
|
 |
|
485
|
|
|
486
|
3. In the pop-up, choose "From scratch". |
|
487
|
4. Enter the app's name and select the workspace to install it in. |
|
488
|
5. Once you're done, click the "Create App" button. |
|
489
|
|
|
490
|
 |
|
491
|
|
|
492
|
6. In the app's settings, go to the "Incoming Webhooks" section. |
|
493
|
7. Enable the "Activate Incoming Webhooks" toggle. |
|
494
|
|
|
495
|
 |
|
496
|
|
|
497
|
8. In the "Webhook URLs for Your Workspace" section, click the "Add New Webhook" button. |
|
498
|
|
|
499
|
 |
|
500
|
|
|
501
|
9. Select the channel or conversation to send notifications to and click the "Allow" button. |
|
502
|
10. Copy the generated webhook URL. |
|
503
|
|
|
504
|
 |
|
505
|
|
|
506
|
Then, in the `.env` file of your Medusa application, set the `SLACK_WEBHOOK_URL` and `SLACK_ADMIN_URL` environment variables: |
|
507
|
|
|
508
|
```shell title=".env" |
|
509
|
SLACK_WEBHOOK_URL=https://hooks.slack.com/... |
|
510
|
SLACK_ADMIN_URL=http://localhost:9000/app |
|
511
|
``` |
|
512
|
|
|
513
|
In development, the Medusa Admin dashboard is running on `http://localhost:9000/app`, so you can use that URL for the `SLACK_ADMIN_URL` environment variable. |
|
514
|
|
|
515
|
You'll test out the integration when you handle the `order.placed` event in the next step. |
|
516
|
|
|
517
|
--- |
|
518
|
|
|
519
|
## Step 3: Handle the `order.placed` Event |
|
520
|
|
|
521
|
Now that you've integrated Slack with Medusa, you can send notifications to Slack at any point, including when an order is created. |
|
522
|
|
|
523
|
To send a notification to Slack when an order is created, you will: |
|
524
|
|
|
525
|
- Implement the order details retrieval and notification sending with Slack in a [workflow](!docs!/learn/fundamentals/workflows). A workflow is a series of actions, called steps, that complete a task with rollback and retry mechanisms. |
|
526
|
- Listen to the `order.placed` event in a [subscriber](!docs!/learn/fundamentals/events-and-subscribers). A subscriber is an asynchronous function that listens to events to perform actions, such as execute a workflow, when the event is emitted. |
|
527
|
|
|
528
|
### a. Create the Workflow |
|
529
|
|
|
530
|
The workflow to send notifications to Slack will have the following steps: |
|
531
|
|
|
532
|
<WorkflowDiagram |
|
533
|
workflow={{ |
|
534
|
name: "orderPlacedNotificationWorkflow", |
|
535
|
steps: [ |
|
536
|
{ |
|
537
|
type: "step", |
|
538
|
name: "useQueryGraphStep", |
|
539
|
description: "Retrieve the order details.", |
|
540
|
link: "/references/helper-steps/useQueryGraphStep", |
|
541
|
depth: 1 |
|
542
|
}, |
|
543
|
{ |
|
544
|
type: "step", |
|
545
|
name: "sendNotificationsStep", |
|
546
|
description: "Send a notification with a configured provider.", |
|
547
|
link: "/references/medusa-workflows/steps/sendNotificationsStep", |
|
548
|
depth: 1 |
|
549
|
} |
|
550
|
] |
|
551
|
}} |
|
552
|
hideLegend |
|
553
|
/> |
|
554
|
|
|
555
|
Medusa provides both steps in its `@medusajs/medusa/core-flows` package. |
|
556
|
|
|
557
|
So, to create the workflow, create the file `src/workflows/order-placed-notification.ts` with the following content: |
|
558
|
|
|
559
|
export const orderPlacedNotificationWorkflowHighlights = [ |
|
560
|
["13", "useQueryGraphStep", "Retrieve the order details using the Query Graph."], |
|
561
|
["34", "sendNotificationsStep", "Send a notification to Slack with the order details."] |
|
562
|
] |
|
563
|
|
|
564
|
```ts title="src/workflows/order-placed-notification.ts" highlights={orderPlacedNotificationWorkflowHighlights} |
|
565
|
import { |
|
566
|
createWorkflow, |
|
567
|
} from "@medusajs/framework/workflows-sdk" |
|
568
|
import { sendNotificationsStep, useQueryGraphStep } from "@medusajs/medusa/core-flows" |
|
569
|
|
|
570
|
type WorkflowInput = { |
|
571
|
id: string |
|
572
|
} |
|
573
|
|
|
574
|
export const orderPlacedNotificationWorkflow = createWorkflow( |
|
575
|
"order-placed-notification", |
|
576
|
({ id }: WorkflowInput) => { |
|
577
|
const { data: orders } = useQueryGraphStep({ |
|
578
|
entity: "order", |
|
579
|
fields: [ |
|
580
|
"id", |
|
581
|
"display_id", |
|
582
|
"email", |
|
583
|
"shipping_address.*", |
|
584
|
"subtotal", |
|
585
|
"shipping_total", |
|
586
|
"currency_code", |
|
587
|
"discount_total", |
|
588
|
"tax_total", |
|
589
|
"total", |
|
590
|
"items.*", |
|
591
|
"original_total", |
|
592
|
], |
|
593
|
filters: { |
|
594
|
id, |
|
595
|
}, |
|
596
|
}) |
|
597
|
|
|
598
|
sendNotificationsStep([{ |
|
599
|
to: "slack-channel", // This will be configured in the Slack app |
|
600
|
channel: "slack", |
|
601
|
template: "order-created", |
|
602
|
data: { |
|
603
|
order: orders[0], |
|
604
|
}, |
|
605
|
}]) |
|
606
|
} |
|
607
|
) |
|
608
|
``` |
|
609
|
|
|
610
|
You create a workflow using `createWorkflow` from the Workflows SDK. It accepts the workflow's unique name as a first parameter. |
|
611
|
|
|
612
|
It accepts as a second parameter a constructor function, which is the workflow's implementation. The function can accept input, which in this case is an object holding the ID of the order placed. |
|
613
|
|
|
614
|
In the workflow's constructor function, you: |
|
615
|
|
|
616
|
- Retrieve the order's details using the `useQueryGraphStep`. This step uses Medusa's [Query](!docs!/learn/fundamentals/query) tool to retrieve data across modules. You pass it the order ID to retrieve. |
|
617
|
- Send a notification using the `sendNotificationsStep`. You pass the step an array of notifications to send, and each notification is an object with the following properties: |
|
618
|
- `to`: The channel to send the notification to. Since you configure this in the Slack app, you just set it to `slack-channel`. |
|
619
|
- `channel`: The channel to use for sending the notification. By setting it to `slack`, the Notification Module will use the Slack Notification Module Provider to send the notification. |
|
620
|
- `template`: The template to use for sending the notification, which is `order-created` in this case. |
|
621
|
- `data`: The data payload to pass with the notification, which contains the order details. |
|
622
|
|
|
623
|
You now have a workflow that retrieves the order details and sends a notification to Slack when an order is placed. |
|
624
|
|
|
625
|
<Note> |
|
626
|
|
|
627
|
Refer to the [Workflows](!docs!/learn/fundamentals/workflows) documentation to learn more about workflows and steps. |
|
628
|
|
|
629
|
</Note> |
|
630
|
|
|
631
|
### b. Create the Subscriber |
|
632
|
|
|
633
|
To execute the workflow when an order is placed, you need to create a subscriber that listens to the `order.placed` event and executes the workflow. |
|
634
|
|
|
635
|
To create the subscriber, create the file `src/subscribers/order-placed.ts` with the following content: |
|
636
|
|
|
637
|
```ts title="src/subscribers/order-placed.ts" |
|
638
|
import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework" |
|
639
|
import { |
|
640
|
orderPlacedNotificationWorkflow, |
|
641
|
} from "../workflows/order-placed-notification" |
|
642
|
|
|
643
|
export default async function orderPlacedHandler({ |
|
644
|
event: { data }, |
|
645
|
container, |
|
646
|
}: SubscriberArgs<{ id: string }>) { |
|
647
|
await orderPlacedNotificationWorkflow(container) |
|
648
|
.run({ |
|
649
|
input: data, |
|
650
|
}) |
|
651
|
} |
|
652
|
|
|
653
|
export const config: SubscriberConfig = { |
|
654
|
event: "order.placed", |
|
655
|
} |
|
656
|
``` |
|
657
|
|
|
658
|
A subscriber file must export: |
|
659
|
|
|
660
|
1. An asynchronous function, which is the subscriber that is executed when the event is emitted. |
|
661
|
2. A configuration object that holds the name of the event that the subscriber listens to, which is `order.placed` in this case. |
|
662
|
|
|
663
|
The subscriber function receives an object as a parameter that has the following properties: |
|
664
|
|
|
665
|
- `event`: An object that holds the event's data payload. The payload of the `order.placed` event is the ID of the order placed. |
|
666
|
- `container`: The [Medusa container](!docs!/learn/fundamentals/medusa-container) to access the Framework and commerce tools. |
|
667
|
|
|
668
|
In the subscriber function, you execute the `orderPlacedNotificationWorkflow` by invoking it, passing the Medusa container as a parameter. Then, you chain a `run` method, passing it the order ID from the event's data payload as input. |
|
669
|
|
|
670
|
<Note> |
|
671
|
|
|
672
|
Refer to the [Events and Subscribers](!docs!/learn/fundamentals/events-and-subscribers) documentation to learn more about creating subscribers. |
|
673
|
|
|
674
|
</Note> |
|
675
|
|
|
676
|
### Test it Out |
|
677
|
|
|
678
|
You'll now test out the integration by placing an order using the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx). |
|
679
|
|
|
680
|
<Note title="Reminder" forceMultiline> |
|
681
|
|
|
682
|
The Next.js Starter Storefront is available in the `apps/storefront` directory of your project: |
|
683
|
|
|
684
|
```bash |
|
685
|
cd apps/storefront |
|
686
|
``` |
|
687
|
|
|
688
|
</Note> |
|
689
|
|
|
690
|
First, start the Medusa application by running the following command in the `apps/backend` directory: |
|
691
|
|
|
692
|
```bash npm2yarn badgeLabel="Medusa Application" badgeColor="green" |
|
693
|
npm run dev |
|
694
|
``` |
|
695
|
|
|
696
|
Then, start the Next.js Starter Storefront by running the following command in the storefront's directory: |
|
697
|
|
|
698
|
```bash npm2yarn badgeLabel="Next.js Starter Storefront" badgeColor="blue" |
|
699
|
npm run dev |
|
700
|
``` |
|
701
|
|
|
702
|
Next, open the Next.js Starter Storefront in your browser at `http://localhost:8000`. Add a product to the cart, proceed to checkout, and place an order. |
|
703
|
|
|
704
|
Afterwards, you'll receive a notification in the Slack channel you configured in the Slack app. The notification will contain the order details. |
|
705
|
|
|
706
|
You can also click on the order's ID in the notification to open the order's details page in the Medusa Admin dashboard. |
|
707
|
|
|
708
|
 |
|
709
|
|
|
710
|
--- |
|
711
|
|
|
712
|
## Next Steps |
|
713
|
|
|
714
|
You've now integrated Slack with Medusa to receive notifications about created orders. You can expand on this integration to send other types of notifications, such as order updates. Refer to the [Events Reference](/references/events) for a list of events you can listen to in your subscribers. |
|
715
|
|
|
716
|
You can also customize the notifications to include more information or change the format of the messages. Refer to [Slack's documentation](https://api.slack.com/reference/surfaces/formatting) for more information on how to format messages in Slack. |
|
717
|
|
|
718
|
If you're new to Medusa, check out the [main documentation](!docs!/learn), where you'll get a more in-depth understanding of all the concepts you've used in this guide and more. |
|
719
|
|
|
720
|
To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx). |
|
721
|
|
|
722
|
### Troubleshooting |
|
723
|
|
|
724
|
If you encounter issues during your development, check out the [troubleshooting guides](../../../troubleshooting/page.mdx). |
|
725
|
|
|
726
|
### Getting Help |
|
727
|
|
|
728
|
If you encounter issues not covered in the troubleshooting guides: |
|
729
|
|
|
730
|
1. Visit the [Medusa GitHub repository](https://github.com/medusajs/medusa) to report issues or ask questions. |
|
731
|
2. Join the [Medusa Discord community](https://discord.gg/medusajs) for real-time support from community members. |
|
732
|
3. Contact the [sales team](https://medusajs.com/contact/) to get help from the Medusa team. |