docs: editing and general fixes of medusa's learning resources (#7261)

* docs: editing and general fixes of medusa's learning resources

* fix build script

* update ui dependency

* fix build

* adjust next.js steps
This commit is contained in:
Shahed Nasser
2024-05-13 18:55:11 +03:00
committed by GitHub
parent 803e4aad02
commit 7cb90f8e82
79 changed files with 488 additions and 1707 deletions
@@ -0,0 +1,238 @@
import { Table } from "docs-ui"
export const metadata = {
title: `Mailchimp Plugin`,
}
# {metadata.title}
## Features
[Mailchimp](https://mailchimp.com) is an email marketing service used to create newsletters and subscriptions.
By integrating Mailchimp with Medusa, customers can subscribe from Medusa to your Mailchimp newsletter and are automatically added to your Mailchimp subscribers list.
---
## Install the Mailchimp Plugin
<Note type="check">
- [Mailchimp account](https://mailchimp.com/signup)
- [Mailchimp API Key](https://mailchimp.com/help/about-api-keys/#Find_or_generate_your_API_key)
- [Mailchimp Audience ID](https://mailchimp.com/help/find-audience-id/)
</Note>
To install the Mailchimp plugin, run the following command in the directory of your Medusa application:
```bash npm2yarn
npm install medusa-plugin-mailchimp
```
Next, add the plugin into the `plugins` array in `medusa-config.js`:
export const highlights = [
["6", "api_key", "The Mailchimp API Key."],
["7", "newsletter_list_id", "The Mailchimp Audience ID."],
]
```js title="medusa-config.js" highlights={highlights}
const plugins = [
// ...,
{
resolve: `medusa-plugin-mailchimp`,
options: {
api_key: process.env.MAILCHIMP_API_KEY,
newsletter_list_id:
process.env.MAILCHIMP_NEWSLETTER_LIST_ID,
},
},
]
```
### Mailchimp Plugin Options
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Option</Table.HeaderCell>
<Table.HeaderCell>Description</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row>
<Table.Cell>
`api_key`
</Table.Cell>
<Table.Cell>
A string indicating the Mailchimp API Key.
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`newsletter_list_id`
</Table.Cell>
<Table.Cell>
A string indicating the Mailchimp Audience ID.
</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
### Environment Variables
Make sure to add the necessary environment variables for the above options in `.env`:
```bash
MAILCHIMP_API_KEY=<YOUR_API_KEY>
MAILCHIMP_NEWSLETTER_LIST_ID=<YOUR_NEWSLETTER_LIST_ID>
```
---
## Test the Plugin
To test the plugin, start the Medusa application:
```bash npm2yarn
npm run dev
```
This plugin adds new `POST` and `PUT` API Routes at `/mailchimp/subscribe`. These API Routes require in the body of the request an `email` field. You can also optionally include a `data` object that holds any additional data you want to send to Mailchimp.
Check out [Mailchimps subscription documentation](https://mailchimp.com/developer/marketing/api/list-merges/) for more details on the data you can send.
### Without Additional Data
Try sending a `POST` or `PUT` request to `/mailchimp/subscribe`:
```bash noReport apiTesting testApiUrl="http://localhost:9000/mailchimp/subscribe" testApiMethod="POST" testBodyParams={{ "email": "example@gmail.com" }}
curl -X POST http://localhost:9000/mailchimp/subscribe \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "example@gmail.com"
}'
```
When the subscription is successful, a `200` response code is returned with `OK` message.
When the same email address is used again in the `POST`, a `400` response is returned. If this can occur in your usecase, use the `PUT` API Route instead.
Check your Mailchimp dashboard, you should find the email added to your Audience list.
### With Additional Data
For example, send in the `data` request body parameter a `tags` array:
```bash noReport apiTesting testApiUrl="http://localhost:9000/mailchimp/subscribe" testApiMethod="POST" testBodyParams={{ "email": "example@gmail.com" }}
curl -X POST http://localhost:9000/mailchimp/subscribe \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "example@gmail.com",
"data": {
"tags": ["customer"]
}
}'
```
All fields inside `data` is sent to Mailchimp along with the email.
---
## Use MailchimpService
Use the `MailchimpService` to subscribe users to the newsletter in other contexts. This service has a method `subscribeNewsletter` that subscribes a customer to the newsletter.
For example:
```ts title="src/subscribers/customer-created.ts"
import {
type SubscriberConfig,
type SubscriberArgs,
CustomerService,
} from "@medusajs/medusa"
export default async function handleCustomerCreated({
data,
container,
}: SubscriberArgs<Record<string, string>>) {
const mailchimpService = container.resolve("mailchimpService")
mailchimpService.subscribeNewsletter(
data.email,
{ tags: ["customer"] } // optional
)
}
export const config: SubscriberConfig = {
event: CustomerService.Events.CREATED,
}
```
This creates a subscriber that listens to the `CustomerService.Events.CREATED` (`customer.created`) event and subscribes the customer automatically using the `mailchimpService`.
---
## Add Subscription Form
This section provides a simple example of adding a subscription form in your storefront. The code is for React-based frameworks, but you can use the same logic for your storefronts regardless of the framework you are using.
You need to use [axios](https://github.com/axios/axios) to send API requests, so start by installing it in your storefront project:
```bash npm2yarn
npm install axios
```
Then, create the following component that uses the mailchimp plugin's API route to subscribe customers:
```tsx
import axios from "axios"
import { useState } from "react"
export default function NewsletterForm() {
const [email, setEmail] = useState("")
function subscribe(e) {
e.preventDefault()
if (!email) {
return
}
axios.post("http://localhost:9000/mailchimp/subscribe", {
email,
})
.then((e) => {
alert("Subscribed successfully!")
setEmail("")
})
.catch((e) => {
console.error(e)
alert("An error occurred")
})
}
return (
<form onSubmit={subscribe}>
<h2>Sign Up for our newsletter</h2>
<input
type="email"
name="email"
id="email"
placeholder="example@gmail.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<button type="submit">Subscribe</button>
</form>
)
}
```
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,160 @@
import { Table } from "docs-ui"
export const metadata = {
title: `Slack Plugin`,
}
# {metadata.title}
## Features
Slack is a communication platform used by teams and organizations for collaboration and messaging. This plugin sends merchants a slack message when a new order is placed.
The notification contains details about the order including:
- Customer's details and address.
- Items ordered, their quantity, and the price.
- Order totals including Tax amount.
- Promotion details if there are any (this is optional and can be turned off).
---
## Install the Slack Plugin
<Note type="check">
- [Slack account](https://slack.com)
- [A Slack app](https://api.slack.com/start/quickstart#creating)
- [Activate incoming webhooks in Slack and create a new webhook](https://api.slack.com/start/quickstart#webhooks)
</Note>
To install the Slack plugin, run the following command in the directory of your Medusa application:
```bash npm2yarn
npm install medusa-plugin-slack-notification
```
Next, add the plugin into the `plugins` array in `medusa-config.js`:
export const highlights = [
["6", "slack_url", "The Slack webhook URL."],
["7", "show_discount_code", "Whether to show the discount code after creating the Slack app."],
["8", "admin_orders_url", "The prefix of the URL of the order detail pages on your admin panel."],
]
```js title="medusa-config.js" highlights={highlights}
const plugins = [
// ...
{
resolve: `medusa-plugin-slack-notification`,
options: {
slack_url: process.env.SLACK_WEBHOOK_URL,
show_discount_code: false,
admin_orders_url: `http://localhost:7001/a/orders`,
},
},
]
```
### Twilio SMS Plugin Options
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Option</Table.HeaderCell>
<Table.HeaderCell>Description</Table.HeaderCell>
<Table.HeaderCell>Required</Table.HeaderCell>
<Table.HeaderCell>Default</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row>
<Table.Cell>
`slack_url`
</Table.Cell>
<Table.Cell>
A string indicating the Slack webhook URL.
</Table.Cell>
<Table.Cell>
Yes
</Table.Cell>
<Table.Cell>
\-
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`show_discount_code`
</Table.Cell>
<Table.Cell>
A boolean whether to show the discount code after creating the Slack app.
</Table.Cell>
<Table.Cell>
No
</Table.Cell>
<Table.Cell>
`false`
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`admin_orders_url`
</Table.Cell>
<Table.Cell>
A string indicating the prefix of the URL of the order detail pages on your admin panel.
If youre using Medusa Admin locally, it should be `http://localhost:7001/a/orders`. This results in a URL like `http://localhost:7001/a/orders/order_01FYP7DM7PS43H9VQ1PK59ZR5G`.
</Table.Cell>
<Table.Cell>
No, but if not provided the order URL in the messages will be `/order_01FYP7DM7PS43H9VQ1PK59ZR5G`
</Table.Cell>
<Table.Cell>
\-
</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
### Environment Variables
Make sure to add the necessary environment variables for the above options in `.env`:
```bash
SLACK_WEBHOOK_URL=<YOUR_WEBHOOK_URL>
```
---
## Test the Plugin
To test the plugin, start the Medusa application:
```bash npm2yarn
npm run dev
```
Then, place an order using either a [storefront](../../../nextjs-starter/page.mdx) or the [Store API Routes](https://docs.medusajs.com/api/store). A message is sent to the DM or slack channel you configured in the Slack webhook.
@@ -0,0 +1,165 @@
import { Table } from "docs-ui"
export const metadata = {
title: `Twilio SMS Plugin`,
}
# {metadata.title}
## Features
[Twilios SMS API](https://www.twilio.com/sms) is used to send users SMS messages instantly. It has a lot of additional features such as Whatsapp messaging and conversations.
By integrating Twilio SMS into Medusa, youll have easy access to Twilios SMS API to send SMS messages to your users and customers. You can use it to send order confirmations, verification codes, reset password messages, and more.
This plugin only gives you access to the Twilio SMS API but doesn't automate sending messages. Youll have to add this yourself where you need it. There's an [example later in this guide](#example-plugin-usage) on how to send an SMS for a new order.
---
## Install the Twilio SMS Plugin
<Note type="check">
- [Twilio account](https://www.twilio.com/sms)
- [Twilio account SID](https://help.twilio.com/articles/14726256820123-What-is-a-Twilio-Account-SID-and-where-can-I-find-it-)
- [Twilio auth token](https://help.twilio.com/articles/223136027-Auth-Tokens-and-How-to-Change-Them?_gl=1*qv22ht*_ga*OTY3NzYwMDAzLjE2OTE0MjA5MDI.*_ga_RRP8K4M4F3*MTcwOTIwMDA2Ny40LjAuMTcwOTIwMDA2Ny4wLjAuMA..)
- [Twilio phone number](https://help.twilio.com/articles/223135247)
</Note>
To install the Twilio SMS plugin, run the following command in the directory of your Medusa application:
```bash npm2yarn
npm install medusa-plugin-twilio-sms
```
Next, add the plugin into the `plugins` array in `medusa-config.js`:
export const highlights = [
["6", "account_sid", "The Twilio account SID."],
["7", "auth_token", "The Twilio auth token."],
["8", "from_number", "The Twilio phone number."],
]
```js title="medusa-config.js" highlights={highlights}
const plugins = [
// ...
{
resolve: `medusa-plugin-twilio-sms`,
options: {
account_sid: process.env.TWILIO_SMS_ACCOUNT_SID,
auth_token: process.env.TWILIO_SMS_AUTH_TOKEN,
from_number: process.env.TWILIO_SMS_FROM_NUMBER,
},
},
]
```
### Twilio SMS Plugin Options
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Option</Table.HeaderCell>
<Table.HeaderCell>Description</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row>
<Table.Cell>
`account_sid`
</Table.Cell>
<Table.Cell>
A string indicating the Twilio account SID.
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`auth_token`
</Table.Cell>
<Table.Cell>
A string indicating the Twilio auth token.
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`from_number`
</Table.Cell>
<Table.Cell>
A string indicating the Twilio phone number.
</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
### Environment Variables
Make sure to add the necessary environment variables for the above options in `.env`:
```bash
TWILIO_SMS_ACCOUNT_SID=<YOUR_ACCOUNT_SID>
TWILIO_SMS_AUTH_TOKEN=<YOUR_AUTH_TOKEN>
TWILIO_SMS_FROM_NUMBER=<YOUR_TWILIO_NUMBER>
```
---
## Example Plugin Usage
Resolve and use the `TwilioSmsService` to send SMS.
For example, create the file `src/subscriber/sms.ts` with the following content:
```ts title="src/subscriber/sms.ts"
import {
type SubscriberConfig,
type SubscriberArgs,
OrderService,
} from "@medusajs/medusa"
export default async function handleOrderPlaced({
data,
container,
}: SubscriberArgs<Record<string, string>>) {
const twilioSmsService = container.resolve("twilioSmsService")
const orderService: OrderService =
container.resolve("orderService")
const order = await orderService.retrieve(data.id, {
relations: ["shipping_address"],
})
if (order.shipping_address.phone) {
twilioSmsService.sendSms({
to: order.shipping_address.phone,
body: "We have received your order #" + data.id,
})
}
}
export const config: SubscriberConfig = {
event: OrderService.Events.PLACED,
}
```
This creates a subscriber that listens to the `OrderService.Events.PLACED` (`order.placed`) event and sends an SMS to the customer confirming their order.
The `sendSms` method of the `TwilioSmsService` accepts an object whose shape is as described in [Twilio's API reference](https://www.twilio.com/docs/sms/api/message-resource#create-a-message-resource).
<Note type="warning">
If youre on a Twilio trial make sure that the phone number you entered on checkout is a [verified Twilio number on your console](https://console.twilio.com/us1/develop/phone-numbers/manage/verified).
</Note>