chore: merge docs from master to develop (#3650)

* Fix issue on fixed total amount discount when using includes tax (#3472)

The calculation of the fixed discount amount breaks when having includes_tax setting active, due to the line item totals are incorrect and returning everything as 0, thus the totalItemPercentage will be Infinitiy due to the division by a subtotal of 0

* chore: Add missing changeset for @medusajs/medusa

* feat(medusa): Improve performance of Products domain (#3417)

* feat(medusa): Improve product update performances

* fix tests and update

* update mock repo

* improve repo

* cleanup

* fix

* cleanup + bulk emit + unit test fix

* improvements

* improve

* fix unit tests

* fix export

* fix product update handler

* enhance mock repo

* fix import integration

* fix end point tests

* revert mock repo product variant

* fix unit

* cleanup

* cleanup

* address feedback

* fix quotes in tests

* address feedback

* Create new-tips-mate.md

* use types

* chore: Remove integration-tests from changeset

* chore(release): v1.7.14

* chore(docs): Generated Docs Announcement Bar (automated) (#3489)

Co-authored-by: olivermrbl <olivermrbl@users.noreply.github.com>

* fix(medusa): EventBusService.emit using Redis mock (#3491)

* Fix eventBusService.emit using redis mock

* revert gitignore

* enqueuer

* unit test add redis_url

* fix test

* chore(docs): Generated Services Reference (automated) (#3490)

Co-authored-by: olivermrbl <olivermrbl@users.noreply.github.com>

* docs: publish restructure (#3496)

* docs: added features and guides overview page

* added image

* added version 2

* added version 3

* added version 4

* docs: implemented new color scheme

* docs: redesigned sidebar (#3193)

* docs: redesigned navbar for restructure (#3199)

* docs: redesigned footer (#3209)

* docs: redesigned cards (#3230)

* docs: redesigned admonitions (#3231)

* docs: redesign announcement bar (#3236)

* docs: redesigned large cards (#3239)

* docs: redesigned code blocks (#3253)

* docs: redesigned search modal and page (#3264)

* docs: redesigned doc footer (#3268)

* docs: added new sidebars + refactored css and assets (#3279)

* docs: redesigned api reference sidebar

* docs: refactored css

* docs: added code tabs transition

* docs: added new sidebars

* removed unused assets

* remove unusued assets

* Fix deploy errors

* fix incorrect link

* docs: fixed code responsivity + missing icons (#3283)

* docs: changed icons (#3296)

* docs: design fixes to the sidebar (#3297)

* redesign fixes

* docs: small design fixes

* docs: several design fixes after restructure (#3299)

* docs: bordered icon fixes

* docs: desgin fixes

* fixes to code blocks and sidebar scroll

* design adjustments

* docs: restructured homepage (#3305)

* docs: restructured homepage

* design fixes

* fixed core concepts icon

* docs: added core concepts page (#3318)

* docs: restructured homepage

* design fixes

* docs: added core concepts page

* changed text of different components

* docs: added architecture link

* added missing prop for user guide

* docs: added regions overview page (#3327)

* docs: added regions overview

* moved region pages to new structure

* docs: fixed description of regions architecture page

* small changes

* small fix

* docs: added customers overview page (#3331)

* docs: added regions overview

* moved region pages to new structure

* docs: fixed description of regions architecture page

* small changes

* small fix

* docs: added customers overview page

* fix link

* resolve link issues

* docs: updated regions architecture image

* docs: second-iteration fixes (#3347)

* docs: redesigned document

* design fixes

* docs: added products overview page (#3354)

* docs: added carts overview page (#3363)

* docs: added orders overview (#3364)

* docs: added orders overview

* added links in overview

* docs: added vercel redirects

* docs: added soon badge for cards (#3389)

* docs: resolved feedback changes + organized troubleshooting pages (#3409)

* docs: resolved feedback changes

* added extra line

* docs: changed icons for restructure (#3421)

* docs: added taxes overview page (#3422)

* docs: added taxes overview page

* docs: fix sidebar label

* added link to taxes overview page

* fixed link

* docs: fixed sidebar scroll (#3429)

* docs: added discounts overview (#3432)

* docs: added discounts overview

* fixed links

* docs: added gift cards overview (#3433)

* docs: added price lists overview page (#3440)

* docs: added price lists overview page

* fixed links

* docs: added sales channels overview page (#3441)

* docs: added sales overview page

* fixed links

* docs: added users overview (#3443)

* docs: fixed sidebar border height (#3444)

* docs: fixed sidebar border height

* fixed svg markup

* docs: added possible solutions to feedback component (#3449)

* docs: added several overview pages + restructured files (#3463)

* docs: added several overview pages

* fixed links

* docs: added feature flags + PAK overview pages (#3464)

* docs: added feature flags + PAK overview pages

* fixed links

* fix link

* fix link

* fixed links colors

* docs: added strategies overview page (#3468)

* docs: automated upgrade guide (#3470)

* docs: automated upgrade guide

* fixed vercel redirect

* docs: restructured files in docs codebase (#3475)

* docs: restructured files

* docs: fixed eslint exception

* docs: finished restructure loose-ends (#3493)

* fixed uses of backend

* docs: finished loose ends

* eslint fixes

* fixed links

* merged master

* added update instructions for v1.7.12

* docs: fixed discount details (#3499)

* docs: fix trailing slash causing 404 (#3508)

* docs: fix error during navigation (#3509)

* docs: removed the gatsby storefront guide (#3527)

* docs: removed the gatsby storefront guide

* docs: fixed query value

* chore(docs): Removed Docs Announcement Bar (automated) (#3536)

Co-authored-by: shahednasser <shahednasser@users.noreply.github.com>

* fix(medusa): Variant update should include the id for the listeners to be able to identify the entity (#3539)

* fix(medusa): Variant update should include the id for the listeners to be able to identify the entity

* fix unit tests

* Create brave-seahorses-film.md

* docs: fix admin redirects (#3548)

* chore(release): v1.7.15

* chore(docs): Generated Docs Announcement Bar (automated) (#3550)

Co-authored-by: olivermrbl <olivermrbl@users.noreply.github.com>

* chore(docs): Generated Services Reference (automated) (#3551)

Automated changes by [create-pull-request](https://github.com/peter-evans/create-pull-request) GitHub action

Co-authored-by: Oliver Windall Juhl <59018053+olivermrbl@users.noreply.github.com>

* chore: updated READMEs of plugins (#3546)

* chore: updated READMEs of plugins

* added notice to plugins

* docs: added a deploy guide for next.js storefront (#3558)

* docs: added a deploy next.js guide

* docs: fix image zoom

* docs: fixes to next.js deployment guide to vercel (#3562)

* chore(workflows): Enable manual workflow in pre-release mode (#3566)

* chore(docs): Removed Docs Announcement Bar (automated) (#3598)

Co-authored-by: shahednasser <shahednasser@users.noreply.github.com>

* fix(medusa): Rounding issues on line item adjustments (#3446)

* chores(medusa): Attempt to fix discount rounding issues

* add migration

* update entities

* apply multipler factor properly

* fix discount service

* WIP

* fix rounding issues in discounts

* fix some tests

* Exclude raw_discount_total from responses

* fix adjustments

* cleanup response

* fix

* fix draft order integration

* fix order integration

* fix order integration

* address feedback

* fix test

* Create .changeset/polite-llamas-sit.md

* remove comment

---------

Co-authored-by: Oliver Windall Juhl <59018053+olivermrbl@users.noreply.github.com>

* chore(workflows): Add release notification (#3629)

---------

Co-authored-by: pepijn-vanvlaanderen <pepijn@webbers.com>
Co-authored-by: olivermrbl <oliver@mrbltech.com>
Co-authored-by: Adrien de Peretti <adrien.deperetti@gmail.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: olivermrbl <olivermrbl@users.noreply.github.com>
Co-authored-by: Carlos R. L. Rodrigues <37986729+carlos-r-l-rodrigues@users.noreply.github.com>
Co-authored-by: shahednasser <shahednasser@users.noreply.github.com>
Co-authored-by: Oliver Windall Juhl <59018053+olivermrbl@users.noreply.github.com>
This commit is contained in:
Shahed Nasser
2023-03-31 10:34:38 +03:00
committed by GitHub
parent e6b5859af2
commit 6f1b49af03
476 changed files with 14241 additions and 6705 deletions

View File

@@ -37,7 +37,7 @@ module.exports = {
"max-len": [
"error",
{
code: 75,
code: 64,
},
],
semi: ["error", "never"],
@@ -86,7 +86,7 @@ module.exports = {
},
ignorePatterns: [
'docs/content/references/**',
'docs/content/advanced/backend/subscribers/events-list.md'
'docs/content/**/events-list.md'
],
overrides: [
{

View File

@@ -25,7 +25,7 @@ In this document, youll learn how to:
### Required Tools
[Git CLI tool](../tutorial/0-set-up-your-development-environment.mdx#git)
[Git CLI tool](../development/backend/prepare-environment.mdx#git)
### Required Accounts
@@ -102,4 +102,4 @@ If your forked repository doesnt have any conflicts with the changes from the
## See Also
- [Admin API reference](/api/admin).
- [Local development of the Medusa server](../usage/local-development.md).
- [Local development with Medusa](../development/fundamentals/local-development.md).

View File

@@ -11,13 +11,13 @@ This document will guide you through setting up the Medusa admin in minutes, as
## Prerequisites
### Medusa Server
### Medusa Backend
The Medusa admin is connected to the Medusa server. So, make sure to install the Medusa server first before proceeding with the admin. You can check out the [quickstart guide to install the Medusa server](../quickstart/quick-start).
The Medusa admin is connected to the Medusa backend. So, make sure to install the Medusa backend first before proceeding with the admin. You can check out the [quickstart guide to install the Medusa backend](../development/backend/install.mdx).
:::tip
If youre not very familiar with Medusas architecture, you can learn more about it in the [Architecture Overview](../introduction#architecture-overview).
If youre not very familiar with Medusas architecture, you can learn more about it in the [Architecture Overview](../development/fundamentals/architecture-overview.md).
:::
@@ -37,8 +37,8 @@ You can install Node from the [official website](https://nodejs.org/en/).
Instead of manually following this guide to install then later deploy the Medusa Admin, you can deploy the Medusa Admin to Netlify with this button:
<a href="https://app.netlify.com/start/deploy?repository=https://github.com/medusajs/admin" class="img-url">
<img src="https://www.netlify.com/img/deploy/button.svg" alt="Deploy to Netlify" class="no-zoom-img" />
<a href="https://app.netlify.com/start/deploy?repository=https://github.com/medusajs/admin" className="img-url">
<img src="https://www.netlify.com/img/deploy/button.svg" alt="Deploy to Netlify" className="no-zoom-img" />
</a>
---
@@ -81,11 +81,11 @@ If you run into errors during the installation, check out [this troubleshooting
## Test it Out
Before running your Medusa admin, make sure that your Medusa server is running.
Before running your Medusa admin, make sure that your Medusa backend is running.
:::tip
To run your Medusa server, go to the directory holding the server and run:
To run your Medusa backend, go to the directory holding the backend and run:
```bash npm2yarn
npm run start
@@ -107,7 +107,7 @@ Use your Medusa admins user credentials to log in.
### Demo Credentials
If you installed the demo data when you installed the Medusa server by using the `--seed` option or running:
If you installed the demo data when you installed the Medusa backend by using the `--seed` option or running:
```bash npm2yarn
npm run seed
@@ -125,7 +125,7 @@ Passwords in Medusa are hashed using the [scrypt-kdf](https://www.npmjs.com/pack
## Create a New Admin User
To create a new admin user from the command line, run the following command in the directory holding your Medusa server:
To create a new admin user from the command line, run the following command in the directory holding your Medusa backend:
```bash
medusa user -e some@email.com -p some-password
@@ -145,9 +145,9 @@ The default port is set in `package.json` in the `dev` script:
If you wish to change the port you can simply change the `7000` to your desired port.
However, if you change your Medusa admin port, you need to change it in your Medusa server. The Medusa server has the Medusa admin and store URLs set in the configurations to avoid Cross-Origin Resource Sharing (CORS) issues.
However, if you change your Medusa admin port, you need to change it in your Medusa backend. The Medusa backend has the Medusa admin and store URLs set in the configurations to avoid Cross-Origin Resource Sharing (CORS) issues.
To change the URL of the Medusa admin in the server, add a new environment variable `ADMIN_CORS` or modify it if you already have it to your Admin URL:
To change the URL of the Medusa admin in the backend, add a new environment variable `ADMIN_CORS` or modify it if you already have it to your Admin URL:
```bash
ADMIN_CORS=<YOUR_ADMIN_URL>
@@ -157,7 +157,7 @@ Make sure to replace `<YOUR_ADMIN_URL>` with your URL.
:::info
For more details about the Admin CORS configuration, check out the [Configure your Server documentation](../usage/configurations.md#admin-cors).
For more details about the Admin CORS configuration, check out the [Configure your Backend documentation](../development/backend/configurations.md#admin-cors).
:::
@@ -167,12 +167,12 @@ For more details about the Admin CORS configuration, check out the [Configure yo
Medusa admin provides a lot of ecommerce features including managing Return Merchandise Authorization (RMA) flows, store settings, products, orders, and much more.
You can learn more about Medusa admin and its features in the [User Guide](../user-guide/index.mdx).
You can learn more about Medusa admin and its features in the [User Guide](../user-guide.mdx).
---
## See Also
- [Customize Medusa Admin](./development.md)
- Install the [Next.js](../starters/nextjs-medusa-starter.mdx) or [Gatsby](../starters/gatsby-medusa-starter.mdx) storefront starters.
- [Use `create-medusa-app` to install all of Medusas 3 components.](../usage/create-medusa-app.mdx)
- Install the [Next.js](../starters/nextjs-medusa-starter.mdx) storefront starter.
- [Use `create-medusa-app` to install all of Medusas 3 components.](../create-medusa-app.mdx)

View File

@@ -1,115 +0,0 @@
---
description: 'Learn what publishable API keys are and how they can be used in the Medusa server. Publishable API keys can be used to scope API calls with an API key.'
---
# Publishable API Keys Overview
In this document, youll learn about Publishable API Keys and their usage.
## Introduction
While using Medusas APIs, you might have to pass some query parameters for certain resources with every or most requests.
Taking Sales Channels as an example, you have to pass the Sales Channels ID as a query parameter to all the necessary endpoints, such as the List Products endpoint.
This is a tedious and error-prone process. This is where Publishable API Keys are useful.
Publishable API Keys can be used to scope API calls with an API key, determining what resources are retrieved when querying the API. Currently, they can be associated only with Sales Channels.
For example, you can associate an API key with a B2B channel, then, on the storefront, retrieve only products available in that channel using the API key.
---
## PublishableApiKey Entity Overview
The `PublishableApiKey` entity represents a publishable API key that is stored in the database. Some of its important attributes include:
- `id`: The ID of the publishable API key. This is the API key youll use in your API requests.
- `created_by`: The ID of the user that created this API key.
- `revoked_by`: The ID of the user that revoked this API key. A revoked publishable API key cannot be used in requests.
---
## Relation to Other Entities
### Sales Channels
A publishable API key can be associated with more than one sales channel, and a sales channel can be associated with more than one publishable API key.
The relation is represented by the entity `PublishableApiKeySalesChannel`.
---
## Using Publishable API Keys in Requests
:::note
Publishable API keys are only for client-side use. They can be publicly accessible in your code, as they are not authorized for the Admin API.
:::
### Using Medusa JS Client
When using [Medusas JS Client](../../../js-client/overview.md), you can pass it to the client only once when you create the instance of the client:
```ts
const medusa = new Medusa({
maxRetries: 3,
baseUrl: "https://api.example.com",
publishableApiKey,
})
```
This will add the API key as in the header parameter `x-publishable-api-key` on all requests.
You can also use the `setPublishableKey` method to set it at a later point:
```ts
const medusa = new Medusa({
// ...
})
// at a later point
medusa.setPublishableKey(publishableApiKey)
```
### Using Medusa React
You can pass the publishable API key to the `MedusaProvider` component:
```tsx
const App = () => {
return (
<MedusaProvider
queryClientProviderProps={{ client: queryClient }}
baseUrl="http://localhost:9000"
// ...
publishableApiKey={publishableApiKey}
>
<MyStorefront />
</MedusaProvider>
)
}
```
Then, the API key will be passed in the header parameter `x-publishable-api-key` of every request.
### Using Other Methods
For other ways of sending requests to your Medusa server, such as using the Fetch API, you must pass `x-publishable-api-key` in the header of every request. Its value is the publishable API keys `id`.
```ts
fetch(`<SERVER_URL>/store/products`, {
credentials: "include",
headers: {
"x-publishable-api-key": publishableApiKey,
},
})
```
---
## See Also
- [How to manage publishable keys as an admin](../../admin/manage-publishable-api-keys.mdx)
- [Publishable API keys admin API reference](/api/admin/#tag/PublishableApiKey)

View File

@@ -1,30 +0,0 @@
---
description: 'Learn what Services are in the Medusa server. Services represent bundled helper methods that you want to use across the server.'
---
# Services
In this document, you'll learn about what Services are in Medusa.
## What are Services
Services in Medusa represent bundled helper methods that you want to use across your server. By convention, they represent a certain entity or functionality in your server.
For example, you can use Medusas `productService` to get the list of products, as well as perform other functionalities related to products. Theres also an `authService` that provides functionalities like authenticating customers and users.
Custom services are TypeScript or JavaScript files located in the `src/services` directory of your Medusa Server installation. Each service should be a class that extends the `TransactionBaseService` class from the core Medusa package `@medusajs/medusa`.
Each file you create in `src/services` should hold one service and export it.
The file name is important as it determines the name of the service when you need to use it elsewhere. The name of the service will be registered as the camel-case version of the file name + `Service` at the end of the name.
For example, if the file name is `hello.ts`, the service will be registered as `helloService`. If the file name is `hello-world.ts`, the service name will be registered as `helloWorldService`.
The registration name of the service is important, as youll be referring to it when you want to get access to the service using dependency injection or in routes.
---
## See Also
- [Create a Service](./create-service.md)
- [Services Reference](/references/services/classes/AuthService)

View File

@@ -1,9 +0,0 @@
{
"position": 3,
"collapsed": true,
"link": null,
"label": "Medusa Admin",
"customProps": {
"sort": "desc"
}
}

View File

@@ -1,24 +0,0 @@
---
hide_table_of_contents: true
description: 'Upgrade guides on how to update the Medusa server along with other Medusa components to the latest version.'
---
import DocCardList from '@theme/DocCardList';
import {useCurrentSidebarCategory} from '@docusaurus/theme-common';
import filterListItems, { flattenList } from '@site/src/utils/filterListItems';
# Upgrade Guides
Find in this page the upgrade guides that require necessary steps when upgrading to a new version.
## Server
<DocCardList items={filterListItems(flattenList(useCurrentSidebarCategory().items), /\/medusa\-core\//)}/>
## Medusa React
<DocCardList items={filterListItems(flattenList(useCurrentSidebarCategory().items), /\/medusa-react\//)}/>
## Admin
<DocCardList items={filterListItems(flattenList(useCurrentSidebarCategory().items), /\/admin\//)}/>

View File

@@ -1,24 +0,0 @@
---
sidebar_position: 2
description: 'Actions Required for v.1.7.6'
---
# v1.7.6
Version 1.7.6 of Medusa introduces some database schema changes which require running the migrations command.
## Overview
The latest versions of Medusa introduce the first implementations of Product Categories. The API layer of this feature is guarded by a [feature flag](../../feature-flags/toggle.md), but the changes to the database schema are not.
This release introduces another migration for Product Categories. So, it is required to run migrations to ensure your server works as expected.
## Actions Required
### Run Migrations
After updating your Medusa server and before running it, run the following command to run the latest migrations:
```bash
medusa migrations run
```

View File

@@ -1,9 +0,0 @@
{
"position": 1,
"collapsed": false,
"link": null,
"label": "Server",
"customProps": {
"sort": "desc"
}
}

View File

@@ -1,9 +0,0 @@
{
"position": 2,
"collapsed": true,
"link": null,
"label": "Medusa React",
"customProps": {
"sort": "desc"
}
}

View File

@@ -1,5 +1,5 @@
---
description: 'Learn how to install the Medusa CLI Tool. Medusa CLI Tool can be used to perform actions such as create a new Medusa server, run migrations, create a new admin user, and more.'
description: 'Learn how to install the Medusa CLI Tool. Medusa CLI Tool can be used to perform actions such as create a new Medusa backend, run migrations, create a new admin user, and more.'
---
# CLI Reference
@@ -10,7 +10,7 @@ This document serves as a reference to the Medusa CLI tool including how to inst
The Medusa CLI serves as a tool that allows you to perform important commands while developing with Medusa.
To use Medusa, it is required to install the CLI tool as it is used to create a new Medusa server.
To use Medusa, it is required to install the CLI tool as it is used to create a new Medusa backend.
---
@@ -57,7 +57,7 @@ Turn on verbose output for detailed logs.
**Default:** `false`
```bash
medusa new test-server --verbose
medusa new my-backend --verbose
```
### --no-color
@@ -69,7 +69,7 @@ Turn off colors in the output.
**Default:** `false`
```bash
medusa new test-server --no-color
medusa new my-backend --no-color
```
### --json
@@ -79,7 +79,7 @@ Turn on JSON logger.
**Default:** `false`
```bash
medusa new test-server --json
medusa new my-backend --json
```
### --version
@@ -98,18 +98,18 @@ medusa --version
### new
Create a new Medusa server.
Create a new Medusa backend.
```bash
medusa new [<server_name> [<starter_url>]]
medusa new [<backend_name> [<starter_url>]]
```
#### Arguments
| Name | Description | Default |
| --- | --- | --- |
| `server_name` | The name of the Medusa server. It will be used as the name of the directory created. | If not provided, youll be prompted to enter it. |
| `starter_url` | The URL of the starter to create the server from. | The default starter is used. |
| `backend_name` | The name of the Medusa backend. It will be used as the name of the directory created. | If not provided, youll be prompted to enter it. |
| `starter_url` | The URL of the starter to create the backend from. | The default starter is used. |
#### Options
@@ -128,7 +128,7 @@ medusa new [<server_name> [<starter_url>]]
### develop
Start development server. This command watches files for any changes to rebuild the files and restart the server.
Start development backend. This command watches files for any changes to rebuild the files and restart the backend.
```bash
medusa develop
@@ -143,7 +143,7 @@ medusa develop
### start
Start development server. This command does not watch for file changes or restart the server.
Start development backend. This command does not watch for file changes or restart the backend.
```bash
medusa start
@@ -220,5 +220,5 @@ medusa telemetry
## See Also
- [Configure your Medusa server](../usage/configurations.md)
- [Set up your development environment](../tutorial/0-set-up-your-development-environment.mdx)
- [Configure Medusa](../development/backend/configurations.md)
- [Set up your development environment](../development/backend/prepare-environment.mdx)

View File

@@ -77,7 +77,7 @@ In the body of the PR, explain clearly what the PR does. If the PR solves an iss
## Sidebar
When you add a new page to the documentation, you must add the new page in `www/docs/sidebars.js` under the `docsSidebar`. You can learn more about the syntax used [here](https://docusaurus.io/docs/sidebar/items).
When you add a new page to the documentation, you must add the new page in `www/docs/sidebars.js`. You can learn more about the syntax used [here](https://docusaurus.io/docs/sidebar/items).
### Terminology
@@ -140,7 +140,7 @@ medusa.admin.uploads.create(file) // file is an instance of File
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<YOUR_SERVER>/admin/uploads' \
curl -L -X POST '<BACKEND_URL>/admin/uploads' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: text/csv' \
-F 'files=@"<FILE_PATH_1>"'

View File

@@ -1,5 +1,5 @@
---
description: 'Learn how to create a composable commerce platform using Medusa. This quickstart guide will help you set up your Medusa server, admin, and storefront all at once.'
description: 'Learn how to create a composable commerce platform using Medusa. This quickstart guide will help you set up your Medusa backend, admin, and storefront all at once.'
addHowToData: true
---
@@ -13,17 +13,17 @@ In this document, youll learn how to use `create-medusa-app` to create a Medu
## Overview
Medusa is composed of three different components: the headless server, the storefront, and the admin dashboard.
Medusa is composed of three different components: the headless backend, the storefront, and the admin dashboard.
Medusa provides the necessary tools and resources to set up the three components separately. This ensures that developers have full freedom to choose their tech stack, as they can choose any framework for the storefront and admin dashboard.
However, if youre interested in using Medusas starters for the three components, you can make use of the `create-medusa-app` command instead of creating each separately.
When you run the `create-medusa-app` command, youll install a Medusa server, a Medusa admin, and optionally a storefront at the same time.
When you run the `create-medusa-app` command, youll install a Medusa backend, a Medusa admin, and optionally a storefront at the same time.
:::note
If you instead want to quickly install and setup only a Medusa server, follow [this quickstart guide](../quickstart/quick-start.mdx).
If you instead want to quickly install and setup only a Medusa backend, follow [this quickstart guide](./development/backend/install.mdx).
:::
@@ -43,13 +43,13 @@ You can install Node from the [official website](https://nodejs.org/en/).
### Git
Git is required for this setup. You can find instructions on how to install it from the [Set up your dev environment documentation](../tutorial/0-set-up-your-development-environment.mdx#git).
Git is required for this setup. You can find instructions on how to install it from the [Set up your dev environment documentation](./development/backend/prepare-environment.mdx#git).
---
## How to Create a Medusa Project
A Medusa project is composed of the server, storefront, and admin.
A Medusa project is composed of the backend, storefront, and admin.
In your terminal, run the following command:
@@ -74,11 +74,11 @@ In your terminal, run the following command:
Youll then be asked to enter the name of the directory you want the project to be installed in. You can either leave the default value `my-medusa-store` or enter a new name.
### Choose Medusa Server Starter
### Choose Medusa Backend Starter
Next, youll be asked to choose the Medusa server starter. The Medusa Server is created from a starter template. By default, it is created from the `medusa-starter-default` template.
Next, youll be asked to choose the Medusa backend starter. The Medusa Backend is created from a starter template. By default, it is created from the `medusa-starter-default` template.
You can either pick the default Medusa server starter, the Contentful starter or enter a starter URL by choosing `Other`:
You can either pick the default Medusa backend starter, the Contentful starter or enter a starter URL by choosing `Other`:
```bash noReport
? Which Medusa starter would you like to install? …
@@ -87,7 +87,7 @@ You can either pick the default Medusa server starter, the Contentful starter or
Other
```
The server will be installed under the `backend` directory under the project directory. An SQLite database will be created inside that directory as well with demo data seeded into it.
The backend will be installed under the `backend` directory under the project directory. An SQLite database will be created inside that directory as well with demo data seeded into it.
### Choose Storefront Starter
@@ -107,7 +107,7 @@ If you choose an option other than `None`, a storefront will be installed under
:::tip
Learn more about the [Next.js](../starters/nextjs-medusa-starter.mdx) and [Gatsby](../starters/gatsby-medusa-starter.mdx) starter storefronts.
Learn more about the [Next.js starter storefront](./starters/nextjs-medusa-starter.mdx).
:::
@@ -150,7 +150,7 @@ Inside the root project directory which was specified at the beginning of the in
```bash noReport
/my-medusa-store
/storefront // Medusa storefront starter
/backend // Medusa server
/backend // Medusa backend
/admin // Medusa admin
```
@@ -158,6 +158,6 @@ Inside the root project directory which was specified at the beginning of the in
## Whats Next
- [Check out Medusa's features](../introduction.md#features)
- [Learn about server configurations](./configurations.md)
- [Set up your environment for advanced development](../tutorial/0-set-up-your-development-environment.mdx)
- [Check out Medusa's features](./modules/overview.mdx)
- [Learn about backend configurations](./development/backend/configurations.md)
- [Set up your environment for advanced development](./development/backend/prepare-environment.mdx)

View File

@@ -19,7 +19,7 @@ Alternatively, you can use this button to deploy the Medusa Admin to Netlify dir
Before proceeding with this documentation, it is assumed you already have a Medusa Admin installed locally. If not, please go through the [quickstart guide](../../admin/quickstart.mdx) first.
Additionally, this documentation does not cover how to deploy the Medusa server. If you want to deploy the Medusa server, check out one of the [deployment documentation related to the Medusa server](../server/index.mdx).
Additionally, this documentation does not cover how to deploy the Medusa backend. If you want to deploy the Medusa backend, check out one of the [deployment documentation related to the Medusa backend](../server/index.mdx).
### Needed Accounts
@@ -34,7 +34,7 @@ If you want to use another Git Provider, its possible to follow along with th
### Required Tools
- Gits CLI tool. You can follow [this documentation to learn how to install it for your operating system](../../tutorial/0-set-up-your-development-environment.mdx#git).
- Gits CLI tool. You can follow [this documentation to learn how to install it for your operating system](../../development/backend/prepare-environment.mdx#git).
---
@@ -118,11 +118,11 @@ Next, click the “Show advanced” button, which is above the “Deploy site”
Under the “Advanced build settings” section click on the “New variable” button. This will show two inputs for the key and value of the environment variable.
For the first field enter the key `MEDUSA_BACKEND_URL` and for the value enter the URL of your Medusa server.
For the first field enter the key `MEDUSA_BACKEND_URL` and for the value enter the URL of your Medusa backend.
:::caution
If you havent deployed your Medusa server yet, you can leave the value blank for now and add it later. However, you will not be able to log in to the Medusa Admin without deploying the Medusa server.
If you havent deployed your Medusa backend yet, you can leave the value blank for now and add it later. However, you will not be able to log in to the Medusa Admin without deploying the Medusa backend.
:::
@@ -150,7 +150,7 @@ If you click on it, youll be redirected to the deployed admin website.
:::note
Before you can use Medusa Admin, you must add the URL as an environment variable on your deployed Medusa server. Follow along in the [Configure Cross-Origin Resource Sharing (CORS) on the Medusa Server](#configure-cors-variable-on-the-medusa-server) section.
Before you can use Medusa Admin, you must add the URL as an environment variable on your deployed Medusa backend. Follow along in the [Configure Cross-Origin Resource Sharing (CORS) on the Medusa Backend](#configure-cors-variable-on-the-medusa-backend) section.
:::
@@ -243,21 +243,21 @@ For the rest of the steps, you can keep most of the default values provided by N
#### Set Environment Variables
After the previous command has finished running, your Netlify website will be created. The next step is to add an environment variable that points to your Medusa server.
After the previous command has finished running, your Netlify website will be created. The next step is to add an environment variable that points to your Medusa backend.
:::caution
If you havent deployed your Medusa server yet, you can leave the value blank for now and add it later. However, you will not be able to log in to the dashboard or use it without deploying the Medusa server.
If you havent deployed your Medusa backend yet, you can leave the value blank for now and add it later. However, you will not be able to log in to the dashboard or use it without deploying the Medusa backend.
:::
Run the following command to add the environment variable:
```bash
netlify env:set MEDUSA_BACKEND_URL "<YOUR_SERVER_URL>"
netlify env:set MEDUSA_BACKEND_URL "<YOUR_BACKEND_URL>"
```
Where `<YOUR_SERVER_URL>` is the URL of your Medusa server.
Where `<YOUR_BACKEND_URL>` is the URL of your Medusa backend.
:::note
@@ -287,13 +287,13 @@ The Medusa Admin will then open in your browser.
![Medusa Admin Login](https://res.cloudinary.com/dza7lstvk/image/upload/v1668001604/Medusa%20Docs/Screenshots/XYqMCo9_hq1fsv.png)
Before you can use Medusa Admin, you must add the URL as an environment variable on your deployed Medusa server.
Before you can use Medusa Admin, you must add the URL as an environment variable on your deployed Medusa backend.
---
## Configure CORS Variable on the Medusa Server
## Configure CORS Variable on the Medusa Backend
To send requests to the Medusa server from the Medusa Admin, you must set the `ADMIN_CORS` environment variable on your server to the Medusa Admins URL.
To send requests to the Medusa backend from the Medusa Admin, you must set the `ADMIN_CORS` environment variable on your backend to the Medusa Admins URL.
:::caution
@@ -301,7 +301,7 @@ If you want to set a custom domain to your Medusa Admin website on Netlify, make
:::
On your Medusa server, add the following environment variable:
On your Medusa backend, add the following environment variable:
```bash
ADMIN_CORS=<ADMIN_URL>
@@ -309,11 +309,11 @@ ADMIN_CORS=<ADMIN_URL>
Where `<ADMIN_URL>` is the URL of your Medusa Admin that you just deployed.
Then, restart your Medusa server. Once the server is running again, you can log in to the Medusa Admin and use it.
Then, restart your Medusa backend. Once the backend is running again, you can log in to the Medusa Admin and use it.
---
## See Also
- [Deploy your storefront](../storefront/index.mdx)
- [Configure your Medusa server](../../usage/configurations.md)
- [Deploy storefront](../storefront/index.mdx)
- [Configure Medusa backend](../../development/backend/configurations.md)

View File

@@ -1,6 +1,6 @@
---
hide_table_of_contents: true
description: 'Learn how to deploy the Medusa Admin to different hosting providers to be used with a deployed Medusa server.'
description: 'Learn how to deploy the Medusa Admin to different hosting providers to be used with a deployed Medusa backend.'
---
import DocCardList from '@theme/DocCardList';

View File

@@ -3,24 +3,24 @@ description: 'Learn step-by-step.'
addHowToData: true
---
# Deploy Your Medusa Server to DigitalOcean Apps
# Deploy Your Medusa Backend to DigitalOcean Apps
In this document, you'll learn how to deploy your Medusa server to a DigitalOcean App.
In this document, you'll learn how to deploy your Medusa backend to a DigitalOcean App.
DigitalOcean is a reliable hosting provider that provides different ways to host websites and servers. One way to host a server is using their DigitalOcean App Platform.
DigitalOcean is a reliable hosting provider that provides different ways to host websites and servers. One way to host a backend is using their DigitalOcean App Platform.
## Prerequisites
### Medusa Server
### Medusa Backend
It is assumed that you already have a Medusa server installed locally. If you dont, please follow the [quickstart guide](../../quickstart/quick-start.mdx).
It is assumed that you already have a Medusa backend installed locally. If you dont, please follow the [quickstart guide](../../development/backend/install.mdx).
Furthermore, your Medusa server should be configured to work with PostgreSQL and Redis. You can follow the [Configure your Server documentation](../../usage/configurations.md) to learn how to do that.
Furthermore, your Medusa backend should be configured to work with PostgreSQL and Redis. You can follow the [Configure your Backend documentation](../../development/backend/configurations.md) to learn how to do that.
### Needed Accounts
- A [DigitalOcean](https://cloud.digitalocean.com/registrations/new) account. You need to provide a payment method on sign up.
- A [GitHub](https://github.com/) account to create a repository to host your servers codebase.
- A [GitHub](https://github.com/) account to create a repository to host your Medusa backends codebase.
:::tip
@@ -30,7 +30,7 @@ If you want to use another Git Provider supported by DigitalOcean, its possib
### Required Tools
- Gits CLI tool. You can follow [this documentation to learn how to install it for your operating system](../../tutorial/0-set-up-your-development-environment.mdx#git).
- Gits CLI tool. You can follow [this documentation to learn how to install it for your operating system](../../development/backend/prepare-environment.mdx#git).
---
@@ -42,7 +42,7 @@ Change the `start` script in `package.json` to the following:
"start": "medusa migrations run && medusa start"
```
This ensures that Migrations are run everytime the Medusa server is restarted.
This ensures that Migrations are run everytime the Medusa backend is restarted.
---
@@ -79,7 +79,7 @@ module.exports = {
## Create GitHub Repository
Before you can deploy your Medusa server you need to create a GitHub repository and push the code base to it.
Before you can deploy your Medusa backend you need to create a GitHub repository and push the code base to it.
On GitHub, click the plus icon at the top right, then click New Repository.
@@ -97,7 +97,7 @@ After creating the repository, youll be redirected to the repositorys page
![GitHub repository's URL](https://res.cloudinary.com/dza7lstvk/image/upload/v1668001818/Medusa%20Docs/Netlify/pHfSTuT_w544lr.png)
Copy the link. Then, open your terminal in the directory that holds your Medusa server codebase and run the following commands:
Copy the link. Then, open your terminal in the directory that holds your Medusa backend codebase and run the following commands:
```bash
git init
@@ -138,7 +138,7 @@ Additional inputs will show up to choose the Branch, Source Directory, and Autod
![Enter master for Branch input, backslash for Source Directory, and check Autodeploy](https://res.cloudinary.com/dza7lstvk/image/upload/v1668002055/Medusa%20Docs/Digital%20Ocean/kjk9E2B_qpwrx4.png)
If you host your Medusa server in a monorepo, you should change the Source Directory to the directory the server is available in the repository. Otherwise, it can be left as is.
If you host your Medusa backend in a monorepo, you should change the Source Directory to the directory the backend is available in the repository. Otherwise, it can be left as is.
Once youre done, click Next to move on to the next step.
@@ -148,7 +148,7 @@ In the next step, youll see the resources to create.
![List of resources showing a docker resource and web service resource](https://res.cloudinary.com/dza7lstvk/image/upload/v1668002067/Medusa%20Docs/Digital%20Ocean/6TlpWB9_wfppc7.png)
If you have a Dockerfile available in the servers codebase (which is available by default), youll have two resources showing. You can remove it by clicking on the trash icon at the right of the resource.
If you have a Dockerfile available in the backends codebase (which is available by default), youll have two resources showing. You can remove it by clicking on the trash icon at the right of the resource.
By default, DigitalOcean hosts the web service in a sub-path of the domain name of the created App. To change it to the root of the domain, click on the edit icon at the right of the Web Service resource.
@@ -176,7 +176,7 @@ Once youre done, click Next to move on to the next step.
### Set Environment Variables
In this section, youll add environment variables that are essential to your Medusa server.
In this section, youll add environment variables that are essential to your Medusa backend.
You should see two ways to add environment variables: Global or specific to the Web Service.
@@ -221,7 +221,7 @@ In the final step, you can see a review of everything you created. If everything
### Create Redis Resource
While the server is being deployed, you can create the Redis resource.
While the backend is being deployed, you can create the Redis resource.
Click the Create button at the top right and choose Database from the dropdown.
@@ -253,7 +253,7 @@ Once youre done click Attach Database. This will add the Redis database to th
---
## Test your Server
## Test your Backend
Once the redeployment is complete, copy the URL of the App which can be found under the Apps name.
@@ -265,9 +265,9 @@ Then, go to `<YOUR_APP_URL>/store/products`. If the deployment was successful, y
---
## Run Commands on Your Server
## Run Commands on Your Backend
To run commands on your server, you can access the console on the Apps page by choosing the Console tab. This opens a console in your browser where you can run commands on your server.
To run commands on your backend, you can access the console on the Apps page by choosing the Console tab. This opens a console in your browser where you can run commands on your backend.
For example, you can run the following commands to create a new admin user:

View File

@@ -7,14 +7,14 @@ import styles from '../deployment.module.css';
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
# Deploy Your Medusa Server on Heroku
# Deploy Your Medusa Backend on Heroku
In this document, you'll learn how to deploy your Medusa server on Heroku. Heroku is a PaaS (Platform as a Service) that allows you to easily deploy your applications in the cloud.
In this document, you'll learn how to deploy your Medusa backend on Heroku. Heroku is a PaaS (Platform as a Service) that allows you to easily deploy your applications in the cloud.
Alternatively, you can use this button to deploy the Medusa server to Heroku directly:
Alternatively, you can use this button to deploy the Medusa backend to Heroku directly:
<a href="https://heroku.com/deploy?template=https://github.com/medusajs/medusa-starter-default/tree/feat/deploy-heroku" class="img-url">
<img src="https://www.herokucdn.com/deploy/button.svg" alt="Deploy to Heroku" class="no-zoom-img" />
<a href="https://heroku.com/deploy?template=https://github.com/medusajs/medusa-starter-default/tree/feat/deploy-heroku" className="img-url">
<img src="https://www.herokucdn.com/deploy/button.svg" alt="Deploy to Heroku" className="no-zoom-img" />
</a>
<div>
@@ -25,11 +25,11 @@ Alternatively, you can use this button to deploy the Medusa server to Heroku dir
## Prerequisites
### Medusa Server
### Medusa Backend
It is assumed that you already have a Medusa server installed locally. If you dont, please follow the [quickstart guide](../../quickstart/quick-start.mdx).
It is assumed that you already have a Medusa backend installed locally. If you dont, please follow the [quickstart guide](../../development/backend/install.mdx).
Furthermore, your Medusa server should be configured to work with PostgreSQL and Redis. You can follow the [Configure your Server documentation](../../usage/configurations.md) to learn how to do that.
Furthermore, your Medusa backend should be configured to work with PostgreSQL and Redis. You can follow the [Configure your Backend documentation](../../development/backend/configurations.md) to learn how to do that.
### Needed Accounts
@@ -37,7 +37,7 @@ Furthermore, your Medusa server should be configured to work with PostgreSQL and
### Required Tools
- Gits CLI tool. You can follow [this documentation to learn how to install it for your operating system](../../tutorial/0-set-up-your-development-environment.mdx#git).
- Gits CLI tool. You can follow [this documentation to learn how to install it for your operating system](../../development/backend/prepare-environment.mdx#git).
- Heroku's CLI tool. You can follow [Heroku's documentation to learn how to install it for your operating system](https://devcenter.heroku.com/articles/heroku-cli).
---
@@ -56,7 +56,7 @@ Depending on your operating system, you must follow either the instructions in y
### 2. Create an App with Heroku
In the root directory of your Medusa server, run the following commands to create an app on Heroku and add it as a remote origin:
In the root directory of your Medusa backend, run the following commands to create an app on Heroku and add it as a remote origin:
```bash
heroku create <APP_NAME>
@@ -97,9 +97,9 @@ This uses the lowest plan in Stackhero Redis. You can check out [the plans and p
### 4. Configure Environment Variables on Heroku
Medusa requires a set of environment variables to be configured. You can learn more about Medusa's configurations in the [Configure your Medusa Server](../../usage/configurations.md) document.
Medusa requires a set of environment variables to be configured. You can learn more about Medusa's configurations in the [Configure your Medusa backend](../../development/backend/configurations.md) document.
Run the following commands in the root directory of your Medusa server to set some environment variables:
Run the following commands in the root directory of your Medusa backend to set some environment variables:
```bash
heroku config:set NODE_ENV=production
@@ -150,7 +150,7 @@ However, if you use another add-on, make sure to set the environment variable `D
#### (Optional) Configure CORS Variables
Optionally, if you've deployed the admin dashboard and you want to ensure it can use the server's REST APIs, you must set the following environment variable:
Optionally, if you've deployed the admin dashboard and you want to ensure it can use the backend's REST APIs, you must set the following environment variable:
```bash
heroku config:set ADMIN_CORS=<YOUR_ADMIN_URL>
@@ -158,7 +158,7 @@ heroku config:set ADMIN_CORS=<YOUR_ADMIN_URL>
Where `<YOUR_ADMIN_URL>` is the URL of your admin dashboard.
Similarly, if you've deployed the storefront and you want to ensure it can use the server's REST APIs, you must set the following environment variable:
Similarly, if you've deployed the storefront and you want to ensure it can use the backend's REST APIs, you must set the following environment variable:
```bash
heroku config:set STORE_CORS=<YOUR_STOREFRONT_URL>
@@ -166,9 +166,9 @@ heroku config:set STORE_CORS=<YOUR_STOREFRONT_URL>
Where `<YOUR_STOREFRONT_URL>` is the URL of your storefront.
### 5. Configure Medusa Server
### 5. Configure Medusa Backend
Before jumping into the deployment, you need to configure your Medusa server to ensure it uses the previous environment variables and the recommended production configurations.
Before jumping into the deployment, you need to configure your Medusa backend to ensure it uses the previous environment variables and the recommended production configurations.
#### medusa-config.js
@@ -205,21 +205,21 @@ Update `scripts` to include the following scripts:
},
```
### 6. Launch your Medusa Server
### 6. Launch your Medusa Backend
Finally, commit and push all changes to Heroku:
```bash
git add .
git commit -m "Deploy Medusa Server on Heroku"
git commit -m "Deploy Medusa Backend on Heroku"
git push heroku HEAD:master
```
This triggers a redeploy of the Medusa server with all the new configurations.
This triggers a redeploy of the Medusa backend with all the new configurations.
## Test your Server
## Test your Backend
To test your server, run the following command to retrieve the server's URL:
To test your backend, run the following command to retrieve the backend's URL:
```bash
heroku apps:info -a <APP_NAME>
@@ -227,13 +227,13 @@ heroku apps:info -a <APP_NAME>
Where `<APP_NAME>` is the name of the app. You should see as the output a bunch of info of the app.
The server's URL is available under "Web URL". You can copy it and perform requests to it to test it out.
The backend's URL is available under "Web URL". You can copy it and perform requests to it to test it out.
For example, you can send a request to `<YOUR_SERVER_URL>/store/products` and you should receive a JSON response with the products in your store.
For example, you can send a request to `<YOUR_BACKEND_URL>/store/products` and you should receive a JSON response with the products in your store.
### Troubleshooting: Inspect Build Logs
If an error occurs during the deployment, you can explore your Heroku app build logs using the following command in the root directory of your Medusa server:
If an error occurs during the deployment, you can explore your Heroku app build logs using the following command in the root directory of your Medusa backend:
```bash
heroku logs -n 500000 --remote heroku --tail -a <APP_NAME>
@@ -243,9 +243,9 @@ Where `<APP_NAME>` is the name of the app.
---
## Run Commands on Your Server
## Run Commands on Your Backend
To run commands on your server, you can use the following command:
To run commands on your backend, you can use the following command:
```bash
heroku run -a <APP_NAME> -- <COMMAND>

View File

@@ -3,9 +3,9 @@ description: 'Learn step-by-step.'
addHowToData: true
---
# Deploy Your Medusa Server on Qovery
# Deploy Your Medusa Backend on Qovery
In this document, you'll learn how to deploy your Medusa server on Qovery with the help of Terraform.
In this document, you'll learn how to deploy your Medusa backend on Qovery with the help of Terraform.
[Qovery](https://www.qovery.com/) is a Continuous Deployment Platform that provides you with the developer experience of Heroku on top of your cloud provider (For example, AWS, DigitalOcean).
@@ -19,17 +19,17 @@ This tutorial explains how to deploy Medusa to a Qovery organization with an AWS
## Prerequisites
### Medusa Server
### Medusa Backend
It is assumed that you already have a Medusa server installed locally. If you dont, please follow the [quickstart guide](../../quickstart/quick-start.mdx).
It is assumed that you already have a Medusa backend installed locally. If you dont, please follow the [quickstart guide](../../development/backend/install.mdx).
Furthermore, your Medusa server should be configured to work with PostgreSQL and Redis. You can follow the [Configure your Server documentation](../../usage/configurations.md) to learn how to do that.
Furthermore, your Medusa backend should be configured to work with PostgreSQL and Redis. You can follow the [Configure your Backend documentation](../../development/backend/configurations.md) to learn how to do that.
### Needed Accounts
- A [Qovery](https://start.qovery.com/) account with a created organization. Qovery provides a free plan that you can use.
- An [AWS](https://aws.amazon.com/) account that youll connect to a Qovery cluster.
- A [GitHub](https://github.com/) account to create a repository to host your servers codebase.
- A [GitHub](https://github.com/) account to create a repository to host your backend's codebase.
:::tip
@@ -39,7 +39,7 @@ If you want to use another [Git Provider supported by Qovery](https://hub.qovery
### Required Tools
- Gits CLI tool. You can follow [this documentation to learn how to install it for your operating system](../../tutorial/0-set-up-your-development-environment.mdx#git).
- Gits CLI tool. You can follow [this documentation to learn how to install it for your operating system](../../development/backend/prepare-environment.mdx#git).
- Terraforms CLI tool. You can follow [this guide to install it based on your operating system](https://www.terraform.io/downloads).
- Qoverys CLI tool. You can follow [this guide to install it based on your operating system](https://hub.qovery.com/docs/using-qovery/interface/cli/#install).
@@ -47,7 +47,7 @@ If you want to use another [Git Provider supported by Qovery](https://hub.qovery
## Create GitHub Repository
Before you can deploy your Medusa server you need to create a GitHub repository and push the code base to it.
Before you can deploy your Medusa backend you need to create a GitHub repository and push the code base to it.
On GitHub, click the plus icon at the top right, then click New Repository.
@@ -65,7 +65,7 @@ After creating the repository, youll be redirected to the repositorys page
![An image of the GitHub URL in a new repository](https://res.cloudinary.com/dza7lstvk/image/upload/v1668001818/Medusa%20Docs/Netlify/pHfSTuT_w544lr.png)
Copy the link. Then, open your terminal in the directory that holds your Medusa server codebase and run the following commands:
Copy the link. Then, open your terminal in the directory that holds your Medusa backend codebase and run the following commands:
```bash
git init
@@ -88,7 +88,7 @@ After pushing the changes, you can find the files in your GitHub repository.
## Deploy to Qovery
In this section, youll learn how to deploy your Medusa server to Qovery with the help of Terraform.
In this section, youll learn how to deploy your Medusa backend to Qovery with the help of Terraform.
### Sign in Using Qovery CLI
@@ -116,7 +116,7 @@ Youll be prompted to choose an organization and add a name and description fo
You need to add some variables to use for your Medusa deployment to Qovery.
In the root directory of your Medusa server, create the file `variables.tf` with the following content:
In the root directory of your Medusa backend, create the file `variables.tf` with the following content:
```
variable "qovery_organization_id" {
@@ -245,19 +245,19 @@ git_root_path = "/"
Heres an explanation of each of the variables and how to retrieve their variables:
- `qovery_organization_id`: The ID of the Qovery organization to deploy the server to. It can be found by logging into your [Qovery Console](https://console.qovery.com/). Youll be redirected to the organizations main page with a URL of the format `https://console.qovery.com/platform/organization/<ORGANIZATION_ID>/projects`. Copy the `<ORGANIZATION_ID>` in the URL to use as the value of this field.
- `qovery_organization_id`: The ID of the Qovery organization to deploy the backend to. It can be found by logging into your [Qovery Console](https://console.qovery.com/). Youll be redirected to the organizations main page with a URL of the format `https://console.qovery.com/platform/organization/<ORGANIZATION_ID>/projects`. Copy the `<ORGANIZATION_ID>` in the URL to use as the value of this field.
- `qovery_create_cluster`: A boolean value indicating whether a new cluster should be created or not. If you already have a cluster that you want to use, you can set the value to `false` and set the value of `qovery_cluster_id`. Otherwise, set the value to `true` and set the values of `aws_access_key_id`, `aws_secret_access_key`, and `aws_region`.
- `qovery_cluster_id`: The ID of the existing cluster to use (if `qovery_create_cluster` is set to `false`). You can use [Qoverys REST API](https://api-doc.qovery.com/#tag/Clusters/operation/listOrganizationCluster) to retrieve the cluster ID. You can use the token you generated earlier for the Bearer authorization token as explained [here](https://hub.qovery.com/docs/using-qovery/interface/cli/#generate-api-token).
- `aws_access_key_id`, `aws_secret_access_key`, and `aws_region`: The credentials used to create the cluster (if `qovery_create_cluster` is set to `true`). You can refer to [this guide](https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-secret-access-keys) to learn how to retrieve the `aws_access_key_id` and `aws_secret_access_key`.
- `medusa_jwt_secret`: The value of the JSON Web Token (JWT) Secret on your Medusa server. Its recommended to use a strong randomly generated string.
- `medusa_cookie_secret`: The value of the Cookie Secret on your Medusa server. Its recommended to use a strong randomly generated string.
- `medusa_jwt_secret`: The value of the JSON Web Token (JWT) Secret on your Medusa backend. Its recommended to use a strong randomly generated string.
- `medusa_cookie_secret`: The value of the Cookie Secret on your Medusa backend. Its recommended to use a strong randomly generated string.
- `git_url`: The URL of the Git repository you created earlier. Make sure it ends with `.git`.
- `git_branch`: The branch to use in the GitHub repo. By default its `master`.
- `git_root_path`: The root path of the Medusa server. By default, its `/`. If you are hosting your Medusa server in a monorepo in a nested directory, you need to change the value of this variable.
- `git_root_path`: The root path of the Medusa backend. By default, its `/`. If you are hosting your Medusa backend in a monorepo in a nested directory, you need to change the value of this variable.
### Add Terraform Configuration File
In the root directory of your Medusa server, create the file `main.tf` with the following content:
In the root directory of your Medusa backend, create the file `main.tf` with the following content:
```bash
# Install the Qovery Terraform provider
@@ -430,25 +430,25 @@ Finally, it creates the Medusa app and sets all the necessary environment variab
:::tip
This deployment uses Docker. By default, you should have the files [`Dockerfile`](https://github.com/medusajs/medusa-starter-default/blob/master/Dockerfile) and [`docker-compose.yml`](https://github.com/medusajs/medusa-starter-default/blob/master/docker-compose.yml)` in the root of your Medusa server.
This deployment uses Docker. By default, you should have the files [`Dockerfile`](https://github.com/medusajs/medusa-starter-default/blob/master/Dockerfile) and [`docker-compose.yml`](https://github.com/medusajs/medusa-starter-default/blob/master/docker-compose.yml)` in the root of your Medusa backend.
:::
### Change develop.sh
The `Dockerfile` runs the file `develop.sh` to start the server. Change the content of `develop.sh` to the following:
The `Dockerfile` runs the file `develop.sh` to start the backend. Change the content of `develop.sh` to the following:
```bash
#!/bin/bash
#Run migrations to ensure the database is updated
# Run migrations to ensure the database is updated
medusa migrations run
#Start production server
# Run backend
medusa start
```
This makes sure the production server is started and not a development server.
This makes sure the production backend is started and not a development backend.
### Initialize Terraform
@@ -480,19 +480,19 @@ If you run into any errors while running this command, you can just re-run it af
---
## Test your Server
## Test the Backend
Once the command finishes and the deployment is successful, you can access your server in the [Qovery Console](https://console.qovery.com/). Go to the project, environment, then the app that you created using Terraform and Qovery. In the app, click the Open button at the top right to open your website in a new tab.
Once the command finishes and the deployment is successful, you can access your backend in the [Qovery Console](https://console.qovery.com/). Go to the project, environment, then the app that you created using Terraform and Qovery. In the app, click the Open button at the top right to open your website in a new tab.
![open button at the top right](https://res.cloudinary.com/dza7lstvk/image/upload/v1668002245/Medusa%20Docs/Qovery/Ji59ZSJ_nrkpvb.png)
You can access any of the endpoints on your server using the server URL. For example, you can get the list of products using the endpoint `/store/products`.
You can access any of the endpoints on your backend using the backend URL. For example, you can get the list of products using the endpoint `/store/products`.
---
## Run Commands on Your Server
## Run Commands on the Backend
To run commands on your server, run the following command:
To run commands on the backend, run the following command:
```bash
qovery shell
@@ -500,7 +500,7 @@ qovery shell
Youll be asked to either confirm the existing context or choose a new context.
After choosing your Medusa app in the context, you should be able to execute any command in the directory of your Medusa server. For example, you can run the [`user` command using Medusas CLI tool to create a new user](../../cli/reference.md#user):
After choosing your Medusa app in the context, you should be able to execute any command in the directory of your Medusa backend. For example, you can run the [`user` command using Medusas CLI tool to create a new user](../../cli/reference.md#user):
```bash
npm install @medusajs/medusa-cli -g

View File

@@ -3,48 +3,48 @@ description: 'Learn step-by-step.'
addHowToData: true
---
# Deploy Your Medusa Server to Railway
# Deploy Your Medusa Backend to Railway
In this document, youll learn how to deploy your Medusa server to Railway.
In this document, youll learn how to deploy your Medusa backend to Railway.
## What is Railway
[Railway](https://railway.app/) is a hosting provider that you can use to deploy web applications and databases without having to worry about managing the full infrastructure.
Railway provides a free plan that allows you to deploy your Medusa server along with PostgreSQL and Redis databases. This is useful mainly for development and demo purposes.
Railway provides a free plan that allows you to deploy your Medusa backend along with PostgreSQL and Redis databases. This is useful mainly for development and demo purposes.
---
## Prerequisites
### Medusa Server
### Medusa Backend
It is assumed that you already have a Medusa server installed locally. If you dont, please follow the [quickstart guide](../../quickstart/quick-start.mdx).
It is assumed that you already have a Medusa backend installed locally. If you dont, please follow the [quickstart guide](../../development/backend/install.mdx).
Furthermore, your Medusa server should be configured to work with PostgreSQL and Redis. You can follow the [Configure your Server documentation](./../../usage/configurations.md) to learn how to do that.
Furthermore, your Medusa backend should be configured to work with PostgreSQL and Redis. You can follow the [Configure your Backend documentation](./../../development/backend/configurations.md) to learn how to do that.
### Needed Accounts
- A [Railway](https://railway.app/) account.
- A [GitHub](https://github.com/) account to create a repository to host your servers codebase.
- A [GitHub](https://github.com/) account to create a repository to host your backend's codebase.
### Required Tools
- Gits CLI tool. You can follow [this documentation to learn how to install it for your operating system](./../../tutorial/0-set-up-your-development-environment.mdx#git).
- Gits CLI tool. You can follow [this documentation to learn how to install it for your operating system](./../../development/backend/prepare-environment.mdx#git).
---
## Changes to Medusa Server Codebase
## Changes to Medusa Backend Codebase
By default, Railway looks for a Dockerfile in the root of the codebase. If there is one, it will try to deploy your server using it.
By default, Railway looks for a Dockerfile in the root of the codebase. If there is one, it will try to deploy your backend using it.
As this guide doesn't use Docker, make sure to delete `Dockerfile` from the root of your Medusa server.
As this guide doesn't use Docker, make sure to delete `Dockerfile` from the root of your Medusa backend.
---
## Create GitHub Repository
Before you can deploy your Medusa server you need to create a GitHub repository and push the code base to it.
Before you can deploy your Medusa backend you need to create a GitHub repository and push the code base to it.
On GitHub, click the plus icon at the top right, then click New Repository.
@@ -62,7 +62,7 @@ After creating the repository, youll be redirected to the repositorys page
![GitHub repository's URL](https://res.cloudinary.com/dza7lstvk/image/upload/v1668001818/Medusa%20Docs/Netlify/pHfSTuT_w544lr.png)
Copy the link. Then, open your terminal in the directory that holds your Medusa server codebase and run the following commands:
Copy the link. Then, open your terminal in the directory that holds your Medusa backend codebase and run the following commands:
```bash
git init
@@ -85,7 +85,7 @@ After pushing the changes, you can find the files in your GitHub repository.
## Deploy to Railway
In this section, youll create the PostgreSQL and Redis databases first, then deploy the server from the GitHub repository.
In this section, youll create the PostgreSQL and Redis databases first, then deploy the backend from the GitHub repository.
### Create the PostgreSQL Database
@@ -118,7 +118,7 @@ To find the Redis database URL which youll need later:
2. Choose the Connect tab.
3. Copy the Redis Connection URL.
### Deploy the Medusa Server Repository
### Deploy the Medusa Backend Repository
In the same project view:
@@ -133,11 +133,11 @@ If the GitHub repositories in the dropdown are stuck on loading and aren't showi
:::
It will take the server a few minutes to deploy successfully.
It will take the backend a few minutes to deploy successfully.
### Configure Environment Variables
To configure the environment variables of your Medusa server:
To configure the environment variables of your Medusa backend:
1. Click on the GitHub repositorys card.
2. Choose the Variables tab.
@@ -161,9 +161,9 @@ Its highly recommended to use strong, randomly generated secrets for `JWT_SE
### Change Start Command
The start command is the command used to run the server. Youll change it to run any available migrations, then run the Medusa server. This way if you create your own migrations or update the Medusa server, it's guaranteed that these migrations are run first before the server starts.
The start command is the command used to run the backend. Youll change it to run any available migrations, then run the Medusa backend. This way if you create your own migrations or update the Medusa backend, it's guaranteed that these migrations are run first before the backend starts.
To change the start command of your Medusa server:
To change the start command of your Medusa backend:
1. Click on the GitHub repositorys card.
2. Click on the Settings tab and scroll down to the Service section.
@@ -175,7 +175,7 @@ medusa migrations run && medusa develop
### Add Domain Name
The last step is to add a domain name to your Medusa server. To do that:
The last step is to add a domain name to your Medusa backend. To do that:
1. Click on the GitHub repositorys card.
2. Click on the Settings tab and scroll down to the Domains section.
@@ -183,11 +183,11 @@ The last step is to add a domain name to your Medusa server. To do that:
---
## Test your Server
## Test the Backend
Every change you make to the settings redeploys the server. You can check the Deployments of the server by clicking on the GitHub repositorys card and choosing the Deployments tab.
Every change you make to the settings redeploys the backend. You can check the Deployments of the backend by clicking on the GitHub repositorys card and choosing the Deployments tab.
After the server is redeployed successfully, open the app in your browser using the domain name. For example, you can open the URL `<YOUR_APP_URL>/store/products` which will return the products available on your server.
After the backend is redeployed successfully, open the app in your browser using the domain name. For example, you can open the URL `<YOUR_APP_URL>/store/products` which will return the products available on your backend.
:::tip
@@ -199,7 +199,7 @@ If you generated a random domain, you can find it by clicking on the GitHub repo
## Troubleshooting
If you run into any issues or a problem with your deployed server, you can check the logs in your Railway container instance by:
If you run into any issues or a problem with your deployed backend, you can check the logs in your Railway container instance by:
1. Click on the GitHub repositorys card.
2. Click on the Deployments tab.
@@ -207,11 +207,11 @@ If you run into any issues or a problem with your deployed server, you can check
---
## Run Commands on Server
## Run Commands on the Backend
To run commands on your server, you can use [Railways CLI tool to run a local shell and execute commands](https://docs.railway.app/develop/cli#local-shell).
To run commands on your backend, you can use [Railways CLI tool to run a local shell and execute commands](https://docs.railway.app/develop/cli#local-shell).
For example, you can run commands on the server to seed the database or create a new user using [Medusas CLI tool](../../cli/reference.md).
For example, you can run commands on the backend to seed the database or create a new user using [Medusas CLI tool](../../cli/reference.md).
---

View File

@@ -1,13 +1,13 @@
---
hide_table_of_contents: true
description: 'Learn how to deploy your Medusa server to different hosting providers including DigitalOcean, Heroku, Railway, and more.'
description: 'Learn how to deploy your Medusa backend to different hosting providers including DigitalOcean, Heroku, Railway, and more.'
---
import DocCardList from '@theme/DocCardList';
import {useCurrentSidebarCategory} from '@docusaurus/theme-common';
# Medusa Server Deployment Guides
# Medusa Backend Deployment Guides
Find in this page guides to deploy your Medusa server on different platforms.
Find in this page guides to deploy your Medusa backend on different platforms.
<DocCardList items={useCurrentSidebarCategory().items}/>

View File

@@ -5,11 +5,17 @@ addHowToData: true
# Deploy Gatsby Storefront on Netlify
:::note
The Gatsby storefront has been deprecated and it's not recommended to use it moving forward. You can use the [Next.js storefront](../../starters/nextjs-medusa-starter.mdx) instead or build your own.
:::
In this document, youll learn how to deploy the Gatsby Storefront on [Netlify](https://www.netlify.com/).
Alternatively, you can use this button to deploy the Gatsby Storefront to Netlify directly:
<a href="https://app.netlify.com/start/deploy?repository=https://github.com/medusajs/gatsby-starter-medusa" class="img-url">
<a href="https://app.netlify.com/start/deploy?repository=https://github.com/medusajs/gatsby-starter-medusa" class="img-url no-zoom-img">
<img src="https://www.netlify.com/img/deploy/button.svg" alt="Deploy to Netlify" class="no-zoom-img" />
</a>
@@ -19,9 +25,9 @@ Alternatively, you can use this button to deploy the Gatsby Storefront to Netlif
### Medusa Components
Before proceeding with this documentation, it is assumed you already have the Gatsby storefront installed locally. If not, please go through the [quickstart guide](../../starters/gatsby-medusa-starter.mdx) first.
Before proceeding with this documentation, it is assumed you already have the Gatsby storefront installed locally.
Additionally, this documentation does not cover how to deploy the Medusa server. If you want to deploy the Medusa server, [check out one of the deployment documentation related to the Medusa server](../server/index.mdx).
Additionally, this documentation does not cover how to deploy the Medusa backend. If you want to deploy the Medusa backend, [check out one of the deployment documentation related to the Medusa backend](../server/index.mdx).
### Needed Accounts
@@ -36,7 +42,7 @@ If you want to use another Git Provider, its possible to follow along with th
### Required Tools
- Gits CLI tool. You can follow [this documentation to learn how to install it for your operating system](../../tutorial/0-set-up-your-development-environment.mdx#git).
- Gits CLI tool. You can follow [this documentation to learn how to install it for your operating system](../../development/backend/prepare-environment.mdx#git).
---
@@ -113,11 +119,11 @@ In the form that shows, keep all fields the same and click on the “Show advanc
Under the “Advanced build settings” section click on the “New variable” button. This will show two inputs for the key and value of the environment variable.
For the first field enter the key `GATSBY_MEDUSA_BACKEND_URL` and for the value enter the URL of your Medusa server.
For the first field enter the key `GATSBY_MEDUSA_BACKEND_URL` and for the value enter the URL of your Medusa backend.
:::caution
If you havent deployed your Medusa server yet, you can leave the value blank for now and add it later. However, the build process for the Gatsby storefront will fail.
If you havent deployed your Medusa backend yet, you can leave the value blank for now and add it later. However, the build process for the Gatsby storefront will fail.
:::
@@ -141,9 +147,9 @@ Once the deployment is done, youll find the URL in the place of the “Site d
:::tip
If you havent added any products to your Medusa server, the build process might fail. Its recommended to add some products to the server first in that case.
If you havent added any products to your Medusa backend, the build process might fail. Its recommended to add some products to the backend first in that case.
Alternatively, you can seed the server with demo data by running this command in the root directory of the server:
Alternatively, you can seed the backend with demo data by running this command in the root directory of the backend:
```bash noReport
medusa seed -f data/seed.json
@@ -159,7 +165,7 @@ If you click on it, youll be redirected to the deployed storefront website.
:::caution
At this point, you will face errors related to Cross-Origin Resource Sharing (CORS) while using the storefront. Before you start using the storefront, follow along the [Configure CORS on the Medusa Server section](#configure-cors-variable-on-the-medusa-server).
At this point, you will face errors related to Cross-Origin Resource Sharing (CORS) while using the storefront. Before you start using the storefront, follow along the [Configure CORS on the Medusa Backend section](#configure-cors-variable-on-the-medusa-backend).
:::
@@ -240,21 +246,21 @@ For the rest of the steps, you can keep the default values provided by Netlify a
#### Set Environment Variables
After the previous command has finished running, your Netlify website will be created. The next step is to add an environment variable that points to your Medusa server.
After the previous command has finished running, your Netlify website will be created. The next step is to add an environment variable that points to your Medusa backend.
:::caution
If you havent deployed your Medusa server yet, you can leave the value blank for now and add it later. However, the build process for the Gatsby storefront will fail.
If you havent deployed your Medusa backend yet, you can leave the value blank for now and add it later. However, the build process for the Gatsby storefront will fail.
:::
Run the following command to add the environment variable:
```bash
netlify env:set GATSBY_MEDUSA_BACKEND_URL "<YOUR_SERVER_URL>"
netlify env:set GATSBY_MEDUSA_BACKEND_URL "<YOUR_BACKKEND_URL>"
```
Where `<YOUR_SERVER_URL>` is the URL of your Medusa server.
Where `<YOUR_BACKKEND_URL>` is the URL of your Medusa backend.
:::note
@@ -274,9 +280,9 @@ After the deployment has been completed, you should see a message saying “Depl
:::tip
If you havent added any products to your Medusa server, the build process might fail. Its recommended to add some products to the server first in that case.
If you havent added any products to your Medusa backend, the build process might fail. Its recommended to add some products to the backend first in that case.
Alternatively, you can seed the server with demo data by running this command in the root directory of the server:
Alternatively, you can seed the backend with demo data by running this command in the root directory of the backend:
```bash noReport
medusa seed -f data/seed.json
@@ -296,13 +302,13 @@ The Gatsby storefront will then open in your browser.
![Gatsby Storefront](https://res.cloudinary.com/dza7lstvk/image/upload/v1668003089/Medusa%20Docs/Netlify/l08cBSA_yfj2rz.png)
Before you can use the Gatsby storefront, you must add the URL as an environment variable on your deployed Medusa server.
Before you can use the Gatsby storefront, you must add the URL as an environment variable on your deployed Medusa backend.
---
## Configure CORS Variable on the Medusa Server
## Configure CORS Variable on the Medusa Backend
To send requests to the Medusa server from the Gatsby storefront, you must set the `STORE_CORS` environment variable on your server to the Gatsby storefronts URL.
To send requests to the Medusa backend from the Gatsby storefront, you must set the `STORE_CORS` environment variable on your backend to the Gatsby storefronts URL.
:::caution
@@ -310,7 +316,7 @@ If you want to set a custom domain to your Gatsby storefront website on Netlify,
:::
On your Medusa server, add the following environment variable:
On your Medusa backend, add the following environment variable:
```bash
STORE_CORS=<STOREFRONT_URL>
@@ -318,11 +324,11 @@ STORE_CORS=<STOREFRONT_URL>
Where `<STOREFRONT_URL>` is the URL of your Gatsby storefront that you just deployed.
Then, restart your Medusa server. Once the server is running again, you can use your Gatsby storefront.
Then, restart your Medusa backend. Once the backend is running again, you can use your Gatsby storefront.
---
## See Also
- [Deploy the Medusa Admin](../admin/index.mdx)
- [Configure your Medusa server](../../usage/configurations.md)
- [Configure your Medusa backend](../../development/backend/configurations.md)

View File

@@ -0,0 +1,154 @@
---
description: 'Learn step-by-step.'
addHowToData: true
---
# Deploy Next.js Storefront on Vercel
In this document, youll learn how to deploy the Next.js Storefront on Vercel.
Alternatively, you can directly deploy the Next.js storefront to Vercel with this button.
<a
href="https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fmedusajs%2Fnextjs-starter-medusa.git&env=NEXT_PUBLIC_MEDUSA_BACKEND_URL&envDescription=URL%20of%20your%20Medusa%20Backend" class="img-url no-zoom-img">
<img src="https://vercel.com/button" alt="Deploy with Vercel" class="no-zoom-img"/>
</a>
## Prerequisites
### Medusa Components
It is assumed you already have installed the Next.js storefront locally. If not, please follow along with [this guide](../../starters/nextjs-medusa-starter.mdx) instead.
Its also assumed you already have the Medusa backend deployed, which the Next.js storefront interacts with. If not, you can check out one of the [deployment documentation related to the Medusa backend](../server/index.mdx).
### Required Accounts
- [Vercel Account](https://vercel.com)
- [GitHub Account](https://github.com/): Only required if youre deploying through the Vercel website.
:::note
If you want to use another Git Provider, its possible to follow along with this guide, but youll have to perform the equivalent steps in your Git Provider.
:::
### Required Tools
- [Git CLI](../../development/backend/prepare-environment.mdx): Only required if youre deploying through the Vercel website.
---
## Step 1: Create GitHub Repository
:::note
This step is only required if youre deploying from the Vercel website. However, its highly recommended to connect your Vercel project to a Git repository for a better developer experience.
:::
Before you can deploy your Next.js storefront, you need to create a GitHub repository and push the code base to it. To do that:
1. On GitHub, click the plus icon at the top right, then click New Repository.
2. Youll then be redirected to a new page with a form. In the form, enter the Repository Name.
3. Scroll down and click Create repository.
### Push Code to GitHub Repository
The next step is to push the code to the GitHub repository you just created.
After creating the repository, youll be redirected to the repositorys page. On that page, you should see a URL that you can copy to connect your repository to a local directory.
Copy the link. Then, open your terminal in the directory that holds your Next.js storefront codebase and run the following commands:
```bash
git init
git remote add origin <GITHUB_URL>
```
Where `<GITHUB_URL>` is the URL you just copied.
Then, add, commit, and push the changes into the repository:
```bash
git add .
git commit -m "initial commit"
git push origin master
```
After pushing the changes, you can find the files in your GitHub repository.
---
## Step 2: Deploy to Vercel
This section covers how to deploy the storefront, either using the Vercel website or using Vercels CLI tool.
### Option 1: Using the Vercel Website
This section explains how to deploy the storefront using the Vercel website:
1. Open the [Vercel dashboard](https://vercel.com/dashboard) after logging in.
2. Click on the “Add New…” button next to the search bar.
3. Choose Project from the dropdown.
4. In the new page that opens, find the Git repository that holds your Next.js storefront and click on the Import button. If you havent connected your Vercel account to any Git provider, you must do that first.
5. In the Configure Project form:
1. Open the Environment Variables collapsible, and add an environment variable with the name `NEXT_PUBLIC_MEDUSA_BACKEND_URL` and the value being the URL to your deployed Medusa Backend.
2. You can optionally edit the Project Name.
6. Once youre done, click on the “Deploy” button.
This will start the deployment of the storefront. Once its done, youll be redirected to the main dashboard of your new project.
:::note
At this point, when you visit the storefront, you will face errors related to Cross-Origin Resource Sharing (CORS) while using the storefront. Before you start using the storefront, follow along the [Configure CORS on the Medusa Backend](#step-3-configure-cors-on-the-medusa-backend) section.
:::
### Option 2: Using Vercels CLI Tool
This section explains how to deploy the storefront using the Vercel CLI tool. You should have the CLI tool installed first, as explained in [Vercels documentation](https://vercel.com/docs/cli).
In the directory holding your storefront, run the following command to deploy your storefront:
```bash
vercel --build-env NEXT_PUBLIC_MEDUSA_BACKEND_URL=<YOUR_BACKEND_URL>
```
Where `<YOUR_BACKEND_URL>` is the URL of your deployed Medusa backend.
Youll then be asked to log in if you havent already, and to choose the scope to deploy your project to. You can also decide to link the storefront to an existing project, or change the projects name.
When asked `In which directory is your code located?`, keep the default `./` and just press Enter.
The project setup will then start. When asked if you want to modify the settings, answer `N` to keep the default settings.
It will take a couple of minutes for the deployment to finish. The link to the storefront will be shown in the final output of the command.
:::note
At this point, when you visit the storefront, you will face errors related to Cross-Origin Resource Sharing (CORS) while using the storefront. Before you start using the storefront, follow along the [Configure CORS on the Medusa Backend](#step-3-configure-cors-on-the-medusa-backend) section.
:::
---
## Step 3: Configure CORS on the Medusa Backend
To send requests to the Medusa backend from the Next.js storefront, you must set the `STORE_CORS` environment variable on your backend to the Next.js storefronts URL.
:::tip
If you want to set a custom domain to your Next.js storefront website on Vercel, make sure to do it before this step. You can refer to this guide on [Vercels documentation](https://vercel.com/docs/concepts/projects/domains/add-a-domain).
:::
On your Medusa backend, add the following environment variable:
```bash
STORE_CORS=<STOREFRONT_URL>
```
Where `<STOREFRONT_URL>` is the URL of your Next.js storefront that you just deployed.
Then, restart your Medusa backend. Once the backend is running again, you can use your Next.js storefront.

View File

@@ -1,6 +1,6 @@
---
hide_table_of_contents: true
description: 'Learn how to deploy your storefronts to different hosting providers to be used with a deployed Medusa server.'
description: 'Learn how to deploy your storefronts to different hosting providers to be used with a deployed Medusa backend.'
---
import DocCardList from '@theme/DocCardList';

View File

@@ -1,20 +1,20 @@
---
description: 'Learn about the different configurations available in a Medusa server. This includes configurations related to the database, CORS, plugins, redis, and more.'
description: 'Learn about the different configurations available in a Medusa backend. This includes configurations related to the database, CORS, plugins, redis, and more.'
---
# Configure Medusa Server
# Configure Medusa Backend
In this document, youll learn what configurations you can add to your Medusa server and how to add them.
In this document, youll learn what configurations you can add to your Medusa backend and how to add them.
## Prerequisites
This document assumes you already followed along with the [“Set up your development environment” documentation](../tutorial/0-set-up-your-development-environment.mdx) and have [installed a Medusa server](../quickstart/quick-start.mdx#create-a-medusa-server).
This document assumes you already followed along with the [“Set up your development environment” documentation](./prepare-environment.mdx) and have [installed a Medusa backend](./install.mdx#create-a-medusa-backend).
---
## Medusa Configurations File
The configurations for your Medusa server are in `medusa-config.js`. This includes database, Redis, and plugin configurations, among other configurations.
The configurations for your Medusa backend are in `medusa-config.js`. This includes database, Redis, and plugin configurations, among other configurations.
Some of the configurations mentioned in this document are already defined in `medusa-config.js` with default values. Its important that you know what these configurations are used for and how to set them.
@@ -28,7 +28,7 @@ By default, Medusa loads environment variables from the systems environment v
:::info
This change in how environment variables are loaded was introduced in version 1.3.0. You can learn more in the [upgrade guide for version 1.3.0](../advanced/backend/upgrade-guides/medusa-core/1-3-0.md).
This change in how environment variables are loaded was introduced in version 1.3.0. You can learn more in the [upgrade guide for version 1.3.0](../../upgrade-guides/medusa-core/1-3-0.md).
:::
@@ -158,11 +158,11 @@ It is recommended to set the Redis URL as an environment variable:
REDIS_URL=<YOUR_REDIS_URL>
```
Where `<YOUR_REDIS_URL>` is the URL of your Redis server.
Where `<YOUR_REDIS_URL>` is the URL of your Redis backend.
:::info
You can learn more about Subscribers and events in the [Subscriber documentation](../advanced/backend/subscribers/create-subscriber.md).
You can learn more about Subscribers and events in the [Subscriber documentation](../events/create-subscriber.md).
:::
@@ -193,7 +193,7 @@ Where `<YOUR_JWT_SECRET>` is the JWT secret you want to use.
:::caution
In a development environment, if this option is not set the default secret is “supersecret”. However, in production, if this option is not set an error will be thrown and your server will crash.
In a development environment, if this option is not set the default secret is “supersecret”. However, in production, if this option is not set an error will be thrown and your backend will crash.
:::
@@ -224,7 +224,7 @@ Where `<YOUR_COOKIE_SECRET>` is the Cookie secret you want to use.
:::caution
In a development environment, if this option is not set the default secret is “supersecret”. However, in production, if this option is not set an error will be thrown and your server will crash.
In a development environment, if this option is not set the default secret is “supersecret”. However, in production, if this option is not set an error will be thrown and your backend will crash.
:::
@@ -232,7 +232,7 @@ In a development environment, if this option is not set the default secret is
## CORS Configurations
Medusa uses Cross-Origin Resource Sharing (CORS) to only allow specific origins to access the server.
Medusa uses Cross-Origin Resource Sharing (CORS) to only allow specific origins to access the backend.
The Admin and the Storefront have different CORS configurations that must be configured.
@@ -241,7 +241,7 @@ The Admin and the Storefront have different CORS configurations that must be con
For both of the Admin and the Storefront CORS configurations, the value is expected to be a string. This string can be a comma-separated list of accepted origins. Every origin in that list can be of the following types:
1. The accepted origin as is. For example, `http://localhost:8000`.
2. A regular expression pattern that can match more than one origin. For example, `*.example.com`. The regex pattern that the server tests for is `^([\/~@;%#'])(.*?)\1([gimsuy]*)$`.
2. A regular expression pattern that can match more than one origin. For example, `*.example.com`. The regex pattern that the backend tests for is `^([\/~@;%#'])(.*?)\1([gimsuy]*)$`.
Here are some examples of common use cases:
@@ -271,7 +271,7 @@ The examples above apply to both Admin and Store CORS.
### Admin CORS
To make sure your Admin dashboard can access the Medusa servers admin endpoints, set this configuration:
To make sure your Admin dashboard can access the Medusa backends admin endpoints, set this configuration:
```jsx
module.exports = {
@@ -300,7 +300,7 @@ Make sure that the URL is without a backslash at the end. For example, you shoul
### Storefront CORS
To make sure your Storefront dashboard can access the Medusa server, set this configuration:
To make sure your Storefront dashboard can access the Medusa backend, set this configuration:
```jsx
module.exports = {
@@ -331,11 +331,11 @@ Make sure that the URL is without a backslash at the end. For example, you shoul
## Plugins
On your Medusa server, you can use Plugins to add custom features or integrate third-party services. For example, installing a plugin to use Stripe as a payment provider.
On your Medusa backend, you can use Plugins to add custom features or integrate third-party services. For example, installing a plugin to use Stripe as a payment provider.
:::info
You can learn more about plugins in the [Plugins Overview documentation](../advanced/backend/plugins/overview.md).
You can learn more about plugins in the [Plugins Overview documentation](../plugins/overview.mdx).
:::
@@ -387,6 +387,5 @@ It is recommended to use environment variables to store values of options instea
## See Also
- Check out the [Next.js](../starters/nextjs-medusa-starter.mdx) and [Gatsby](../starters/gatsby-medusa-starter.mdx) starter storefronts
- [Install the Medusa admin](../admin/quickstart.mdx)
- [Deploy the Medusa server](../deployments/server/index.mdx)
- [Medusa architecture overview](../fundamentals/architecture-overview.md)
- [Plugins](../plugins/overview.mdx)

View File

@@ -0,0 +1,104 @@
---
description: 'This quickstart guide will help you set up a Medusa backend in three steps.'
addHowToData: true
---
import Feedback from '@site/src/components/Feedback';
# Install Medusa Backend
This document will guide you through setting up your Medusa backend in a three steps.
## Prerequisites
### Node.js
Medusa supports Node versions 14 and 16. You can check which version of Node you have by running the following command:
```bash noReport
node -v
```
You can install Node from the [official website](https://nodejs.org/en/).
### Git
Git is required for this setup. You can find instructions on how to install it from the [Set up your dev environment documentation](../../development/backend/prepare-environment.mdx#git).
---
## Create a Medusa Backend
:::tip
It is recommended to use [Yarn](https://yarnpkg.com/getting-started/install) for the installation process as it's much faster than using NPM.
:::
### 1. Install Medusa CLI
```bash npm2yarn
npm install @medusajs/medusa-cli -g
```
:::note
If you run into any errors while installing the CLI tool, check out the [troubleshooting guide](../../troubleshooting/cli-installation-errors.mdx).
:::
### 2. Create a new Medusa project
```bash noReport
medusa new my-medusa-store --seed
```
### 3. Start your Medusa backend
```bash noReport
cd my-medusa-store
medusa develop
```
<Feedback
event="survey_server_quickstart"
question="Did you set up the backend successfully?"
positiveQuestion="Is there anything that should improved?"
negativeQuestion="Please describe the issue you faced."
/>
### Test the Backend
After these three steps and in only a couple of minutes, you now have a complete commerce engine running locally. You can test it out by sending a request using a tool like Postman or through the command line:
```bash noReport
curl localhost:9000/store/products
```
---
## Next Steps
### Learn about the Architecture
Medusa backend is made up of different resources that make it a powerful server. Get an overview of them in the [Medusa Architecture Overview](../fundamentals/architecture-overview.md) documentation.
### Set Up Development Environment
For an optimal experience developing with Medusa and to make sure you can use its advanced functionalities, you'll need to install more tools such as Redis or PostgreSQL.
Follow [this documentation to learn how to set up your development environment](../../development/backend/prepare-environment.mdx).
### Backend Configurations
It's important to configure your Medusa backend properly and learn how environment variables are loaded.
You can learn more about configuring your backend and loading environment variables in the [Configure your Backend documentation](../../development/backend/configurations.md).
### File Service Plugin
To upload product images to your Medusa backend, you must install and configure one of the following file service plugins:
- [MinIO](../../plugins/file-service/minio.md) (Recommended for local development)
- [S3](../../plugins/file-service/s3.md)
- [DigitalOcean Spaces](../../plugins/file-service/spaces.md)

View File

@@ -1,14 +1,14 @@
---
description: 'Learn how to set up your development environment while using Medusa. This guide includes how to install Node.js, Git, Medusa CLI tool, PostgreSQL, and Redis.'
description: 'Learn how to prepare your development environment while using Medusa. This guide includes how to install Node.js, Git, Medusa CLI tool, PostgreSQL, and Redis.'
---
import styles from './development.module.css';
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
# Set up Development Environment
# Prepare Development Environment
This document will guide you to set up your development environment to efficiently and properly use Medusa.
This document will guide you to prepare your development environment to efficiently and properly use Medusa.
## Required Tools
@@ -139,29 +139,29 @@ medusa -v
:::note
If you run into any errors while installing the CLI tool, check out the [troubleshooting guide](../troubleshooting/cli-installation-errors.mdx).
If you run into any errors while installing the CLI tool, check out the [troubleshooting guide](../../troubleshooting/cli-installation-errors.mdx).
:::
---
## Install Medusa Server
## Install Medusa Backend
If you're not interested in installing the optional tools and want to get started quickly, check out the [quickstart guide](../quickstart/quick-start.mdx).
If you're not interested in installing the optional tools and want to get started with Medusa quickly, check out the [Medusa Backend Quickstart](./install.mdx).
---
## Optional Tools
These tools are not required to have to run a Medusa server, but it's highly recommended that you have them installed.
These tools are not required to have to run a Medusa backend, but it's highly recommended that you have them installed.
### PostgreSQL
Although you can use an SQLite database with Medusa which would require no necessary database installations, it is recommended to use a PostgreSQL database for your server.
Although you can use an SQLite database with Medusa which would require no necessary database installations, it is recommended to use a PostgreSQL database for your backend.
:::tip
After installing PostgreSQL, check out the [Configure your Server documentation](../usage/configurations.md#postgresql-configurations) to learn how to configure PostgreSQL to work with Medusa.
After installing PostgreSQL, check out the [Configure your Backend documentation](./configurations.md#postgresql-configurations) to learn how to configure PostgreSQL to work with Medusa.
:::
@@ -206,7 +206,7 @@ Where:
- `--name` creates a new container named `postgres`.
- `-e` creates environment variables `POSTGRES_USER`, `POSTGRES_PASSWORD` and `POSTGRES_DB`. These will be used to set up a database named `medusa-docker` with the username and password being `postgres`.
- `-p` maps the container port `5432` to the external host `5432`. This allows you to connect to the database server from outside of the container.
- `-p` maps the container port `5432` to the external host `5432`. This allows you to connect to the database backend from outside of the container.
- `-d` enables Docker to run the container in the background.
- The last section of the command, `postgres` grabs the latest postgres image from the Docker hub.
@@ -215,13 +215,13 @@ Where:
### Redis
Medusa uses Redis as the event queue in the server. If you want to use subscribers to handle events such as when an order is placed and perform actions based on the events, then you need to install and configure Redis.
Medusa uses Redis as the event queue in the backend. If you want to use subscribers to handle events such as when an order is placed and perform actions based on the events, then you need to install and configure Redis.
If you dont install and configure Redis with your Medusa server, then it will work without any events-related features.
If you dont install and configure Redis with your Medusa backend, then it will work without any events-related features.
:::tip
After installing Redis, check out the [Configure your Server documentation](../usage/configurations.md#redis) to learn how to configure Redis to work with Medusa.
After installing Redis, check out the [Configure your Backend documentation](./configurations.md#redis) to learn how to configure Redis to work with Medusa.
:::
@@ -284,7 +284,5 @@ To install Redis without Homebrew you can check out [Rediss guide on installi
## See Also
- [Install Medusa server](../quickstart/quick-start.mdx)
- [Configure your Medusa server](../usage/configurations.md).
- Install a storefront with [Next.js](../starters/nextjs-medusa-starter.mdx) or [Gatsby](./../starters/gatsby-medusa-starter.mdx).
- [Install the Medusa Admin](../admin/quickstart.mdx).
- [Install Medusa backend](./install.mdx)
- [Configure the Medusa backend](./configurations.md)

View File

@@ -1,5 +1,5 @@
---
description: 'Learn how to create a batch job strategy in the Medusa server. This guide also includes how to test your batch job strategy.'
description: 'Learn how to create a batch job strategy in Medusa. This guide also includes how to test your batch job strategy.'
addHowToData: true
---
@@ -8,17 +8,17 @@ import TabItem from '@theme/TabItem';
# Create a Batch Job Strategy
In this document, youll learn how to create a batch job strategy on your Medusa server.
In this document, youll learn how to create a batch job strategy in Medusa.
:::info
If youre interested to learn more about what Batch Jobs are and how they work, check out [this documentation](./index.md).
If youre interested to learn more about what Batch Jobs are and how they work, check out [this documentation](./index.mdx).
:::
## Overview
Batch jobs can be used to perform long tasks in the background of your Medusa server. Batch jobs are handled by batch job strategies. An example of a batch job strategy is the Import Products functionality.
Batch jobs can be used to perform long tasks in the background of your Medusa backend. Batch jobs are handled by batch job strategies. An example of a batch job strategy is the Import Products functionality.
This documentation helps you learn how to create a batch job strategy. The batch job strategy used in this example changes the status of all draft products to `published`.
@@ -28,15 +28,15 @@ This documentation helps you learn how to create a batch job strategy. The batch
### Medusa Components
It is assumed that you already have a Medusa server installed and set up. If not, you can follow our [quickstart guide](../../../quickstart/quick-start.mdx) to get started.
It is assumed that you already have a Medusa backend installed and set up. If not, you can follow our [quickstart guide](../backend/install.mdx) to get started.
### Redis
Redis is required for batch jobs to work. Make sure you [install Redis](../../../tutorial/0-set-up-your-development-environment.mdx#redis) and [configure it with your Medusa server](../../../usage/configurations.md#redis).
Redis is required for batch jobs to work. Make sure you [install Redis](../backend/prepare-environment.mdx#redis) and [configure it with your Medusa backend](../backend/configurations.md#redis).
### PostgreSQL
If you use SQLite during your development, its highly recommended that you use PostgreSQL when working with batch jobs. Learn how to [install PostgreSQL](../../../tutorial/0-set-up-your-development-environment.mdx#postgresql) and [configure it with your Medusa server](../../../usage/configurations.md#postgresql-configurations).
If you use SQLite during your development, its highly recommended that you use PostgreSQL when working with batch jobs. Learn how to [install PostgreSQL](../backend/prepare-environment.mdx#postgresql) and [configure it with your Medusa backend](../backend/configurations.md#postgresql-configurations).
---
@@ -102,7 +102,7 @@ class PublishStrategy extends AbstractBatchJobStrategy {
### (Optional) prepareBatchJobForProcessing
Medusa runs this method before it creates the batch job to prepare the content of the batch job record in the database. It accepts two parameters: the batch job data sent in the body of the [Create Batch Job request](https://docs.medusajs.com/api/admin/#tag/Batch-Job/operation/PostBatchJobs), and the request instance.
Medusa runs this method before it creates the batch job to prepare the content of the batch job record in the database. It accepts two parameters: the batch job data sent in the body of the [Create Batch Job request](/api/admin/#tag/Batch-Job/operation/PostBatchJobs), and the request instance.
Implementing this method is optional. For example:
@@ -129,32 +129,34 @@ For example, this implementation of the `preProcessBatchJob` method calculates h
class PublishStrategy extends AbstractBatchJobStrategy {
// ...
async preProcessBatchJob(batchJobId: string): Promise<void> {
return await this.atomicPhase_(async (transactionManager) => {
const batchJob = (await this.batchJobService_
.withTransaction(transactionManager)
.retrieve(batchJobId))
const count = await this.productService_
.withTransaction(transactionManager)
.count({
status: ProductStatus.DRAFT,
})
return await this.atomicPhase_(
async (transactionManager) => {
const batchJob = (await this.batchJobService_
.withTransaction(transactionManager)
.retrieve(batchJobId))
const count = await this.productService_
.withTransaction(transactionManager)
.count({
status: ProductStatus.DRAFT,
})
await this.batchJobService_
.withTransaction(transactionManager)
.update(batchJob, {
result: {
advancement_count: 0,
count,
stat_descriptors: [
{
key: "product-publish-count",
name: "Number of products to publish",
message: `${count} product(s) will be published.`,
},
],
},
})
await this.batchJobService_
.withTransaction(transactionManager)
.update(batchJob, {
result: {
advancement_count: 0,
count,
stat_descriptors: [
{
key: "product-publish-count",
name: "Number of products to publish",
message:
`${count} product(s) will be published.`,
},
],
},
})
})
}
}
@@ -272,7 +274,7 @@ class PublishStrategy extends AbstractBatchJobStrategy {
## 5. Run Build Command
After you create the batch job and before testing it out, you must run the build command in the directory of your Medusa server:
After you create the batch job and before testing it out, you must run the build command in the directory of your Medusa backend:
```bash
npm run build
@@ -282,7 +284,7 @@ npm run build
## Test your Batch Job Strategy
This section covers how to test and use your batch job strategy. Make sure to start your server first:
This section covers how to test and use your batch job strategy. Make sure to start your backend first:
```bash
npm run start
@@ -290,17 +292,17 @@ npm run start
:::info
If your `start` script uses the `medusa develop` command, whenever you make changes in the `src` directory the `build` command will automatically run and the server will restart.
If your `start` script uses the `medusa develop` command, whenever you make changes in the `src` directory the `build` command will automatically run and the backend will restart.
:::
You must also use an authenticated user to send batch job requests. You can refer to the [authentication guide in the API reference](https://docs.medusajs.com/api/admin/#section/Authentication) for more details.
You must also use an authenticated user to send batch job requests. You can refer to the [authentication guide in the API reference](/api/admin/#section/Authentication) for more details.
If you follow along with the JS Client code snippets, make sure to [install and set it up first](../../../js-client/overview.md).
If you follow along with the JS Client code snippets, make sure to [install and set it up first](../../js-client/overview.md).
### Create Batch Job
The first step is to create a batch job using the [Create Batch Job endpoint](https://docs.medusajs.com/api/admin/#tag/Batch-Job/operation/PostBatchJobs). In the body of the request, you must set the `type` to the value of `batchType` in the batch job strategy you created.
The first step is to create a batch job using the [Create Batch Job endpoint](/api/admin/#tag/Batch-Job/operation/PostBatchJobs). In the body of the request, you must set the `type` to the value of `batchType` in the batch job strategy you created.
For example, this creates a batch job of the type `publish-products`:
@@ -322,7 +324,7 @@ medusa.admin.batchJobs.create({
<TabItem value="fetch" label="Fetch API">
```jsx
fetch(`<YOUR_SERVER>/admin/batch-jobs`, {
fetch(`<BACKEND_URL>/admin/batch-jobs`, {
method: "POST",
credentials: "include",
headers: {
@@ -344,7 +346,7 @@ fetch(`<YOUR_SERVER>/admin/batch-jobs`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<YOUR_SERVER>/admin/batch-jobs' \
curl -L -X POST '<BACKEND_URL>/admin/batch-jobs' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -359,7 +361,7 @@ curl -L -X POST '<YOUR_SERVER>/admin/batch-jobs' \
You set the `dry_run` to `true` to disable automatic confirmation and running of the batch job. If you want the batch job to run automatically, you can remove this body parameter.
Make sure to replace `<YOUR_SERVER>` with the server URL where applicable.
Make sure to replace `<BACKEND_URL>` with the backend URL where applicable.
### (Optional) Retrieve Batch Job
@@ -379,7 +381,7 @@ medusa.admin.batchJobs.retrieve(batchJobId)
<TabItem value="fetch" label="Fetch API">
```jsx
fetch(`<YOUR_SERVER>/admin/batch-jobs/${batchJobId}`, {
fetch(`<BACKEND_URL>/admin/batch-jobs/${batchJobId}`, {
credentials: "include",
})
.then((response) => response.json())
@@ -392,7 +394,7 @@ fetch(`<YOUR_SERVER>/admin/batch-jobs/${batchJobId}`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X GET '<YOUR_SERVER>/admin/batch-jobs/<BATCH_JOB_ID>' \
curl -L -X GET '<BACKEND_URL>/admin/batch-jobs/<BATCH_JOB_ID>' \
-H 'Authorization: Bearer <API_TOKEN>'
# <BATCH_JOB_ID> is the ID of the batch job
```
@@ -418,7 +420,7 @@ Based on the batch job strategy implemented in this documentation, the `result`
### Confirm Batch Job
To process the batch job, send a request to [confirm the batch job](https://docs.medusajs.com/api/admin/#tag/Batch-Job/operation/PostBatchJobsBatchJobConfirmProcessing):
To process the batch job, send a request to [confirm the batch job](/api/admin/#tag/Batch-Job/operation/PostBatchJobsBatchJobConfirmProcessing):
<Tabs groupId="request-type" wrapperClassName="code-tabs">
<TabItem value="client" label="Medusa JS Client" default>
@@ -434,7 +436,7 @@ medusa.admin.batchJobs.confirm(batchJobId)
<TabItem value="fetch" label="Fetch API">
```jsx
fetch(`<YOUR_SERVER>/admin/batch-jobs/${batchJobId}/confirm`, {
fetch(`<BACKEND_URL>/admin/batch-jobs/${batchJobId}/confirm`, {
method: "POST",
credentials: "include",
})
@@ -448,7 +450,7 @@ fetch(`<YOUR_SERVER>/admin/batch-jobs/${batchJobId}/confirm`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<YOUR_SERVER>/admin/batch-jobs/<BATCH_JOB_ID>/confirm' \
curl -L -X POST '<BACKEND_URL>/admin/batch-jobs/<BATCH_JOB_ID>/confirm' \
-H 'Authorization: Bearer <API_TOKEN>'
# <BATCH_JOB_ID> is the ID of the batch job
```
@@ -459,10 +461,3 @@ curl -L -X POST '<YOUR_SERVER>/admin/batch-jobs/<BATCH_JOB_ID>/confirm' \
The batch job will start processing afterward. Based on the batch job strategy implemented in this documentation, draft products will be published.
You can [retrieve the batch job](#optional-retrieve-batch-job) at any given point to check its status.
---
## See Also
- [Batch Jobs Overview](./index.md).
- [Import products using the Admin API](../../admin/import-products.mdx).

View File

@@ -19,15 +19,15 @@ Although this documentation specifically targets import strategies, you can use
### Medusa Components
It's assumed that you already have a Medusa server installed and set up. If not, you can follow our [quickstart guide](../../../quickstart/quick-start.mdx) to get started.
It's assumed that you already have a Medusa backend installed and set up. If not, you can follow our [quickstart guide](../backend/install.mdx) to get started.
### Redis
Redis is required for batch jobs to work. Make sure you [install Redis](../../../tutorial/0-set-up-your-development-environment.mdx#redis) and [configure it with your Medusa server](../../../usage/configurations.md#redis).
Redis is required for batch jobs to work. Make sure you [install Redis](../backend/prepare-environment.mdx#redis) and [configure it with your Medusa backend](../backend/configurations.md#redis).
### PostgreSQL
If you use SQLite during your development, its highly recommended that you use PostgreSQL when working with batch jobs. Learn how to [install PostgreSQL](../../../tutorial/0-set-up-your-development-environment.mdx#postgresql) and [configure it with your Medusa server](../../../usage/configurations.md#postgresql-configurations).
If you use SQLite during your development, its highly recommended that you use PostgreSQL when working with batch jobs. Learn how to [install PostgreSQL](../backend/prepare-environment.mdx#postgresql) and [configure it with your Medusa backend](../backend/configurations.md#postgresql-configurations).
---
@@ -39,7 +39,7 @@ If youre interested to learn more about batch job strategies and how they wor
### 1. Create a File
You must store batch job strategies in the `src/strategies` directory of your Medusa server. They are either TypeScript or JavaScript files.
You must store batch job strategies in the `src/strategies` directory of your Medusa backend. They are either TypeScript or JavaScript files.
So, for example, you can create the file `src/strategies/import.ts`.
@@ -111,21 +111,20 @@ npm run build
Since you didnt create a new batch job type and overwrote the functionality of the strategy, you can test out your functionality using the [same steps used with the default strategy](./create.mdx#test-your-batch-job-strategy).
Specifically, since you create batch jobs using the [Create Batch Job](https://docs.medusajs.com/api/admin/#tag/Batch-Job/operation/PostBatchJobs) endpoint which accepts the batch job type as a body parameter, you just need to send the same type you used for this field. In the example of this documentation, the `type` would be `product-import`.
Specifically, since you create batch jobs using the [Create Batch Job](/api/admin/#tag/Batch-Job/operation/PostBatchJobs) endpoint which accepts the batch job type as a body parameter, you just need to send the same type you used for this field. In the example of this documentation, the `type` would be `product-import`.
If you overwrote the import functionality, you can follow [these steps to learn how to import products using the Admin APIs](../../admin/import-products.mdx).
If you overwrote the import functionality, you can follow [these steps to learn how to import products using the Admin APIs](../../modules/products/admin/import-products.mdx).
---
## Create Custom Batch Job Strategy
If you dont want to overwrite Medusas batch job strategy, you can create a custom batch job strategy with a different `batchType` value. Then, use that type when you send a request to [Create a Batch Job](https://docs.medusajs.com/api/admin/#tag/Batch-Job).
If you dont want to overwrite Medusas batch job strategy, you can create a custom batch job strategy with a different `batchType` value. Then, use that type when you send a request to [Create a Batch Job](/api/admin/#tag/Batch-Job).
For more details on creating custom batch job strategies, please check out the [Create Batch Job Strategy documentation](create.mdx).
For more details on creating custom batch job strategies, please check out the [Create Batch Job Strategy documentation](./create.mdx).
---
## Whats Next
## See Also
- [Batch Jobs Overview](./index.md).
- [Use the Import Product APIs](../../admin/import-products.mdx).
- [Use the Import Product APIs](../../modules/products/admin/import-products.mdx).

View File

@@ -1,16 +1,19 @@
---
description: 'Learn what batch jobs in the Medusa server are and their flow. Batch jobs are tasks that can be performed asynchronously and iteratively in the Medusa server.'
description: 'Learn what batch jobs in Medusa are and their flow. Batch jobs are tasks that can be performed asynchronously and iteratively in Medusa.'
---
import DocCardList from '@theme/DocCardList';
import Icons from '@theme/Icon';
# Batch Jobs
In this document, youll learn what Batch Jobs are and how they work in Medusa.
## What are Batch Jobs
Batch Jobs are tasks that can be performed asynchronously and iteratively. They can be [created using the Admin API](https://docs.medusajs.com/api/admin/#tag/Batch-Job/operation/PostBatchJobs), then, once confirmed, they are processed asynchronously.
Batch Jobs are tasks that can be performed asynchronously and iteratively. They can be [created using the Admin API](/api/admin/#tag/Batch-Job/operation/PostBatchJobs), then, once confirmed, they are processed asynchronously.
Batch jobs require Redis, which Medusa uses as a queuing system to register and handle events. Every status change of a batch job triggers an event that can be handled using [subscribers](../subscribers/overview.md).
Batch jobs require Redis, which Medusa uses as a queuing system to register and handle events. Every status change of a batch job triggers an event that can be handled using [subscribers](../events/subscribers.mdx).
Medusa uses batch jobs in its core to perform some asynchronous tasks. For example, the Export Products functionality uses batch jobs.
@@ -18,7 +21,7 @@ You can also create a custom batch job or overwrite Medusas batch jobs.
### BatchJob Entity Overview
A batch job is stored in the database as a [BatchJob](https://docs.medusajs.com/references/entities/classes/BatchJob) entity. Some of its important attributes are:
A batch job is stored in the database as a [BatchJob](../../references/entities/classes/BatchJob) entity. Some of its important attributes are:
- `status`: A string that determines the current status of the Batch Job.
- `context`: An object that can be used to store configurations related to the batch job. For example, you can use it to store listing configurations such as the limit or offset of the list to be retrieved during the processing of the batch job.
@@ -46,15 +49,15 @@ When you create a batch job strategy, the `batchType` class property indicates t
A batch jobs flow from creation to completion is:
1. A batch job is created using the [Create Batch Job API endpoint](https://docs.medusajs.com/api/admin/#tag/Batch-Job/operation/PostBatchJobs).
1. A batch job is created using the [Create Batch Job API endpoint](/api/admin/#tag/Batch-Job/operation/PostBatchJobs).
2. Once the batch job is created, the batch jobs status is changed to `created` and the `batch.created` event is triggered by the `BatchJobService`.
3. The `BatchJobSubscriber` handles the `created` event. It resolves the batch job strategy based on the `type` of the batch job, then uses it to pre-process the batch job. After this, the batch jobs status is changed to `pre_processed`. Only when the batch job has the status `pre_processed` can be confirmed.
4. If `dry_run` is not set in the Create Batch Job request in step one or if it is set to `false`, the batch job will automatically be confirmed after processing. Otherwise, if `dry_run` is set to `true`, the batch job can be confirmed using the [Confirm Batch Job API](https://docs.medusajs.com/api/admin/#tag/Batch-Job/operation/PostBatchJobsBatchJobConfirmProcessing) endpoint.
4. If `dry_run` is not set in the Create Batch Job request in step one or if it is set to `false`, the batch job will automatically be confirmed after processing. Otherwise, if `dry_run` is set to `true`, the batch job can be confirmed using the [Confirm Batch Job API](/api/admin/#tag/Batch-Job/operation/PostBatchJobsBatchJobConfirmProcessing) endpoint.
5. Once the batch job is confirmed, the batch jobs status is changed to `confirmed` and the `batch.confirmed` event is triggered by the `BatchJobService`.
6. The `BatchJobSubscriber` handles the `confirmed` event. It resolves the batch job strategy, then uses it to process the batch job.
7. Once the batch job is processed succesfully, the batch job has the status `completed`.
You can track the progress of the batch job at any point using the [Retrieve Batch Job](https://docs.medusajs.com/api/admin/#tag/Batch-Job/operation/GetBatchJobsBatchJob) endpoint.
You can track the progress of the batch job at any point using the [Retrieve Batch Job](/api/admin/#tag/Batch-Job/operation/GetBatchJobsBatchJob) endpoint.
:::info
@@ -66,6 +69,27 @@ If the batch job fails at any point in this flow, its status is changed to `fail
---
## Whats Next
## Custom Development
- [Batch Jobs Events Reference](../subscribers/events-list.md#batch-jobs-events).
Developers can create custom batch jobs in the Medusa backend, a plugin, or in a Commerce Module. Developers can also customize existing batch job strategies in the core, such as the import strategy.
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/development/batch-jobs/create',
label: 'Create a Batch Job Strategy',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create a batch job strategy in Medusa.'
}
},
{
type: 'link',
href: '/development/batch-jobs/customize-import',
label: 'Customize Import Strategy',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to customize the import strategy in Medusa.'
}
},
]} />

View File

@@ -9,13 +9,13 @@ In this document, youll learn how to add a middleware to an existing or custo
## Overview
As the Medusa server is built on top of [Express](https://expressjs.com/), Expresss features can be utilized during your development with Medusa.
As the Medusa backend is built on top of [Express](https://expressjs.com/), Expresss features can be utilized during your development with Medusa.
One feature in particular is adding a [middleware](http://expressjs.com/en/guide/using-middleware.html#using-middleware). A middleware is a function that has access to the request and response objects.
A middleware can be used to perform an action when an endpoint is called or modify the response, among other usages.
You can add a middleware to an existing route in the Medusa server, a route in a plugin, or your custom routes.
You can add a middleware to an existing route in the Medusa backend, a route in a plugin, or your custom routes.
---
@@ -25,7 +25,7 @@ Adding a middleware is very similar to adding a custom endpoint. The middleware
:::info
Learn more about creating custom endpoints in [this documentation](./add.md).
Learn more about creating custom endpoints in [this documentation](./create.md).
:::
@@ -38,8 +38,8 @@ export default () => {
const router = Router()
router.use("/store/products", (req, res, next) => {
// / perform an action when retrieving products
next()
// perform an action when retrieving products
next()
})
return router
@@ -60,9 +60,9 @@ You can learn more about Middlewares and their capabilities in [Expresss docu
## Building Files
Similar to custom endpoints, you must transpile the files under `src` into the `dist` directory for the server to load them.
Similar to custom endpoints, you must transpile the files under `src` into the `dist` directory for the backend to load them.
To do that, run the following command before running the Medusa server:
To do that, run the following command before running the Medusa backend:
```bash npm2yarn
npm run build
@@ -72,6 +72,5 @@ npm run build
## See Also
- [Create an Endpoint](./add.md)
- [Store API reference](/api/store)
- [Admin API reference](/api/admin)

View File

@@ -1,15 +1,17 @@
---
description: 'Learn how to create endpoints in the Medusa server. This guide also includes how to add CORS configurations, creating multiple endpoints, adding protected routes, and more.'
description: 'Learn how to create endpoints in Medusa. This guide also includes how to add CORS configurations, creating multiple endpoints, adding protected routes, and more.'
addHowToData: true
---
# How to Create Endpoints
In this document, youll learn how to create endpoints in your Medusa server.
In this document, youll learn how to create endpoints in Medusa.
## Overview
Custom endpoints reside under the `src/api` directory in your Medusa Backend. They're defined in a TypeScript or JavaScript file that is named `index` (for example, `index.ts`). This file should export a function that returns an Express router.
Custom endpoints are created under the `src/api` directory in your Medusa Backend. They're defined in a TypeScript or JavaScript file named `index` (for example, `index.ts`). This file should export a function that returns an Express router
They're then transpiled into the `/dist/api` directory to be consumed.
---
@@ -35,7 +37,7 @@ export default (rootDirectory, pluginOptions) => {
This exports a function that returns an Express router. The function receives two parameters:
- `rootDirectory` is the absolute path to the root directory that your server is running from.
- `rootDirectory` is the absolute path to the root directory that your backend is running from.
- `pluginOptions` is an object that has your plugin's options. If your API route is not implemented in a plugin, then it will be an empty object.
### Endpoints Path
@@ -58,12 +60,17 @@ If youre adding a storefront or admin endpoint and you want to access these e
First, you need to import the necessary utility functions and types from Medusa's packages with the `cors` library:
```ts
import { getConfigFile, parseCorsOrigins } from "medusa-core-utils"
import { ConfigModule } from "@medusajs/medusa/dist/types/global"
import {
getConfigFile,
parseCorsOrigins,
} from "medusa-core-utils"
import {
ConfigModule,
} from "@medusajs/medusa/dist/types/global"
import cors from "cors"
```
Next, in the exported function, retrieve the CORS configurations of your server using the utility functions you imported:
Next, in the exported function, retrieve the CORS configurations of your backend using the utility functions you imported:
```ts
export default (rootDirectory) => {
@@ -114,18 +121,26 @@ You can add more than one endpoint in `src/api/index.ts`:
```ts title=src/api/index.ts
router.options("/store/hello", cors(storeCorsOptions))
router.get("/store/hello", cors(storeCorsOptions), (req, res) => {
res.json({
message: "Welcome to Your Store!",
})
})
router.get(
"/store/hello",
cors(storeCorsOptions),
(req, res) => {
res.json({
message: "Welcome to Your Store!",
})
}
)
router.options("/admin/hello", cors(adminCorsOptions))
router.get("/admin/hello", cors(adminCorsOptions), (req, res) => {
res.json({
message: "Welcome to Your Admin!",
})
})
router.get(
"/admin/hello",
cors(adminCorsOptions),
(req, res) => {
res.json({
message: "Welcome to Your Admin!",
})
}
)
```
### Multiple Files
@@ -144,11 +159,15 @@ export default (router) => {
credentials: true,
}
router.options("/store/hello", cors(storeCorsOptions))
router.get("/store/hello", cors(storeCorsOptions), (req, res) => {
res.json({
message: "Welcome to Your Store!",
})
})
router.get(
"/store/hello",
cors(storeCorsOptions),
(req, res) => {
res.json({
message: "Welcome to Your Store!",
})
}
)
}
```
@@ -166,11 +185,15 @@ export default (router) => {
credentials: true,
}
router.options("/admin/hello", cors(adminCorsOptions))
router.get("/admin/hello", cors(adminCorsOptions), (req, res) => {
res.json({
message: "Welcome to Your Admin!",
})
})
router.get(
"/admin/hello",
cors(adminCorsOptions),
(req, res) => {
res.json({
message: "Welcome to Your Admin!",
})
}
)
}
```
@@ -207,6 +230,8 @@ Protected routes are routes that should be accessible by logged-in customers or
To make a storefront route protected, first, import the `authenticate-customer` middleware:
<!-- eslint-disable max-len -->
```ts
import
authenticate
@@ -236,6 +261,8 @@ To disallow guest customers from accessing the endpoint, you can throw an error
To make an admin route protected, first, import the `authenticate` middleware:
<!-- eslint-disable max-len -->
```ts
import
authenticate
@@ -246,7 +273,10 @@ Then, add the middleware to your route:
```ts
router.options("/admin/products/count", cors(corsOptions))
router.get("/admin/products/count", cors(corsOptions), authenticate(),
router.get(
"/admin/products/count",
cors(corsOptions),
authenticate(),
async (req, res) => {
// access current user
const id = req.user.userId
@@ -271,7 +301,10 @@ You can retrieve any registered service in your endpoint using `req.scope.resol
Heres an example of an endpoint that retrieves the count of products in your store:
```ts
router.get("/admin/products/count", cors(corsOptions), authenticate(),
router.get(
"/admin/products/count",
cors(corsOptions),
authenticate(),
(req, res) => {
const productService = req.scope.resolve("productService")
@@ -290,7 +323,9 @@ The `productService` has a `count` method that returns a Promise. This Promi
## Building Files
Custom endpoints must be transpiled and moved to the `dist` directory. This happens when you run your server using `medusa develop` and while its running, and when you run the following command:
Custom endpoints must be transpiled and moved to the `dist` directory before you can start consuming them. When you run your backend using the `medusa develop` command, it watches the files under `src` for any changes, then triggers the `build` command and restarts the server.
The build isn't triggerd though when the backend first starts running. So, make sure to run the `build` command before starting the backend:
```bash npm2yarn
npm run build
@@ -300,7 +335,5 @@ npm run build
## See Also
- [Add a Middleware](./add-middleware.md)
- [Storefront API Reference](/api/store)
- [Admin API Reference](/api/admin)
- [Create a Service](./../services/create-service.md).

View File

@@ -0,0 +1,76 @@
---
description: "Learn what endpoints are in Medusa. Endpoints are REST APIs that allow a frontend or external system to interact with the Backend."
---
import DocCardList from '@theme/DocCardList';
import Icons from '@theme/Icon';
# Endpoints
In this document, youll learn what endpoints are in Medusa.
## Introduction
The Medusa Backend is a web server built on top of [Express](https://expressjs.com/), a Node.js web framework. This provides developers with all the functionalities available within Express during development. One of those are endpoints.
Endpoints are REST APIs that allow a frontend or an external system to interact with the Medusa Backend to retrieve and process data, or perform business logic. Endpoints are [Express routes](https://expressjs.com/en/starter/basic-routing.html).
Each [Commerce Module](../../modules/overview.mdx) contains a set of endpoints specific to the functionalities that it provides. Since the core package that powers the Medusa Backend acts as an orchestrator of Commerce Modules and exposes their endpoints, the endpoints of each of these Commerce Modules are available within the Medusa Backend.
The Commerce Modules provide two types of endpoints: Store APIs and Admin APIs. The Store APIs are typically accessed from the storefront. For example, you can use the Store APIs to show customers available products or implement a cart and checkout flow.
The Admin APIs are typically accessed from an admin dashboard. For example, you can use the Admin APIs to allow admins to manage the stores data such as products, orders, and so on.
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/api/store',
label: 'Store APIs',
customProps: {
icon: Icons['server-solid'],
description: 'Check out available Store REST APIs.'
}
},
{
type: 'link',
href: '/api/admin',
label: 'Admin APIs',
customProps: {
icon: Icons['server-solid'],
description: 'Check out available Admin REST APIs.'
}
},
]} />
---
## Custom Development
Aside from using the endpoints that Commerce Modules, developers can create their own REST APIs either directly in the Medusa Backend, in a plugin, or in a custom Commerce Module.
:::tip
As the core Medusa package is completely customizable, developers can also extend the functionality even further to implement GraphQL endpoints.
:::
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/development/endpoints/create',
label: 'Create an Endpoint',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create an endpoint in Medusa.'
}
},
{
type: 'link',
href: '/development/endpoints/add-middleware',
label: 'Add a Middleware',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to add a middleware in Medusa.'
}
},
]} />

View File

@@ -1,18 +1,23 @@
---
description: 'Learn how to create an entity in the Medusa server. This guide also explains how to create a repository and access and delete the entity.'
description: 'Learn how to create an entity in Medusa. This guide also explains how to create a repository and access and delete the entity.'
addHowToData: true
---
# Create an Entity
In this document, youll learn how you can create an [Entity](overview.md).
In this document, youll learn how you can create an [Entity](./overview.mdx).
## Create the Entity
To create an entity, create a TypeScript file in `src/models`. For example, heres a `Post` entity defined in the file `src/models/post.ts`:
```ts title=src/models/post.ts
import { BeforeInsert, Column, Entity, PrimaryColumn } from "typeorm"
import {
BeforeInsert,
Column,
Entity,
PrimaryColumn,
} from "typeorm"
import { BaseEntity } from "@medusajs/medusa"
import { generateEntityId } from "@medusajs/medusa/dist/utils"
@@ -51,7 +56,7 @@ You can learn more about what decorators and column types you can use in [Typeor
Additionally, you must create a migration for your entity. Migrations are used to update the database schema with new tables or changes to existing tables.
You can learn more about Migrations, how to create them, and how to run them in the [Migration documentation](../migrations/overview.md).
You can learn more about Migrations, how to create them, and how to run them in the [Migration documentation](./migrations/overview.mdx).
### Create a Repository
@@ -137,6 +142,5 @@ await postRepository.softDelete(post.id)
## See Also
- [Entities' reference](../../../references/entities/classes/Address.md)
- [Migrations Overview](../migrations/overview.md)
- [Create a Services](../services/create-service.md)
- [Migrations Overview](./migrations/overview.mdx)
- [Create a Plugin](../plugins/create.md)

View File

@@ -1,11 +1,11 @@
---
description: 'Learn how to create a migration in the Medusa server. This guide explains how to write and run migrations.'
description: 'Learn how to create a migration in Medusa. This guide explains how to write and run migrations.'
addHowToData: true
---
# How to Create Migrations
In this document, youll learn how to create a [Migration](overview.md) using [Typeorm](https://typeorm.io) on your Medusa server.
In this document, youll learn how to create a [Migration](./overview.mdx) using [Typeorm](https://typeorm.io) in Medusa.
## Step 1: Create Migration File
@@ -17,7 +17,7 @@ npx typeorm migration:create -n UserChanged --dir src/migrations
This will create the migration file in the path you specify. You can use this without the need to install Typeorm's CLI tool. You can then go ahead and make changes to it as necessary.
The migration file must be inside the `src/migrations` directory. When you run the build command, it will be transpiled into the directory `dist/migrations`. The `migrations run` command can only pick up migrations under the `dist/migrations` directory on a Medusa server. This applies to migrations created in a Medusa server, and not in a Medusa plugin. For plugins, check out the [Plugin's Structure section](../plugins/create.md).
The migration file must be inside the `src/migrations` directory. When you run the build command, it will be transpiled into the directory `dist/migrations`. The `migrations run` command can only pick up migrations under the `dist/migrations` directory on a Medusa backend. This applies to migrations created in a Medusa backend, and not in a Medusa plugin. For plugins, check out the [Plugin's Structure section](../../plugins/create.md).
<details>
<summary>Generating Migrations for Entities</summary>
@@ -104,6 +104,6 @@ If you check your database now you should see that the change defined by the mig
---
## Whats Next
## See Also
- [Set up your development server](../../../tutorial/0-set-up-your-development-environment.mdx).
- [Create a Plugin](../../plugins/create.md)

View File

@@ -1,22 +1,25 @@
---
description: 'Learn what Migrations are in the Medusa server and how to run them. Migrations are used to make changes to the database schema the Medusa server is linked to.'
description: 'Learn what Migrations are in Medusa and how to run them. Migrations are used to make changes to the database schema that Medusa is linked to.'
---
import DocCardList from '@theme/DocCardList';
import Icons from '@theme/Icon';
# Migrations
In this document, you'll learn what Migrations are in Medusa.
:::note
Medusas Migrations do not work with SQLite databases. They are intended to be used with PostgreSQL databases, which is the recommended Database for your Medusa production server.
Medusas Migrations do not work with SQLite databases. They are intended to be used with PostgreSQL databases, which is the recommended database for using Medusa in production.
:::
## What are Migrations
Migrations are scripts that are used to make additions or changes to your database schema. In Medusa, they are essential for both when you first install your server and for subsequent server upgrades later on.
Migrations are scripts that are used to make additions or changes to your database schema. In Medusa, they are essential for both when you first install your backend and for subsequent backend upgrades later on.
When you first create your Medusa server, the database schema used must have all the tables necessary for the server to run.
When you first create your Medusa backend, the database schema used must have all the tables necessary for the backend to run.
When a new Medusa version introduces changes to the database schema, you'll have to run migrations to apply them to your own database.
@@ -40,7 +43,7 @@ Using the Medusa CLI tool, you can run migrations with the following command:
medusa migrations run
```
This will check for any migrations that contain changes to your database schema that aren't applied yet and run them on your server.
This will check for any migrations that contain changes to your database schema that aren't applied yet and run them on your backend.
### Seed Command
@@ -52,11 +55,31 @@ You can use the following command to seed your database:
npm run seed
```
This will use the underlying `seed` command provided by Medusa's CLI to seed your database with data from the file `data/seed.json` on your Medusa server.
This will use the underlying `seed` command provided by Medusa's CLI to seed your database with data from the file `data/seed.json` on your Medusa backend.
---
## See Also
## Custom Development
- [Create a migration](index.md)
- [Set up your development environment](../../../tutorial/set-up-your-development-environment)
Developers can create custom entities in the Medusa backend, a plugin, or in a Commerce Module, then ensure it reflects in the database using a migration.
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/development/entities/migrations/create',
label: 'Create a Migration',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create migrations in Medusa.'
}
},
{
type: 'link',
href: '/development/entities/create',
label: 'Create an Endpoint',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create endpoints in Medusa.'
}
},
]} />

View File

@@ -1,7 +1,10 @@
---
description: 'Learn what entities are in the Medusa server. There are entities in the Medusa server, and developers can create custom entities.'
description: 'Learn what entities are in Medusa. There are entities defined in the Medusa backend, and developers can create custom entities.'
---
import DocCardList from '@theme/DocCardList';
import Icons from '@theme/Icon';
# Entities
In this document, you'll learn what Entities are in Medusa.
@@ -10,7 +13,7 @@ In this document, you'll learn what Entities are in Medusa.
Entities in medusa represent tables in the database as classes. An example of this would be the `Order` entity which represents the `order` table in the database. Entities provide a uniform way of defining and interacting with data retrieved from the database.
Aside from Medusas core entities, you can also create your own entities to use in your Medusa server. Custom entities are TypeScript or JavaScript files located in the `src/models` directory of your Medusa server.
Aside from the entities in the Medusa core package, you can also create your own entities to use in your Medusa backend. Custom entities are TypeScript or JavaScript files located in the `src/models` directory of your Medusa backend. These entities are then transpiled to the `dist/models` directory to be used during the backend's runtime.
Entities are TypeScript files and they are based on [Typeorms Entities](https://typeorm.io/entities) and use Typeorm decorators.
@@ -65,7 +68,27 @@ If you want to remove a property from the `metadata` object, you can pass the `m
---
## See Also
## Custom Development
- [Create an entity](./index.md)
- [Entities' reference](../../../references/entities/classes/Address.md)
Developers can create custom entities in the Medusa backend, a plugin, or in a Commerce Module, then ensure it reflects in the database using a migration.
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/development/entities/create',
label: 'Create an Endpoint',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create endpoints in Medusa.'
}
},
{
type: 'link',
href: '/development/entities/migrations/create',
label: 'Create a Migration',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create migrations in Medusa.'
}
},
]} />

View File

@@ -1,17 +1,17 @@
---
description: 'Learn how to create a subscriber in the Medusa server. You can use subscribers to implement functionalities like sending an order confirmation email.'
description: 'Learn how to create a subscriber in Medusa. You can use subscribers to implement functionalities like sending an order confirmation email.'
addHowToData: true
---
# How to Create a Subscriber
In this document, youll learn how to create a [Subscriber](overview.md) in your Medusa server that listens to events to perform an action.
In this document, youll learn how to create a [Subscriber](./subscribers.mdx) in Medusa that listens to events to perform an action.
## Prerequisites
Medusa's event system works by pushing data to a Queue that each handler then gets notified of. The queuing system is based on Redis, so it's required for subscribers to work.
You can learn how to [install Redis](../../../tutorial/0-set-up-your-development-environment.mdx#redis) and [configure it with Medusa](../../../usage/configurations.md#redis) before you get started.
You can learn how to [install Redis](../backend/prepare-environment.mdx#redis) and [configure it with Medusa](../backend/configurations.md#redis) before you get started.
---
@@ -60,7 +60,10 @@ class OrderNotifierSubscriber {
constructor({ productService, eventBusService }) {
this.productService = productService
eventBusService.subscribe("order.placed", this.handleOrder)
eventBusService.subscribe(
"order.placed",
this.handleOrder
)
}
// ...
}
@@ -88,5 +91,4 @@ When using attributes defined in the subscriber, such as the `productService` in
## See Also
- [Events reference](events-list.md)
- [Create a Service](../services/create-service)
- [Create a Plugin](../plugins/create.md)

View File

@@ -8,7 +8,7 @@ This document details all events in Medusa, when they are triggered, and what da
## Prerequisites
It is assumed youre already familiar with [Subscribers in Medusa and how to listen to events](create-subscriber.md). You can then use the name of events from this documentation in your subscriber to listen to events.
It is assumed youre already familiar with [Subscribers in Medusa and how to listen to events](./create-subscriber.md). You can then use the name of events from this documentation in your subscriber to listen to events.
---
@@ -1761,7 +1761,7 @@ Triggered when a payment is created.
</td>
<td>
The entire payment passed as an object. You can refer to the [Payment entity](../../../references/entities/classes/Payment.md) for an idea of what fields to expect.
The entire payment passed as an object. You can refer to the [Payment entity](../../references/entities/classes/Payment.md) for an idea of what fields to expect.
</td>
</tr>
@@ -1779,7 +1779,7 @@ Triggered when a payment is updated.
</td>
<td>
The entire payment passed as an object. You can refer to the [Payment entity](../../../references/entities/classes/Payment.md) for an idea of what fields to expect.
The entire payment passed as an object. You can refer to the [Payment entity](../../references/entities/classes/Payment.md) for an idea of what fields to expect.
</td>
</tr>
@@ -1797,7 +1797,7 @@ Triggered when a payment is captured.
</td>
<td>
The entire payment passed as an object. You can refer to the [Payment entity](../../../references/entities/classes/Payment.md) for an idea of what fields to expect.
The entire payment passed as an object. You can refer to the [Payment entity](../../references/entities/classes/Payment.md) for an idea of what fields to expect.
</td>
</tr>
@@ -1815,7 +1815,7 @@ Triggered when the capturing of a payment fails.
</td>
<td>
The entire payment passed as an object. You can refer to the [Payment entity](../../../references/entities/classes/Payment.md) for an idea of what fields to expect.
The entire payment passed as an object. You can refer to the [Payment entity](../../references/entities/classes/Payment.md) for an idea of what fields to expect.
In addition, an error object is passed within the same object as the Payment provider:
@@ -1847,7 +1847,7 @@ Triggered when a refund of a payment is created.
</td>
<td>
The entire refund passed as an object. You can refer to the [Refund entity](../../../references/entities/classes/Refund.md) for an idea of what fields to expect.
The entire refund passed as an object. You can refer to the [Refund entity](../../references/entities/classes/Refund.md) for an idea of what fields to expect.
</td>
</tr>
@@ -1865,7 +1865,7 @@ Triggered when a payment's refund fails.
</td>
<td>
The entire payment passed as an object. You can refer to the [Payment entity](../../../references/entities/classes/Payment.md) for an idea of what fields to expect.
The entire payment passed as an object. You can refer to the [Payment entity](../../references/entities/classes/Payment.md) for an idea of what fields to expect.
</td>
</tr>
@@ -1908,7 +1908,7 @@ Triggered when a payment collection is created.
</td>
<td>
The entire payment collection passed as an object. You can refer to the [Payment Collection entity](../../../references/entities/classes/PaymentCollection.md) for an idea of what fields to expect.
The entire payment collection passed as an object. You can refer to the [Payment Collection entity](../../references/entities/classes/PaymentCollection.md) for an idea of what fields to expect.
</td>
</tr>
@@ -1926,7 +1926,7 @@ Triggered when a payment collection is update.
</td>
<td>
The entire payment collection passed as an object. You can refer to the [Payment Collection entity](../../../references/entities/classes/PaymentCollection.md) for an idea of what fields to expect.
The entire payment collection passed as an object. You can refer to the [Payment Collection entity](../../references/entities/classes/PaymentCollection.md) for an idea of what fields to expect.
</td>
</tr>
@@ -1944,7 +1944,7 @@ Triggered when a payment collection is deleted.
</td>
<td>
The entire payment collection passed as an object. You can refer to the [Payment Collection entity](../../../references/entities/classes/PaymentCollection.md) for an idea of what fields to expect.
The entire payment collection passed as an object. You can refer to the [Payment Collection entity](../../references/entities/classes/PaymentCollection.md) for an idea of what fields to expect.
</td>
</tr>
@@ -1962,7 +1962,7 @@ Triggered when a payment collection is either marked authorized or its payment s
</td>
<td>
The entire payment collection passed as an object. You can refer to the [Payment Collection entity](../../../references/entities/classes/PaymentCollection.md) for an idea of what fields to expect.
The entire payment collection passed as an object. You can refer to the [Payment Collection entity](../../references/entities/classes/PaymentCollection.md) for an idea of what fields to expect.
</td>
</tr>
@@ -2029,7 +2029,7 @@ Triggered when a product and data associated with it (options, variant orders, e
</td>
<td>
The entire product passed as an object. You can refer to the [Product entity](../../../references/entities/classes/Product.md) for an idea of what fields to expect.
The entire product passed as an object. You can refer to the [Product entity](../../references/entities/classes/Product.md) for an idea of what fields to expect.
In one case, when the `/admin/products/{id}` endpoint is used to update the product, the payload is an object of the following format:
@@ -2442,17 +2442,6 @@ Object of the following format:
This section holds all events related to sales channels.
:::note
As of Medusa v1.3.5, Sales Channels are available but guarded by a feature flag. To use Sales Channels either:
1. Enable the `MEDUSA_FF_SALES_CHANNELS` environment variable;
2. Or enable the `sales_channels` key in the Medusa server's settings.
You can learn more about enabling it in the [feature flags](../feature-flags/toggle.md) documentation.
:::
<table class="reference-table">
<thead>
<tr>
@@ -2969,6 +2958,6 @@ Object of the following format:
## See Also
- [Events architecture overview](../events/architecture.md)
- [Use services in subscribers](create-subscriber.md#using-services-in-subscribers)
- [Create a notification provider](../notification/overview.md)
- [Events architecture overview](./index.md)
- [Use services in subscribers](./create-subscriber.md#using-services-in-subscribers)
- [Create a notification provider](../notification/overview.mdx)

View File

@@ -14,7 +14,7 @@ Those events can be subscribed to using subscribers. When you subscribe to an ev
:::info
You can learn more about subscribers and their use cases in the [Subscribers](../subscribers/overview.md) documentation.
You can learn more about subscribers and their use cases in the [Subscribers](./subscribers.mdx) documentation.
:::
@@ -48,7 +48,8 @@ export default class EventBusService {
async emit<T>(
eventName: string,
data: T,
options: Record<string, unknown> & EmitOptions = { attempts: 1 }
options: Record<string, unknown> &
EmitOptions = { attempts: 1 }
): Promise<StagedJob | void>
}
```
@@ -111,7 +112,7 @@ In the constructor of a subscriber, you use the `EventBusService` to subscribe t
:::note
You can learn more about how to create a subscriber in [this documentation](../subscribers/create-subscriber.md)
You can learn more about how to create a subscriber in [this documentation](./create-subscriber.md)
:::
@@ -154,7 +155,7 @@ Here's what each of these options mean:
### Note on Subscriber IDs
If you have more than one handler methods attached to a single event, or if you have multiple server instances running, you must pass a subscriber ID as a third parameter to the `subscribe` method. This allows the `EventBusService` to differentiate between handler methods when retrying a failed one.
If you have more than one handler methods attached to a single event, or if you have multiple backend instances running, you must pass a subscriber ID as a third parameter to the `subscribe` method. This allows the `EventBusService` to differentiate between handler methods when retrying a failed one.
If a subscriber ID is not passed on subscription, all handler methods are run again. This can lead to data inconsistencies or general unwanted behavior in your system.
@@ -196,7 +197,7 @@ Transactions in Medusa ensure atomicity, consistency, isolation, and durability,
<!-- vale docs.Acronyms = YES -->
In many cases, [services](../services/overview.md) typically update resources in the database and emit an event within a transactional operation. To ensure that these events don't cause data inconsistencies (for example, a plugin subscribes to an event to contact a third-party service, but the transaction fails) the concept of a staged job is introduced.
In many cases, [services](../services/overview.mdx) typically update resources in the database and emit an event within a transactional operation. To ensure that these events don't cause data inconsistencies (for example, a plugin subscribes to an event to contact a third-party service, but the transaction fails) the concept of a staged job is introduced.
Instead of events being processed immediately, they're stored in the database as a staged job until they're ready. In other words, until the transaction has succeeded.
@@ -222,6 +223,5 @@ This pattern is heavily inspired by the [Transactionally-staged Job Drain descri
## See Also
- [Events reference](../subscribers/events-list.md)
- [Subscribers overview](../subscribers/overview.md)
- [How to create a subscriber](../subscribers/create-subscriber.md)
- [Events reference](./events-list.md)
- [Create a subscriber](./create-subscriber.md)

View File

@@ -1,7 +1,10 @@
---
description: 'Learn what subscribers are in the Medusa server. Subscribers are used to listen to triggered events to perform an action.'
description: 'Learn what subscribers are in Medusa. Subscribers are used to listen to triggered events to perform an action.'
---
import DocCard from '@theme/DocCard';
import Icons from '@theme/Icon';
# Subscribers
In this document, you'll learn what Subscribers are in Medusa.
@@ -12,7 +15,7 @@ In Medusa, there are events that are emitted when a certain action occurs. For e
The purpose of these events is to allow other parts of the platform, or third-party integrations, to listen to those events and perform a certain action. That is done by creating subscribers.
Medusa's queuing and events system is handled by Redis. So, you must have [Redis configured](../../../tutorial/0-set-up-your-development-environment.mdx#redis) on your server to use subscribers.
Medusa's queuing and events system is handled by Redis. So, you must have [Redis configured](../backend/prepare-environment.mdx#redis) on your backend to use subscribers.
---
@@ -36,8 +39,17 @@ Subscribers are useful in many use cases, including:
---
## See Also
## Custom Development
- [Create a Subscriber](create-subscriber.md).
- [Events architecture overview](../events/architecture.md)
- [Events reference](events-list.md).
Developers can create custom subscribers in the Medusa backend, a plugin, or in a Commerce Module.
<DocCard item={{
type: 'link',
href: '/development/events/create-subscriber',
label: 'Create a Subscriber',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create a subscriber in Medusa.'
}
}}
/>

View File

@@ -0,0 +1,28 @@
---
description: "Learn what feature flags in Medusa. Feature flags are used in Medusa to guard beta features that arent ready for live and production applications."
---
import DocCard from '@theme/DocCard';
import Icons from '@theme/Icon';
# Feature Flags
In this document, youll learn what feature flags in Medusa.
## Introduction
Feature flags are used in Medusa to guard beta features that arent ready for live and production applications. This allows the Medusa team to keep publishing releases more frequently, while also working on necessary future features behind the scenes. To use these beta features, you must enable their feature flags.
If a feature is guarded by a flag, entities, migrations, endpoints, and other resources associated with that feature are guarded by that flag as well. So, these resources will only be available to use in Medusa if you have enabled the associated feature flag.
You can view a list of available feature flags that you can toggle in [the Medusa GitHub mono-repository](https://github.com/medusajs/medusa/tree/master/packages/medusa/src/loaders/feature-flags). In each feature flag file, you can find the default value of the feature flag, its name, environment variable name, and more.
<DocCard item={{
type: 'link',
href: '/development/feature-flags/toggle',
label: 'Toggle Feature Flags',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to enable or disabled a feature flag.'
}
}} />

View File

@@ -1,23 +1,11 @@
---
description: 'Learn how to toggle feature flags in the Medusa server. This guide explains the steps required to toggle a feature flag.'
description: 'Learn how to toggle feature flags in Medusa. This guide explains the steps required to toggle a feature flag.'
addHowToData: true
---
# How to Toggle Feature Flags
In this document, youll learn about what feature flags are and how to toggle them.
## Overview
Feature flags are used in Medusa to guard beta features that arent ready for live and production servers. This allows the Medusa team to keep publishing releases more frequently, while also working on necessary future features behind the scenes.
To use these beta features, you must enable their feature flags.
---
## Available Feature Flags
You can view a list of available feature flags that you can toggle in [the Medusa GitHub mono-repository](https://github.com/medusajs/medusa/tree/master/packages/medusa/src/loaders/feature-flags). In each feature flag file, you can find the default value of the feature flag, its name, environment variable name, and more.
In this document, youll learn about how to toggle feature flags.
:::info
@@ -25,8 +13,6 @@ If a feature flag is enabled/disabled by default, you dont need to manually e
:::
---
## Enable Feature Flags
:::caution
@@ -47,9 +33,9 @@ For example, to enable the Tax-Inclusive Pricing beta feature, add the following
MEDUSA_FF_TAX_INCLUSIVE_PRICING=true
```
### Method Two: Using Server Settings
### Method Two: Using Backend Configurations
You can enable a feature by using the server settings in `medusa-config.js`. You can find [a feature flags key in the loader file](https://github.com/medusajs/medusa/tree/master/packages/medusa/src/loaders/feature-flags) its defined in. It is defined under the property `key` in the exported object.
You can enable a feature by using the backend configurations in `medusa-config.js`. You can find [a feature flags key in the loader file](https://github.com/medusajs/medusa/tree/master/packages/medusa/src/loaders/feature-flags) its defined in. It is defined under the property `key` in the exported object.
For example, to enable the Tax-Inclusive Pricing beta feature, add the following to the exported object in `medusa-config.js`:
@@ -64,9 +50,9 @@ module.exports = {
### Note About Precedence
The environment variables value has higher precedence over the server settings. So, if you use both these methods on your server, the value of the environment variable will be used.
The environment variables value has higher precedence over the backend configurations. So, if you use both these methods on your backend, the value of the environment variable will be used.
For example, if the value of the environment variable is set to `false`, but the value of the feature flag in the server settings is set to `true`, the feature flag will take the value of the environment variable and will be disabled.
For example, if the value of the environment variable is set to `false`, but the value of the feature flag in the backend configurations is set to `true`, the feature flag will take the value of the environment variable and will be disabled.
### Running Migrations
@@ -86,7 +72,7 @@ You can learn more about migrations in this documentation.
## Disable Feature Flags
Disabling feature flags follows the same process as enabling the feature flags. All you have to do is change the value in the environment variables or the server settings to `false`.
Disabling feature flags follows the same process as enabling the feature flags. All you have to do is change the value in the environment variables or the backend configurations to `false`.
Once you disable a feature flag, all endpoints, entities, services, or other related classes and functionalities are disabled.
@@ -94,11 +80,4 @@ Once you disable a feature flag, all endpoints, entities, services, or other rel
If you had the feature flag previously enabled, and you want to disable this feature flag completely, you might need to revert the migrations you ran when you enabled it.
You can follow [this documentation to learn how to revert the last migration you ran](https://docs.medusajs.com/cli/reference#migrations).
---
## See Also
- [Migrations Overview](../migrations/overview.md).
- [Configure your Medusa server](../../../usage/configurations.md).
You can follow [this documentation to learn how to revert the last migration you ran](../../cli/reference.md#migrations).

View File

@@ -0,0 +1,35 @@
---
description: "Learn what a file service is in Medusa. A file service defines how files are stored in the Medusa Backend."
---
import DocCard from '@theme/DocCard';
import Icons from '@theme/Icon';
# File Service
In this document, youll learn what a file service is in Medusa.
## Introduction
A file service defines how files are stored in the Medusa Backend. Those files include products images and files used to import or export data.
Medusa Backend includes a default file service that acts as a placeholder, but does not actually perform any storage functionalities. So, you must either install one of the [existing file-service plugins](../../plugins/file-service/index.mdx), such as [MinIO](../../plugins/file-service/minio.md) or [S3](../../plugins/file-service/s3.md), or create your own file service if you want to utilize storage functionalities.
A file service is a TypeScript or JavaScript class that extends the `AbstractFileService` class from the core `@medusajs/medusa` package. By extending this class, the file service must implement the necessary methods that take care of general upload and download functionalities. The Medusa Backend then uses these methods when necessary, for example, when a product image is uploaded.
---
## Custom Development
Developers can create a custom file service with the desired functionality directly within the Medusa Core, in a plugin, or in a Commerce Module.
<DocCard item={{
type: 'link',
href: '#',
label: 'Create a File Service',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create a file service.',
isSoon: true
}
}} />

View File

@@ -0,0 +1,27 @@
---
description: "Learn about Medusa's architecture and get a general overview of how all different tools work together."
---
# Medusa Architecture Overview
In this document, you'll get an overview of Medusa's architecture to better understand how all resources and tools work together.
## Architecture Overview
Medusa's core package `@medusajs/medusa` is a Node.js backend built on top of [Express](https://expressjs.com/). It combines all the [**Commerce Modules**](../../modules/overview.mdx) that Medusa provides. Commerce Modules are ecommerce features that can be used as building blocks in an ecommerce ecosystem. Product is an example of a Commerce Module.
![Medusa Core Architecture](https://res.cloudinary.com/dza7lstvk/image/upload/v1677607702/Medusa%20Docs/Diagrams/medusa-architecture-3_e385zk.jpg)
The backend connects to a **database**, such as [PostgreSQL](https://www.postgresql.org/), to store the ecommerce stores data. The tables in that database are represented by [**Entities**](../entities/overview.mdx), built on top of [Typeorm](https://typeorm.io/). Entities can also be reflected in the database using [**Migrations**](../entities/migrations/overview.mdx).
The retrieval, manipulation, and other utility methods related to that entity are created inside a [**Service**](../services/overview.mdx). Services are TypeScript or JavaScript classes that, similar along with other resources, can be accessed throughout the Medusa backend through [**dependency injection**](./dependency-injection.md).
The backend does not have any tightly-coupled frontend. Instead, it exposes [**Endpoints**](../endpoints/overview.mdx) which are REST APIs that frontends such as an admin or a storefront can use to communicate with the backend. Endpoints are [Express routes](https://expressjs.com/en/guide/routing.html).
Medusa also uses an [**Events Architecture**](../events/index.md) to trigger and handle events. Events are triggered when a specific action occurs, such as when an order is placed. To manage this events system, Medusa connects to a service that implements a pub/sub model, such as [Redis](https://redis.io/).
Events can be handled using [**Subscribers**](../events/subscribers.mdx). Subscribers are TypeScript or JavaScript classes that add their methods as handlers for specific events. These handler methods are only executed when an event is triggered.
You can create any of the resources in the backends architecture, such as entities, endpoints, services, and more, as part of your custom development without directly modifying the backend itself. The Medusa backend uses **loaders** to load the backends resources, as well as your custom resources and resources in [**Plugins**](../plugins/overview.mdx).
You can package your customizations into Plugins to reuse them in different Medusa backends or publish them for others to use. You can also install existing plugins into your Medusa backend.

View File

@@ -2,9 +2,9 @@
description: 'Learn what the dependency container is and how to use it in Medusa. Learn also what dependency injection is, and what the resources regsitered and their names are.'
---
# Dependency Container
# Dependency Injection
In this document, youll learn what the dependency container is and how you can use it in Medusa.
In this document, youll learn what the dependency injection is and how you can use it in Medusa.
## Introduction
@@ -16,25 +16,25 @@ Generally, all resources are registered in a container. Then, whenever a class d
### Medusas Dependency Container
Medusa uses a dependency container to register essential resources of your server. You can then access these resources in classes and endpoints using the dependency container.
Medusa uses a dependency container to register essential resources of the backend. You can then access these resources in classes and endpoints using the dependency container.
For example, if you create a custom service, you can access any other service registered in Medusa in your services constructor. That includes Medusas core services, services defined in plugins, or other services that you create on your server.
For example, if you create a custom service, you can access any other service registered in Medusa in your services constructor. That includes Medusas core services, services defined in plugins, or other services that you create on your backend.
You can load more than services in your Medusa server. You can load the Entity Manager, logger instance, and much more.
You can load more than services in your Medusa backend. You can load the Entity Manager, logger instance, and much more.
### MedusaContainer
To manage dependency injections, Medusa uses [Awilix](https://github.com/jeffijoe/awilix). Awilix is an NPM package that implements dependency injection in Node.js projects.
When you run the Medusa server, a container of the type `MedusaContainer` is created. This type extends the [AwilixContainer](https://github.com/jeffijoe/awilix#the-awilixcontainer-object) object.
When you run the Medusa backend, a container of the type `MedusaContainer` is created. This type extends the [AwilixContainer](https://github.com/jeffijoe/awilix#the-awilixcontainer-object) object.
The server then registers all important resources in the container, which makes them accessible in classes and endpoints.
The backend then registers all important resources in the container, which makes them accessible in classes and endpoints.
---
## Registered Resources
The Medusa server scans the core Medusa package, plugins, and your files in the `dist` directory and registers the following resources:
The Medusa backend scans the core Medusa package, plugins, and your files in the `dist` directory and registers the following resources:
:::note
@@ -72,7 +72,7 @@ Configurations
</td>
<td>
The configurations that are exported from medusa-config.js.
The configurations that are exported from `medusa-config.js`.
</td>
<td>
@@ -560,7 +560,7 @@ Its camel-case name.
## Loading Resources
This section covers how to load resources that the Medusa server registers when it starts running.
This section covers how to load resources that the Medusa backend registers when it starts running.
### In Endpoints
@@ -596,5 +596,5 @@ class OrderSubscriber {
## See Also
- [Create services](../services/create-service.md).
- [Create subscribers](../subscribers/create-subscriber.md).
- [Create services](../services/create-service.md)
- [Create subscribers](../events/create-subscriber.md)

View File

@@ -2,7 +2,7 @@
description: 'Learn how to perform local development in the Medusa monorepo. This includes how to use the dev CLI tool and perform unit, integration, and plugin tests.'
---
# Local Development of Medusa Server and Monorepo
# Local Development of Medusa Backend and Monorepo
In this document, youll learn how to customize Medusas core and run tests.
@@ -10,11 +10,11 @@ In this document, youll learn how to customize Medusas core and run tests.
As an open-source platform, Medusas core can be completely customized.
Whether you want to implement something differently, introduce a new future as part of Medusas core or any of the other packages, or contribute to Medusa, this guide helps you learn how to run Medusas integration tests, as well as test your own Medusa core in a local server.
Whether you want to implement something differently, introduce a new future as part of Medusas core or any of the other packages, or contribute to Medusa, this guide helps you learn how to run Medusas integration tests, as well as test your own Medusa core in a local backend.
### Medusa Repository Overview
[Medusas repository on GitHub](https://github.com/medusajs/medusa) includes all packages related to Medusa under the [`packages` directory](https://github.com/medusajs/medusa/tree/master/packages). This includes the [core Medusa server](https://github.com/medusajs/medusa/tree/master/packages/medusa), the [JS Client](https://github.com/medusajs/medusa/tree/master/packages/medusa-js), the CLI tools, and much more.
[Medusas repository on GitHub](https://github.com/medusajs/medusa) includes all packages related to Medusa under the [`packages` directory](https://github.com/medusajs/medusa/tree/master/packages). This includes the [core Medusa package](https://github.com/medusajs/medusa/tree/master/packages/medusa), the [JS Client](https://github.com/medusajs/medusa/tree/master/packages/medusa-js), the CLI tools, and much more.
All the packages are part of a [Yarn workspace](https://classic.yarnpkg.com/lang/en/docs/workspaces/). So, when you run a command in the root of the project, such as `yarn build`, it goes through all registered packages in the workspace under the `packages` directory and runs the `build` command in each of those packages.
@@ -114,11 +114,11 @@ yarn test:integration:plugins
---
## Test in a Local Server
## Test in a Local Backend
Using Medusas dev CLI tool, you can test any changes you make to Medusas packages in a local server installation. This eliminates the need to publish these packages on NPM publicly to be able to use them.
Using Medusas dev CLI tool, you can test any changes you make to Medusas packages in a local backend installation. This eliminates the need to publish these packages on NPM publicly to be able to use them.
Medusas dev CLI tool scans and finds the Medusa packages used in your Medusa server. Then, it copies the files of these packages from the `packages` directory in the Medusa repository into the `node_modules` directory of your Medusa server.
Medusas dev CLI tool scans and finds the Medusa packages used in your Medusa backend. Then, it copies the files of these packages from the `packages` directory in the Medusa repository into the `node_modules` directory of your Medusa backend.
:::info
@@ -126,14 +126,14 @@ Medusas Dev CLI tool uses the [path you specified earlier](#set-the-location-
:::
### Copy Files to Local Server
### Copy Files to Local Backend
To test in a local server:
To test in a local backend:
1. Change to the directory of the server you want to test your changes in:
1. Change to the directory of the backend you want to test your changes in:
```bash
cd medusa-server
cd medusa-backend
```
2\. Run the following command to copy the files from the `packages` directory of your Medusa repository into `node_modules`:
@@ -148,7 +148,7 @@ By default, Medusas dev CLI runs in watch mode. So, it copies the files when
While the above command is running, it's recommended to run the `watch` command inside the directory of every package you're making changes to.
The combination of these two commands running at the same time will compile the package into the `dist` directory of the package, then copy the compiled changes into your local server.
The combination of these two commands running at the same time will compile the package into the `dist` directory of the package, then copy the compiled changes into your local backend.
For example, if you're making changes in the `medusa` package, run the following command inside the directory of the `medusa` package:
@@ -190,5 +190,5 @@ medusa-dev --packages @medusajs/medusa-cli medusa-file-minio
## See Also
- [Create a Plugin](../advanced/backend/plugins/create.md)
- [Create a Plugin](../plugins/create.md)
- [Contribution Guidelines](https://github.com/medusajs/medusa/blob/master/CONTRIBUTING.md)

View File

@@ -1,23 +1,23 @@
---
description: 'Learn how to create a notification provider in the Medusa server. This guide explains the different methods available in a Notification provider.'
description: 'Learn how to create a notification provider in Medusa. This guide explains the different methods available in a Notification provider.'
addHowToData: true
---
# How to Create a Notification Provider
In this document, youll learn how to add a Notification Provider to your Medusa server.
In this document, youll learn how to create a Notification Provider in Medusa.
:::note
If youre unfamiliar with the Notification architecture in Medusa, it is recommended to check out the [architecture overview](overview.md) first.
If youre unfamiliar with the Notification architecture in Medusa, it is recommended to check out the [architecture overview](./overview.mdx) first.
:::
## Prerequisites
Before you start creating a Notification Provider, you need to install a [Medusa server](../../../quickstart/quick-start.mdx).
Before you start creating a Notification Provider, you need to either install a [Medusa backend](../backend/install.mdx), or create it in a [plugin](../plugins/overview.mdx).
You also need to [setup Redis](../../../tutorial/0-set-up-your-development-environment.mdx#redis) and [configure it with the Medusa server](../../../usage/configurations.md#redis).
You also need to [setup Redis](../backend/prepare-environment.mdx#redis) and [configure it with the Medusa backend](../backend/configurations.md#redis) to test out the Notification provider.
---
@@ -96,15 +96,15 @@ You can use the `constructor` of your Notification Provider to have access to
You can also use the constructor to initialize your integration with the third-party provider. For example, if you use a client to connect to the third-party providers APIs, you can initialize it in the constructor and use it in other methods in the Service.
Additionally, if youre creating your Notification Provider as an external plugin to be installed on any Medusa server and you want to access the options added for the plugin, you can access it in the constructor. The options are passed as a second parameter.
Additionally, if youre creating your Notification Provider as an external plugin to be installed on any Medusa backend and you want to access the options added for the plugin, you can access it in the constructor. The options are passed as a second parameter.
:::info
You can learn more about plugins and how to create them in the [Plugins](../plugins/overview.md) documentation.
You can learn more about plugins and how to create them in the [Plugins](../plugins/overview.mdx) documentation.
:::
Continuing on with the previous example, if you want to use the [`OrderService`](../../../references/services/classes/OrderService.md) later when sending notifications, you can inject it into the constructor:
Continuing on with the previous example, if you want to use the [`OrderService`](../../references/services/classes/OrderService.md) later when sending notifications, you can inject it into the constructor:
```ts
import {
@@ -132,7 +132,7 @@ class EmailSenderService extends AbstractNotificationService {
### sendNotification
When an event is triggered that your Notification Provider is registered as a handler for, the [`NotificationService`](../../../references/services/classes/NotificationService.md) in Medusas core will execute the `sendNotification` method of your Notification Provider.
When an event is triggered that your Notification Provider is registered as a handler for, the [`NotificationService`](../../references/services/classes/NotificationService.md) in Medusas core will execute the `sendNotification` method of your Notification Provider.
In this method, you can perform the necessary operation to send the Notification. Following the example above, you can send an email to the customer when they place an order.
@@ -140,11 +140,11 @@ This method receives three parameters:
1. `eventName`: This is the name of the event that was triggered. For example, `order.placed`.
2. `eventData`: This is the data payload of the event that was triggered. For example, if the `order.placed` event is triggered, the `eventData` object contains the property `id` which is the ID of the order that was placed.
3. `attachmentGenerator`: If youve previously attached a generator to the `NotificationService` using the [`registerAttachmentGenerator`](../../../references/services/classes/NotificationService.md#registerattachmentgenerator) method, you have access to it here. You can use the `attachmentGenerator` to generate on-demand invoices or other documents. The default value of this parameter is null.
3. `attachmentGenerator`: If youve previously attached a generator to the `NotificationService` using the [`registerAttachmentGenerator`](../../references/services/classes/NotificationService.md#registerattachmentgenerator) method, you have access to it here. You can use the `attachmentGenerator` to generate on-demand invoices or other documents. The default value of this parameter is null.
:::info
You can learn more about what events are triggered in Medusa and their data payload in the [Events List](../subscribers/events-list.md) documentation.
You can learn more about what events are triggered in Medusa and their data payload in the [Events List](../events/events-list.md) documentation.
:::
@@ -196,19 +196,19 @@ Finally, you return an object with the `to` property set to the customer email a
:::note
The `to` and `data` properties are used in the `NotificationService` in Medusas core to create a new `Notification` record in the database. You can learn more about the `Notification` entity in the [Architecture Overview](overview.md#notification-entity-overview) documentation.
The `to` and `data` properties are used in the `NotificationService` in Medusas core to create a new `Notification` record in the database. You can learn more about the `Notification` entity in the [Architecture Overview](./overview.mdx#notification-entity-overview) documentation.
:::
### resendNotification
Using the [Resend Notification endpoint](https://docs.medusajs.com/api/admin/#tag/Notification/operation/PostNotificationsNotificationResend), an admin user can resend a Notification to the customer. The [`NotificationService`](../../../references/services/classes/NotificationService.md) in Medusas core then executes the `resendNotification` method in your Notification Provider.
Using the [Resend Notification endpoint](/api/admin/#tag/Notification/operation/PostNotificationsNotificationResend), an admin user can resend a Notification to the customer. The [`NotificationService`](../../references/services/classes/NotificationService.md) in Medusas core then executes the `resendNotification` method in your Notification Provider.
This method receives three parameters:
1. `notification`: This is the original Notification record that was created after you sent the notification with `sendNotification`. You can get an overview of the entity and its attributes in the [architecture overview](overview.md#notification-entity-overview), but most notably it includes the `to` and `data` attributes which are populated originally using the `to` and `data` properties of the object you return in `sendNotification`.
1. `notification`: This is the original Notification record that was created after you sent the notification with `sendNotification`. You can get an overview of the entity and its attributes in the [architecture overview](./overview.mdx#notification-entity-overview), but most notably it includes the `to` and `data` attributes which are populated originally using the `to` and `data` properties of the object you return in `sendNotification`.
2. `config`: In the Resend Notification endpoint you may specify an alternative receiver of the notification using the `to` request body parameter. For example, you may want to resend the order confirmation email to a different email. If thats the case, you have access to it in the `config` parameter object. Otherwise, `config` will be an empty object.
3. `attachmentGenerator`: If youve previously attached a generator to the Notification Service using the [`registerAttachmentGenerator`](../../../references/services/classes/NotificationService.md#registerattachmentgenerator) method, you have access to it here. You can use the `attachmentGenerator` to generate on-demand invoices or other documents. The default value of this parameter is null.
3. `attachmentGenerator`: If youve previously attached a generator to the Notification Service using the [`registerAttachmentGenerator`](../../references/services/classes/NotificationService.md#registerattachmentgenerator) method, you have access to it here. You can use the `attachmentGenerator` to generate on-demand invoices or other documents. The default value of this parameter is null.
Similarly to the `sendNotification` method, this method must return an object containing two properties:
@@ -229,7 +229,7 @@ class EmailSenderService extends AbstractNotificationService {
status: string;
data: Record<string, unknown>;
}> {
// check if the receiver of the notification should be changed
// check if the receiver should be changed
const to: string = config.to ? config.to : notification.to
// TODO resend the notification using the same data
@@ -239,7 +239,7 @@ class EmailSenderService extends AbstractNotificationService {
return {
to,
status: "done",
data: notification.data, // you can also make changes to the data
data: notification.data, // make changes to the data
}
}
}
@@ -253,7 +253,7 @@ Finally, you return an object with the `to` property set to the email (either ne
:::note
The `to` and `data` properties are used in the `NotificationService` in Medusas core to create a new `Notification` record in the database. No changes are made to the original `Notification` record created after the `sendNotification` method. This new record is associated with the original `Notification` record using the `parent_id` attribute in the entity. You can learn more about the `Notification` entity in the [Architecture Overview](overview.md#notification-entity-overview) documentation.
The `to` and `data` properties are used in the `NotificationService` in Medusas core to create a new `Notification` record in the database. No changes are made to the original `Notification` record created after the `sendNotification` method. This new record is associated with the original `Notification` record using the `parent_id` attribute in the entity. You can learn more about the `Notification` entity in the [Architecture Overview](./overview.mdx#notification-entity-overview) documentation.
:::
@@ -265,7 +265,7 @@ After creating your Notification Provider Service, you must create a Subscriber
:::note
This section will not cover the basics of Subscribers. You can read the [Subscribers](../subscribers/create-subscriber.md) documentation to learn more about them and how to create them.
This section will not cover the basics of Subscribers. You can read the [Subscribers](../events/create-subscriber.md) documentation to learn more about them and how to create them.
:::
@@ -274,7 +274,10 @@ Following the previous example, to make sure the `email-sender` Notification Pro
```ts title=src/subscribers/notification.js
class NotificationSubscriber {
constructor({ notificationService }) {
notificationService.subscribe("order.placed", "email-sender")
notificationService.subscribe(
"order.placed",
"email-sender"
)
}
// ...
}
@@ -294,19 +297,19 @@ Notice that the value of the `identifier` static property defined in the `EmailS
## Test Sending Notifications with your Notification Provider
Make sure you've configured Redis with your Medusa server as explained in the Prerequisites section and that the Redis service is running.
Make sure you've configured Redis with your Medusa backend as explained in the [Prerequisites](#prerequisites) section and that the Redis service is running.
Then, start by running your Medusa server:
Then, start by running your Medusa backend:
```bash npm2yarn
npm run start
```
Then, place an order either using the [REST APIs](https://docs.medusajs.com/api/store) or using the storefront.
Then, place an order either using the [REST APIs](/api/store) or using the storefront.
:::tip
If you dont have a storefront installed you can get started with either the [Next.js](../../../starters/nextjs-medusa-starter.mdx) or [Gatsby](../../../starters/gatsby-medusa-starter.mdx) starter storefronts in minutes.
If you dont have a storefront installed you can get started with the [Next.js](../../starters/nextjs-medusa-starter.mdx) starter storefront in minutes.
:::
@@ -316,17 +319,17 @@ After placing an order, you can see in your console the message “Notification
## Test Resending Notifications with your Notification Provider
To test resending a notification, first, retrieve the ID of the notification you just sent using the [List Notifications admin endpoint](https://docs.medusajs.com/api/admin/#tag/Notification/operation/GetNotifications). You can pass as a body parameter the `to` or `event_name` parameters to filter out the notification you just sent.
To test resending a notification, first, retrieve the ID of the notification you just sent using the [List Notifications admin endpoint](/api/admin/#tag/Notification/operation/GetNotifications). You can pass as a body parameter the `to` or `event_name` parameters to filter out the notification you just sent.
:::tip
You must be authenticated as an admin user before sending this request. You can use the [Authenticate a User](https://docs.medusajs.com/api/admin) endpoint to get authenticated.
You must be authenticated as an admin user before sending this request. You can use the [Authenticate a User](/api/admin) endpoint to get authenticated.
:::
![List Notifications Request](https://res.cloudinary.com/dza7lstvk/image/upload/v1668001650/Medusa%20Docs/Screenshots/iF1rZX1_msps2t.png)
Then, send a request to the [Resend Notification](https://docs.medusajs.com/api/admin/#tag/Notification/operation/PostNotificationsNotificationResend) endpoint using the ID retrieved from the previous request. You can pass the `to` parameter in the body to change the receiver of the notification. You should see the message “Notification Resent” in your console and if you implemented your own logic for resending the notification it will be resent.
Then, send a request to the [Resend Notification](/api/admin/#tag/Notification/operation/PostNotificationsNotificationResend) endpoint using the ID retrieved from the previous request. You can pass the `to` parameter in the body to change the receiver of the notification. You should see the message “Notification Resent” in your console and if you implemented your own logic for resending the notification it will be resent.
![Resend Notifications Request](https://res.cloudinary.com/dza7lstvk/image/upload/v1668001659/Medusa%20Docs/Screenshots/0zFfPed_og7one.png)
@@ -336,8 +339,4 @@ This request returns the same notification object as the List Notifications endp
## See Also
- [Events reference](../subscribers/events-list.md)
- [SendGrid Plugin](../../../add-plugins/sendgrid.mdx)
- [Create a Subscriber](../subscribers/create-subscriber.md)
- [Create a Service](../services/create-service.md)
- [Create a Plugin](../plugins/create.md)

View File

@@ -2,6 +2,9 @@
description: 'Learn about the Notificaiton architecture in Medusa and the automation flow. The Notification Architecture is made up of the Notification Provider and Notification.'
---
import DocCard from '@theme/DocCard';
import Icons from '@theme/Icon';
# Notification Architecture Overview
This document gives an overview of the notification architecture and how it works.
@@ -22,11 +25,11 @@ An example of a notification provider is SendGrid. When an order is placed, the
### How Notification Provider is Created
A Notification Provider is essentially a Medusa [Service](../services/create-service.md) with a unique identifier, and it extends the [`NotificationService`](../../../references/services/classes/NotificationService.md) provided by the `medusa-interfaces` package. It can be created as part of a [Plugin](../plugins/overview.md), or it can be created just as a Service file in your Medusa server.
A Notification Provider is essentially a Medusa [Service](../services/create-service.md) with a unique identifier, and it extends the [`NotificationService`](../../references/services/classes/NotificationService.md) provided by the `medusa-interfaces` package. It can be created as part of a [Plugin](../plugins/overview.mdx), or it can be created just as a Service file in your Medusa backend.
As a developer, you mainly work with the Notification Provider when integrating a third-party service that handles notifications in Medusa.
When you run your Medusa server, the Notification Provider is registered on your server if it isnt already. This means that it will be inserted into the `notification_provider` table in your database.
When you run your Medusa backend, the Notification Provider is registered in your backend. If it's a new Notification Provider, it will be inserted into the `notification_provider` table in your database.
### NotificationProvider Entity Overview
@@ -55,7 +58,7 @@ A Notification also represents a resent notification. So, when a notification is
### Notification Entity Overview
The two most important properties in the [`Notification`](../../../references/entities/classes/Notification.md) entity are the `to` and `data` properties.
The two most important properties in the [`Notification`](../../references/entities/classes/Notification.md) entity are the `to` and `data` properties.
The `to` property is a string that represents the receiver of the Notification. For example, if the Notification was sent to an email address, the `to` property holds the email address the Notification was sent to.
@@ -83,17 +86,24 @@ With Medusa you can create notifications as a reaction to a wide spectrum of eve
An example of a flow that can be implemented using Medusa's Notification API is automated return flows:
- A customer requests a return by sending a `POST` request to the `/store/returns` endpoint.
- The Notification Provider listens to the `order.return_requested` event and sends an email to the customer with a return invoice and return label generated by the Fulfillment Provider.
- The customer returns the items triggering the `return.recieved` event.
- The Notification Provider listens to the `return.received` event and sends an email to the customer with confirmation that their items have been received and that a refund has been issued.
- A customer requests a return by sending a `POST` request to the `/store/returns` endpoint.
- The Notification Provider listens to the `order.return_requested` event and sends an email to the customer with a return invoice and return label generated by the Fulfillment Provider.
- The customer returns the items triggering the `return.recieved` event.
- The Notification Provider listens to the `return.received` event and sends an email to the customer with confirmation that their items have been received and that a refund has been issued.
---
## See Also
## Custom Development
- [Create a Notification Provider](how-to-create-notification-provider.md)
- [Events reference](../subscribers/events-list.md)
- [SendGrid Plugin](../../../add-plugins/sendgrid.mdx)
- [Subscribers Overview](../subscribers/create-subscriber.md)
- [Services Overview](../services/create-service.md)
Developers can create custom notification providers in the Medusa backend, a plugin, or in a Commerce Module.
<DocCard item={{
type: 'link',
href: '/development/notification/create-notification-provider',
label: 'Create a Notification Provider',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create a notification provider in Medusa.'
}
}}
/>

View File

@@ -0,0 +1,203 @@
---
description: "Learn about development with Medusa, fundamental concepts, and more."
hide_table_of_contents: true
---
import DocCardList from '@theme/DocCardList';
import Icons from '@theme/Icon';
# Medusa Development
This part of the documentation provides you with the fundamental concepts and guides that can help you build and customize commerce applications with Medusa.
## Introduction
Medusa is a set of tools that developers can use to build digital commerce applications. Whether you want to offer unique customer experiences, create powerful automations, or build rich commerce applications like marketplaces, Medusa provides all the necessary tools.
Other ecommerce platforms offer a finite set of features accessible through an API. Medusa is different because it provides building blocks for businesses and developers to build commerce features. This means that you can extend your commerce API for your exact needs.
Medusa's building blocks ship as NPM packages of the following types:
- [Commerce Modules](../modules/overview.mdx), which are isolated commerce logic for different domains. For example, an Inventory Module.
- A core package responsible for orchestrating the different commerce modules and exposing REST APIs.
---
## How Does Medusa Work
The core package is the NPM package `@medusajs/medusa`. It's a Node.js server built with Express and other tools that offer functionalities for managing events, caching, job queues, and more.
The core package has two main objectives.
### Orchestrate Commerce Modules
When you build a commerce application with Medusa, youll typically interact with more than one commerce module. The core package manages relationships between modules, and forwarding calls to modules at the right time during business logic execution.
For example, imagine an Inventory module that contains lightweight logic to increment and decrement stock levels for a Stock-Keeping Unit (SKU). In a commerce application, you typically want to associate the stock levels with a specific product. Medusa offers both an Inventory module and a Product module, and the core package creates associations between these modules and executing the related business logic. So, the core package contains code similar to this:
```ts
function handler(req, res) {
// ...
// associate a product with an inventory item
const product = await productService.create(data)
const inventoryItem = await inventoryService.create(
inventoryData
)
await productVariantInventoryService.associate(
product.id,
inventoryItem.id
)
// ...
}
```
### Expose REST APIs
The goal of orchestrating the modules is to expose an API that client applications, like websites or apps, can consume. By default, Medusas core package exposes a REST API that offers commerce functionalities similar to what other platforms give you.
The core package also holds the logic that allows developers to extend and add custom endpoints, among other available customizations.
---
## Backend First Steps
<DocCardList colSize={4} items={[
{
type: 'link',
href: '/development/backend/install',
label: 'Backend Quickstart',
customProps: {
icon: Icons['server-stack-solid'],
description: 'Learn how to install a Medusa backend and the available next steps.'
}
},
{
type: 'link',
href: '/development/backend/prepare-environment',
label: 'Prepare Environment',
customProps: {
icon: Icons['tools-solid'],
description: 'Install tools that supercharge development with Medusa.'
}
},
{
type: 'link',
href: '/development/backend/configurations',
label: 'Configure Backend',
customProps: {
icon: Icons['cog-six-tooth-solid'],
description: 'Learn how to configure the Medusa backend.'
}
},
]} />
---
## Understanding Fundamental Concepts
These concepts will guide you through your development and building customization with Medusa.
<DocCardList colSize={4} items={[
{
type: 'link',
href: '/development/entities/overview',
label: 'Entities',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'A class representation of database tables to handle commerce data.'
}
},
{
type: 'link',
href: '/development/endpoints/overview',
label: 'Endpoints',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'REST APIs that frontends consume to communicate with the backend.'
}
},
{
type: 'link',
href: '/development/services/overview',
label: 'Services',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Utility classes associated with Entities or a specific functionality.'
}
},
{
type: 'link',
href: '/development/events/index',
label: 'Events and Subscribers',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Perform an asynchronous task when an action occurs.'
}
},
{
type: 'link',
href: '/development/scheduled-jobs/overview',
label: 'Scheduled Jobs',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Automate tasks to be executed at specified times.'
}
},
{
type: 'link',
href: '/development/plugins/overview',
label: 'Plugins',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Publish customizations as NPM packages to be reused.'
}
},
]} />
---
## Medusa Use Cases
To better understand how you can use Medusa, here are some common use cases that Medusa is the ideal solution for.
### Ecommerce Building Blocks
Developers can set up the core package and handpick the Commerce Modules they want to use. This gives them great flexibility in choosing the features they want to provide in their ecommerce store, while utilizing the powerful architecture in the core package.
![Ecommerce Building Blocks](https://res.cloudinary.com/dza7lstvk/image/upload/v1678954316/Medusa%20Docs/Diagrams/ecommerce-building-blocks_llgnn2.jpg)
Developers can modify and tailor the modules that Medusa offers to their use case. They can also create custom Modules to implement new features. All these modules become building blocks that shape their ecommerce system.
### Medusa in Microservices Architectures
Medusas Commerce Modules can be used in isolation from the core package and within a larger ecosystem. For example, you can use Medusas Cart module within a blog to allow readers to buy merch.
![Medusa in Microservices Architecture](https://res.cloudinary.com/dza7lstvk/image/upload/v1678954316/Medusa%20Docs/Diagrams/microservices-architecture-use-case_vubgno.jpg)
Developers can benefit from Medusas Modules that provide essential ecommerce features while maintaining the ecommerce ecosystem of their choice. Commerce Modules can be installed in your setup as NPM packages.
### Vertical Ecommerce Platforms
A Vertical Ecommerce Platform is a platform that provides features and functionalities specialized for a type of business sector. For example, a platform for pharmaceuticals.
Developers can use Medusa to build a vertical ecommerce platform as it provides the stepping stones that eliminate the need to reinvent the wheel for basic ecommerce features, but are customizable enough to be changed for their use case.
### Out-of-Box APIs
Since Medusas Commerce Modules are NPM packages, they can be installed and used in any JavaScript project.
By installing a Module in your project and expose its APIs based on the framework youre using, you can get ecommerce REST APIs right from your frontend framework without having to create a separate project.
### Full-Fledged Ecommerce System
Developers can use Medusas toolkit to create their ecommerce system. With the use of the [create-medusa-app](../create-medusa-app.mdx) command, developers can set up a Medusa Backend, Medusa admin, and a storefront.
![Full-Fledged Ecommerce System](https://res.cloudinary.com/dza7lstvk/image/upload/v1678954316/Medusa%20Docs/Diagrams/fully-fledged-ecom_qqwraq.jpg)
Developers can still benefit from customization opportunities here that Medusa provides. This includes creating resources such as endpoints and services, creating plugins, integrating third-party services, create a custom storefront, and more.
### Your Own Use Case
Medusas vision is to allow developers to build anything they want using it. There are no limitations to what you can build and the ideas you can come up with. If you have an idea, you can use Medusas tools to start building it.

View File

@@ -5,7 +5,7 @@ addHowToData: true
# How to Create a Plugin
In this document, youll learn how to create a plugin and some tips for develoment. If youre interested to learn more about what plugins are and where to find available official and community plugins, check out the [overview document](overview.md).
In this document, youll learn how to create a plugin and some tips for develoment. If youre interested to learn more about what plugins are and where to find available official and community plugins, check out the [overview document](./overview.mdx).
## Prerequisites
@@ -17,7 +17,7 @@ npm install @medusajs/medusa-cli -g
:::note
If you run into any errors while installing the CLI tool, check out the [troubleshooting guide](../../../troubleshooting/cli-installation-errors.mdx).
If you run into any errors while installing the CLI tool, check out the [troubleshooting guide](../../troubleshooting/cli-installation-errors.mdx).
:::
@@ -41,7 +41,7 @@ By convention, all plugin names start with `medusa` followed by a descriptive na
### Change Dependencies
A basic Medusa server installed with the `medusa new` command has dependencies similar to this:
A basic Medusa backend installed with the `medusa new` command has dependencies similar to this:
```json title=package.json
"dependencies": {
@@ -61,7 +61,7 @@ A basic Medusa server installed with the `medusa new` command has dependencies s
}
```
For a plugin, some dependencies are not necessary. You can remove the packages `medusa-fulfillment-manual`, `medusa-payment-manual`, and `medusa-payment-stripe` as they are fulfillment and payment plugins necessary for a Medusa server, but not for a plugin.
For a plugin, some dependencies are not necessary. You can remove the packages `medusa-fulfillment-manual`, `medusa-payment-manual`, and `medusa-payment-stripe` as they are fulfillment and payment plugins necessary for a Medusa backend, but not for a plugin.
Additionally, you can remove `@medusajs/medusa-cli` as you dont need to use the Medusa CLI while developing a plugin.
@@ -102,11 +102,11 @@ Now, You can start developing your plugin. This can include adding services, end
While developing your plugin, you can create your TypeScript or JavaScript files under the `src` directory. This includes creating services, endpoints, migrations, etc...
However, before you test the changes on a Medusa server or publish your plugin, you must transpile your files, which moves them into the root of your plugin directory.
However, before you test the changes on a Medusa backend or publish your plugin, you must transpile your files, which moves them into the root of your plugin directory.
For example, if you have an endpoint in `src/api/index.js`, after running the `build` or `watch` commands [as defined earlier](#change-scripts), the file should be transpiled into `api/index.js` in your plugin's root.
If files and directories aren't placed in the root of your plugin, the Medusa server won't detect or load them.
If files and directories aren't placed in the root of your plugin, the Medusa backend won't detect or load them.
An example of a plugin's directory before testing or publishing:
@@ -139,11 +139,11 @@ medusa-plugin-custom
This guide doesn't cover how to create different files and components. If youre interested in learning how to do that, you can check out these guides:
- How to [create endpoints](../endpoints/add.md)
- How to [create endpoints](../endpoints/create.md)
- How to [create a service](../services/create-service.md)
- How to [create a subscriber](../subscribers/create-subscriber.md)
- How to [create an entity](./../entities/index.md)
- How to [create a migration](../migrations/index.md)
- How to [create a subscriber](../events/create-subscriber.md)
- How to [create an entity](../entities/create.md)
- How to [create a migration](../entities/migrations/create.md)
---
@@ -151,7 +151,7 @@ This guide doesn't cover how to create different files and components. If you
Plugins often allow developers that will later use them to enter their own configuration. For example, you can allow developers to specify the API key of a service youre integrating.
To pass a plugin its configurations on a Medusa server, you have to add it to the `plugins` array in `medusa-config.js`:
To pass a plugin its configurations on a Medusa backend, you have to add it to the `plugins` array in `medusa-config.js`:
```jsx title=medusa-config.js
const plugins = [
@@ -189,7 +189,8 @@ export default (rootDirectory, options) => {
router.get("/hello-world", (req, res) => {
res.json({
message: `Welcome to ${options.name ? options.name : "Medusa"}!`,
message:
`Welcome to ${options.name ? options.name : "Medusa"}!`,
})
})
@@ -207,7 +208,7 @@ Make sure to include in the README of your plugin the configurations that can be
## Test Your Plugin
While you develop your plugin, youll need to test it on an actual Medusa server. This can be done by using the [npm link](https://docs.npmjs.com/cli/v8/commands/npm-link) command.
While you develop your plugin, youll need to test it on an actual Medusa backend. This can be done by using the [npm link](https://docs.npmjs.com/cli/v8/commands/npm-link) command.
In the root of your plugin directory, run the following command:
@@ -215,7 +216,7 @@ In the root of your plugin directory, run the following command:
npm link
```
Then, change to the directory of the Medusa server you want to test the plugin on and run the following command:
Then, change to the directory of the Medusa backend you want to test the plugin on and run the following command:
```bash npm2yarn
npm link medusa-plugin-custom
@@ -223,7 +224,7 @@ npm link medusa-plugin-custom
Where `medusa-plugin-custom` is the package name of your plugin.
After linking to your plugin in a local Medusa server, either run the `build` or `watch` commands in your plugin directory:
After linking to your plugin in a local Medusa backend, either run the `build` or `watch` commands in your plugin directory:
```bash npm2yarn
# in the directory of the plugin
@@ -253,11 +254,11 @@ const plugins = [
:::note
If your plugin has migrations, you must run them before you start the server. Check out the [Migrations guide](../migrations/overview.md#migrate-command) for more details.
If your plugin has migrations, you must run them before you start the backend. Check out the [Migrations guide](../entities/migrations/overview.mdx#migrate-command) for more details.
:::
Finally, start your server and test your plugins functionalities:
Finally, start your backend and test your plugins functionalities:
```bash npm2yarn
npm run start
@@ -270,9 +271,9 @@ npm run start
Please make sure that your plugin is following the correct structure. If the error persists then please try the following fix:
```bash npm2yarn
cd <SERVER_PATH>/node_modules/medusa-interfaces
cd <BACKEND_PATH>/node_modules/medusa-interfaces
npm link
cd <SERVER_PATH>/node_modules/@medusajs/medusa
cd <BACKEND_PATH>/node_modules/@medusajs/medusa
npm link
cd <PLUGIN_PATH>
rm -rf node_modules/medusa-interfaces
@@ -280,30 +281,30 @@ rm -rf node_modules/@medusajs/medusa
npm link medusa-interfaces
npm link @medusajs/medusa
npm link
cd <SERVER_PATH>
cd <BACKEND_PATH>
npm link your-plugin
```
Where `<SERVER_PATH>` is the path to your Medusa server and `<PLUGIN_PATH>` is the path to your plugin.
Where `<BACKEND_PATH>` is the path to your Medusa backend and `<PLUGIN_PATH>` is the path to your plugin.
This links the `medusa-interfaces` and `@medusajs/medusa` packages from your `medusa-backend` to your plugin directory and then links your plugin to your `medusa-backend`.
#### APIs not loading
If the APIs you added to your Medussa server are not loading then please try the following steps:
If the APIs you added to your Medussa backend are not loading then please try the following steps:
```bash npm2yarn
cd <PLUGIN_PATH>
rm -rf node_modules
cd <SERVER_PATH>/node_modules/<PLUGIN_NAME>
cd <BACKEND_PATH>/node_modules/<PLUGIN_NAME>
npm install
cd <PLUGIN_PATH>
npm run build
cd <SERVER_PATH>
cd <BACKEND_PATH>
npm run start
```
Where `<SERVER_PATH>` is the path to your Medusa server, `<PLUGIN_PATH>` is the path to your plugin and `<PLUGIN_NAME>` is the name of your plugin as it is in your plugin `package.json` file.
Where `<BACKEND_PATH>` is the path to your Medusa backend, `<PLUGIN_PATH>` is the path to your plugin and `<PLUGIN_NAME>` is the name of your plugin as it is in your plugin `package.json` file.
:::note
@@ -318,11 +319,3 @@ It is safe to ignore any `cross-env: command not found` error you may receive.
Once you're done with the development of the plugin, you can publish it to NPM so that other Medusa developers and users can use it.
Please refer to [this guide on required steps to publish a plugin](./publish.md).
---
## See Also
- [Available official plugins](https://github.com/medusajs/medusa/tree/master/packages)
- [Services reference](references/services/../../../../../references/services/classes/AuthService.md)
- [Events reference](../subscribers/events-list.md)

View File

@@ -1,7 +1,10 @@
---
description: 'Learn what Plugins are and how they are used in Medusa. Plugins are re-usable customizations that can be added to a Medusa server.'
description: 'Learn what Plugins are and how they are used in Medusa. Plugins are re-usable customizations that can be added to a Medusa backend.'
---
import DocCardList from '@theme/DocCardList';
import Icons from '@theme/Icon';
# Plugins
In this document, youll get an overview of plugins in Medusa, where to find them, and how to install them. If you want to learn how to create a plugin, check out [this guide](create.md) instead.
@@ -12,11 +15,11 @@ Medusa was built with flexibility and extendibility in mind. All different compo
Developers can use plugins to take advantage of this abstraction, flexibility, and extendibility. Plugins allow developers to implement custom features or integrate third-party services into Medusa.
For example, if you want to use Stripe as a payment provider in your store, then you can install the Stripe plugin on your server and use it.
For example, if you want to use Stripe as a payment provider in your store, then you can install the Stripe plugin on your backend and use it.
An alternative approach is developing a custom way of handling payment on your ecommerce store. Both approaches are achievable by either creating a plugin or using an existing plugin.
Plugins run within the same process as the core Medusa server eliminating the need for extra server capacity, infrastructure, and maintenance. As a result, plugins can use all other services as dependencies and access the database.
Plugins run within the same process as the core Medusa backend eliminating the need for extra backend capacity, infrastructure, and maintenance. As a result, plugins can use all other services as dependencies and access the database.
---
@@ -24,7 +27,7 @@ Plugins run within the same process as the core Medusa server eliminating the ne
### Official Plugins
Medusa has official plugins that cover different aspects and functionalities such as payment, Content Management System (CMS), fulfillment, and notifications. You can check out the available plugins under the [packages directory in the Medusa repository on GitHub](https://github.com/medusajs/medusa/tree/master/packages).
Medusa has official plugins that cover different aspects and functionalities such as payment, Content Management System (CMS), fulfillment, and notifications. You can check out the available plugins under the [Plugins section of this documentation](../../plugins/overview.mdx).
:::tip
@@ -40,7 +43,7 @@ You can also check the [Awesome Medusa repository](https://github.com/adrien2p/a
## How to Install a Plugin
To install an existing plugin, in your Medusa server run the following command:
To install an existing plugin, in your Medusa backend run the following command:
```bash npm2yarn
npm install <plugin_name>
@@ -56,8 +59,27 @@ For community plugins, please refer to the installation instructions of that plu
---
## See Also
## Custom Development
- [Create a plugin](create.md)
- [Publish a plugin](publish.md)
- [Create a fulfillment provider](../shipping/add-fulfillment-provider.md) or a [payment provider](../payment/how-to-create-payment-provider.md)
Developers can create plugins and reuse them across different Medusa backends. They can also share them with the community to help out other developers.
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/development/plugins/create',
label: 'Create a Plugin',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create plugins in Medusa.'
}
},
{
type: 'link',
href: '/development/plugins/publish',
label: 'Publish a Plugin',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to publish a plugin to NPM.'
}
},
]} />

View File

@@ -34,7 +34,7 @@ Before publishing your plugin, make sure you've set the following fields in your
- `medusa-plugin-shipping`: For plugins that add shipping functionalities or integrations.
- `medusa-plugin-storage`: For plugins that add a file service or storage integration.
- `medusa-plugin-source`: For plugins that help migrate or import data into Medusa from another platform.
- `medusa-plugin-storefront`: For storefronts that can be integrated with a Medusa server.
- `medusa-plugin-storefront`: For storefronts that can be integrated with a Medusa backend.
- `medusa-plugin-other`: For any other type of plugin.
### Scripts in package.json
@@ -131,7 +131,7 @@ Your package is then published on NPM and everyone can use it and install it.
### Install Plugin
To install your published plugin, you can run the following command on any Medusa server project:
To install your published plugin, you can run the following command on any Medusa backend project:
```bash npm2yarn
npm install medusa-plugin-custom
@@ -151,10 +151,4 @@ Then, publish the new update:
```bash
npm publish
```
---
## See Also
- [Available official plugins](https://github.com/medusajs/medusa/tree/master/packages)
```

View File

@@ -37,19 +37,19 @@ You want to use or implement the following admin functionalities:
### Medusa Components
It is assumed that you already have a Medusa server installed and set up. If not, you can follow the [quickstart guide](../../quickstart/quick-start.mdx) to get started.
It is assumed that you already have a Medusa backend installed and set up. If not, you can follow the [quickstart guide](../../backend/install.mdx) to get started.
### JS Client
This guide includes code snippets to send requests to your Medusa server using Medusas JS Client, among other methods.
This guide includes code snippets to send requests to your Medusa backend using Medusas JS Client, among other methods.
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client](../../js-client/overview.md) installed and have [created an instance of the client](../../js-client/overview.md#configuration).
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client](../../../js-client/overview.md) installed and have [created an instance of the client](../../../js-client/overview.md#configuration).
### Medusa React
This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods.
This guide also includes code snippets to send requests to your Medusa backend using Medusa React, among other methods.
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage).
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../../medusa-react/overview.md#usage).
### Authenticated Admin User
@@ -81,7 +81,8 @@ import { PublishableApiKey } from "@medusajs/medusa"
import { useAdminPublishableApiKeys } from "medusa-react"
const PublishabelApiKeys = () => {
const { publishable_api_keys, isLoading } = useAdminPublishableApiKeys()
const { publishable_api_keys, isLoading } =
useAdminPublishableApiKeys()
return (
<div>
@@ -89,11 +90,14 @@ const PublishabelApiKeys = () => {
{publishable_api_keys && !publishable_api_keys.length && (
<span>No Publishable API Keys</span>
)}
{publishable_api_keys && publishable_api_keys.length > 0 && (
{publishable_api_keys &&
publishable_api_keys.length > 0 && (
<ul>
{publishable_api_keys.map(
(publishableApiKey: PublishableApiKey) => (
<li key={publishableApiKey.id}>{publishableApiKey.title}</li>
<li key={publishableApiKey.id}>
{publishableApiKey.title}
</li>
)
)}
</ul>
@@ -109,7 +113,7 @@ export default PublishabelApiKeys
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/admin/publishable-api-keys`, {
fetch(`<BACKEND_URL>/admin/publishable-api-keys`, {
credentials: "include",
})
.then((response) => response.json())
@@ -122,7 +126,7 @@ fetch(`<SERVER_URL>/admin/publishable-api-keys`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X GET '<SERVER_URL>/admin/publishable-api-keys' \
curl -L -X GET '<BACKEND_URL>/admin/publishable-api-keys' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -188,7 +192,7 @@ export default CreatePublishableApiKey
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/admin/publishable-api-keys`, {
fetch(`<BACKEND_URL>/admin/publishable-api-keys`, {
method: "POST",
credentials: "include",
headers: {
@@ -208,7 +212,7 @@ fetch(`<SERVER_URL>/admin/publishable-api-keys`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<SERVER_URL>/admin/publishable-api-keys' \
curl -L -X POST '<BACKEND_URL>/admin/publishable-api-keys' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -248,7 +252,9 @@ medusa.admin.publishableApiKeys.update(publishableApiKeyId, {
import { useAdminUpdatePublishableApiKey } from "medusa-react"
const UpdatePublishableApiKey = () => {
const updateKey = useAdminUpdatePublishableApiKey(publishableApiKeyId)
const updateKey = useAdminUpdatePublishableApiKey(
publishableApiKeyId
)
// ...
const handleUpdate = (title: string) => {
@@ -266,8 +272,10 @@ export default UpdatePublishableApiKey
</TabItem>
<TabItem value="fetch" label="Fetch API">
<!-- eslint-disable max-len -->
```ts
fetch(`<SERVER_URL>/admin/publishable-api-keys/${publishableApiKeyId}`, {
fetch(`<BACKEND_URL>/admin/publishable-api-keys/${publishableApiKeyId}`, {
method: "POST",
credentials: "include",
headers: {
@@ -287,7 +295,7 @@ fetch(`<SERVER_URL>/admin/publishable-api-keys/${publishableApiKeyId}`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<SERVER_URL>/admin/publishable-api-keys/<PUBLISHABLE_API_KEY>' \
curl -L -X POST '<BACKEND_URL>/admin/publishable-api-keys/<PUBLISHABLE_API_KEY>' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -327,7 +335,9 @@ medusa.admin.publishableApiKeys.revoke(publishableApiKeyId)
import { useAdminRevokePublishableApiKey } from "medusa-react"
const PublishableApiKey = () => {
const revokeKey = useAdminRevokePublishableApiKey(publishableApiKeyId)
const revokeKey = useAdminRevokePublishableApiKey(
publishableApiKeyId
)
// ...
const handleRevoke = () => {
@@ -343,9 +353,11 @@ export default PublishableApiKey
</TabItem>
<TabItem value="fetch" label="Fetch API">
<!-- eslint-disable max-len -->
```ts
fetch(
`<SERVER_URL>/admin/publishable-api-keys/${publishableApiKeyId}/revoke`,
`<BACKEND_URL>/admin/publishable-api-keys/${publishableApiKeyId}/revoke`,
{
method: "POST",
credentials: "include",
@@ -361,7 +373,7 @@ fetch(
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<SERVER_URL>/admin/publishable-api-keys/<PUBLISHABLE_API_KEY>/revoke' \
curl -L -X POST '<BACKEND_URL>/admin/publishable-api-keys/<PUBLISHABLE_API_KEY>/revoke' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -393,7 +405,9 @@ medusa.admin.publishableApiKeys.delete(publishableApiKeyId)
import { useAdminDeletePublishableApiKey } from "medusa-react"
const PublishableApiKey = () => {
const deleteKey = useAdminDeletePublishableApiKey(publishableApiKeyId)
const deleteKey = useAdminDeletePublishableApiKey(
publishableApiKeyId
)
// ...
const handleDelete = () => {
@@ -409,8 +423,10 @@ export default PublishableApiKey
</TabItem>
<TabItem value="fetch" label="Fetch API">
<!-- eslint-disable max-len -->
```ts
fetch(`<SERVER_URL>/admin/publishable-api-keys/${publishableApiKeyId}`, {
fetch(`<BACKEND_URL>/admin/publishable-api-keys/${publishableApiKeyId}`, {
method: "DELETE",
credentials: "include",
})
@@ -424,7 +440,7 @@ fetch(`<SERVER_URL>/admin/publishable-api-keys/${publishableApiKeyId}`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X DELETE '<SERVER_URL>/admin/publishable-api-keys/<PUBLISHABLE_API_KEY>' \
curl -L -X DELETE '<BACKEND_URL>/admin/publishable-api-keys/<PUBLISHABLE_API_KEY>' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -453,7 +469,8 @@ You can retrieve the list of sales channels associated with a publishable API ke
<TabItem value="client" label="Medusa JS Client" default>
```ts
medusa.admin.publishableApiKeys.listSalesChannels(publishableApiKeyId)
medusa.admin.publishableApiKeys
.listSalesChannels(publishableApiKeyId)
.then(({ sales_channels }) => {
console.log(sales_channels)
})
@@ -464,7 +481,9 @@ medusa.admin.publishableApiKeys.listSalesChannels(publishableApiKeyId)
```tsx
import { SalesChannel } from "@medusajs/medusa"
import { useAdminPublishableApiKeySalesChannels } from "medusa-react"
import {
useAdminPublishableApiKeySalesChannels,
} from "medusa-react"
const SalesChannels = () => {
const { sales_channels, isLoading } =
@@ -499,7 +518,7 @@ export default SalesChannels
```ts
fetch(
`<SERVER_URL>/admin/publishable-api-keys/${publishableApiKeyId}/sales-channels`,
`<BACKEND_URL>/admin/publishable-api-keys/${publishableApiKeyId}/sales-channels`,
{
credentials: "include",
}
@@ -514,7 +533,7 @@ fetch(
<TabItem value="curl" label="cURL">
```bash
curl -L -X GET '<SERVER_URL>/admin/publishable-api-keys/<PUBLISHABLE_API_KEY>/sales-channels' \
curl -L -X GET '<BACKEND_URL>/admin/publishable-api-keys/<PUBLISHABLE_API_KEY>/sales-channels' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -552,12 +571,15 @@ medusa.admin.publishableApiKeys.addSalesChannelsBatch(
<TabItem value="medusa-react" label="Medusa React">
```tsx
import { useAdminAddPublishableKeySalesChannelsBatch } from "medusa-react"
import {
useAdminAddPublishableKeySalesChannelsBatch,
} from "medusa-react"
const PublishableApiKey = () => {
const addSalesChannels = useAdminAddPublishableKeySalesChannelsBatch(
publishableApiKeyId
)
const addSalesChannels =
useAdminAddPublishableKeySalesChannelsBatch(
publishableApiKeyId
)
// ...
const handleAdd = (salesChannelId: string) => {
@@ -583,7 +605,7 @@ export default PublishableApiKey
```ts
fetch(
`<SERVER_URL>/admin/publishable-api-keys/${publishableApiKeyId}/sales-channels/batch`,
`<BACKEND_URL>/admin/publishable-api-keys/${publishableApiKeyId}/sales-channels/batch`,
{
method: "POST",
credentials: "include",
@@ -609,7 +631,7 @@ fetch(
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<SERVER_URL>/admin/publishable-api-keys/<PUBLISHABLE_API_KEY>/sales-channels/batch' \
curl -L -X POST '<BACKEND_URL>/admin/publishable-api-keys/<PUBLISHABLE_API_KEY>/sales-channels/batch' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -693,7 +715,7 @@ export default PublishableApiKey
```ts
fetch(
`<SERVER_URL>/admin/publishable-api-keys/${publishableApiKeyId}/sales-channels/batch`,
`<BACKEND_URL>/admin/publishable-api-keys/${publishableApiKeyId}/sales-channels/batch`,
{
method: "DELETE",
credentials: "include",
@@ -719,7 +741,7 @@ fetch(
<TabItem value="curl" label="cURL">
```bash
curl -L -X DELETE '<SERVER_URL>/admin/publishable-api-keys/<PUBLISHABLE_API_KEY>/sales-channels/batch' \
curl -L -X DELETE '<BACKEND_URL>/admin/publishable-api-keys/<PUBLISHABLE_API_KEY>/sales-channels/batch' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -746,5 +768,4 @@ This request returns the updated publishable API key in the response.
## See Also
- [Publishable API key overview](../backend/publishable-api-keys/index.md)
- [Publishable API key admin API reference](/api/admin/#tag/PublishableApiKey)
- [Use publishable API keys in client requests](../storefront/use-in-requests.md)

View File

@@ -0,0 +1,69 @@
---
description: 'Learn what publishable API keys are and how they can be used in the Medusa backend. Publishable API keys can be used to scope API calls with an API key.'
---
import DocCardList from '@theme/DocCardList';
import Icons from '@theme/Icon';
# Publishable API Keys
In this document, youll learn about Publishable API Keys and their architecture.
## Introduction
While using Medusas APIs, you might have to pass some query parameters for certain resources with every or most requests.
Taking Sales Channels as an example, you have to pass the Sales Channels ID as a query parameter to all the necessary endpoints, such as the List Products endpoint.
This is a tedious and error-prone process. This is where Publishable API Keys are useful.
Publishable API Keys can be used to scope API calls with an API key, determining what resources are retrieved when querying the API. Currently, they can be associated only with Sales Channels.
For example, you can associate an API key with a B2B channel, then, on the storefront, retrieve only products available in that channel using the API key.
---
## PublishableApiKey Entity Overview
The `PublishableApiKey` entity represents a publishable API key that is stored in the database. Some of its important attributes include:
- `id`: The ID of the publishable API key. This is the API key youll use in your API requests.
- `created_by`: The ID of the user that created this API key.
- `revoked_by`: The ID of the user that revoked this API key. A revoked publishable API key cannot be used in requests.
---
## Relation to Other Entities
### Sales Channels
A publishable API key can be associated with more than one sales channel, and a sales channel can be associated with more than one publishable API key.
The relation is represented by the entity `PublishableApiKeySalesChannel`.
---
## Custom Development
Developers can manage Publishable API Keys and use them when making requests to the Store APIs.
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/development/publishable-api-keys/admin/manage-publishable-api-keys',
label: 'Admin: Manage Publishable API Keys',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to manage publishable API keys using Admin APIs.'
}
},
{
type: 'link',
href: '/development/publishable-api-keys/storefront/use-in-requests',
label: 'Storefront: Use in Requests',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to use publishable API keys in a storefront.'
}
},
]} />

View File

@@ -0,0 +1,78 @@
---
description: 'Learn how to use Publishable API Keys in Client Requests using Medusa JS Client, Medusa React, or other methods.'
---
# Use Publishable API Keys in Client Requests
In this document, you'll learn how to use Publishable API Keys in client requests.
:::note
[Publishable API keys](../index.mdx) are only for client-side use. They can be publicly accessible in your code, as they are not authorized for the Admin API.
:::
## Using Medusa JS Client
When using [Medusas JS Client](../../../js-client/overview.md), you can pass it to the client only once when you create the instance of the client:
```ts
const medusa = new Medusa({
maxRetries: 3,
baseUrl: "https://api.example.com",
publishableApiKey,
})
```
This will add the API key as in the header parameter `x-publishable-api-key` on all requests.
You can also use the `setPublishableKey` method to set it at a later point:
```ts
const medusa = new Medusa({
// ...
})
// at a later point
medusa.setPublishableKey(publishableApiKey)
```
## Using Medusa React
You can pass the publishable API key to the `MedusaProvider` component:
```tsx
const App = () => {
return (
<MedusaProvider
queryClientProviderProps={{ client: queryClient }}
baseUrl="http://localhost:9000"
// ...
publishableApiKey={publishableApiKey}
>
<MyStorefront />
</MedusaProvider>
)
}
```
Then, the API key will be passed in the header parameter `x-publishable-api-key` of every request.
## Using Other Methods
For other ways of sending requests to your Medusa backend, such as using the Fetch API, you must pass `x-publishable-api-key` in the header of every request. Its value is the publishable API keys `id`.
```ts
fetch(`<BACKEND_URL>/store/products`, {
credentials: "include",
headers: {
"x-publishable-api-key": publishableApiKey,
},
})
```
---
## See Also
- [Manage publishable keys as an admin](../admin/manage-publishable-api-keys.mdx)

View File

@@ -1,5 +1,5 @@
---
description: 'Learn how to create a scheduled job in the Medusa server. The scheduled job in this example will simply change the status of draft products to published.'
description: 'Learn how to create a scheduled job in Medusa. The scheduled job in this example will simply change the status of draft products to published.'
addHowToData: true
---
@@ -9,9 +9,9 @@ In this document, youll learn how to create a scheduled job in Medusa.
## Overview
Medusa allows you to create scheduled jobs that run at specific times during your servers lifetime. For example, you can synchronize your inventory with an Enterprise Resource Planning (ERP) system once a day.
Medusa allows you to create scheduled jobs that run at specific times during your backend's lifetime. For example, you can synchronize your inventory with an Enterprise Resource Planning (ERP) system once a day.
This guide explains how to create a scheduled job on your Medusa server. The scheduled job in this example will simply change the status of draft products to `published`.
This guide explains how to create a scheduled job on your Medusa backend. The scheduled job in this example will simply change the status of draft products to `published`.
---
@@ -19,11 +19,11 @@ This guide explains how to create a scheduled job on your Medusa server. The sch
### Medusa Components
It is assumed that you already have a Medusa server installed and set up. If not, you can follow the [quickstart guide](../../../quickstart/quick-start.mdx) to get started.
It is assumed that you already have a Medusa backend installed and set up. If not, you can follow the [quickstart guide](../backend/install.mdx) to get started.
### Redis
Redis is required for scheduled jobs to work. Make sure you [install Redis](../../../tutorial/0-set-up-your-development-environment.mdx#redis) and [configure it with your Medusa server](../../../usage/configurations.md#redis).
Redis is required for scheduled jobs to work. Make sure you [install Redis](../../development/backend/prepare-environment.mdx#redis) and [configure it with your Medusa backend](../../development/backend/configurations.md#redis).
---
@@ -43,8 +43,12 @@ To create a scheduled job, add the following code in the file you created, which
```ts title=src/loaders/publish.ts
const publishJob = async (container, options) => {
const jobSchedulerService = container.resolve("jobSchedulerService")
jobSchedulerService.create("publish-products", {}, "0 0 * * *",
const jobSchedulerService =
container.resolve("jobSchedulerService")
jobSchedulerService.create(
"publish-products",
{},
"0 0 * * *",
async () => {
// job to execute
const productService = container.resolve("productService")
@@ -77,7 +81,7 @@ You then resolve the `JobSchedulerService` and use the `jobSchedulerService.crea
- The first parameter is a unique name to give to the scheduled job. In the example above, you use the name `publish-products`;
- The second parameter is an object which can be used to [pass data to the job](#pass-data-to-the-scheduled-job);
- The third parameter is the scheduled job expression pattern. In this example, it will execute the scheduled job once a day at 12 AM.
- The fourth parameter is the function to execute. This is where you add the code to execute once the scheduled job runs. In this example, you retrieve the draft products using the [ProductService](../../../references/services/classes/ProductService.md) and update the status of each of these products to `published`.
- The fourth parameter is the function to execute. This is where you add the code to execute once the scheduled job runs. In this example, you retrieve the draft products using the [ProductService](../../references/services/classes/ProductService.md) and update the status of each of these products to `published`.
:::tip
@@ -104,23 +108,23 @@ jobSchedulerService.create("publish-products", {
---
## 3. Run Medusa Server
## 3. Run Medusa Backend
:::info
Cron Jobs only run while the Medusa server is running.
Cron Jobs only run while the Medusa backend is running.
:::
In your terminal run the following command to run your Medusa server:
In your terminal run the following command to run your Medusa backend:
```bash npm2yarn
npm run start
```
This builds your code under the `src` directory into the `dist` directory, then runs the Medusa server.
This builds your code under the `src` directory into the `dist` directory, then runs the Medusa backend.
If the scheduled job was registered successfully, you should see a message similar to this logged on your Medusa server:
If the scheduled job was registered successfully, you should see a message similar to this logged on your Medusa backend:
```bash
Registering publish-products
@@ -128,15 +132,15 @@ Registering publish-products
Where `publish-products` is the unique name you provided to the scheduled job.
Once it is time to run your scheduled job based on the scheduled job expression pattern, the scheduled job will run and you can see it logged on your Medusa server.
Once it is time to run your scheduled job based on the scheduled job expression pattern, the scheduled job will run and you can see it logged on your Medusa backend.
For example, the above scheduled job will run at 12 AM and, when it runs, you can see the following logged on your Medusa server:
For example, the above scheduled job will run at 12 AM and, when it runs, you can see the following logged on your Medusa backend:
```bash noReport
info: Processing scheduled job: publish-products
```
If you log anything in the scheduled job, for example using `console.log`, or if any errors are thrown, itll also be logged on your Medusa server.
If you log anything in the scheduled job, for example using `console.log`, or if any errors are thrown, itll also be logged on your Medusa backend.
:::tip
@@ -148,4 +152,4 @@ To test the previous example out instantly, you can change the scheduled job exp
## See Also
- [Services Overview](../services/overview.md).
- [Create a Plugin](../plugins/create.md)

View File

@@ -0,0 +1,40 @@
---
description: "Learn what scheduled jobs are in Medusa. Scheduled jobs (also known as cron jobs) are tasks performed at a specific time in the Medusa Backend."
---
import DocCard from '@theme/DocCard';
import Icons from '@theme/Icon';
# Scheduled Jobs
In this document, youll learn what scheduled jobs are in Medusa.
## Introduction
Scheduled jobs (also known as cron jobs) are tasks performed at a specific time while the Medusa Backend is running. Theyre used to perform asynchronous tasks in the background.
For example, you can synchronize your inventory with an Enterprise Resource Planning (ERP) system once a day using a scheduled job.
In the Medusa Backend, the scheduled jobs queue is implemented using [Redis](https://redis.io/) and [Bull](https://www.npmjs.com/package/bull). So, for scheduled jobs to work, you must have [Redis enabled](../../development/backend/configurations.md#redis).
:::tip
Future versions of Medusa will allow switching out Redis and using a different pub/sub service.
:::
---
## Custom Development
Developers can create an unlimited number of scheduled jobs within the Medusa Backend, a plugin, or a custom Commerce Module.
<DocCard item={{
type: 'link',
href: '/development/scheduled-jobs/create',
label: 'Create a Scheduled Job',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create a scheduled job.'
}
}} />

View File

@@ -5,7 +5,7 @@ addHowToData: true
# Create a Service
In this document, youll learn how you can create a [Service](./overview.md) and use it across your Medusa server just like any of the core services.
In this document, youll learn how you can create a [Service](./overview.mdx) and use it across your Medusa backend just like any of the core services.
## Implementation
@@ -63,7 +63,7 @@ class HelloService extends TransactionBaseService {
## Use a Service
In this section, you'll learn how to use services throughout your Medusa server. This includes both Medusa's services and your custom services.
In this section, you'll learn how to use services throughout your Medusa backend. This includes both Medusa's services and your custom services.
:::note
@@ -118,5 +118,4 @@ class MySubscriber {
## See Also
- [Services Reference](/references/services/classes/AuthService)
- [Create an Endpoint](../endpoints/add.md)
- [Create a Plugin](../plugins/create.md)

View File

@@ -0,0 +1,49 @@
---
description: 'Learn what Services are in Medusa. Services represent bundled helper methods that you want to use across your commerce application.'
---
import DocCard from '@theme/DocCard';
import Icons from '@theme/Icon';
# Services
In this document, you'll learn about what Services are in Medusa.
## What are Services
Services in Medusa represent bundled helper methods that you want to use across your commerce application. By convention, they represent a certain entity or functionality in Medusa.
For example, you can use Medusas `productService` to get the list of products, as well as perform other functionalities related to products. Theres also an `authService` that provides functionalities like authenticating customers and users.
In the Medusa backend, custom services are TypeScript or JavaScript files located in the `src/services` directory. Each service should be a class that extends the `TransactionBaseService` class from the core Medusa package `@medusajs/medusa`. Each file you create in `src/services` should hold one service and export it.
The file name is important as it determines the name of the service when you need to use it elsewhere. The name of the service will be registered as the camel-case version of the file name + `Service` at the end of the name.
For example, if the file name is `hello.ts`, the service will be registered as `helloService`. If the file name is `hello-world.ts`, the service name will be registered as `helloWorldService`.
The registration name of the service is important, as youll be referring to it when you want to get access to the service using dependency injection or in routes.
The service must then be transpiled using the `build` command, which moves them to the `dist` directory, to be used across your commerce application.
:::tip
If you're creating a service in a plugin, learn more about the required structure [here](../plugins/create.md#plugin-structure).
:::
---
## Custom Development
Developers can create custom services in the Medusa backend, a plugin, or in a Commerce Module.
<DocCard item={{
type: 'link',
href: '/development/services/create-service',
label: 'Create a Service',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create a service in Medusa.'
}
}}
/>

View File

@@ -0,0 +1,68 @@
---
description: "Learn what a Strategy is in Medusa. A strategy is an isolated piece of business logic that can be overridden and customized."
---
import DocCardList from '@theme/DocCardList';
import Icons from '@theme/Icon';
# Strategy
In this document, youll learn what a Strategy is in Medusa.
## Introduction
A strategy is an isolated piece of business logic that can be overridden and customized. Its a TypeScript or JavaScript class that doesnt have to follow a specific definition, but performs only a single functionality.
For example, in the core `@medusajs/medusa` package, strategies are used to implement functionalities like cart completion and product import.
These strategy classes are then resolved in endpoints, services, or wherever needed using dependency injection and used to perform their designated functionality.
For example, the `CartCompletionStrategy` is resolved in the Complete Cart endpoint that is defined in the core `@medusajs/medusa` package. Its then used to complete the cart and place the order:
```ts
export default async (req, res) => {
// ...
const completionStrat: AbstractCartCompletionStrategy =
req.scope.resolve(
"cartCompletionStrategy"
)
const {
response_code,
response_body,
} = await completionStrat.complete(
id,
idempotencyKey,
req.request_context
)
res.status(response_code).json(response_body)
}
```
Developers can override these strategies defined in the core to customize their functionality. Dependency injection then resolves the strategy (in the code example above, `CartCompletionStrategy`) to the custom strategy that the developer created. Then, the method (in the code example above, `complete`) of the custom strategy will be executed instead of the one defined in the core package.
## Custom Development
<DocCardList colSize={6} items={[
{
type: 'link',
href: '#',
label: 'Backend: Create a Strategy',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create a strategy.',
isSoon: true
}
},
{
type: 'link',
href: '#',
label: 'Backend: Override a Strategy',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to override a strategy.',
isSoon: true
}
},
]} />

View File

@@ -8,72 +8,45 @@ hide_footer: true
---
import DocCardList from '@theme/DocCardList';
import DocCard from '@theme/DocCard';
import Icons from '@theme/Icon';
# Medusa Documentation
Get an overview of Medusa's features, integrations, and how to use them.
Medusa is a set of commerce tools and modules that can be used to build unique commerce experiences.
## Medusa basics
Medusa provides the essential building blocks that developers can put together to create a powerful commerce store. Developers have full control over their tech stack and the logic behind the commerce features.
Learn about Medusa basic features and kickstart your ecommerce project.
<DocCard item={{
type: 'link',
href: '/create-medusa-app',
label: 'Get Started',
customProps: {
icon: Icons['bolt-solid'],
html: 'Create a full-fledged Medusa project with one command.',
className: 'card-highlighted'
}
}} />
## Explore Medusa
<DocCardList colSize={4} items={[
{
type: 'link',
href: '/usage/create-medusa-app',
label: 'Quickstart Guide',
href: '/modules/overview',
label: 'Commerce Modules',
customProps: {
image: '/img/quickstart-icon.svg',
description: 'Create your first Medusa server.',
className: 'card-highlight'
icon: Icons['puzzle-solid'],
description: 'Learn about the available ecommerce features and how to use and customize them.'
}
},
{
type: 'link',
href: '/introduction#features',
label: 'Features',
href: '/development/overview',
label: 'Medusa Development',
customProps: {
themedImage: {
light: '/img/dev-env-icon.svg',
dark: '/img/dev-env-icon-dark.svg'
},
description: 'Learn about Medusa\'s features'
}
},
{
type: 'link',
href: '/starters/nextjs-medusa-starter',
label: 'Next.js Storefront',
customProps: {
themedImage: {
light: '/img/nextjs-icon.svg',
dark: '/img/nextjs-icon-dark.svg'
},
description: 'Install Medusa\'s Next.js storefront.'
},
},
{
type: 'link',
href: '/starters/gatsby-medusa-starter',
label: 'Gatsby Storefront',
customProps: {
themedImage: {
light: '/img/gatsby-icon.svg',
dark: '/img/gatsby-icon-dark.svg'
},
description: 'Install Medusa\'s Gatsby storefront.'
}
},
{
type: 'link',
href: '/admin/quickstart',
label: 'Admin Quickstart',
customProps: {
themedImage: {
light: '/img/admin-icon.svg',
dark: '/img/admin-icon-dark.svg'
},
description: 'Install Medusa\'s Admin to manage your store.'
icon: Icons['server-stack-solid'],
description: 'Learn how to develop customized digital commerce applications with Medusa.'
}
},
{
@@ -81,90 +54,145 @@ Learn about Medusa basic features and kickstart your ecommerce project.
href: '/user-guide',
label: 'User Guide',
customProps: {
themedImage: {
light: '/img/user-guide.svg',
dark: '/img/user-guide-dark.svg'
},
description: 'Take a look at the features available in Medusa Admin'
icon: Icons['users-solid'],
description: 'No-code guides to help users manage their ecommerce stores using the Medusa admin.'
}
}
]} />
## Most popular
## Medusa Toolkit
Best of the greatest.
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/development/backend/install',
label: 'Medusa Backend',
customProps: {
icon: Icons['circle-stack-solid'],
html: 'A Medusa Backend is any Node.js project with @medusajs/medusa installed. The core Medusa package orchestrates Medusa\'s Commerce Modules to expose a powerful and customizable REST API.',
}
},
{
type: 'link',
href: '/admin/quickstart',
label: 'Medusa Admin Quickstart',
customProps: {
icon: Icons['computer-desktop-solid'],
description: 'The Medusa admin is an intuitive admin dashboard that can be used along with the Medusa backend and modules. Merchants can use it to perform data management and processes such as manage orders, products, customers, and much more.'
}
},
]} />
<DocCardList colSize={4} items={[
{
type: 'link',
href: '/advanced/backend/plugins/create',
label: 'Create a Plugin',
href: '/js-client/overview',
label: 'JavaScript Client',
customProps: {
themedImage: {
light: '/img/terminal-icon.svg',
dark: '/img/terminal-icon-dark.svg'
},
description: 'Create, test, and publish a plugins.'
icon: Icons['javascript'],
description: 'Interact with a Medusa backend from a storefront or an admin built with any JavaScript framework.'
}
},
{
type: 'link',
href: '/add-plugins/stripe',
label: 'Integrate Stripe',
href: '/medusa-react/overview',
label: 'Medusa React',
customProps: {
themedImage: {
light: '/img/stripe-icon.svg',
dark: '/img/stripe-icon-dark.svg'
},
description: 'Install Stripe on your Medusa server.'
icon: Icons['react'],
description: 'Interact with a Medusa backend from a React storefront or admin with utilities, hooks, and contexts.'
}
},
{
type: 'link',
href: '/advanced/storefront/how-to-implement-checkout-flow',
label: 'Implement Checkout',
href: '/plugins/overview',
label: 'Plugins',
customProps: {
themedImage: {
light: '/img/cart-icon.svg',
dark: '/img/cart-icon-dark.svg'
},
description: 'Implement the checkout flow in your storefront.'
icon: Icons['squares-plus-solid'],
description: 'Supercharge your Medusa backend with plugins for Storage, Notifications, Analytics, and more.'
}
},
]} />
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/cli/reference',
label: 'Medusa CLI',
customProps: {
icon: Icons['command-line-solid'],
description: 'Use the Medusa CLI tool to execute commands on your Medusa backend.'
}
},
{
type: 'link',
href: '/advanced/admin/import-products',
label: 'Import Products',
href: '/starters/nextjs-medusa-starter',
label: 'Next.js Storefront Quickstart',
customProps: {
themedImage: {
light: '/img/tee-icon.svg',
dark: '/img/tee-icon-dark.svg'
},
description: 'Bulk import products into Medusa.'
},
icon: Icons['nextjs'],
description: 'Install the Next.js starter storefront and use it with the Medusa backend.'
}
},
]} />
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/advanced/backend/shipping/overview',
label: 'Shipping Overview',
href: '/api/admin',
label: 'Admin API Reference',
customProps: {
themedImage: {
light: '/img/fast-delivery-icon.svg',
dark: '/img/fast-delivery-icon-dark.svg'
},
description: 'Learn how shipping works in Medusa.'
icon: Icons['circle-stack-solid'],
description: 'Check out available REST APIs with example code snippets.'
}
},
{
type: 'link',
href: '/advanced/backend/payment/overview',
label: 'Payment Overview',
href: '/api/admin',
label: 'Store API Reference',
customProps: {
themedImage: {
light: '/img/payment-accepted-icon.svg',
dark: '/img/payment-accepted-icon-dark.svg'
},
description: 'Learn how payment works in Medusa'
icon: Icons['computer-desktop-solid'],
description: 'Check out available REST APIs with example code snippets.'
}
}
]} />
},
]} />
## What's New
Learn about all the new features and enhancements in Medusa.
<DocCardList colSize={4} items={[
{
type: 'link',
href: '/modules/orders/admin/edit-order',
label: 'Edit an Order',
customProps: {
icon: Icons['pencil-square-solid'],
description: 'Gain more control over the order process by editing items in an order.'
}
},
{
type: 'link',
href: '/modules/sales-channels',
label: 'Sales Channels',
customProps: {
icon: Icons['channels-solid'],
description: 'Expand your market and set configurations for different channels.'
}
},
{
type: 'link',
href: '/development/publishable-api-keys',
label: 'Publishable API Keys',
customProps: {
icon: Icons['key-solid'],
description: 'Scope API calls to specific resources using an API key'
}
},
]} />
<!-- vale docs.HeadingPunctuation = NO -->
## Need Help?
<!-- vale docs.HeadingPunctuation = YES -->
If youre still not sure that Medusa is the right solution for you, you can get in-touch with the core Medusa team over at [Discord](https://discord.gg/medusajs) and get help from the community.

View File

@@ -1,53 +0,0 @@
---
description: 'Medusa is composed of three architectures: Medusa server, admin dashboard, and storefront. It also provides advanced ecommerce features such as order management and automated RMA flows.'
---
# Overview
## Architecture
Medusa is composed of three components: The Medusa server, the admin dashboard, and the storefront.
![Medusa's Architecture](https://res.cloudinary.com/dza7lstvk/image/upload/v1667999772/Medusa%20Docs/Diagrams/ZHvM2bu_td4rnx.png)
### Medusa Server
The Medusa server is a headless backend built on Node.js. This is the main component that holds all the logic and data of the store. Your admin dashboard and storefront interact with the backend to retrieve, create, and modify data through REST APIs.
Your Medusa server will include all functionalities related to your stores checkout workflow. That includes cart management, shipping and payment providers, user management, and more. It also allows you to configure your store including your stores region, tax rules, discounts, gift cards, and more.
### Admin Dashboard
The admin dashboard is accessible by store operators. Store operators can use the admin dashboard to view, create, and modify data such as orders and products.
Medusa provides a beautiful [admin dashboard](https://demo.medusajs.com) that you can use right off the bat. Medusa's admin dashboard provides a lot of functionalities to manage your store including Order management, Product management, User management, and more.
You can also create your own admin dashboard by utilizing the [Admin REST APIs](https://docs.medusajs.com/api/admin).
### Storefront
Your customers use the Storefront to view products and make orders. Medusa provides two storefronts, one built with [Next.js](https://docs.medusajs.com/starters/nextjs-medusa-starter) and one with [Gatsby](https://docs.medusajs.com/starters/gatsby-medusa-starter). You are also free to create your own storefront using the [Storefront REST APIs](https://docs.medusajs.com/api/store/).
---
## Features
- [Orders, Exchanges, and Returns](./user-guide/orders/index.md): Aside from the standard order management that comes with ecommerce platforms, Medusa also provides an easy and automated way to manage swaps, returns, and claims.
- [Customers and Customer Groups](./user-guide/customers/index.md): Manage Customers and assign them to customer groups.
- [Products and Collections](./user-guide/products/index.mdx): Add products with extensive customization settings and sort them into collections.
- [Region](./user-guide/regions/index.md): Configure and manage multiple regions and currencies all from one platform.
- [Plugins](./advanced/backend/plugins/overview.md): Easily integrate fulfillment providers, payment providers, notification services, and many other custom tools and third-party services.
- [PriceList](./user-guide/price-lists/index.md) and [Discounts](./user-guide/discounts/): Advanced pricing for products with conditions based on the amount in the cart or promotions and discounts.
- [Taxes](./user-guide/taxes/index.md): Advanced tax configurations specific to multiple regions, with the capability of specifying taxes for specific products.
- [Sales Channels](./user-guide/sales-channels/index.md): Create multiple sales channels and control which sales channels products are available in.
- [Bulk Import](./user-guide/products/import.mdx): Bulk import strategies for different entities including [products](./advanced/admin/import-products.mdx) and [price lists](./advanced/admin/import-prices.mdx).
- [Bulk Export](./user-guide/products/export.mdx): Bulk export strategies for different entities including [products](./user-guide/products/export.mdx) and [orders](./user-guide/orders/export.mdx).
- Complete Customization Capabilities: Aside from all the features that Medusa provides, it is completely customizable providing capabilities to create custom [endpoints](./advanced/backend/endpoints/add.md), [services](./advanced/backend/services/create-service.md), [subscribers](./advanced/backend/subscribers/create-subscriber.md), [batch job strategies](./advanced/backend/batch-jobs/create.mdx), and much more!
---
## See Also
- [Quickstart guide](./quickstart/quick-start.mdx)
- [Install the Next.js Storefront](./starters/nextjs-medusa-starter.mdx)
- [Install Medusa Admin](./admin/quickstart.mdx)

View File

@@ -1,10 +1,10 @@
---
description: 'Learn how to install Medusa React in a React storefront. Medusa React is a React library that provides a set of utilities and hooks for interactive with the Medusa server.'
description: 'Learn how to install Medusa React in a React storefront. Medusa React is a React library that provides a set of utilities and hooks for interactive with the Medusa backend.'
---
# Medusa React
[Medusa React](https://www.npmjs.com/package/medusa-react) is a React library that provides a set of utilities and hooks for interacting seamlessly with the Medusa server. It can be used to build custom React-based storefronts or admin dashboards.
[Medusa React](https://www.npmjs.com/package/medusa-react) is a React library that provides a set of utilities and hooks for interacting seamlessly with the Medusa backend. It can be used to build custom React-based storefronts or admin dashboards.
:::tip
@@ -46,7 +46,7 @@ To use the hooks exposed by Medusa React, you need to include the `MedusaProvi
The `MedusaProvider` requires two props:
1. `baseUrl`: The URL to your Medusa server
1. `baseUrl`: The URL to your Medusa backend
2. `queryClientProviderProps`: An object used to set the Tanstack Query client. The object requires a `client` property, which should be an instance of [QueryClient](https://tanstack.com/query/v4/docs/react/reference/QueryClient).
For example:
@@ -88,9 +88,9 @@ You can also pass the following props to Medusa Provider:
### Queries
To fetch data from the Medusa server (in other words, perform `GET` requests), you can use [Queries](https://tanstack.com/query/v4/docs/react/guides/queries). Query hooks simply wrap around Tanstack Query's `useQuery` hook to fetch data from your medusa server.
To fetch data from the Medusa backend (in other words, perform `GET` requests), you can use [Queries](https://tanstack.com/query/v4/docs/react/guides/queries). Query hooks simply wrap around Tanstack Query's `useQuery` hook to fetch data from your medusa backend.
For example, to fetch products from your Medusa server:
For example, to fetch products from your Medusa backend:
```tsx title=src/Products.ts
import { Product } from "@medusajs/medusa"
@@ -133,7 +133,7 @@ You can learn more about using queries in [Tanstack Querys documentation](htt
### Mutations
To create, update, or delete data on the Medusa server (in other words, perform `POST`, `PUT`, and `DELETE` requests), you can use [Mutations](https://tanstack.com/query/v4/docs/react/guides/mutations). Mutation hooks wrap around Tanstack Query's `useMutation` to mutate data on your medusa server.
To create, update, or delete data on the Medusa backend (in other words, perform `POST`, `PUT`, and `DELETE` requests), you can use [Mutations](https://tanstack.com/query/v4/docs/react/guides/mutations). Mutation hooks wrap around Tanstack Query's `useMutation` to mutate data on your medusa backend.
For example, to create a cart:
@@ -166,7 +166,7 @@ export default Cart
In the example above, you import the `useCreateCart` hook from `medusa-react`. This hook, and every other mutation hook exposed by `medusa-react`, returns everything that [useMutation](https://tanstack.com/query/v4/docs/react/reference/useMutation) returns. You can also pass the same options you would pass to `useMutation` to mutation hooks exposed by `medusa-react`.
To create a cart, you call the `createCart.mutate` method. In the underlying logic, this method sends a `POST` request to the Medusa server to create a cart.
To create a cart, you call the `createCart.mutate` method. In the underlying logic, this method sends a `POST` request to the Medusa backend to create a cart.
If the request accepts any parameters, they can be passed as parameters to the `mutate` request. For example:
@@ -200,8 +200,8 @@ This utility function can be used to compute the price of a variant for a region
It accepts an object with the following properties:
- `variant`: A variant object retrieved from the Medusa server. It should mainly include the `prices` array in the object.
- `region`: A region object retrieved from the Medusa server.
- `variant`: A variant object retrieved from the Medusa backend. It should mainly include the `prices` array in the object.
- `region`: A region object retrieved from the Medusa backend.
- `includeTaxes`: (optional) A boolean value that indicates whether the computed price should include taxes or not. The default value is `true`.
- `minimumFractionDigits`: (optional) The minimum number of fraction digits to use when formatting the price. This is passed as an option to `Intl.NumberFormat` in the underlying layer. You can learn more about this methods options in [MDNs documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#parameters).
- `maximumFractionDigits`: (optional) The maximum number of fraction digits to use when formatting the price. This is passed as an option to `Intl.NumberFormat` which is used within the utility method. You can learn more about this methods options in [MDNs documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#parameters).
@@ -243,8 +243,8 @@ This utility function can be used to compute the price of a variant for a region
It accepts an object with the following properties:
- `variant`: A variant object retrieved from the Medusa server. It should mainly include the `prices` array in the variant.
- `region`: A region object retrieved from the Medusa server.
- `variant`: A variant object retrieved from the Medusa backend. It should mainly include the `prices` array in the variant.
- `region`: A region object retrieved from the Medusa backend.
- `includeTaxes`: (optional) A boolean value that indicates whether the computed price should include taxes or not. The default value is `true`.
For example:
@@ -286,7 +286,7 @@ The main difference between this utility function and `formatVariantPrice` is th
It accepts an object with the following properties:
- `amount`: A number that should be used for computation.
- `region`: A region object retrieved from the Medusa server.
- `region`: A region object retrieved from the Medusa backend.
- `includeTaxes`: (optional) A boolean value that indicates whether the computed price should include taxes or not. The default value is `true`.
- `minimumFractionDigits`: (optional) The minimum number of fraction digits to use when formatting the price. This is passed as an option to `Intl.NumberFormat` in the underlying layer. You can learn more about this methods options in [MDNs documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#parameters).
- `maximumFractionDigits`: (optional) The maximum number of fraction digits to use when formatting the price. This is passed as an option to `Intl.NumberFormat` which is used within the utility method. You can learn more about this methods options in [MDNs documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#parameters).
@@ -319,7 +319,7 @@ The main difference between this utility function and `computeVariantPrice` is t
It accepts an object with the following properties:
- `amount`: A number that should be used for computation.
- `region`: A region object retrieved from the Medusa server.
- `region`: A region object retrieved from the Medusa backend.
- `includeTaxes`: (optional) A boolean value that indicates whether the computed price should include taxes or not. The default value is `true`.
For example:
@@ -354,7 +354,7 @@ To facilitate building custom storefronts, `medusa-react` also exposes a `CartP
### CartProvider
`CartProvider` makes use of some of the hooks already exposed by `medusa-react` to perform cart operations on the Medusa server. You can use it to create a cart, start the checkout flow, authorize payment sessions, and so on.
`CartProvider` makes use of some of the hooks already exposed by `medusa-react` to perform cart operations on the Medusa backend. You can use it to create a cart, start the checkout flow, authorize payment sessions, and so on.
It also manages one single global piece of state which represents a cart, exactly like the one created on your medusa backend.
@@ -432,7 +432,7 @@ const Cart = () => {
export default Cart
```
In the example above, you retrieve the `createCart` mutation and `cart` state object using the `useCart` hook. If the `cart` is not set, a button is shown. When the button is clicked, the `createCart` mutation is executed, which interacts with the server and creates a new cart.
In the example above, you retrieve the `createCart` mutation and `cart` state object using the `useCart` hook. If the `cart` is not set, a button is shown. When the button is clicked, the `createCart` mutation is executed, which interacts with the backend and creates a new cart.
After the cart is created, the `cart` state variable is set and its ID is shown instead of the button.
@@ -444,9 +444,9 @@ The example above does not store in the browser the ID of the cart created, so t
### SessionProvider
Unlike the `CartProvider`, `SessionProvider` never interacts with the Medusa server. It can be used to implement the user experience related to managing a carts items. Its state variables are JavaScript objects living in the browser, but are in no way communicated with the server.
Unlike the `CartProvider`, `SessionProvider` never interacts with the Medusa backend. It can be used to implement the user experience related to managing a carts items. Its state variables are JavaScript objects living in the browser, but are in no way communicated with the backend.
You can use the `SessionProvider` as a lightweight client-side cart functionality. Its not stored in any database or on the Medusa server.
You can use the `SessionProvider` as a lightweight client-side cart functionality. Its not stored in any database or on the Medusa backend.
To use `SessionProvider`, you first have to insert it somewhere in your component tree below the `MedusaProvider`.

View File

@@ -1,19 +1,19 @@
---
description: 'Learn how to create a fulfillment provider in the Medusa server. This guide explains the different methods in the fulfillment provider.'
description: 'Learn how to create a fulfillment provider in the Medusa backend. This guide explains the different methods in the fulfillment provider.'
addHowToData: true
---
# How to Add a Fulfillment Provider
In this document, youll learn how to add a fulfillment provider to a Medusa server. If youre unfamiliar with the Shipping architecture in Medusa, make sure to [check out the overview first](overview.md).
In this document, youll learn how to add a fulfillment provider to a Medusa backend. If youre unfamiliar with the Shipping architecture in Medusa, make sure to [check out the overview first](../shipping.md).
## Overview
A fulfillment provider is the shipping provider used to fulfill orders and deliver them to customers. An example of a fulfillment provider is FedEx.
By default, a Medusa Server has a `manual` fulfillment provider which has minimal implementation. It allows you to accept orders and fulfill them manually. However, you can integrate any fulfillment provider into Medusa, and your fulfillment provider can interact with third-party shipping providers.
By default, a Medusa Backend has a `manual` fulfillment provider which has minimal implementation. It allows you to accept orders and fulfill them manually. However, you can integrate any fulfillment provider into Medusa, and your fulfillment provider can interact with third-party shipping providers.
Adding a fulfillment provider is as simple as creating one [service](../services/create-service.md) file in `src/services`. A fulfillment provider is essentially a service that extends the `FulfillmentService`. It requires implementing 4 methods:
Adding a fulfillment provider is as simple as creating one [service](../../../development/services/create-service.md) file in `src/services`. A fulfillment provider is essentially a service that extends the `FulfillmentService`. It requires implementing 4 methods:
1. `getFulfillmentOptions`: used to retrieve available fulfillment options provided by this fulfillment provider.
2. `validateOption`: used to validate the shipping option when its being created by the admin.
@@ -22,7 +22,7 @@ Adding a fulfillment provider is as simple as creating one [service](../services
Also, the fulfillment provider class should have a static property `identifier`. It is the name that will be used to install and refer to the fulfillment provider throughout Medusa.
Fulfillment providers are loaded and installed on the server startup.
Fulfillment providers are loaded and installed on the backend startup.
---
@@ -44,7 +44,7 @@ Fulfillment provider services must extend the `FulfillmentService` class importe
:::note
Following the naming convention of Services, the name of the file should be the slug name of the fulfillment provider, and the name of the class should be the camel case name of the fulfillment provider suffixed with “Service”. You can learn more in the [service documentation](../services/create-service.md).
Following the naming convention of Services, the name of the file should be the slug name of the fulfillment provider, and the name of the class should be the camel case name of the fulfillment provider suffixed with “Service”. You can learn more in the [service documentation](../../../development/services/create-service.md).
:::
@@ -54,7 +54,7 @@ As mentioned in the overview, fulfillment providers should have a static `identi
The `FulfillmentProvider` entity has 2 properties: `identifier` and `is_installed`. The `identifier` property in the class will be used when the fulfillment provider is created in the database.
The value of this property will also be used to reference the fulfillment provider throughout Medusa. For example, it is used to [add a fulfillment provider](https://docs.medusajs.com/api/admin/#tag/Region/operation/PostRegionsRegionFulfillmentProviders) to a region.
The value of this property will also be used to reference the fulfillment provider throughout Medusa. For example, it is used to [add a fulfillment provider](/api/admin/#tag/Region/operation/PostRegionsRegionFulfillmentProviders) to a region.
```ts
import { FulfillmentService } from "medusa-interfaces"
@@ -72,7 +72,7 @@ You can use the `constructor` of your fulfillment provider to have access to dif
You can also use the constructor to initialize your integration with the third-party provider. For example, if you use a client to connect to the third-party providers APIs, you can initialize it in the constructor and use it in other methods in the service.
Additionally, if youre creating your fulfillment provider as an external plugin to be installed on any Medusa server and you want to access the options added for the plugin, you can access it in the constructor. The options are passed as a second parameter.
Additionally, if youre creating your fulfillment provider as an external plugin to be installed on any Medusa backend and you want to access the options added for the plugin, you can access it in the constructor. The options are passed as a second parameter.
For example:
@@ -118,7 +118,7 @@ For that reason, the fulfillment option doesn't have any required structure and
### validateOption
Once the admin creates the shipping option, the data will be validated first using this method in the underlying fulfillment provider of that shipping option. This method is called when a `POST` request is sent to [`/admin/shipping-options`](https://docs.medusajs.com/api/admin/#tag/Shipping-Option/operation/PostShippingOptions).
Once the admin creates the shipping option, the data will be validated first using this method in the underlying fulfillment provider of that shipping option. This method is called when a `POST` request is sent to [`/admin/shipping-options`](/api/admin/#tag/Shipping-Option/operation/PostShippingOptions).
This method accepts the `data` object that is sent in the body of the request. You can use this data to validate the shipping option before it is saved.
@@ -141,7 +141,7 @@ If your fulfillment provider does not need to run any validation, you can simply
When the customer chooses a shipping option on checkout, the shipping option and its data are validated before the shipping method is created.
`validateFulfillmentOption` is called when a `POST` request is sent to [`/carts/:id/shipping-methods`](https://docs.medusajs.com/api/store/#tag/Cart/operation/PostCartsCartShippingMethod).
`validateFulfillmentOption` is called when a `POST` request is sent to [`/carts/:id/shipping-methods`](/api/store/#tag/Cart/operation/PostCartsCartShippingMethod).
This method accepts three parameters:
@@ -221,7 +221,7 @@ If this method returns `true`, that means that the price should be calculated dy
If the method returns `false`, an error is thrown as it means the selected shipping option can only be chosen if the price type is set to `flat_rate`.
This method receives as a parameter the `data` object sent with the request that [creates the shipping option.](https://docs.medusajs.com/api/admin/#tag/Shipping-Option/operation/PostShippingOptions) You can use this data to determine whether the shipping option should be calculated or not. This is useful if the fulfillment provider you are integrating has both flat rate and dynamically priced fulfillment options.
This method receives as a parameter the `data` object sent with the request that [creates the shipping option.](/api/admin/#tag/Shipping-Option/operation/PostShippingOptions) You can use this data to determine whether the shipping option should be calculated or not. This is useful if the fulfillment provider you are integrating has both flat rate and dynamically priced fulfillment options.
For example:
@@ -241,7 +241,7 @@ This method is called on checkout when the shipping method is being created if t
This method receives three parameters:
1. The `data` parameter of the selected shipping option.
2. The `data` parameter sent with [the request](https://docs.medusajs.com/api/store/#tag/Cart/operation/PostCartsCartShippingMethod).
2. The `data` parameter sent with [the request](/api/store/#tag/Cart/operation/PostCartsCartShippingMethod).
3. The customers cart data.
If your fulfillment provider does not provide any dynamically calculated rates you can keep the function empty:
@@ -270,7 +270,7 @@ class MyFulfillmentService extends FulfillmentService {
Fulfillment providers can also be used to return products. A shipping option can be used for returns if the `is_return` property is `true` or if an admin creates a Return Shipping Option from the settings.
This method is called when the admin [creates a return request](https://docs.medusajs.com/api/admin/#tag/Order/operation/PostOrdersOrderReturns) for an order or when the customer [creates a return of their order](https://docs.medusajs.com/api/store/#tag/Return/operation/PostReturns).
This method is called when the admin [creates a return request](/api/admin/#tag/Order/operation/PostOrdersOrderReturns) for an order or when the customer [creates a return of their order](/api/store/#tag/Return/operation/PostReturns).
It gives you access to the return being created in case you need to perform any additional actions with the third-party provider.

View File

@@ -1,11 +1,11 @@
---
description: 'Learn how to create a payment provider in the Medusa server. This guide explains the different methods available in a fulfillment provider.'
description: 'Learn how to create a payment provider in the Medusa backend. This guide explains the different methods available in a fulfillment provider.'
addHowToData: true
---
# How to Create a Payment Provider
In this document, youll learn how to add a Payment Provider to your Medusa server. If youre unfamiliar with the Payment architecture in Medusa, make sure to check out the [overview](./overview.md) first.
In this document, youll learn how to add a Payment Provider to your Medusa backend. If youre unfamiliar with the Payment architecture in Medusa, make sure to check out the [overview](../payment.md) first.
## Overview
@@ -13,13 +13,13 @@ A Payment Provider is the payment method used to authorize, capture, and refund
By default, Medusa has a [manual payment provider](https://github.com/medusajs/medusa/tree/master/packages/medusa-payment-manual) that has minimal implementation. It can be synonymous with a Cash on Delivery payment method. It allows store operators to manage the payment themselves but still keep track of its different stages on Medusa.
Adding a Payment Provider is as simple as creating a [service](../services/create-service.md) file in `src/services`. A Payment Provider is essentially a service that extends `AbstractPaymentService` from the core Medusa package `@medusajs/medusa`.
Adding a Payment Provider is as simple as creating a [service](../../../development/services/create-service.md) file in `src/services`. A Payment Provider is essentially a service that extends `AbstractPaymentService` from the core Medusa package `@medusajs/medusa`.
Payment Provider Services must have a static property `identifier`. It's the name that will be used to install and refer to the Payment Provider in the Medusa server.
Payment Provider Services must have a static property `identifier`. It's the name that will be used to install and refer to the Payment Provider in the Medusa backend.
:::tip
Payment Providers are loaded and installed at the server startup.
Payment Providers are loaded and installed at the backend startup.
:::
@@ -29,7 +29,7 @@ The Payment Provider service is also required to implement the following methods
2. `retrievePayment`: Used to retrieve payment data from the third-party provider, if theres any.
3. `getStatus`: Used to get the status of a Payment or Payment Session.
4. `updatePayment`: Used to update the Payment Session whenever the cart and its related data are updated.
5. `updatePaymentData`: Used to update the `data` field of Payment Sessions. Specifically called when a request is sent to the [Update Payment Session](https://docs.medusajs.com/api/store/#tag/Cart/operation/PostCartsCartPaymentSessionUpdate) endpoint.
5. `updatePaymentData`: Used to update the `data` field of Payment Sessions. Specifically called when a request is sent to the [Update Payment Session](/api/store/#tag/Cart/operation/PostCartsCartPaymentSessionUpdate) endpoint.
6. `deletePayment`: Used to perform any action necessary before a Payment Session is deleted.
7. `authorizePayment`: Used to authorize the payment amount of the cart before the order or swap is created.
8. `getPaymentData`: Used to retrieve the data that should be stored in the `data` field of a new Payment instance after the payment amount has been authorized.
@@ -45,7 +45,7 @@ All these methods must be declared async in the Payment Provider Service.
These methods are used at different points in the Checkout flow as well as when processing the order after its placed.
![Checkout Flow - Payment](https://res.cloudinary.com/dza7lstvk/image/upload/v1668001750/Medusa%20Docs/Diagrams/WeDr0ph_idcrir.jpg)
![Checkout Flow - Payment](https://res.cloudinary.com/dza7lstvk/image/upload/v1677770739/Medusa%20Docs/Diagrams/checkout-payment_rouet2.png)
---
@@ -68,7 +68,9 @@ class MyPaymentService extends AbstractPaymentService {
protected manager_: EntityManager
protected transactionManager_: EntityManager | undefined
async getPaymentData(paymentSession: PaymentSession): Promise<Data> {
async getPaymentData(
paymentSession: PaymentSession
): Promise<Data> {
throw new Error("Method not implemented.")
}
async updatePaymentData(
@@ -94,7 +96,10 @@ class MyPaymentService extends AbstractPaymentService {
async authorizePayment(
paymentSession: PaymentSession,
context: Data
): Promise<{ data: PaymentSessionData; status: PaymentSessionStatus }> {
): Promise<{
data: PaymentSessionData;
status: PaymentSessionStatus
}> {
throw new Error("Method not implemented.")
}
async capturePayment(payment: Payment): Promise<PaymentData> {
@@ -109,7 +114,9 @@ class MyPaymentService extends AbstractPaymentService {
async cancelPayment(payment: Payment): Promise<PaymentData> {
throw new Error("Method not implemented.")
}
async deletePayment(paymentSession: PaymentSession): Promise<void> {
async deletePayment(
paymentSession: PaymentSession
): Promise<void> {
throw new Error("Method not implemented.")
}
async getStatus(data: Data): Promise<PaymentSessionStatus> {
@@ -127,7 +134,7 @@ Payment Providers must extend `AbstractPaymentService` from the core Medusa pack
:::tip
Following the naming convention of Services, the name of the file should be the slug name of the Payment Provider, and the name of the class should be the camel case name of the Payment Provider suffixed with “Service”. In the example above, the name of the file should be `my-payment.js`. You can learn more in the [service documentation](../services/create-service.md).
Following the naming convention of Services, the name of the file should be the slug name of the Payment Provider, and the name of the class should be the camel case name of the Payment Provider suffixed with “Service”. In the example above, the name of the file should be `my-payment.js`. You can learn more in the [service documentation](../../../development/services/create-service.md).
:::
@@ -137,7 +144,7 @@ As mentioned in the overview, Payment Providers should have a static `identifie
The `PaymentProvider` entity has 2 properties: `identifier` and `is_installed`. The value of the `identifier` property in the class will be used when the Payment Provider is created in the database.
The value of this property will also be used to reference the Payment Provider throughout the Medusa server. For example, the identifier is used when a [Payment Session in a cart is selected on checkout](https://docs.medusajs.com/api/store/#tag/Cart/operation/PostCartsCartPaymentSession).
The value of this property will also be used to reference the Payment Provider throughout the Medusa backend. For example, the identifier is used when a [Payment Session in a cart is selected on checkout](/api/store/#tag/Cart/operation/PostCartsCartPaymentSession).
### constructor
@@ -145,7 +152,7 @@ You can use the `constructor` of your Payment Provider to have access to diffe
You can also use the constructor to initialize your integration with the third-party provider. For example, if you use a client to connect to the third-party providers APIs, you can initialize it in the constructor and use it in other methods in the service.
Additionally, if youre creating your Payment Provider as an external plugin to be installed on any Medusa server and you want to access the options added for the plugin, you can access it in the constructor. The options are passed as a second parameter:
Additionally, if youre creating your Payment Provider as an external plugin to be installed on any Medusa backend and you want to access the options added for the plugin, you can access it in the constructor. The options are passed as a second parameter:
```ts
class MyPaymentService extends AbstractPaymentService {
@@ -160,7 +167,7 @@ class MyPaymentService extends AbstractPaymentService {
### createPayment
This method is called during checkout when [Payment Sessions are initialized](https://docs.medusajs.com/api/store/#tag/Cart/operation/PostCartsCartPaymentSessions) to present payment options to the customer. It is used to allow you to make any necessary calls to the third-party provider to initialize the payment.
This method is called during checkout when [Payment Sessions are initialized](/api/store/#tag/Cart/operation/PostCartsCartPaymentSessions) to present payment options to the customer. It is used to allow you to make any necessary calls to the third-party provider to initialize the payment.
For example, in Stripe this method is used to initialize a Payment Intent for the customer.
@@ -192,20 +199,25 @@ This method must return an object of type `PaymentSessionResponse`. It should ha
```ts
type PaymentSessionResponse = {
update_requests: { customer_metadata: Record<string, unknown> }
update_requests: {
customer_metadata: Record<string, unknown>
}
session_data: Record<string, unknown>
}
```
Where:
- `session_data` is the data that is going to be stored in the `data` field of the Payment Session to be created. As mentioned in the [Architecture Overview](./overview.md), the `data` field is useful to hold any data required by the third-party provider to process the payment or retrieve its details at a later point.
- `session_data` is the data that is going to be stored in the `data` field of the Payment Session to be created. As mentioned in the [Architecture Overview](../payment.md), the `data` field is useful to hold any data required by the third-party provider to process the payment or retrieve its details at a later point.
- `update_requests` is an object that can be used to pass data from the payment provider plugin to the core to update internal resources. Currently, it only has one attribute `customer_metadata` which allows updating the `metadata` field of the customer.
An example of a minimal implementation of `createPayment`:
```ts
import { PaymentContext, PaymentSessionResponse } from "@medusajs/medusa"
import {
PaymentContext,
PaymentSessionResponse,
} from "@medusajs/medusa"
class MyPaymentService extends AbstractPaymentService {
// ...
@@ -281,7 +293,7 @@ This code block assumes the status is stored in the `data` field as demonstrated
### updatePayment
This method is used to perform any necessary updates on the payment. This method is called whenever the cart or any of its related data is updated. For example, when a [line item is added to the cart](https://docs.medusajs.com/api/store/#tag/Cart/operation/PostCartsCartLineItems) or when a [shipping method is selected](https://docs.medusajs.com/api/store/#tag/Cart/operation/PostCartsCartShippingMethod).
This method is used to perform any necessary updates on the payment. This method is called whenever the cart or any of its related data is updated. For example, when a [line item is added to the cart](/api/store/#tag/Cart/operation/PostCartsCartLineItems) or when a [shipping method is selected](/api/store/#tag/Cart/operation/PostCartsCartShippingMethod).
:::tip
@@ -319,14 +331,16 @@ This method must return an object of type `PaymentSessionResponse`. It should ha
```ts
type PaymentSessionResponse = {
update_requests: { customer_metadata: Record<string, unknown> }
update_requests: {
customer_metadata: Record<string, unknown>
}
session_data: Record<string, unknown>
}
```
Where:
- `session_data` is the data that is going to be stored in the `data` field of the Payment Session to be created. As mentioned in the [Architecture Overview](./overview.md), the `data` field is useful to hold any data required by the third-party provider to process the payment or retrieve its details at a later point.
- `session_data` is the data that is going to be stored in the `data` field of the Payment Session to be created. As mentioned in the [Architecture Overview](../payment.md), the `data` field is useful to hold any data required by the third-party provider to process the payment or retrieve its details at a later point.
- `update_requests` is an object that can be used to request from the Medusa core to update internal resources. Currently, it only has one attribute `customer_metadata` which allows updating the `metadata` field of the customer.
An example of a minimal implementation of `updatePayment`:
@@ -357,7 +371,7 @@ class MyPaymentService extends AbstractPaymentService {
### updatePaymentData
This method is used to update the `data` field of a Payment Session. Particularly, it is called when a request is sent to the [Update Payment Session](https://docs.medusajs.com/api/store/#tag/Cart/operation/PostCartsCartPaymentSessionUpdate) endpoint. This endpoint receives a `data` object in the body of the request that should be used to update the existing `data` field of the Payment Session.
This method is used to update the `data` field of a Payment Session. Particularly, it is called when a request is sent to the [Update Payment Session](/api/store/#tag/Cart/operation/PostCartsCartPaymentSessionUpdate) endpoint. This endpoint receives a `data` object in the body of the request that should be used to update the existing `data` field of the Payment Session.
This method accepts the current `data` field of the Payment Session as the first parameter, and the new `data` field sent in the body request as the second parameter.
@@ -386,8 +400,8 @@ class MyPaymentService extends AbstractPaymentService {
This method is used to perform any actions necessary before a Payment Session is deleted. The Payment Session is deleted in one of the following cases:
1. When a request is sent to [delete the Payment Session](https://docs.medusajs.com/api/store/#tag/Cart/operation/DeleteCartsCartPaymentSessionsSession).
2. When the [Payment Session is refreshed](https://docs.medusajs.com/api/store/#tag/Cart/operation/PostCartsCartPaymentSessionsSession). The Payment Session is deleted so that a newer one is initialized instead.
1. When a request is sent to [delete the Payment Session](/api/store/#tag/Cart/operation/DeleteCartsCartPaymentSessionsSession).
2. When the [Payment Session is refreshed](/api/store/#tag/Cart/operation/PostCartsCartPaymentSessionsSession). The Payment Session is deleted so that a newer one is initialized instead.
3. When the Payment Provider is no longer available. This generally happens when the store operator removes it from the available Payment Provider in the admin.
4. When the region of the store is changed based on the cart information and the Payment Provider is not available in the new region.
@@ -403,7 +417,9 @@ import { PaymentSession } from "@medusajs/medusa"
class MyPaymentService extends AbstractPaymentService {
// ...
async deletePayment(paymentSession: PaymentSession): Promise<void> {
async deletePayment(
paymentSession: PaymentSession
): Promise<void> {
return
}
}
@@ -411,7 +427,7 @@ class MyPaymentService extends AbstractPaymentService {
### authorizePayment
This method is used to authorize payment using the Payment Session for an order. This is called when the [cart is completed](https://docs.medusajs.com/api/store/#tag/Cart/operation/PostCartsCartComplete) and before the order is created.
This method is used to authorize payment using the Payment Session for an order. This is called when the [cart is completed](/api/store/#tag/Cart/operation/PostCartsCartComplete) and before the order is created.
This method is also used for authorizing payments of a swap of an order.
@@ -430,7 +446,7 @@ The payment authorization status is determined using the `getStatus` method as m
This method accepts the Payment Session as an object for its first parameter, and a `context` object as a second parameter. The `context` object contains the following properties:
1. `ip`: The customers IP.
2. `idempotency_key`: The [Idempotency Key](./overview.md#idempotency-key) that is associated with the current cart. It is useful when retrying payments, retrying checkout at a failed point, or for payments that require additional actions from the customer.
2. `idempotency_key`: The [Idempotency Key](../payment.md#idempotency-key) that is associated with the current cart. It is useful when retrying payments, retrying checkout at a failed point, or for payments that require additional actions from the customer.
This method must return an object containing the property `status` which is a string that indicates the current status of the payment, and the property `data` which is an object containing any additional information required to perform additional payment processing such as capturing the payment. The values of both of these properties are stored in the Payment Sessions `status` and `data` fields respectively.
@@ -452,7 +468,10 @@ class MyPaymentService extends AbstractPaymentService {
async authorizePayment(
paymentSession: PaymentSession,
context: Data
): Promise<{ data: PaymentSessionData; status: PaymentSessionStatus }> {
): Promise<{
data: PaymentSessionData;
status: PaymentSessionStatus
}> {
return {
status: PaymentSessionStatus.AUTHORIZED,
data: {
@@ -479,7 +498,9 @@ import { Data, PaymentSession } from "@medusajs/medusa"
class MyPaymentService extends AbstractPaymentService {
// ...
async getPaymentData(paymentSession: PaymentSession): Promise<Data> {
async getPaymentData(
paymentSession: PaymentSession
): Promise<Data> {
return paymentSession.data
}
}
@@ -583,7 +604,7 @@ class MyPaymentService extends AbstractPaymentService {
This method can be added to your Payment Provider service if your third-party provider supports saving the customers payment methods. Please note that in Medusa there is no way to save payment methods.
This method is called when a request is sent to [Retrieve Saved Payment Methods](https://docs.medusajs.com/api/store/#tag/Customer/operation/GetCustomersCustomerPaymentMethods).
This method is called when a request is sent to [Retrieve Saved Payment Methods](/api/store/#tag/Customer/operation/GetCustomersCustomerPaymentMethods).
This method accepts the customer as an object for its first parameter.
@@ -591,7 +612,7 @@ This method returns an array of saved payment methods retrieved from the third-p
:::note
If youre using Medusas [Next.js](../../../starters/nextjs-medusa-starter.mdx) or [Gatsby](../../../starters/gatsby-medusa-starter.mdx) storefront starters, note that the presentation of this method is not implemented. Youll need to implement the UI and pages for this method based on your implementation and the provider you are using.
If youre using Medusas [Next.js](../../../starters/nextjs-medusa-starter.mdx) storefront starter, note that the presentation of this method is not implemented. Youll need to implement the UI and pages for this method based on your implementation and the provider you are using.
:::
@@ -604,11 +625,14 @@ import { Customer, Data } from "@medusajs/medusa"
class MyPaymentService extends AbstractPaymentService {
// ...
/**
* Fetches a customers saved payment methods if registered in Stripe.
* Fetches a customers saved payment methods
* if they're saved in Stripe.
* @param {object} customer - customer to fetch saved cards for
* @return {Promise<Array<object>>} saved payments methods
*/
async retrieveSavedMethods(customer: Customer): Promise<Data[]> {
async retrieveSavedMethods(
customer: Customer
): Promise<Data[]> {
if (customer.metadata && customer.metadata.stripe_id) {
const methods = await this.stripe_.paymentMethods.list({
customer: customer.metadata.stripe_id,
@@ -628,4 +652,3 @@ class MyPaymentService extends AbstractPaymentService {
## See Also
- Implementation Examples: [Stripe](https://github.com/medusajs/medusa/tree/2e6622ec5d0ae19d1782e583e099000f0a93b051/packages/medusa-payment-stripe) and [PayPal](https://github.com/medusajs/medusa/tree/2e6622ec5d0ae19d1782e583e099000f0a93b051/packages/medusa-payment-paypal) payment providers.
- [Implement checkout flow on the storefront](./../../storefront/how-to-implement-checkout-flow.mdx).

View File

@@ -0,0 +1,172 @@
---
description: "A cart is a virtual shopping basket that customers can use to pick products they want to purchase. Learn about the available features and guides."
---
import DocCardList from '@theme/DocCardList';
import Icons from '@theme/Icon';
# Carts and Checkout
A cart is a virtual shopping basket that customers can use to pick products they want to purchase. Checkout is the process of the customer placing an order. This overview introduces the available features related to carts and checkout.
## Features
### Cart Management
Customers can manage their cart including adding, updating, and removing items from the cart.
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/modules/carts-and-checkout/storefront/implement-cart',
label: 'Storefront: Implement Cart',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to implement cart functionality in a storefront.'
}
},
{
type: 'link',
href: '/api/store/#tag/Cart',
label: 'Storefront APIs: Carts',
customProps: {
icon: Icons['server-solid'],
description: 'Check available Store REST APIs for Carts.'
}
},
]} />
### Shipping and Payment
Developers can integrate any third-party provider or custom logic to offer shipping and payment options for customers during checkout. They can integrate them using existing plugins or by creating their own.
Admins can specify available shipping and payment providers during checkout for customers based on their [Region](../regions-and-currencies/overview.mdx).
<DocCardList colSize={4} items={[
{
type: 'link',
href: '/modules/carts-and-checkout/backend/add-fulfillment-provider',
label: 'Backend: Create Fulfillment Provider',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create a fulfillment provider in the backend.'
}
},
{
type: 'link',
href: '/modules/carts-and-checkout/backend/add-payment-provider',
label: 'Backend: Create Payment Provider',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create a fulfillment provider in the backend.'
}
},
{
type: 'link',
href: '/user-guide/regions/providers',
label: 'User Guide: Manage Providers',
customProps: {
icon: Icons['users-solid'],
description: 'Learn how to manage available providers using Medusa Admin.'
}
},
]} />
### Checkout Flow
Developers can implement a seamless checkout flow that include steps related to shipping and payment, tax calculation, and more.
Customers can place orders using the checkout flow.
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/modules/carts-and-checkout/storefront/implement-checkout-flow',
label: 'Storefront: Implement Checkout',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to implement the checkout flow in a storefront.'
}
},
{
type: 'link',
href: '/api/store/#tag/Cart',
label: 'Storefront APIs: Cart',
customProps: {
icon: Icons['server-solid'],
description: 'Check available Store REST APIs for Carts related to checkout.'
}
},
]} />
---
## Understand the Architecture
Learn how cart-related entities are build, their relation to other modules, and more.
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/modules/carts-and-checkout/shipping',
label: 'Architecture: Shipping',
customProps: {
icon: Icons['circle-stack-solid'],
description: 'Learn about the Shipping architecture.'
}
},
{
type: 'link',
href: '/modules/carts-and-checkout/payment',
label: 'Architecture: Payment',
customProps: {
icon: Icons['circle-stack-solid'],
description: 'Learn about the Payment architecture.'
}
},
]} />
---
## Related Modules
Discover Carts and Checkouts relation to other modules in Medusa
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/modules/products/overview',
label: 'Products',
customProps: {
icon: Icons['tag-solid'],
description: 'Customers can add products to cart and purchase them.'
}
},
{
type: 'link',
href: '/modules/taxes/overview',
label: 'Taxes',
customProps: {
icon: Icons['cash-solid'],
description: 'Taxes can be calculated for a cart either automatically or manually.',
}
},
{
type: 'link',
href: '/modules/discounts/overview',
label: 'Discounts',
customProps: {
icon: Icons['currency-dollar-solid'],
description: 'Discounts can be applied on a cart to reduce its total.',
}
},
{
type: 'link',
href: '/modules/gift-cards/overview',
label: 'Gift Cards',
customProps: {
icon: Icons['gift-solid'],
description: 'Purchased gift cards can be applied during checkout.'
}
},
]} />

View File

@@ -1,5 +1,5 @@
---
description: 'Learn about the payment architecture in the Medusa server. The payment architecture refers to all operations in the ecommerce store related to processing payments.'
description: 'Learn about the payment architecture in the Medusa backend. The payment architecture refers to all operations in the ecommerce store related to processing payments.'
---
# Payment Architecture Overview
@@ -30,13 +30,13 @@ Payment Providers can also be related to a custom way of handling payment operat
### How Payment Provider is Created
A Payment Provider is essentially a Medusa [service](../services/create-service.md) with a unique identifier, and it extends the ``AbstractPaymentService` from the core Medusa package `@medusajs/medusa`. It can be created as part of a [plugin](../plugins/overview.md), or it can be created just as a service file in your Medusa server.
A Payment Provider is essentially a Medusa [service](../../development/services/create-service.md) with a unique identifier, and it extends the ``AbstractPaymentService` from the core Medusa package `@medusajs/medusa`. It can be created as part of a [plugin](../../development/plugins/overview.mdx), or it can be created just as a service file in your Medusa backend.
As a developer, you will mainly work with the Payment Provider when integrating a payment method in Medusa.
When you run your Medusa server, the Payment Provider will be registered on your server if it hasnt been already.
When you run your Medusa backend, the Payment Provider will be registered on your backend if it hasnt been already.
Once the Payment Provider is added to the server, the store operator will be able to choose on the [Medusa Admin](../../../admin/quickstart.mdx) the payment providers available in a region. These payment providers are shown to the customer at checkout to choose from and use.
Once the Payment Provider is added to the backend, the store operator will be able to choose on the [Medusa Admin](../../admin/quickstart.mdx) the payment providers available in a region. These payment providers are shown to the customer at checkout to choose from and use.
:::caution
@@ -46,7 +46,7 @@ Its important to choose a payment provider in the list of payment providers i
### PaymentProvider Entity Overview
The [`PaymentProvider`](../../../references/entities/classes/PaymentProvider.md) entity only has 2 attributes: `is_installed` to indicate if the payment provider is installed and its value is a boolean; and `id` which is the unique identifier that you define in the Payment Provider service.
The [`PaymentProvider`](../../references/entities/classes/PaymentProvider.md) entity only has 2 attributes: `is_installed` to indicate if the payment provider is installed and its value is a boolean; and `id` which is the unique identifier that you define in the Payment Provider service.
---
@@ -70,7 +70,7 @@ Among the Payment Sessions available only one will be selected based on the cust
### PaymentSession Entity Overview
The [`PaymentSession`](../../../references/entities/classes/PaymentSession.md) entity belongs to a `Cart`. This is the customers cart that was used for checkout which lead to the creation of the Payment Session.
The [`PaymentSession`](../../references/entities/classes/PaymentSession.md) entity belongs to a `Cart`. This is the customers cart that was used for checkout which lead to the creation of the Payment Session.
The `PaymentSession` also belongs to a `PaymentProvider`. This is the Payment Provider that was used to create the Payment Session and that controls it for further actions like authorizing the payment.
@@ -104,7 +104,7 @@ When the store operator then chooses to capture the order from the Medusa Admin,
### Payment Entity Overview
The [`Payment`](../../../references/entities/classes/Payment.md) entity belongs to the `Cart` that it was originally created from when the customers payment was authorized. It also belongs to an `Order` once its placed. Additionally, it belongs to a `PaymentProvider` which is the payment provider that the customer chose on checkout.
The [`Payment`](../../references/entities/classes/Payment.md) entity belongs to the `Cart` that it was originally created from when the customers payment was authorized. It also belongs to an `Order` once its placed. Additionally, it belongs to a `PaymentProvider` which is the payment provider that the customer chose on checkout.
In case a `Swap` is created for an order, `Payment` will be associated with that swap to handle payment operations related to it.
@@ -124,7 +124,7 @@ That Idempotency Key is then set in the header under the `Idempotency-Key` respo
If an error occurs or the purchase is interrupted at any step, the client can retry the payment by adding the Idempotency Key of the cart as the `Idempotency-Key` header field in their subsequent requests.
The server wraps each essential part of the checkout completion in its own step and stores the current step of checkout with its associated Idempotency Key.
The backend wraps each essential part of the checkout completion in its own step and stores the current step of checkout with its associated Idempotency Key.
If then the request is interrupted for any reason or the payment fails, the client can retry completing the check out using the Idempotency Key, and the flow will continue from the last stored step.
@@ -134,5 +134,5 @@ This prevents any payment issues from occurring with the customers and allows fo
## See Also
- [Create a Payment Provider](./how-to-create-payment-provider.md)
- [Implement the checkout flow in the storefront](./../../storefront/how-to-implement-checkout-flow.mdx)
- [Available Payment Plugins](../../plugins/payment/index.mdx)
- [Create a Payment Provider](./backend/add-payment-provider.md)

View File

@@ -1,5 +1,5 @@
---
description: 'Learn how the shipping architecture is implemented in the Medusa server. This includes an overview of what the Fulfillment Provider, Shipping Profile, Shipping Option, and Shipping Methods.'
description: 'Learn how the shipping architecture is implemented in the Medusa backend. This includes an overview of what the Fulfillment Provider, Shipping Profile, Shipping Option, and Shipping Methods.'
---
# Shipping Architecture Overview
@@ -18,12 +18,12 @@ Its also constructed to support multiple regions, provide different shipment
## Summary
- **Fulfillment Provider:** Fulfillment providers are plugins or [Services](../services/create-service.md) used to ship the products to your customers, whether physically or virtually. An example of a fulfillment provider would be FedEx.
- **Fulfillment Provider:** Fulfillment providers are plugins or [Services](../../development/services/create-service.md) used to ship the products to your customers, whether physically or virtually. An example of a fulfillment provider would be FedEx.
- **Shipping Profiles:** created by the admin. They are used to group products that should be shipped in a different manner than the default. Shipping profiles can have multiple shipping options.
- **Shipping Options:** created by the admin and belong to a shipping profile. They are specific to certain regions and can have cart conditions. They use an underlying fulfillment provider. Once a customer checks out, they can choose the shipping option thats available and most relevant to them.
- **Shipping Method:** created when the customer chooses a shipping option on checkout. The shipping method is basically a copy of the shipping option, but with values specific to the customer and the cart its associated with. When the order is placed, the shipping method will then be associated with the order and fulfilled based on the integration with the fulfillment provider.
![Shipping Architecture](https://res.cloudinary.com/dza7lstvk/image/upload/v1668001762/Medusa%20Docs/Diagrams/QII2Hvn_vjkrdy.png)
![Shipping Architecture](https://res.cloudinary.com/dza7lstvk/image/upload/v1677698747/Medusa%20Docs/Diagrams/shipping-architecture_oszxhj.jpg)
---
@@ -39,17 +39,17 @@ Fulfillment Providers can also be related to a custom way of handling fulfillmen
### How Fulfillment Provider is Created
A Fulfillment Provider is essentially a Medusa [Service](../services/create-service.md) with a unique identifier, and it extends the `FulfillmentService` provided by the `medusa-interfaces` package. It can be created as part of a [plugin](../plugins/overview.md), or it can be created just as a Service file in your Medusa server.
A Fulfillment Provider is essentially a Medusa [Service](../../development/services/create-service.md) with a unique identifier, and it extends the `FulfillmentService` provided by the `medusa-interfaces` package. It can be created as part of a [plugin](../../development/plugins/overview.mdx), or it can be created just as a Service file in your Medusa backend.
As a developer, you will mainly work with the Fulfillment Provider when integrating a fulfillment method in Medusa.
When you run your Medusa server, the Fulfillment Provider will be registered on your server if it hasnt been already.
When you run your Medusa backend, the Fulfillment Provider will be registered on your backend if it hasnt been already.
Once the Fulfillment Provider is added to the server, the store operator will be able to associate on the [Medusa Admin](../../../quickstart/quick-start.mdx) the Fulfillment Provider with shipping options.
Once the Fulfillment Provider is added to the backend, the store operator will be able to associate on the [Medusa Admin](../../development/backend/install.mdx) the Fulfillment Provider with shipping options.
### FulfillmentProvider Entity Overview
The [`FulfillmentProvider`](../../../references/entities/classes/FulfillmentProvider.md) entity only has 2 attributes: `is_installed` to indicate if the fulfillment provider is installed and its value is a boolean; and `id` which is the unique identifier that you define in the Fulfillment Provider Service.
The [`FulfillmentProvider`](../../references/entities/classes/FulfillmentProvider.md) entity only has 2 attributes: `is_installed` to indicate if the fulfillment provider is installed and its value is a boolean; and `id` which is the unique identifier that you define in the Fulfillment Provider Service.
---
@@ -73,7 +73,7 @@ For example, shipping heavy items might be more expensive than others, which wou
### ShippingProfile Entity Overview
The [`ShippingProfile`](../../../references/entities/classes/ShippingProfile.md) entity can have a set of `Product` instances. These would be the products the shipping profile is providing shipping options for.
The [`ShippingProfile`](../../references/entities/classes/ShippingProfile.md) entity can have a set of `Product` instances. These would be the products the shipping profile is providing shipping options for.
The `ShippingProfile` has a `type` attribute that can be `default`, `gift_card`, or `custom`.
@@ -101,7 +101,7 @@ Think of a shipping option as a template defined by the admin that indicates wha
### ShippingOption Entity Overview
The [`ShippingOption`](../../../references/entities/classes/ShippingOption.md) entity belongs to the `ShippingProfile` entity.
The [`ShippingOption`](../../references/entities/classes/ShippingOption.md) entity belongs to the `ShippingProfile` entity.
The `ShippingOption` entity also belongs to a `FulfillmentProvider`. This can be either a custom third-party provider or one of Medusas default fulfillment providers.
@@ -139,7 +139,7 @@ This separation allows for developers to implement the custom integration with t
A lot of the shipping methods attributes are similar to the shipping options attribute.
The [`ShippingMethod`](../../../references/entities/classes/ShippingMethod.md) entity belongs to a `ShippingOption`.
The [`ShippingMethod`](../../references/entities/classes/ShippingMethod.md) entity belongs to a `ShippingOption`.
Similar to the `data` attribute explained for the `ShippingOption` entity, a `ShippingMethod` has a similar `data` attribute that includes all the data to be sent to the fulfillment provider when fulfilling the order.
@@ -153,5 +153,5 @@ The `ShippingMethod` instance holds a `price` attribute, which will either b
## See Also
- [Create a Fulfillment Provider](./add-fulfillment-provider.md)
- [Create a Fulfillment Provider](./backend/add-fulfillment-provider.md)
- [Available shipping plugins](https://github.com/medusajs/medusa/tree/master/packages)

View File

@@ -18,7 +18,7 @@ This document helps you understand how to add the cart functionality to your sto
:::note
This document does not cover implementing the checkout flow. You can refer to [this documentation instead to learn how to implement the checkout flow](../advanced/storefront/how-to-implement-checkout-flow.mdx).
This document does not cover implementing the checkout flow. You can refer to [this documentation instead to learn how to implement the checkout flow](./implement-checkout-flow.mdx).
:::
@@ -28,23 +28,23 @@ This document does not cover implementing the checkout flow. You can refer to [t
### Medusa Components
It's assumed that you already have a Medusa server installed and set up. If not, you can follow our [quickstart guide](../quickstart/quick-start.mdx) to get started.
It's assumed that you already have a Medusa backend installed and set up. If not, you can follow our [quickstart guide](../../../development/backend/install.mdx) to get started.
It is also assumed you already have a storefront set up. It can be a custom storefront or one of Medusas storefronts. If you dont have a storefront set up, you can install either the [Next.js](../starters/nextjs-medusa-starter.mdx) or [Gatsby](../starters/gatsby-medusa-starter.mdx) storefronts.
It is also assumed you already have a storefront set up. It can be a custom storefront or one of Medusas storefronts. If you dont have a storefront set up, you can install the [Next.js starter storefront](../../../starters/nextjs-medusa-starter.mdx).
### JS Client
This guide includes code snippets to send requests to your Medusa server using Medusas JS Client, among other methods.
This guide includes code snippets to send requests to your Medusa backend using Medusas JS Client, among other methods.
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client installed](../js-client/overview.md) and have [created an instance of the client](../js-client/overview.md#configuration).
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client installed](../../../js-client/overview.md) and have [created an instance of the client](../../../js-client/overview.md#configuration).
### Medusa React
This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods.
This guide also includes code snippets to send requests to your Medusa backend using Medusa React, among other methods.
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../medusa-react/overview.md#usage).
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../../medusa-react/overview.md#usage).
It's also assumed you already have [used CartProvider higher in your component tree](../medusa-react/overview.md#cartprovider).
It's also assumed you already have [used CartProvider higher in your component tree](../../../medusa-react/overview.md#cartprovider).
---
@@ -77,7 +77,9 @@ const Cart = () => {
createCart.mutate(
{}, // create an empty cart
{
onSuccess: ({ cart }) => localStorage.setItem("cart_id", cart.id),
onSuccess: ({ cart }) => {
localStorage.setItem("cart_id", cart.id)
},
}
)
}
@@ -92,7 +94,7 @@ export default Cart
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/carts`, {
fetch(`<BACKEND_URLL>/store/carts`, {
method: "POST",
credentials: "include",
})
@@ -142,7 +144,9 @@ const Cart = () => {
region_id,
},
{
onSuccess: ({ cart }) => localStorage.setItem("cart_id", cart.id),
onSuccess: ({ cart }) => {
localStorage.setItem("cart_id", cart.id)
},
}
)
}
@@ -157,7 +161,7 @@ export default Cart
<TabItem value="fetch" label="Fetch API">
```jsx
fetch(`<SERVER_URL>/store/carts`, {
fetch(`<BACKEND_URLL>/store/carts`, {
method: "POST",
credentials: "include",
headers: {
@@ -178,7 +182,7 @@ fetch(`<SERVER_URL>/store/carts`, {
</TabItem>
</Tabs>
Check out the [API Reference](https://docs.medusajs.com/api/store/#tag/Cart/operation/PostCart) for a full list of available request body parameters.
Check out the [API Reference](/api/store/#tag/Cart/operation/PostCart) for a full list of available request body parameters.
:::note
@@ -228,7 +232,7 @@ export default Cart
const id = localStorage.getItem("cart_id")
if (id) {
fetch(`<SERVER_URL>/store/carts/${id}`, {
fetch(`<BACKEND_URLL>/store/carts/${id}`, {
credentials: "include",
})
.then((response) => response.json())
@@ -241,7 +245,7 @@ if (id) {
This request accepts the ID of the cart as a path parameter and returns the cart of that ID.
You can run this code snippet every time the storefront is opened. If a customer has a cart ID stored in their local storage, its loaded from the server.
You can run this code snippet every time the storefront is opened. If a customer has a cart ID stored in their local storage, its loaded from the backend.
:::tip
@@ -294,7 +298,7 @@ export default Cart
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/carts/${cartId}`, {
fetch(`<BACKEND_URLL>/store/carts/${cartId}`, {
method: "POST",
credentials: "include",
headers: {
@@ -315,7 +319,7 @@ This request accepts the ID of the cart as a path parameter. In its body, you ca
It returns the updated cart.
Check out the full list of available request body parameters in the [API Reference](https://docs.medusajs.com/api/store/#tag/Cart/operation/PostCartsCart).
Check out the full list of available request body parameters in the [API Reference](/api/store/#tag/Cart/operation/PostCartsCart).
### Associate a Logged-In Customer with the Cart
@@ -360,7 +364,7 @@ export default Cart
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/carts/${cartId}`, {
fetch(`<BACKEND_URLL>/store/carts/${cartId}`, {
method: "POST",
credentials: "include",
headers: {
@@ -422,7 +426,7 @@ export default Cart
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/carts/${cartId}`, {
fetch(`<BACKEND_URLL>/store/carts/${cartId}`, {
method: "POST",
credentials: "include",
headers: {
@@ -484,7 +488,7 @@ export default Cart
<TabItem value="fetch" label="Fetch API">
```jsx
fetch(`<SERVER_URL>/store/carts/${cartId}/line-items`, {
fetch(`<BACKEND_URLL>/store/carts/${cartId}/line-items`, {
method: "POST",
credentials: "include",
headers: {
@@ -557,8 +561,10 @@ export default Cart
</TabItem>
<TabItem value="fetch" label="Fetch API">
<!-- eslint-disable max-len -->
```ts
fetch(`<SERVER_URL>/store/carts/${cartId}/line-items/${lineItemId}`, {
fetch(`<BACKEND_URLL>/store/carts/${cartId}/line-items/${lineItemId}`, {
method: "POST",
credentials: "include",
headers: {
@@ -619,8 +625,10 @@ export default Cart
</TabItem>
<TabItem value="fetch" label="Fetch API">
<!-- eslint-disable max-len -->
```ts
fetch(`<SERVER_URL>/store/carts/${cartId}/line-items/${lineItemId}`, {
fetch(`<BACKEND_URLL>/store/carts/${cartId}/line-items/${lineItemId}`, {
method: "DELETE",
credentials: "include",
})
@@ -639,5 +647,4 @@ It returns the updated cart.
## See Also
- [Implement the checkout flow in your storefront](../advanced/storefront/how-to-implement-checkout-flow.mdx)
- [Medusa JS Client Overview](../js-client/overview.md)
- [Implement the checkout flow in your storefront](./implement-checkout-flow.mdx)

View File

@@ -18,7 +18,7 @@ This document will take you through the general process of a checkout flow. You
:::note
Its recommended to go through the [Shipping Architecture Overview](../backend/shipping/overview.md) and [Payment Architecture Overview](../backend/payment/overview.md) first to have a better understanding of Medusas architecture.
Its recommended to go through the [Shipping Architecture Overview](../shipping.md) and [Payment Architecture Overview](../payment.md) first to have a better understanding of Medusas architecture.
:::
@@ -28,29 +28,29 @@ Its recommended to go through the [Shipping Architecture Overview](../backend
### Medusa Components
It's assumed that you already have a Medusa server installed and set up. If not, you can follow our [quickstart guide](../../quickstart/quick-start.mdx) to get started.
It's assumed that you already have a Medusa backend installed and set up. If not, you can follow our [quickstart guide](../../../development/backend/install.mdx) to get started.
It is also assumed you already have a storefront set up. It can be a custom storefront or one of Medusas storefronts. If you dont have a storefront set up, you can install either the [Next.js](../../starters/nextjs-medusa-starter.mdx) or [Gatsby](../../starters/gatsby-medusa-starter.mdx) storefronts.
It is also assumed you already have a storefront set up. It can be a custom storefront or one of Medusas storefronts. If you dont have a storefront set up, you can install the [Next.js starter storefront](../../../starters/nextjs-medusa-starter.mdx).
### JS Client
This guide includes code snippets to send requests to your Medusa server using Medusas JS Client and JavaScripts Fetch API.
This guide includes code snippets to send requests to your Medusa backend using Medusas JS Client and JavaScripts Fetch API.
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client installed](../../js-client/overview.md) and have [created an instance of the client](../../js-client/overview.md#configuration).
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client installed](../../../js-client/overview.md) and have [created an instance of the client](../../../js-client/overview.md#configuration).
### Medusa React
This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods.
This guide also includes code snippets to send requests to your Medusa backend using Medusa React, among other methods.
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage).
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../../medusa-react/overview.md#usage).
It's also assumed you already have [used CartProvider higher in your component tree](../../medusa-react/overview.md#cartprovider).
It's also assumed you already have [used CartProvider higher in your component tree](../../../medusa-react/overview.md#cartprovider).
### Previous Steps
This document assumes youve already taken care of the add-to-cart flow. So, you should have a [cart created](/api/store/#tag/Cart/operation/PostCart) for the customer with at least [one product in it](/api/store/#tag/Cart/operation/PostCartsCartLineItems).
You can learn how to implement the cart flow using [this documentation](../../guides/carts-in-medusa.mdx).
You can learn how to implement the cart flow using [this documentation](./implement-cart.mdx).
---
@@ -96,22 +96,23 @@ const Cart = () => {
const { updateCart } = useCart()
const addShippingAddress = (address: Record<string, string>) => {
updateCart.mutate({
shipping_address: {
company: address.company,
first_name: address.first_name,
last_name: address.last_name,
address_1: address.address_1,
address_2: address.address_2,
city: address.city,
country_code: address.country_code,
province: address.province,
postal_code: address.postal_code,
phone: address.phone,
},
})
}
const addShippingAddress =
(address: Record<string, string>) => {
updateCart.mutate({
shipping_address: {
company: address.company,
first_name: address.first_name,
last_name: address.last_name,
address_1: address.address_1,
address_2: address.address_2,
city: address.city,
country_code: address.country_code,
province: address.province,
postal_code: address.postal_code,
phone: address.phone,
},
})
}
// ...
}
@@ -123,7 +124,7 @@ export default Cart
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/carts/${cartId}`, {
fetch(`<BACKEND_URL>/store/carts/${cartId}`, {
method: "POST",
credentials: "include",
body: JSON.stringify({
@@ -161,7 +162,7 @@ The request returns the updated cart, with the new shipping address available in
### List Shipping Options
After updating the cart with the customers address, the list of available [shipping options](../backend/shipping/overview.md#shipping-option) for that cart might change. So, you should retrieve the updated list of options.
After updating the cart with the customers address, the list of available [shipping options](../shipping.md#shipping-option) for that cart might change. So, you should retrieve the updated list of options.
You can retrieve the list of shipping options by sending a `GET` request to the [Retrieve Shipping Options for Cart API](/api/store/#tag/Shipping-Option/operation/GetShippingOptionsCartId) endpoint:
@@ -187,7 +188,8 @@ type Props = {
}
const ShippingOptions = ({ cartId }: Props) => {
const { shipping_options, isLoading } = useCartShippingOptions(cartId)
const { shipping_options, isLoading } =
useCartShippingOptions(cartId)
return (
<div>
@@ -197,9 +199,13 @@ const ShippingOptions = ({ cartId }: Props) => {
)}
{shipping_options && (
<ul>
{shipping_options.map((shipping_option: ShippingOption) => (
<li key={shipping_option.id}>{shipping_option.name}</li>
))}
{shipping_options.map(
(shipping_option: ShippingOption) => (
<li key={shipping_option.id}>
{shipping_option.name}
</li>
)
)}
</ul>
)}
</div>
@@ -213,7 +219,7 @@ export default ShippingOptions
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/shipping-options/${cartId}`, {
fetch(`<BACKEND_URL>/store/shipping-options/${cartId}`, {
credentials: "include",
})
.then((response) => response.json())
@@ -229,7 +235,7 @@ The request accepts the ID of the cart as a path parameter. It returns the array
### Choose Shipping Option
Once the customer chooses one of the available shipping options, send a `POST` request to the [Add a Shipping Method](/api/store/#tag/Cart/operation/PostCartsCartShippingMethod) API endpoint. This will create a [shipping method](../backend/shipping/overview.md#shipping-method) based on the shipping option chosen and will associate it with the customers cart:
Once the customer chooses one of the available shipping options, send a `POST` request to the [Add a Shipping Method](/api/store/#tag/Cart/operation/PostCartsCartShippingMethod) API endpoint. This will create a [shipping method](../shipping.md#shipping-method) based on the shipping option chosen and will associate it with the customers cart:
<Tabs groupId="request-type" wrapperClassName="code-tabs">
<TabItem value="client" label="Medusa JS Client" default>
@@ -270,11 +276,11 @@ export default ShippingOptions
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/carts/${cartId}/shipping-methods`, {
fetch(`<BACKEND_URL>/store/carts/${cartId}/shipping-methods`, {
method: "POST",
credentials: "include",
body: JSON.stringify({
option_id: shippingOptionId, // the ID of the selected option
option_id: shippingOptionId, // ID of the selected option
}),
headers: {
"Content-Type": "application/json",
@@ -301,7 +307,7 @@ In this step, the customer generally chooses a payment method to complete their
### Initialize Payment Sessions
When the page opens and before the payment providers are displayed to the customer to choose from, you must initialize the [payment sessions](./../backend/payment/overview.md#payment-session) for the current cart. Each payment provider will have a payment session associated with it. These payment sessions will be used later when the customer chooses the payment provider they want to complete their purchase with.
When the page opens and before the payment providers are displayed to the customer to choose from, you must initialize the [payment sessions](../payment.md#payment-session) for the current cart. Each payment provider will have a payment session associated with it. These payment sessions will be used later when the customer chooses the payment provider they want to complete their purchase with.
To initialize the payment sessions, send a `POST` request to the [Initialize Payment Sessions](/api/store/#tag/Cart/operation/PostCartsCartPaymentSessions) API endpoint:
@@ -332,11 +338,17 @@ const PaymentProviders = () => {
return (
<div>
{!cart?.payment_sessions.length && <span>No payment providers</span>}
{!cart?.payment_sessions.length && (
<span>No payment providers</span>
)}
<ul>
{cart?.payment_sessions.map((paymentSession: PaymentSession) => (
<li key={paymentSession.id}>{paymentSession.provider_id}</li>
))}
{cart?.payment_sessions.map(
(paymentSession: PaymentSession) => (
<li key={paymentSession.id}>
{paymentSession.provider_id}
</li>
)
)}
</ul>
</div>
)
@@ -349,7 +361,7 @@ export default PaymentProviders
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/carts/${cartId}/payment-sessions`, {
fetch(`<BACKEND_URL>/store/carts/${cartId}/payment-sessions`, {
method: "POST",
credentials: "include",
})
@@ -407,11 +419,11 @@ export default PaymentProviders
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/carts/${cartId}/payment-session`, {
fetch(`<BACKEND_URL>/store/carts/${cartId}/payment-session`, {
method: "POST",
credentials: "include",
body: JSON.stringify({
// retrieved from the payment session selected by the customer
// the payment session selected by the customer
provider_id: paymentProviderId,
}),
headers: {
@@ -439,7 +451,7 @@ If you have one payment provider or if only one payment provider is available fo
### Update Payment Session
This step is optional and is only necessary for some payment providers. As mentioned in the [Payment Architecture](../backend/payment/overview.md#overview) documentation, the `PaymentSession` model has a `data` attribute that holds any data required for the Payment Provider to perform payment operations such as capturing payment.
This step is optional and is only necessary for some payment providers. As mentioned in the [Payment Architecture](../payment.md#overview) documentation, the `PaymentSession` model has a `data` attribute that holds any data required for the Payment Provider to perform payment operations such as capturing payment.
If you need to update that data at any point before the purchase is made, send a request to [Update a Payment Session](/api/store/#tag/Cart/operation/PostCartsCartPaymentSessionUpdate) API endpoint:
@@ -494,7 +506,7 @@ export default PaymentProviders
```ts
fetch(
`<SERVER_URL>/store/carts/${cartId}/payment-sessions/${paymentProviderId}`,
`<BACKEND_URL>/store/carts/${cartId}/payment-sessions/${paymentProviderId}`,
{
method: "POST",
credentials: "include",
@@ -525,7 +537,7 @@ It returns the updated cart. You can access the payment session's data on `cart.
### Complete Cart
The last step is to place the order by completing the cart. When you complete the cart, your Medusa server will try to authorize the payment first, then place the order if the authorization is successful. So, you should perform any necessary action with your payment provider first to make sure the authorization is successful when you send the request to complete the cart.
The last step is to place the order by completing the cart. When you complete the cart, your Medusa backend will try to authorize the payment first, then place the order if the authorization is successful. So, you should perform any necessary action with your payment provider first to make sure the authorization is successful when you send the request to complete the cart.
To complete a cart, send a `POST` request to the [Complete a Cart](/api/store/#tag/Cart/operation/PostCartsCartComplete) API endpoint:
@@ -564,7 +576,7 @@ export default Cart
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/carts/${cartId}/complete`, {
fetch(`<BACKEND_URL>/store/carts/${cartId}/complete`, {
method: "POST",
credentials: "include",
headers: {
@@ -584,13 +596,4 @@ This request accepts the ID of the cart as a path parameter.
The request returns two properties: `type` and `data`. If the order was placed successfully, `type` will be `order` and `data` will be the order's data.
If an error occurred while placing the order, `type` will be `cart` and `data` will be the cart's data.
---
## See Also
- [Medusa JS Client Overview](../../js-client/overview.md).
- Check out available plugins for popular payment providers such as [Stripe](../../add-plugins/stripe.md) and [PayPal](/add-plugins/paypal.md).
- [Payment Architecture](../backend/payment/overview.md)
- [Shipping Architecture](../backend/shipping/overview.md)
If an error occurred while placing the order, `type` will be `cart` and `data` will be the cart's data.

View File

@@ -24,25 +24,25 @@ This guide covers how to use these APIs to perform these tasks.
### Medusa Components
It is assumed that you already have a Medusa server installed and set up. If not, you can follow our [quickstart guide](../../quickstart/quick-start.mdx) to get started.
It is assumed that you already have a Medusa backend installed and set up. If not, you can follow our [quickstart guide](../../../development/backend/install.mdx) to get started.
### JS Client
This guide includes code snippets to send requests to your Medusa server using Medusas JS Client, among other methods.
This guide includes code snippets to send requests to your Medusa backend using Medusas JS Client, among other methods.
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client](../../js-client/overview.md) installed and have [created an instance of the client](../../js-client/overview.md#configuration).
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client](../../../js-client/overview.md) installed and have [created an instance of the client](../../../js-client/overview.md#configuration).
### Medusa React
This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods.
This guide also includes code snippets to send requests to your Medusa backend using Medusa React, among other methods.
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage).
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../../medusa-react/overview.md#usage).
### Authenticated Admin User
You must be an authenticated admin user before following along with the steps in the tutorial.
You can learn more about [authenticating as an admin user in the API reference](https://docs.medusajs.com/api/admin/#section/Authentication).
You can learn more about [authenticating as an admin user in the API reference](/api/admin/#section/Authentication).
---
@@ -94,7 +94,7 @@ export default CreateCustomerGroup
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/admin/customer-groups`, {
fetch(`<BACKEND_URL>/admin/customer-groups`, {
method: "POST",
credentials: "include",
headers: {
@@ -114,7 +114,7 @@ fetch(`<SERVER_URL>/admin/customer-groups`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<SERVER_URL>/admin/customer-groups' \
curl -L -X POST '<BACKEND_URL>/admin/customer-groups' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -151,7 +151,10 @@ import { CustomerGroup } from "@medusajs/medusa"
import { useAdminCustomerGroups } from "medusa-react"
const CustomerGroups = () => {
const { customer_groups, isLoading } = useAdminCustomerGroups()
const {
customer_groups,
isLoading,
} = useAdminCustomerGroups()
return (
<div>
@@ -161,9 +164,13 @@ const CustomerGroups = () => {
)}
{customer_groups && customer_groups.length > 0 && (
<ul>
{customer_groups.map((customerGroup: CustomerGroup) => (
<li key={customerGroup.id}>{customerGroup.name}</li>
))}
{customer_groups.map(
(customerGroup: CustomerGroup) => (
<li key={customerGroup.id}>
{customerGroup.name}
</li>
)
)}
</ul>
)}
</div>
@@ -177,7 +184,7 @@ export default CustomerGroups
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/admin/customer-groups`, {
fetch(`<BACKEND_URL>/admin/customer-groups`, {
credentials: "include",
})
.then((response) => response.json())
@@ -190,7 +197,7 @@ fetch(`<SERVER_URL>/admin/customer-groups`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X GET '<SERVER_URL>/admin/customer-groups' \
curl -L -X GET '<BACKEND_URL>/admin/customer-groups' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -199,7 +206,7 @@ curl -L -X GET '<SERVER_URL>/admin/customer-groups' \
This request returns an array of customer groups, as well as pagination fields.
You can also pass filters and other selection query parameters to the request. Check out the [API reference](https://docs.medusajs.com/api/admin/#tag/Customer-Group/operation/GetCustomerGroups) for more details on available query parameters.
You can also pass filters and other selection query parameters to the request. Check out the [API reference](/api/admin/#tag/Customer-Group/operation/GetCustomerGroups) for more details on available query parameters.
---
@@ -243,9 +250,12 @@ export default CustomerGroup
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/admin/customer-groups/${customerGroupId}`, {
credentials: "include",
})
fetch(
`<BACKEND_URL>/admin/customer-groups/${customerGroupId}`,
{
credentials: "include",
}
)
.then((response) => response.json())
.then(({ customer_group }) => {
console.log(customer_group.id)
@@ -256,7 +266,7 @@ fetch(`<SERVER_URL>/admin/customer-groups/${customerGroupId}`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X GET '<SERVER_URL>/admin/customer-groups/<CUSTOMER_GROUP_ID>' \
curl -L -X GET '<BACKEND_URL>/admin/customer-groups/<CUSTOMER_GROUP_ID>' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -292,7 +302,9 @@ medusa.admin.customerGroups.update(customerGroupId, {
import { useAdminUpdateCustomerGroup } from "medusa-react"
const UpdateCustomerGroup = () => {
const updateCustomerGroup = useAdminUpdateCustomerGroup(customerGroupId)
const updateCustomerGroup = useAdminUpdateCustomerGroup(
customerGroupId
)
// ..
const handleUpdate = () => {
@@ -317,18 +329,21 @@ export default UpdateCustomerGroup
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/admin/customer-groups/${customerGroupId}`, {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
metadata: {
is_seller: true,
},
}),
})
fetch(
`<BACKEND_URL>/admin/customer-groups/${customerGroupId}`,
{
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
metadata: {
is_seller: true,
},
}),
}
)
.then((response) => response.json())
.then(({ customer_group }) => {
console.log(customer_group.id)
@@ -339,7 +354,7 @@ fetch(`<SERVER_URL>/admin/customer-groups/${customerGroupId}`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<SERVER_URL>/admin/customer-groups/<CUSTOMER_GROUP_ID>' \
curl -L -X POST '<BACKEND_URL>/admin/customer-groups/<CUSTOMER_GROUP_ID>' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -377,7 +392,9 @@ medusa.admin.customerGroups.delete(customerGroupId)
import { useAdminDeleteCustomerGroup } from "medusa-react"
const CustomerGroup = () => {
const deleteCustomerGroup = useAdminDeleteCustomerGroup(customerGroupId)
const deleteCustomerGroup = useAdminDeleteCustomerGroup(
customerGroupId
)
// ...
const handleDeleteCustomerGroup = () => {
@@ -394,10 +411,13 @@ export default CustomerGroup
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/admin/customer-groups/${customerGroupId}`, {
method: "DELETE",
credentials: "include",
})
fetch(
`<BACKEND_URL>/admin/customer-groups/${customerGroupId}`,
{
method: "DELETE",
credentials: "include",
}
)
.then((response) => response.json())
.then(({ id, object, deleted }) => {
console.log(id)
@@ -408,7 +428,7 @@ fetch(`<SERVER_URL>/admin/customer-groups/${customerGroupId}`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X DELETE '<SERVER_URL>/admin/customer-groups/<CUSTOMER_GROUP_ID>' \
curl -L -X DELETE '<BACKEND_URL>/admin/customer-groups/<CUSTOMER_GROUP_ID>' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -445,10 +465,14 @@ medusa.admin.customerGroups.addCustomers(customerGroupId, {
<TabItem value="medusa-react" label="Medusa React">
```tsx
import { useAdminAddCustomersToCustomerGroup } from "medusa-react"
import {
useAdminAddCustomersToCustomerGroup,
} from "medusa-react"
const CustomerGroup = () => {
const addCustomers = useAdminAddCustomersToCustomerGroup(customerGroupId)
const addCustomers = useAdminAddCustomersToCustomerGroup(
customerGroupId
)
// ...
const handleAddCustomers= (customerId: string) => {
@@ -470,9 +494,11 @@ export default CustomerGroup
</TabItem>
<TabItem value="fetch" label="Fetch API">
<!-- eslint-disable max-len -->
```ts
fetch(
`<SERVER_URL>/admin/customer-groups/${customerGroupId}/customers/batch`,
`<BACKEND_URL>/admin/customer-groups/${customerGroupId}/customers/batch`,
{
method: "POST",
credentials: "include",
@@ -498,7 +524,7 @@ fetch(
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<SERVER_URL>/admin/customer-groups/<CUSTOMER_GROUP_ID>/customers/batch' \
curl -L -X POST '<BACKEND_URL>/admin/customer-groups/<CUSTOMER_GROUP_ID>/customers/batch' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -537,14 +563,19 @@ import { Customer } from "@medusajs/medusa"
import { useAdminCustomerGroupCustomers } from "medusa-react"
const CustomerGroup = () => {
const { customers, isLoading } = useAdminCustomerGroupCustomers(
const {
customers,
isLoading,
} = useAdminCustomerGroupCustomers(
customerGroupId
)
return (
<div>
{isLoading && <span>Loading...</span>}
{customers && !customers.length && <span>No customers</span>}
{customers && !customers.length && (
<span>No customers</span>
)}
{customers && customers.length > 0 && (
<ul>
{customers.map((customer: Customer) => (
@@ -562,8 +593,10 @@ export default CustomerGroup
</TabItem>
<TabItem value="fetch" label="Fetch API">
<!-- eslint-disable max-len -->
```ts
fetch(`<SERVER_URL>/admin/customer-groups/${customerGroupId}/customers`, {
fetch(`<BACKEND_URL>/admin/customer-groups/${customerGroupId}/customers`, {
credentials: "include",
})
.then((response) => response.json())
@@ -576,7 +609,7 @@ fetch(`<SERVER_URL>/admin/customer-groups/${customerGroupId}/customers`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X GET '<SERVER_URL>/admin/customer-groups/<CUSTOMER_GROUP_ID>/customers' \
curl -L -X GET '<BACKEND_URL>/admin/customer-groups/<CUSTOMER_GROUP_ID>/customers' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -599,13 +632,16 @@ You can remove customers from a customer group by sending a request to the Remov
<TabItem value="client" label="Medusa JS Client" default>
```ts
medusa.admin.customerGroups.removeCustomers(customer_group_id, {
customer_ids: [
{
id: customer_id,
},
],
})
medusa.admin.customerGroups.removeCustomers(
customer_group_id,
{
customer_ids: [
{
id: customer_id,
},
],
}
)
.then(({ customer_group }) => {
console.log(customer_group.id)
})
@@ -616,12 +652,15 @@ medusa.admin.customerGroups.removeCustomers(customer_group_id, {
```tsx
import { Customer } from "@medusajs/medusa"
import { useAdminRemoveCustomersFromCustomerGroup } from "medusa-react"
import {
useAdminRemoveCustomersFromCustomerGroup,
} from "medusa-react"
const CustomerGroup = () => {
const removeCustomers = useAdminRemoveCustomersFromCustomerGroup(
customerGroupId
)
const removeCustomers =
useAdminRemoveCustomersFromCustomerGroup(
customerGroupId
)
// ...
const handleRemoveCustomer = (customer_id: string) => {
@@ -643,9 +682,11 @@ export default CustomerGroup
</TabItem>
<TabItem value="fetch" label="Fetch API">
<!-- eslint-disable max-len -->
```ts
fetch(
`<SERVER_URL>/admin/customer-groups/${customerGroupId}/customers/batch`,
`<BACKEND_URL>/admin/customer-groups/${customerGroupId}/customers/batch`,
{
method: "DELETE",
credentials: "include",
@@ -671,7 +712,7 @@ fetch(
<TabItem value="curl" label="cURL">
```bash
curl -L -X DELETE '<SERVER_URL>/admin/customer-groups/<CUSTOMER_GROUP_ID>/customers/batch' \
curl -L -X DELETE '<BACKEND_URL>/admin/customer-groups/<CUSTOMER_GROUP_ID>/customers/batch' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -694,11 +735,4 @@ This request returns the customer group.
## Use Customer Groups as Conditions in a Price List
When you create or update a price list, you can specify one or more customer groups as conditions for the price list. You can learn how to do that in the [PriceList API documentation](../backend/price-lists/use-api.mdx).
---
## See Also
- [Customer Groups Overview](../backend/customer-groups/index.md).
- [Use Sales Channels Admin APIs](../backend/sales-channels/manage-admin.mdx).
When you create or update a price list, you can specify one or more customer groups as conditions for the price list. You can learn how to do that in the [PriceList API documentation](../../price-lists/admin/manage-price-lists.mdx).

View File

@@ -28,19 +28,19 @@ You want to add or use the following admin functionalities:
### Medusa Components
It is assumed that you already have a Medusa server installed and set up. If not, you can follow the [quickstart guide](../../quickstart/quick-start.mdx) to get started.
It is assumed that you already have a Medusa backend installed and set up. If not, you can follow the [quickstart guide](../../../development/backend/install.mdx) to get started.
### JS Client
This guide includes code snippets to send requests to your Medusa server using Medusas JS Client, JavaScripts Fetch API, or cURL.
This guide includes code snippets to send requests to your Medusa backend using Medusas JS Client, JavaScripts Fetch API, or cURL.
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client](../../js-client/overview.md) installed and have [created an instance of the client](../../js-client/overview.md#configuration).
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client](../../../js-client/overview.md) installed and have [created an instance of the client](../../../js-client/overview.md#configuration).
### Medusa React
This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods.
This guide also includes code snippets to send requests to your Medusa backend using Medusa React, among other methods.
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage).
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../../medusa-react/overview.md#usage).
### Authenticated Admin User
@@ -77,7 +77,9 @@ const Customers = () => {
return (
<div>
{isLoading && <span>Loading...</span>}
{customers && !customers.length && <span>No customers</span>}
{customers && !customers.length && (
<span>No customers</span>
)}
{customers && customers.length > 0 && (
<ul>
{customers.map((customer: Customer) => (
@@ -96,7 +98,7 @@ export default Customers
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/admin/customers`, {
fetch(`<BACKEND_URL>/admin/customers`, {
credentials: "include",
})
.then((response) => response.json())
@@ -109,7 +111,7 @@ fetch(`<SERVER_URL>/admin/customers`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X GET '<SERVER_URL>/admin/customers' \
curl -L -X GET '<BACKEND_URL>/admin/customers' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -190,7 +192,7 @@ export default CreateCustomer
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/admin/customers`, {
fetch(`<BACKEND_URL>/admin/customers`, {
method: "POST",
credentials: "include",
headers: {
@@ -213,7 +215,7 @@ fetch(`<SERVER_URL>/admin/customers`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<SERVER_URL>/admin/customers' \
curl -L -X POST '<BACKEND_URL>/admin/customers' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -294,7 +296,7 @@ export default UpdateCustomer
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/admin/customers/${customerId}`, {
fetch(`<BACKEND_URL>/admin/customers/${customerId}`, {
method: "POST",
credentials: "include",
headers: {
@@ -314,7 +316,7 @@ fetch(`<SERVER_URL>/admin/customers/${customerId}`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<SERVER_URL>/admin/customers/<CUSTOMER_ID>' \
curl -L -X POST '<BACKEND_URL>/admin/customers/<CUSTOMER_ID>' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -333,7 +335,4 @@ This request returns the updated customer object in the response.
## See Also
- [Manage customer groups](./use-customergroups-api.mdx)
- [Customers admin API reference](/api/admin)
- [Customers overview](../backend/customers/index.md)
- [Implement customer profiles in the storefront](../storefront/customer-profiles.mdx)
- [Implement customer profiles in the storefront](../storefront/implement-customer-profiles.mdx)

View File

@@ -1,5 +1,5 @@
---
description: 'Learn what Customer Groups are and how they can be used in the Medusa server. Customer Groups allow to combine customers with similar attributes into a single group.'
description: 'Learn what Customer Groups are and how they can be used in the Medusa backend. Customer Groups allow to combine customers with similar attributes into a single group.'
---
# Customer Groups
@@ -24,7 +24,7 @@ The customer groups feature can be used in a variety of use cases including:
## CustomerGroup Entity Overview
A customer group is stored in the database as a [CustomerGroup](../../../references/entities/classes/CustomerGroup.md) entity. This entity has two attributes other than the `id`: `name` and `metadata`.
A customer group is stored in the database as a [CustomerGroup](../../references/entities/classes/CustomerGroup.md) entity. This entity has two attributes other than the `id`: `name` and `metadata`.
Similar to all entities in Medusa, you can use the `metadata` object attribute to store any custom data you want. For example, you can add some flag or tag to the customer group for a custom use case:
@@ -60,5 +60,4 @@ The relation between the `PriceList` and `CustomerGroup` entities is available o
## See Also
- [Manage customer groups using the Admin APIs](../../admin/use-customergroups-api.mdx).
- [Price Lists Overview](../price-lists/index.md).
- [Manage customer groups using the Admin APIs](./admin/manage-customer-groups.mdx)

View File

@@ -34,7 +34,7 @@ In the example mentioned above, after the unregistered customer places an order
:::info
This architecture allows creating the Claim Order flow, where a registered customer can claim an order they placed as an unregistered customer. You can learn more about it in [this documentation](../../storefront/implement-claim-order.mdx).
This architecture allows creating the Claim Order flow, where a registered customer can claim an order they placed as an unregistered customer. You can learn more about it in [this documentation](../orders/storefront/implement-claim-order.mdx).
:::
@@ -48,7 +48,7 @@ Customer groups allow dividing customers into groups of similar attributes, then
:::info
You can learn more about customer groups in [this documentation](../customer-groups/index.md).
You can learn more about customer groups in [this documentation](./customer-groups.md).
:::
@@ -77,6 +77,5 @@ The relation between the `Customer` and `Address` entities is available on both
## See Also
- [Implement customer profiles in the storefront](../../storefront/customer-profiles.mdx)
- [Manage customers using the admin APIs](../../admin/manage-customers.mdx)
- Customers [Admin](/api/admin/#tag/Customer) and [Storefront](/api/store/#tag/Customer) API References
- [Implement customer profiles in the storefront](./storefront/implement-customer-profiles.mdx)
- [Manage customers using the admin APIs](./admin/manage-customers.mdx)

View File

@@ -0,0 +1,160 @@
---
description: "Customers are individuals that make purchases in your store. Learn about the available features and guides."
---
import DocCardList from '@theme/DocCardList';
import Icons from '@theme/Icon';
# Customers
Customers are individuals that make purchases in your store. This overview introduces the available features related to customers.
:::note
Not a developer? Check out the [Customers user guide](../../user-guide/customers/index.md).
:::
## Features
### Customer Accounts
Customers can make purchases as guests, or they can create an account.
When a customer creates an account, they can manage their details and review their order history.
An admin can manage all customers and their details.
<DocCardList colSize={4} items={[
{
type: 'link',
href: '#',
label: 'Storefront: Add Customer Profiles',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to implement customer accounts in a storefront.',
isSoon: true,
}
},
{
type: 'link',
href: '#',
label: 'Admin: Manage Customers',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to manage customers using Admin APIs.',
isSoon: true,
}
},
{
type: 'link',
href: '/user-guide/customers/manage',
label: 'User Guide: Manage Customers',
customProps: {
icon: Icons['users-solid'],
description: 'Learn how to manage customers in Medusa Admin.'
}
},
]} />
### Customer Groups
Admins can segment customers or assign them to different customer groups. This can be useful for marketing purposes.
For example, an admin can specify a different pricing or special discounts for specific customer groups.
<DocCardList colSize={4} items={[
{
type: 'link',
href: '#',
label: 'Admin: Manage Customer Groups',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to manage customer groups using Admin APIs.',
isSoon: true,
}
},
{
type: 'link',
href: '/user-guide/customers/groups',
label: 'User Guide: Customer Groups',
customProps: {
icon: Icons['users-solid'],
description: 'Learn how to manage customer groups in Medusa Admin.'
}
},
{
type: 'link',
href: '/api/admin#tag/Customer-Group',
label: 'Admin APIs: Customer Groups',
customProps: {
icon: Icons['server-solid'],
description: 'Check available Admin REST APIs for Customer Groups.'
}
},
]} />
---
## Understand the Architecture
Learn how Customer-related entities are built, their relation to other modules, and more.
<DocCardList colSize={6} items={[
{
type: 'link',
href: '#',
label: 'Architecture: Customer',
customProps: {
icon: Icons['circle-stack-solid'],
description: 'Learn about the Customer Architecture.',
isSoon: true,
}
},
{
type: 'link',
href: '#',
label: 'Architecture: Customer Group',
customProps: {
icon: Icons['circle-stack-solid'],
description: 'Learn about the Customer Group Architecture.',
isSoon: true,
}
},
]} />
---
## Related Modules
Discover Customers relation to other modules in Medusa.
<DocCardList colSize={4} items={[
{
type: 'link',
href: '/modules/orders/overview',
label: 'Orders',
customProps: {
icon: Icons['check-circle-solid'],
description: 'Customers can place orders, request returns and exchanges, and more.'
}
},
{
type: 'link',
href: '/modules/discounts/overview',
label: 'Discounts',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Discounts can be associated with a specific customer group.'
}
},
{
type: 'link',
href: '/modules/price-lists/overview',
label: 'Price Lists',
customProps: {
icon: Icons['currency-dollar-solid'],
description: 'Set special prices for specific customer groups.'
}
},
]} />

View File

@@ -36,21 +36,21 @@ You can use Medusas Store APIs to achieve more functionalities as well. Check
### Medusa Components
It's assumed that you already have a Medusa server installed and set up. If not, you can follow the [quickstart guide](../../quickstart/quick-start.mdx) to get started.
It's assumed that you already have a Medusa backend installed and set up. If not, you can follow the [quickstart guide](../../../development/backend/install.mdx) to get started.
It's also assumed you already have a storefront set up. It can be a custom storefront or one of Medusas storefronts. If you dont have a storefront set up, you can install either the [Next.js](../../starters/nextjs-medusa-starter.mdx) or [Gatsby](../../starters/gatsby-medusa-starter.mdx) storefronts.
It's also assumed you already have a storefront set up. It can be a custom storefront or one of Medusas storefronts. If you dont have a storefront set up, you can install the [Next.js starter storefront](../../../starters/nextjs-medusa-starter.mdx).
### JS Client
This guide includes code snippets to send requests to your Medusa server using Medusas JS Client, among other methods.
This guide includes code snippets to send requests to your Medusa backend using Medusas JS Client, among other methods.
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client installed](../../js-client/overview.md) and have [created an instance of the client](../../js-client/overview.md#configuration).
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client installed](../../../js-client/overview.md) and have [created an instance of the client](../../../js-client/overview.md#configuration).
### Medusa React
This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods.
This guide also includes code snippets to send requests to your Medusa backend using Medusa React, among other methods.
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage).
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../../medusa-react/overview.md#usage).
---
@@ -111,7 +111,7 @@ export default RegisterCustomer
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/customers`, {
fetch(`<BACKEND_URL>/store/customers`, {
method: "POST",
credentials: "include",
headers: {
@@ -169,7 +169,7 @@ medusa.auth.authenticate({
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/auth`, {
fetch(`<BACKEND_URL>/store/auth`, {
method: "POST",
credentials: "include",
headers: {
@@ -215,7 +215,7 @@ medusa.auth.deleteSession()
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/auth`, {
fetch(`<BACKEND_URL>/store/auth`, {
method: "DELETE",
credentials: "include",
})
@@ -260,7 +260,7 @@ medusa.customers.generatePasswordToken({
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/customers/password-token`, {
fetch(`<BACKEND_URL>/store/customers/password-token`, {
method: "POST",
credentials: "include",
headers: {
@@ -287,7 +287,7 @@ If the request has been processed successfully, it returns a `204` status code i
:::note
If the customer doesnt receive an email after this request, make sure that youve set up a Notification provider like [SendGrid](../../add-plugins/sendgrid.mdx) successfully. You also need to add a subscriber that handles the [customer.password_reset](../backend/subscribers/events-list.md#customer-events) event and sends the email.
If the customer doesnt receive an email after this request, make sure that youve set up a Notification provider like [SendGrid](../../../plugins/notifications/sendgrid.mdx) successfully. You also need to add a subscriber that handles the [customer.password_reset](../../../development/events/events-list.md#customer-events) event and sends the email.
:::
@@ -315,7 +315,7 @@ medusa.customers.resetPassword({
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/customers/password-reset`, {
fetch(`<BACKEND_URL>/store/customers/password-reset`, {
method: "POST",
credentials: "include",
headers: {
@@ -398,7 +398,7 @@ export default UpdateCustomer
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/customers/me`, {
fetch(`<BACKEND_URL>/store/customers/me`, {
method: "POST",
credentials: "include",
headers: {
@@ -465,7 +465,7 @@ medusa.customers.addresses.addAddress({
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/customers/me/addresses`, {
fetch(`<BACKEND_URL>/store/customers/me/addresses`, {
method: "POST",
credentials: "include",
headers: {
@@ -529,16 +529,18 @@ medusa.customers.addresses.updateAddress(addressId, {
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/customers/me/addresses/${addressId}`, {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
first_name,
}),
})
fetch(`<BACKEND_URL>/store/customers/me/addresses/${addressId}`,
{
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
first_name,
}),
}
)
.then((response) => response.json())
.then(({ customer }) => {
console.log(customer.id)
@@ -570,10 +572,12 @@ medusa.customers.addresses.deleteAddress(addressId)
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/customers/me/addresses/${addressId}`, {
method: "DELETE",
credentials: "include",
})
fetch(`<BACKEND_URL>/store/customers/me/addresses/${addressId}`,
{
method: "DELETE",
credentials: "include",
}
)
.then((response) => response.json())
.then(({ customer }) => {
console.log(customer.id)
@@ -636,7 +640,7 @@ export default Orders
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/customers/me/orders`, {
fetch(`<BACKEND_URL>/store/customers/me/orders`, {
credentials: "include",
})
.then((response) => response.json())
@@ -661,13 +665,4 @@ It returns the following data in the response:
You can learn more about pagination in the [API reference](/api/store/#section/Pagination).
:::
---
## See Also
- [Implement order-claim flow](./implement-claim-order.mdx)
- [Customers Store API reference](/api/store)
- [Customers overview](../backend/customers/index.md)
- [Manage customers using the admin APIs](../admin/manage-customers.mdx)
:::

View File

@@ -12,7 +12,7 @@ In this document, youll learn how to use the Admins Discount APIs to manag
:::tip
If you want to learn about the Discount architecture in-depth, check out the [Discount Architecture](../backend/discounts/index.md) documentation instead.
If you want to learn about the Discount architecture in-depth, check out the [Discount Architecture](../discounts.md) documentation instead.
:::
@@ -40,19 +40,19 @@ You can use Medusas Admin APIs to achieve more functionalities as well. Check
### Medusa Components
It is assumed that you already have a Medusa server installed and set up. If not, you can follow the [quickstart guide](../../quickstart/quick-start.mdx) to get started.
It is assumed that you already have a Medusa backend installed and set up. If not, you can follow the [quickstart guide](../../../development/backend/install.mdx) to get started.
### JS Client
This guide includes code snippets to send requests to your Medusa server using Medusas JS Client, JavaScripts Fetch API, or cURL.
This guide includes code snippets to send requests to your Medusa backend using Medusas JS Client, JavaScripts Fetch API, or cURL.
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client](../../js-client/overview.md) installed and have [created an instance of the client](../../js-client/overview.md#configuration).
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client](../../../js-client/overview.md) installed and have [created an instance of the client](../../../js-client/overview.md#configuration).
### Medusa React
This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods.
This guide also includes code snippets to send requests to your Medusa backend using Medusa React, among other methods.
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage).
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../../medusa-react/overview.md#usage).
### Authenticated Admin User
@@ -70,7 +70,10 @@ You can create a discount by sending a request to the [Create Discount](/api/adm
<TabItem value="client" label="Medusa JS Client" default>
```ts
import { AllocationType, DiscountRuleType } from "@medusajs/medusa"
import {
AllocationType,
DiscountRuleType,
} from "@medusajs/medusa"
// ...
medusa.admin.discounts.create({
code,
@@ -94,8 +97,13 @@ medusa.admin.discounts.create({
<TabItem value="medusa-react" label="Medusa React">
```tsx
import { useAdminCreateDiscount } from "medusa-react"
import { AllocationType, DiscountRuleType } from "@medusajs/medusa"
import {
useAdminCreateDiscount,
} from "medusa-react"
import {
AllocationType,
DiscountRuleType,
} from "@medusajs/medusa"
const CreateDiscount = () => {
const createDiscount = useAdminCreateDiscount()
@@ -128,7 +136,7 @@ export default CreateDiscount
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<YOUR_SERVER>/admin/discounts`, {
fetch(`<BACKEND_URL>/admin/discounts`, {
method: "POST",
credentials: "include",
headers: {
@@ -158,7 +166,7 @@ fetch(`<YOUR_SERVER>/admin/discounts`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<YOUR_SERVER>/admin/discounts' \
curl -L -X POST '<BACKEND_URL>/admin/discounts' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -183,9 +191,9 @@ This request accepts [many request-body parameters](/api/admin/#tag/Discount/ope
- `code`: This parameter is required. It is a unique code. The customer redeems the discount using this code.
- `rule`: This parameter is required. It is an object having at least the following fields:
- `type`: A string indicating the type of discount. It can be `fixed`, `percentage`, or `free_shipping`. When using the Medusa JS Client, you must use the enum type [DiscountRuleType](../../references/js-client/enums/internal.discountruletype/) for the value.
- `type`: A string indicating the type of discount. It can be `fixed`, `percentage`, or `free_shipping`. When using the Medusa JS Client, you must use the enum type [DiscountRuleType](../../../references/js-client/enums/internal.discountruletype/) for the value.
- `value`: A number indicating the value of the discount. If the discount type is `fixed`, then it will be the fixed amount to discount from the carts totals or its items. If the discount type is `percentage`, then it will be the percentage to discount from the items in the cart. If the type is `free_shipping`, it has no effect and can be set to `0`.
- `allocation`: A string indicating how the discount should be applied. Can be `item` or `total`. If the type is not `fixed`, then this has no effect. When using the Medusa JS Client, you must use the enum type [AllocationType](../../references/js-client/enums/internal.allocationtype/) for the value.
- `allocation`: A string indicating how the discount should be applied. Can be `item` or `total`. If the type is not `fixed`, then this has no effect. When using the Medusa JS Client, you must use the enum type [AllocationType](../../../references/js-client/enums/internal.allocationtype/) for the value.
- `regions`: An array of region IDs this discount can be used in. If the type of discount is `fixed`, only one region can be passed.
This request returns the full `discount` object.
@@ -237,7 +245,7 @@ export default UpdateDiscount
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<YOUR_SERVER>/admin/discounts/${discountId}`, {
fetch(`<BACKEND_URL>/admin/discounts/${discountId}`, {
method: "POST",
credentials: "include",
headers: {
@@ -257,7 +265,7 @@ fetch(`<YOUR_SERVER>/admin/discounts/${discountId}`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<YOUR_SERVER>/admin/discounts/<DISCOUNT_ID>' \
curl -L -X POST '<BACKEND_URL>/admin/discounts/<DISCOUNT_ID>' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -282,7 +290,7 @@ This updates the discounts information and returns the full updated `discount
:::tip
You can learn more about conditions and conditions types in the [Discount Architecture](../backend/discounts/index.md) documentation.
You can learn more about conditions and conditions types in the [Discount Architecture](../discounts.md) documentation.
:::
@@ -313,7 +321,9 @@ import { useAdminDiscountCreateCondition } from "medusa-react"
import { DiscountConditionOperator } from "@medusajs/medusa"
const Discount = () => {
const createCondition = useAdminDiscountCreateCondition(discount_id)
const createCondition = useAdminDiscountCreateCondition(
discount_id
)
// ...
const handleCreateCondition = (
@@ -339,19 +349,21 @@ export default Discount
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<YOUR_SERVER>/admin/discounts/${discountId}/conditions`, {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
operator: "in",
products: [
productId,
],
}),
})
fetch(`<BACKEND_URL>/admin/discounts/${discountId}/conditions`,
{
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
operator: "in",
products: [
productId,
],
}),
}
)
.then((response) => response.json())
.then(({ discount }) => {
console.log(discount.id)
@@ -362,7 +374,7 @@ fetch(`<YOUR_SERVER>/admin/discounts/${discountId}/conditions`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<YOUR_SERVER>/admin/discounts/<DISCOUNT_ID>/conditions' \
curl -L -X POST '<BACKEND_URL>/admin/discounts/<DISCOUNT_ID>/conditions' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -401,11 +413,18 @@ You can retrieve a condition and its resources by sending a request to the [Get
<TabItem value="client" label="Medusa JS Client" default>
```ts
medusa.admin.discounts.getCondition(discountId, conditionId, {
expand: "products",
})
medusa.admin.discounts.getCondition(
discountId,
conditionId,
{
expand: "products",
}
)
.then(({ discount_condition }) => {
console.log(discount_condition.id, discount_condition.products)
console.log(
discount_condition.id,
discount_condition.products
)
})
```
@@ -417,7 +436,10 @@ import { useAdminGetDiscountCondition } from "medusa-react"
import { Product } from "@medusajs/medusa"
const DiscountCondition = () => {
const { discount_condition, isLoading } = useAdminGetDiscountCondition(
const {
discount_condition,
isLoading,
} = useAdminGetDiscountCondition(
discount_id,
conditionId
)
@@ -430,9 +452,11 @@ const DiscountCondition = () => {
<>
<span>{discount_condition.id}</span>
<ul>
{discount_condition.products.map((product: Product) => (
<li key={product.id}>{product.title}</li>
))}
{discount_condition.products.map(
(product: Product) => (
<li key={product.id}>{product.title}</li>
)
)}
</ul>
</>
)}
@@ -448,7 +472,7 @@ export default DiscountCondition
```ts
fetch(
`<YOUR_SERVER>/admin/discounts/${discountId}` +
`<BACKEND_URL>/admin/discounts/${discountId}` +
`/conditions/${conditionId}&expand=products`,
{
credentials: "include",
@@ -456,7 +480,10 @@ fetch(
)
.then((response) => response.json())
.then(({ discount_condition }) => {
console.log(discount_condition.id, discount_condition.products)
console.log(
discount_condition.id,
discount_condition.products
)
})
```
@@ -464,7 +491,7 @@ fetch(
<TabItem value="curl" label="cURL">
```bash
curl -L -X GET '<YOUR_SERVER>/admin/discounts/<DISCOUNT_ID>/conditions/<CONDITION_ID>&expand=products' \
curl -L -X GET '<BACKEND_URL>/admin/discounts/<DISCOUNT_ID>/conditions/<CONDITION_ID>&expand=products' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -487,12 +514,15 @@ For example, to update the products in a condition:
<TabItem value="client" label="Medusa JS Client" default>
```ts
medusa.admin.discounts.updateCondition(discountId, conditionId, {
products: [
productId1,
productId2,
],
})
medusa.admin.discounts.updateCondition(
discountId,
conditionId, {
products: [
productId1,
productId2,
],
}
)
.then(({ discount }) => {
console.log(discount.id)
})
@@ -527,9 +557,11 @@ export default DiscountCondition
</TabItem>
<TabItem value="fetch" label="Fetch API">
<!-- eslint-disable max-len -->
```ts
fetch(
`<YOUR_SERVER>/admin/discounts/${discountId}/conditions/${conditionId}`,
`<BACKEND_URL>/admin/discounts/${discountId}/conditions/${conditionId}`,
{
method: "POST",
credentials: "include",
@@ -554,7 +586,7 @@ fetch(
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<YOUR_SERVER>/admin/discounts/<DISCOUNT_ID>/conditions/<CONDITION_ID>' \
curl -L -X POST '<BACKEND_URL>/admin/discounts/<DISCOUNT_ID>/conditions/<CONDITION_ID>' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -582,7 +614,10 @@ You can delete a condition by sending a request to the [Delete Condition](/api/a
<TabItem value="client" label="Medusa JS Client" default>
```ts
medusa.admin.discounts.deleteCondition(discountId, conditionId)
medusa.admin.discounts.deleteCondition(
discountId,
conditionId
)
.then(({ discount }) => {
console.log(discount)
})
@@ -595,7 +630,9 @@ medusa.admin.discounts.deleteCondition(discountId, conditionId)
import { useAdminDiscountRemoveCondition } from "medusa-react"
const Discount = () => {
const deleteCondition = useAdminDiscountRemoveCondition(discount_id)
const deleteCondition = useAdminDiscountRemoveCondition(
discount_id
)
// ...
const handleUpdateCondition = (conditionId: string) => {
@@ -611,9 +648,11 @@ export default Discount
</TabItem>
<TabItem value="fetch" label="Fetch API">
<!-- eslint-disable max-len -->
```ts
fetch(
`<YOUR_SERVER>/admin/discounts/${discountId}/conditions/${conditionId}`,
`<BACKEND_URL>/admin/discounts/${discountId}/conditions/${conditionId}`,
{
method: "DELETE",
credentials: "include",
@@ -629,7 +668,7 @@ fetch(
<TabItem value="curl" label="cURL">
```bash
curl -L -X DELETE '<YOUR_SERVER>/admin/discounts/<DISCOUNT_ID>/conditions/<CONDITION_ID>' \
curl -L -X DELETE '<BACKEND_URL>/admin/discounts/<DISCOUNT_ID>/conditions/<CONDITION_ID>' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -680,7 +719,7 @@ export default Discount
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<YOUR_SERVER>/admin/discounts/${discountId}`, {
fetch(`<BACKEND_URL>/admin/discounts/${discountId}`, {
method: "DELETE",
credentials: "include",
})
@@ -694,7 +733,7 @@ fetch(`<YOUR_SERVER>/admin/discounts/${discountId}`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X DELETE '<YOUR_SERVER>/admin/discounts/<DISCOUNT_ID>' \
curl -L -X DELETE '<BACKEND_URL>/admin/discounts/<DISCOUNT_ID>' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -713,5 +752,4 @@ It returns in the response the following fields:
## See Also
- [Discounts API reference](/api/admin/#tag/Discount)
- [Use Discounts on the storefront](../storefront/use-discounts-in-checkout.mdx)

View File

@@ -1,5 +1,5 @@
---
description: 'Learn about the discount architecture in the Medusa server. Discounts are used to offer promotions to the user for marketing purposes.'
description: 'Learn about the discount architecture in the Medusa backend. Discounts are used to offer promotions to the user for marketing purposes.'
---
# Discounts Architecture
@@ -32,7 +32,7 @@ Discounts can be used in many use cases including:
## Discount Entity Overview
A discount is represented by the [`Discount`](../../../references/entities/classes/Discount.md) entity. Some of its important attributes are:
A discount is represented by the [`Discount`](../../references/entities/classes/Discount.md) entity. Some of its important attributes are:
- `code` is a unique code that you specify when you create the discount. Customers use this code to apply the discount during checkout. The code can only include upper-case letters and numbers.
- `rule_id` is the ID of the rule of this discount. The `rule` attribute is the expanded object of the `DiscountRule` entity. You can use the `rule` attribute to get details regarding the discount type. You can learn more about this in the [`DiscountRule` entity overview](#discountrule-entity-overview) later.
@@ -54,7 +54,7 @@ The `is_dynamic` attribute in the `Discount` entity is a boolean value that dete
## DiscountRule Entity Overview
Every `Discount` entity belongs to a [`DiscountRule`](./../../../references/entities/classes/DiscountRule.md) entity. `DiscountRule` includes details such as the type of discount, the amount to be discounted, and more.
Every `Discount` entity belongs to a [`DiscountRule`](../../references/entities/classes/DiscountRule.md) entity. `DiscountRule` includes details such as the type of discount, the amount to be discounted, and more.
Some of the `DiscountRule` entitys important attributes are:
@@ -71,7 +71,7 @@ Some of the `DiscountRule` entitys important attributes are:
A discount can optionally have discount conditions. Discount conditions are used to further add limitations on when the discount can be applied.
A [`DiscountCondition`](../../../references/entities/classes/DiscountCondition.md) belongs to a `DiscountRule` entity. The `discount_rule_id` attribute indicates the ID of the `DiscountRule` it belongs to.
A [`DiscountCondition`](../../references/entities/classes/DiscountCondition.md) belongs to a `DiscountRule` entity. The `discount_rule_id` attribute indicates the ID of the `DiscountRule` it belongs to.
Discount conditions have an attribute `type` that indicates the conditions type. Its value must be one of the following:
@@ -92,17 +92,17 @@ Discount conditions also have an attribute `operator` that indicates how the con
Based on the value of `type`, one of the following relations can be used to retrieve the conditions items:
- `products` is an array of products that this condition applies to if the conditions `type` is `products`. Each item of the array would be a [`DiscountConditionProduct`](../../../references/entities/classes/DiscountConditionProduct.md).
- `product_types` is an array of product types that this condition applies to if the conditions `type` is `product_types`. Each item of the array would be a [`DiscountConditionProductType`](../../../references/entities/classes/DiscountConditionProductType.md).
- `product_collections` is an array of product types that this condition applies to if the conditions `type` is `product_collections`. Each item of the array would be a [`DiscountConditionProductCollection`](../../../references/entities/classes/DiscountConditionProductCollection.md).
- `product_tags` is an array of product types that this condition applies to if the conditions `type` is `product_tags`. Each item of the array would be a [`DiscountConditionProductTag`](../../../references/entities/classes/DiscountConditionProductTag.md).
- `customer_groups` is an array of product types that this condition applies to if the conditions `type` is `customer_groups`. Each item of the array would be a [`DiscountConditionCustomerGroup`](../../../references/entities/classes/DiscountConditionCustomerGroup.md).
- `products` is an array of products that this condition applies to if the conditions `type` is `products`. Each item of the array would be a [`DiscountConditionProduct`](../../references/entities/classes/DiscountConditionProduct.md).
- `product_types` is an array of product types that this condition applies to if the conditions `type` is `product_types`. Each item of the array would be a [`DiscountConditionProductType`](../../references/entities/classes/DiscountConditionProductType.md).
- `product_collections` is an array of product types that this condition applies to if the conditions `type` is `product_collections`. Each item of the array would be a [`DiscountConditionProductCollection`](../../references/entities/classes/DiscountConditionProductCollection.md).
- `product_tags` is an array of product types that this condition applies to if the conditions `type` is `product_tags`. Each item of the array would be a [`DiscountConditionProductTag`](../../references/entities/classes/DiscountConditionProductTag.md).
- `customer_groups` is an array of product types that this condition applies to if the conditions `type` is `customer_groups`. Each item of the array would be a [`DiscountConditionCustomerGroup`](../../references/entities/classes/DiscountConditionCustomerGroup.md).
![Discounts Architecture](https://res.cloudinary.com/dza7lstvk/image/upload/v1669900544/Medusa%20Docs/Diagrams/discounts_cdxec1.jpg)
![Discounts Architecture](https://res.cloudinary.com/dza7lstvk/image/upload/v1678372360/Medusa%20Docs/Diagrams/discounts_ioivrl.png)
---
## See Also
- [Create a discount using the admin APIs](../../admin/manage-discounts.mdx)
- [Use discounts on the storefront](../../storefront/use-discounts-in-checkout.mdx)
- [Manage discounts using the admin APIs](./admin/manage-discounts.mdx)
- [Use discounts on the storefront](./storefront/use-discounts-in-checkout.mdx)

View File

@@ -0,0 +1,113 @@
---
description: "Discounts are deductions in the checkout total that are generally used for marketing and promotional purposes. Learn about the available features and guides."
---
import DocCardList from '@theme/DocCardList';
import DocCard from '@theme/DocCard';
import Icons from '@theme/Icon';
# Discounts
Discounts are deductions in the checkout total that are generally used for marketing and promotional purposes. This overview introduces the available features related to discounts.
:::note
Not a developer? Check out the [Discounts user guide](../../user-guide/discounts/index.md).
:::
## Features
### Discounts Management
Admins can create discounts with various conditions and rules that can be used to deduct a fixed or percentage amount from the cart total, or that can be used for free shipping.
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/modules/discounts/admin/manage-discounts',
label: 'Admin: Manage Discounts',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to manage discounts using Admin APIs.'
}
},
{
type: 'link',
href: '/user-guide/discounts/manage',
label: 'User Guide: Manage Discounts',
customProps: {
icon: Icons['users-solid'],
description: 'Learn how to manage discounts using Medusa Admin.'
}
},
]} />
### Applying Discounts during Checkout
Customers can benefit from discounts by using a discount code during checkout.
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/modules/discounts/storefront/use-discounts-in-checkout',
label: 'Storefront: Use Discounts in Checkout',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to use discounts during checkout.'
}
},
{
type: 'link',
href: '/api/store#tag/Cart/operation/GetCartsCart',
label: 'Store APIs: Discounts',
customProps: {
icon: Icons['server-solid'],
description: 'Check available Store REST APIs for Discounts with carts.'
}
},
]} />
---
## Understand the Architecture
Learn how discount-related entities and concepts are built, their relation to other modules, and more.
<DocCard item={{
type: 'link',
href: '/modules/discounts',
label: 'Architecture: Discounts',
customProps: {
icon: Icons['circle-stack-solid'],
description: 'Learn about the Discount architecture.'
}
}}
/>
---
## Related Modules
Discover Discounts relation to other modules in Medusa
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/modules/carts-and-checkout/overview',
label: 'Cart and Checkout',
customProps: {
icon: Icons['shopping-cart-solid'],
description: 'Customers can apply discounts during checkout.'
}
},
{
type: 'link',
href: '/modules/products/overview',
label: 'Product',
customProps: {
icon: Icons['tag-solid'],
description: 'Discounts can be associated with specific products.'
}
},
]} />

View File

@@ -12,7 +12,7 @@ In this document, learn how to use discounts during checkout on the storefront.
:::info
You can check out the [Discounts Architecture documentation](../backend/discounts/index.md) to learn more about how discounts work.
You can check out the [Discounts Architecture documentation](../discounts.md) to learn more about how discounts work.
:::
@@ -32,29 +32,29 @@ You want to implement discount functionality in your store to allow customers to
### Medusa Components
It's assumed that you already have a Medusa server installed and set up. If not, you can follow the [quickstart guide](../../quickstart/quick-start.mdx) to get started.
It's assumed that you already have a Medusa backend installed and set up. If not, you can follow the [quickstart guide](../../../development/backend/install.mdx) to get started.
It is also assumed you already have a storefront set up. It can be a custom storefront or one of Medusas storefronts. If you dont have a storefront set up, you can install either the [Next.js](../../starters/nextjs-medusa-starter.mdx) or [Gatsby](../../starters/gatsby-medusa-starter.mdx) storefronts.
It is also assumed you already have a storefront set up. It can be a custom storefront or one of Medusas storefronts. If you dont have a storefront set up, you can install the [Next.js starter storefront](../../../starters/nextjs-medusa-starter.mdx).
### JS Client
This guide includes code snippets to send requests to your Medusa server using Medusas JS Client, among other methods.
This guide includes code snippets to send requests to your Medusa backend using Medusas JS Client, among other methods.
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client installed](../../js-client/overview.md) and have [created an instance of the client](../../js-client/overview.md#configuration).
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client installed](../../../js-client/overview.md) and have [created an instance of the client](../../../js-client/overview.md#configuration).
### Medusa React
This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods.
This guide also includes code snippets to send requests to your Medusa backend using Medusa React, among other methods.
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage).
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../../medusa-react/overview.md#usage).
It's also assumed you already have [used CartProvider higher in your component tree](../../medusa-react/overview.md#cartprovider).
It's also assumed you already have [used CartProvider higher in your component tree](../../../medusa-react/overview.md#cartprovider).
### Previous Steps
This document assumes youve already taken care of the add-to-cart flow. So, you should have a [cart created](/api/store/#tag/Cart/operation/PostCart) for the customer with at least [one product in it](/api/store/#tag/Cart/operation/PostCartsCartLineItems).
You can learn how to implement the cart flow using [this documentation](../../guides/carts-in-medusa.mdx).
You can learn how to implement the cart flow using [this documentation](../../../modules/carts-and-checkout/storefront/implement-cart.mdx).
---
@@ -115,7 +115,7 @@ export default Cart
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/carts/${cartId}`, {
fetch(`<BACKEND_URL>/store/carts/${cartId}`, {
method: "POST",
credentials: "include",
body: JSON.stringify({
@@ -146,7 +146,7 @@ This request requires the customers cart ID as a path parameter. In the body
:::info
Customers can add more than one discount to their cart.
Customers can add more than one discount to their cart, however, only one non-free shipping discount is allowed per cart.
:::
@@ -269,7 +269,7 @@ medusa.carts.deleteDiscount(cartId, code)
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/carts/${cartId}/discounts/${code}`, {
fetch(`<BACKEND_URL>/store/carts/${cartId}/discounts/${code}`, {
method: "DELETE",
credentials: "include",
})
@@ -285,10 +285,3 @@ fetch(`<SERVER_URL>/store/carts/${cartId}/discounts/${code}`, {
This request accepts the cart ID and the code of the discount to remove. If the discount is removed successfully, the request returns the updated cart object, where you wont find the discount in the `discounts` array anymore.
The totals of the cart and its items will be updated as well.
---
## See Also
- [Implement the checkout flow in a storefront](./how-to-implement-checkout-flow.mdx).
- [Manage discounts using the admin APIs](../admin/manage-discounts.mdx).

View File

@@ -12,7 +12,7 @@ In this document, youll learn how to manage gift cards using the admin APIs.
:::note
You can learn more about what gift cards are and how theyre used in [this documentation](../backend/gift-cards/index.md)
You can learn more about what gift cards are and how theyre used in [this documentation](../gift-cards.md)
:::
@@ -33,19 +33,19 @@ You want to add or use the following admin functionalities:
### Medusa Components
It is assumed that you already have a Medusa server installed and set up. If not, you can follow the [quickstart guide](../../quickstart/quick-start.mdx) to get started.
It is assumed that you already have a Medusa backend installed and set up. If not, you can follow the [quickstart guide](../../../development/backend/install.mdx) to get started.
### JS Client
This guide includes code snippets to send requests to your Medusa server using Medusas JS Client, among other methods.
This guide includes code snippets to send requests to your Medusa backend using Medusas JS Client, among other methods.
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client](../../js-client/overview.md) installed and have [created an instance of the client](../../js-client/overview.md#configuration).
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client](../../../js-client/overview.md) installed and have [created an instance of the client](../../../js-client/overview.md#configuration).
### Medusa React
This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods.
This guide also includes code snippets to send requests to your Medusa backend using Medusa React, among other methods.
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage).
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../../medusa-react/overview.md#usage).
### Authenticated Admin User
@@ -87,7 +87,9 @@ medusa.admin.products.list({
```tsx
import { Product } from "@medusajs/medusa"
import { PricedProduct } from "@medusajs/medusa/dist/types/pricing"
import {
PricedProduct,
} from "@medusajs/medusa/dist/types/pricing"
import { useAdminProducts } from "medusa-react"
const GiftCard = () => {
@@ -100,12 +102,16 @@ const GiftCard = () => {
{isLoading && <span>Loading...</span>}
{products && products.length > 0 && (
<ul>
{products.map((product: (Product | PricedProduct)) => (
<li key={product.id}>{product.title}</li>
))}
{products.map(
(product: (Product | PricedProduct)) => (
<li key={product.id}>{product.title}</li>
)
)}
</ul>
)}
{products && !products.length && <span>No Gift Cards</span>}
{products && !products.length && (
<span>No Gift Cards</span>
)}
</div>
)
}
@@ -117,7 +123,7 @@ export default GiftCard
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/admin/products?is_giftcard=true`, {
fetch(`<BACKEND_URL>/admin/products?is_giftcard=true`, {
credentials: "include",
})
.then((response) => response.json())
@@ -135,7 +141,7 @@ fetch(`<SERVER_URL>/admin/products?is_giftcard=true`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X GET '<SERVER_URL>/admin/products?is_giftcard=true' \
curl -L -X GET '<BACKEND_URL>/admin/products?is_giftcard=true' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -244,7 +250,7 @@ export default CreateGiftCard
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/admin/products`, {
fetch(`<BACKEND_URL>/admin/products`, {
method: "POST",
credentials: "include",
headers: {
@@ -290,7 +296,7 @@ fetch(`<SERVER_URL>/admin/products`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<SERVER_URL>/admin/products' \
curl -L -X POST '<BACKEND_URL>/admin/products' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -383,7 +389,7 @@ export default UpdateGiftCard
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/admin/products/${giftCardId}`, {
fetch(`<BACKEND_URL>/admin/products/${giftCardId}`, {
method: "POST",
credentials: "include",
headers: {
@@ -403,7 +409,7 @@ fetch(`<SERVER_URL>/admin/products/${giftCardId}`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<SERVER_URL>/admin/products/<GIFT_CARD_ID>' \
curl -L -X POST '<BACKEND_URL>/admin/products/<GIFT_CARD_ID>' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -458,7 +464,7 @@ export default GiftCard
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/admin/products/${giftCardId}`, {
fetch(`<BACKEND_URL>/admin/products/${giftCardId}`, {
method: "DELETE",
credentials: "include",
})
@@ -472,7 +478,7 @@ fetch(`<SERVER_URL>/admin/products/${giftCardId}`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X DELETE '<SERVER_URL>/admin/products/<GIFT_CARD_ID>' \
curl -L -X DELETE '<BACKEND_URL>/admin/products/<GIFT_CARD_ID>' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -541,7 +547,7 @@ export default CustomGiftCards
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/admin/gift-cards`, {
fetch(`<BACKEND_URL>/admin/gift-cards`, {
credentials: "include",
})
.then((response) => response.json())
@@ -554,7 +560,7 @@ fetch(`<SERVER_URL>/admin/gift-cards`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X GET '<SERVER_URL>/admin/gift-cards' \
curl -L -X GET '<BACKEND_URL>/admin/gift-cards' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -611,7 +617,7 @@ export default CreateCustomGiftCards
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/admin/gift-cards`, {
fetch(`<BACKEND_URL>/admin/gift-cards`, {
method: "POST",
credentials: "include",
headers: {
@@ -632,7 +638,7 @@ fetch(`<SERVER_URL>/admin/gift-cards`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<SERVER_URL>/admin/gift-cards' \
curl -L -X POST '<BACKEND_URL>/admin/gift-cards' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -675,7 +681,9 @@ medusa.admin.giftCards.update(giftCardId, {
import { useAdminUpdateGiftCard } from "medusa-react"
const UpdateCustomGiftCards = () => {
const updateGiftCard = useAdminUpdateGiftCard(customGiftCardId)
const updateGiftCard = useAdminUpdateGiftCard(
customGiftCardId
)
// ...
const handleUpdate = (regionId: string) => {
@@ -694,7 +702,7 @@ export default UpdateCustomGiftCards
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/admin/gift-cards/${giftCardId}`, {
fetch(`<BACKEND_URL>/admin/gift-cards/${giftCardId}`, {
method: "POST",
credentials: "include",
headers: {
@@ -714,7 +722,7 @@ fetch(`<SERVER_URL>/admin/gift-cards/${giftCardId}`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<SERVER_URL>/admin/gift-cards/<GIFT_CARD_ID>' \
curl -L -X POST '<BACKEND_URL>/admin/gift-cards/<GIFT_CARD_ID>' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -752,7 +760,9 @@ medusa.admin.giftCards.delete(giftCardId)
import { useAdminDeleteGiftCard } from "medusa-react"
const CustomGiftCard = () => {
const deleteGiftCard = useAdminDeleteGiftCard(customGiftCardId)
const deleteGiftCard = useAdminDeleteGiftCard(
customGiftCardId
)
// ...
const handleDelete = () => {
@@ -769,7 +779,7 @@ export default CustomGiftCard
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/admin/gift-cards/${giftCardId}`, {
fetch(`<BACKEND_URL>/admin/gift-cards/${giftCardId}`, {
method: "DELETE",
credentials: "include",
})
@@ -783,7 +793,7 @@ fetch(`<SERVER_URL>/admin/gift-cards/${giftCardId}`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X DELETE '<SERVER_URL>/admin/gift-card/<GIFT_CARD_ID>' \
curl -L -X DELETE '<BACKEND_URL>/admin/gift-card/<GIFT_CARD_ID>' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -802,7 +812,4 @@ It returns the following fields in the response:
## See Also
- [Gift cards overview](../backend/gift-cards/index.md)
- [Use gift cards on the storefront](../storefront/use-gift-cards.mdx)
- [Send the customer a gift card](../ecommerce/send-gift-card-to-customer.md)
- Gift cards [store](/api/store/#tag/Gift-Card) and [admin](/api/admin/#tag/Gift-Card) APIs
- [Use gift cards on the storefront](../storefront/use-gift-cards.mdx)

View File

@@ -17,7 +17,7 @@ This document shows you how to track when a gift card has been purchased so that
:::tip
You can alternatively use the [SendGrid](../../add-plugins/sendgrid.mdx) plugin, which handles sending the email automatically.
You can alternatively use the [SendGrid](../../../plugins/notifications/sendgrid.mdx) plugin, which handles sending the email automatically.
:::
@@ -27,15 +27,15 @@ You can alternatively use the [SendGrid](../../add-plugins/sendgrid.mdx) plugin,
### Medusa Components
It's assumed that you already have a Medusa server installed and set up. If not, you can follow the [quickstart guide](../../quickstart/quick-start.mdx) to get started.
It's assumed that you already have a Medusa backend installed and set up. If not, you can follow the [quickstart guide](../../../development/backend/install.mdx) to get started.
### Redis
Redis is required for batch jobs to work. Make sure you [install Redis](../../tutorial/0-set-up-your-development-environment.mdx#redis) and [configure it with your Medusa server](../../usage/configurations.md#redis).
Redis is required for batch jobs to work. Make sure you [install Redis](../../../development/backend/prepare-environment.mdx#redis) and [configure it with the Medusa backend](../../../development/backend/configurations.md#redis).
### Notification Provider
To send an email or another type of notification method, you must have a notification provider installed or configured. You can either install an existing plugin or [create your own](../backend/notification/how-to-create-notification-provider.md).
To send an email or another type of notification method, you must have a notification provider installed or configured. You can either install an existing plugin or [create your own](../../../development/notification/create-notification-provider.md).
---
@@ -45,7 +45,7 @@ To subscribe to and handle an event, you must create a subscriber.
:::info
You can learn more about subscribers in the [Subscribers](../backend/subscribers/overview.md) documentation.
You can learn more about subscribers in the [Subscribers](../../../development/events/subscribers.mdx) documentation.
:::
@@ -69,7 +69,7 @@ Youll be adding in the next step the necessary dependencies to the subscriber
:::info
You can learn more about [dependency injection](../backend/dependency-container/index.md) in this documentation.
You can learn more about [dependency injection](../../../development/fundamentals/dependency-injection.md) in this documentation.
:::
@@ -108,7 +108,7 @@ Where `<NOTIFICATION_PROVIDER_IDENTIFIER>` is the identifier for your notificati
:::info
You can learn more about handling events with the Notification Service using [this documentation](../backend/notification/how-to-create-notification-provider.md).
You can learn more about handling events with the Notification Service using [this documentation](../../../development/notification/create-notification-provider.md).
:::
@@ -117,7 +117,10 @@ You can learn more about handling events with the Notification Service using [th
If the notification provider youre using isnt configured to handle this event, or you want to implement some other custom logic, you can subscribe to the event using the `EventBusService`:
```ts title=src/subscribers/gift-card.ts
import { EventBusService, GiftCardService } from "@medusajs/medusa"
import {
EventBusService,
GiftCardService,
} from "@medusajs/medusa"
type InjectedDependencies = {
eventBusService: EventBusService
@@ -127,13 +130,19 @@ type InjectedDependencies = {
class GiftCardSubscriber {
giftCardService: GiftCardService
constructor({ eventBusService, giftCardService }: InjectedDependencies) {
constructor({
eventBusService,
giftCardService,
}: InjectedDependencies) {
this.giftCardService = giftCardService
eventBusService.subscribe("gift_card.created", this.handleGiftCard)
eventBusService.subscribe(
"gift_card.created", this.handleGiftCard)
}
handleGiftCard = async (data) => {
const giftCard = await this.giftCardService.retrieve(data.id)
const giftCard = await this.giftCardService.retrieve(
data.id
)
// TODO send customer the gift card code
}
}
@@ -143,12 +152,4 @@ export default GiftCardSubscriber
When using this method, youll have to handle the logic of sending the code to the customer inside the handler function, which in this case is `handleGiftCard`.
The `handleGiftCard` event receives a `data` object as a parameter. This object holds the `id` property which is the ID of the gift card. You can retrieve the full gift card object using the [GiftCardService](../../references/services/classes/GiftCardService.md)
---
## See Also
- [Subscribers overview](../backend/subscribers/overview.md)
- [Notification architecture overview](../backend/notification/overview.md)
- [Gift cards overview](../backend/gift-cards/index.md)
The `handleGiftCard` event receives a `data` object as a parameter. This object holds the `id` property which is the ID of the gift card. You can retrieve the full gift card object using the [GiftCardService](../../../references/services/classes/GiftCardService.md)

View File

@@ -1,5 +1,5 @@
---
description: 'Learn what gift cards are and how they work in the Medusa server. Learn about the relations between Gift Cards and other entities.'
description: 'Learn what gift cards are and how they work in the Medusa backend. Learn about the relations between Gift Cards and other entities.'
---
# Gift Cards
@@ -34,7 +34,7 @@ As custom gift cards can be used once theyre created, theyre also represen
## GiftCard Entity Overview
Some of the [GiftCard](../../../references/entities/classes/GiftCard.md) entitys attributes are:
Some of the [GiftCard](../../references/entities/classes/GiftCard.md) entitys attributes are:
- `code`: a unique string of random characters. This is the code that the customer can use during their checkout to redeem the gift card.
- `value`: The amount of the gift card. This is the amount the customer purchased, or was gifted in the case of custom gift cards.
@@ -70,7 +70,6 @@ You can also access the gift cards used in an order by expanding the `gift_cards
## See Also
- Gift cards [store](/api/store/#tag/Gift-Card) and [admin](/api/admin/#tag/Gift-Card) APIs
- [How to manage gift cards using admin APIs](../../admin/manage-gift-cards.mdx)
- [How to use gift cards in the storefront](../../storefront/use-gift-cards.mdx)
- [How to send the customer a gift card](../../ecommerce/send-gift-card-to-customer.md)
- [Manage gift cards using admin APIs](./admin/manage-gift-cards.mdx)
- [Use gift cards in the storefront](./storefront/use-gift-cards.mdx)
- [Send the customer a gift card](./backend/send-gift-card-to-customer.md)

View File

@@ -0,0 +1,149 @@
---
description: "Gift cards are prepaid codes that can be purchased and used during checkout as an alternative to payment methods or to receive a discount. Learn about the available features and guides."
---
import DocCardList from '@theme/DocCardList';
import DocCard from '@theme/DocCard';
import Icons from '@theme/Icon';
# Gift Cards
Gift cards are prepaid codes that can be purchased and used during checkout as an alternative to payment methods or to receive a discount. This overview introduces the available features related to gift cards.
:::note
Not a developer? Check out the [Gift Cards user guide](../../user-guide/gift-cards/index.md).
:::
## Features
### Gift Card Management
Admins can manage their main gift card with unlimited denominations.
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/modules/gift-cards/admin/manage-gift-cards',
label: 'Admin: Manage Gift Cards',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to manage gift cards using Admin APIs.'
}
},
{
type: 'link',
href: '/user-guide/gift-cards/manage',
label: 'User Guide: Manage Discounts',
customProps: {
icon: Icons['users-solid'],
description: 'Learn how to manage gift cards using Medusa Admin.'
}
},
]} />
### Gift Card Purchasing
Customers can view the gift card and purchase it on the storefront. Customers can also use the gift card during checkout to deduct the gift cards balance from the checkout total.
Developers can implement custom logic to send the gift card to the customer. They can alternatively implement a Shipping Profile that specifically handles the fulfillment of gift cards.
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/modules/gift-cards/backend/send-gift-card-to-customer',
label: 'Backend: Send Gift Card Code',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to use send a gift card code to a customer after their purchase.'
}
},
{
type: 'link',
href: '/modules/gift-cards/storefront/use-gift-cards',
label: 'Storefront: Use Gift Cards',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to show gift cards to customers and allow them to redeem them.'
}
},
]} />
### Custom Gift Cards
Admins can create custom gift cards that are sent to specific customers. These customers can then use the gift card during checkout, the same way they would if they purchased one.
<DocCardList colSize={4} items={[
{
type: 'link',
href: '/user-guide/gift-cards/custom',
label: 'User Guide: Custom Gift Cards',
customProps: {
icon: Icons['users-solid'],
description: 'Learn how to manage custom gift cards using Medusa Admin.'
}
},
{
type: 'link',
href: '/modules/gift-cards/admin/manage-gift-cards#manage-custom-gift-cards',
label: 'Admin: Manage Custom Gift Cards',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to manage custom gift cards using Admin APIs.'
}
},
{
type: 'link',
href: '/modules/gift-cards/backend/send-gift-card-to-customer',
label: 'Backend: Send Gift Card Code',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to use send a custom gift card code to a customer.'
}
},
]} />
---
## Understand the Architecture
Learn how gift card related entities and concepts are built, their relation to other modules, and more.
<DocCard item={{
type: 'link',
href: '/modules/gift-cards',
label: 'Architecture: Gift Card',
customProps: {
icon: Icons['circle-stack-solid'],
description: 'Learn about the Gift Card architecture.'
}
}}
/>
---
## Related Modules
Discover Gift Card's relation to other modules in Medusa
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/modules/products/overview',
label: 'Product',
customProps: {
icon: Icons['tag-solid'],
description: 'A stores main gift card is essentially a Product.'
}
},
{
type: 'link',
href: '/modules/carts-and-checkout/overview',
label: 'Cart and Checkout',
customProps: {
icon: Icons['shopping-cart-solid'],
description: 'Gift Cards can be used during checkout.'
}
},
]} />

View File

@@ -28,29 +28,29 @@ You want to implement the following features in a storefront:
### Medusa Components
It's assumed that you already have a Medusa server installed and set up. If not, you can follow the [quickstart guide](../../quickstart/quick-start.mdx) to get started.
It's assumed that you already have a Medusa backend installed and set up. If not, you can follow the [quickstart guide](../../../development/backend/install.mdx) to get started.
It is also assumed you already have a storefront set up. It can be a custom storefront or one of Medusas storefronts. If you dont have a storefront set up, you can install either the [Next.js](../../starters/nextjs-medusa-starter.mdx) or [Gatsby](../../starters/gatsby-medusa-starter.mdx) storefronts.
It is also assumed you already have a storefront set up. It can be a custom storefront or one of Medusas storefronts. If you dont have a storefront set up, you can install the [Next.js starter storefront](../../../starters/nextjs-medusa-starter.mdx).
### JS Client
This guide includes code snippets to send requests to your Medusa server using Medusas JS Client, among other methods.
This guide includes code snippets to send requests to your Medusa backend using Medusas JS Client, among other methods.
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client installed](../../js-client/overview.md) and have [created an instance of the client](../../js-client/overview.md#configuration).
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client installed](../../../js-client/overview.md) and have [created an instance of the client](../../../js-client/overview.md#configuration).
### Medusa React
This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods.
This guide also includes code snippets to send requests to your Medusa backend using Medusa React, among other methods.
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage).
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../../medusa-react/overview.md#usage).
For requests that use the cart, it's also assumed you already have [used CartProvider higher in your component tree](../../medusa-react/overview.md#cartprovider).
For requests that use the cart, it's also assumed you already have [used CartProvider higher in your component tree](../../../medusa-react/overview.md#cartprovider).
### Previous Steps
To use gift cards, you must have a gift card created first. You can follow this documentation to learn how to do it using the admin APIs.
In addition, this document doesn't cover how to implement checkout functionality. You can follow [this document](./how-to-implement-checkout-flow.mdx) to learn how to implement that.
In addition, this document doesn't cover how to implement checkout functionality. You can follow [this document](../../carts-and-checkout/storefront/implement-checkout-flow.mdx) to learn how to implement that.
---
@@ -99,7 +99,9 @@ const GiftCard = () => {
))}
</ul>
)}
{products && !products.length && <span>No Gift Cards</span>}
{products && !products.length && (
<span>No Gift Cards</span>
)}
</div>
)
}
@@ -111,7 +113,7 @@ export default GiftCard
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/products?is_giftcard=true`, {
fetch(`<BACKEND_URL>/store/products?is_giftcard=true`, {
credentials: "include",
})
.then((response) => response.json())
@@ -186,7 +188,7 @@ export default GiftCard
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/gift-cards/${code}`, {
fetch(`<BACKEND_URL>/store/gift-cards/${code}`, {
credentials: "include",
})
.then((response) => response.json())
@@ -273,7 +275,7 @@ export default Cart
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/cart/${cartId}`, {
fetch(`<BACKEND_URL>/store/cart/${cartId}`, {
method: "POST",
credentials: "include",
headers: {
@@ -318,13 +320,4 @@ You can show the details of the applied gift cards by accessing `cart.gift_cards
You can also use the following properties to display changes on the carts totals:
- `gift_card_total`: The total amount applied by all the gift cards.
- `gift_card_tax_total`: The total tax applied for all gift cards.
---
## See Also
- [Gift cards overview](../backend/gift-cards/index.md)
- [Manage gift cards using admin APIs](../admin/manage-gift-cards.mdx)
- [Send the customer a gift card](../ecommerce/send-gift-card-to-customer.md)
- Gift cards [store](/api/store/#tag/Gift-Card) and [admin](/api/admin/#tag/Gift-Card) APIs
- `gift_card_tax_total`: The total tax applied for all gift cards.

View File

@@ -26,7 +26,7 @@ The Order Edit can then either be confirmed using the Storefront API as a custom
The changes are only reflected on the original order once the Order Edit is confirmed.
![Order edit documentation](https://res.cloudinary.com/dza7lstvk/image/upload/v1671719712/Medusa%20Docs/Diagrams/Order_Edits_xvquwc.jpg)
![Order edit flow](https://res.cloudinary.com/dza7lstvk/image/upload/v1677782269/Medusa%20Docs/Diagrams/order-edit_mcnfc3.jpg)
### Scenario
@@ -50,19 +50,19 @@ You can perform other functionalities related to order editing. To learn more, c
### Medusa Components
It is assumed that you already have a Medusa server installed and set up. If not, you can follow our [quickstart guide](../../quickstart/quick-start.mdx) to get started.
It is assumed that you already have a Medusa backend installed and set up. If not, you can follow our [quickstart guide](../../../development/backend/install.mdx) to get started.
### JS Client
This guide includes code snippets to send requests to your Medusa server using Medusas JS Client, among other methods.
This guide includes code snippets to send requests to your Medusa backend using Medusas JS Client, among other methods.
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client](../../js-client/overview.md) installed and have [created an instance of the client](../../js-client/overview.md#configuration).
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client](../../../js-client/overview.md) installed and have [created an instance of the client](../../../js-client/overview.md#configuration).
### Medusa React
This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods.
This guide also includes code snippets to send requests to your Medusa backend using Medusa React, among other methods.
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage).
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../../medusa-react/overview.md#usage).
### Authenticated Admin User
@@ -119,7 +119,7 @@ export default OrderEdit
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<YOUR_SERVER>/admin/order-edits`, {
fetch(`<BACKEND_URL>/admin/order-edits`, {
method: "POST",
credentials: "include",
headers: {
@@ -139,7 +139,7 @@ fetch(`<YOUR_SERVER>/admin/order-edits`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<SERVER_URL>/admin/order-edits' \
curl -L -X POST '<BACKEND_URL>/admin/order-edits' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -198,12 +198,13 @@ import { useAdminOrderEditAddLineItem } from "medusa-react"
const OrderEdit = () => {
const addLineItem = useAdminOrderEditAddLineItem(orderEditId)
const handleAddLineItem = (quantity: number, variantId: string) => {
addLineItem.mutate({
quantity,
variant_id: variantId,
})
}
const handleAddLineItem =
(quantity: number, variantId: string) => {
addLineItem.mutate({
quantity,
variant_id: variantId,
})
}
// ...
}
@@ -215,7 +216,7 @@ export default OrderEdit
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<YOUR_SERVER>/admin/order-edits/${orderEditId}/items`, {
fetch(`<BACKEND_URL>/admin/order-edits/${orderEditId}/items`, {
method: "POST",
credentials: "include",
headers: {
@@ -236,7 +237,7 @@ fetch(`<YOUR_SERVER>/admin/order-edits/${orderEditId}/items`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<SERVER_URL>/admin/order-edits/<ORDER_EDIT_ID>/items' \
curl -L -X POST '<BACKEND_URL>/admin/order-edits/<ORDER_EDIT_ID>/items' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -299,8 +300,10 @@ export default OrderEdit
</TabItem>
<TabItem value="fetch" label="Fetch API">
<!-- eslint-disable max-len -->
```ts
fetch(`<YOUR_SERVER>/admin/order-edits/${orderEditId}/items/${itemId}`, {
fetch(`<BACKEND_URL>/admin/order-edits/${orderEditId}/items/${itemId}`, {
method: "POST",
credentials: "include",
headers: {
@@ -320,7 +323,7 @@ fetch(`<YOUR_SERVER>/admin/order-edits/${orderEditId}/items/${itemId}`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<SERVER_URL>/admin/order-edits/<ORDER_EDIT_ID>/items/<ITEM_ID>' \
curl -L -X POST '<BACKEND_URL>/admin/order-edits/<ORDER_EDIT_ID>/items/<ITEM_ID>' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -376,8 +379,10 @@ export default OrderEdit
</TabItem>
<TabItem value="fetch" label="Fetch API">
<!-- eslint-disable max-len -->
```ts
fetch(`<YOUR_SERVER>/admin/order-edits/${orderEditId}/items/${itemId}`, {
fetch(`<BACKEND_URL>/admin/order-edits/${orderEditId}/items/${itemId}`, {
method: "DELETE",
credentials: "include",
})
@@ -391,7 +396,7 @@ fetch(`<YOUR_SERVER>/admin/order-edits/${orderEditId}/items/${itemId}`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X DELETE '<SERVER_URL>/admin/order-edits/<ORDER_EDIT_ID>/items/<ITEM_ID>' \
curl -L -X DELETE '<BACKEND_URL>/admin/order-edits/<ORDER_EDIT_ID>/items/<ITEM_ID>' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -445,9 +450,11 @@ export default OrderEdit
</TabItem>
<TabItem value="fetch" label="Fetch API">
<!-- eslint-disable max-len -->
```ts
fetch(
`<YOUR_SERVER>/admin/order-edits/${orderEditId}/changes/${changeId}`,
`<BACKEND_URL>/admin/order-edits/${orderEditId}/changes/${changeId}`,
{
method: "DELETE",
credentials: "include",
@@ -463,7 +470,7 @@ fetch(
<TabItem value="curl" label="cURL">
```bash
curl -L -X DELETE '<SERVER_URL>/admin/order-edits/<ORDER_EDIT_ID>/changes/<CHANGE_ID>' \
curl -L -X DELETE '<BACKEND_URL>/admin/order-edits/<ORDER_EDIT_ID>/changes/<CHANGE_ID>' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -492,7 +499,10 @@ To move an Order Edit into the request state, send a request to the [Request Con
```ts
medusa.admin.orderEdits.requestConfirmation(orderEditId)
.then(({ order_edit }) => {
console.log(order_edit.requested_at, order_edit.requested_by)
console.log(
order_edit.requested_at,
order_edit.requested_by
)
})
```
@@ -500,7 +510,9 @@ medusa.admin.orderEdits.requestConfirmation(orderEditId)
<TabItem value="medusa-react" label="Medusa React">
```tsx
import { useAdminRequestOrderEditConfirmation } from "medusa-react"
import {
useAdminRequestOrderEditConfirmation,
} from "medusa-react"
const OrderEdit = () => {
const requestOrderConfirmation =
@@ -521,8 +533,10 @@ export default OrderEdit
</TabItem>
<TabItem value="fetch" label="Fetch API">
<!-- eslint-disable max-len -->
```ts
fetch(`<YOUR_SERVER>/admin/order-edits/${orderEditId}/request`, {
fetch(`<BACKEND_URL>/admin/order-edits/${orderEditId}/request`, {
method: "POST",
credentials: "include",
})
@@ -536,7 +550,7 @@ fetch(`<YOUR_SERVER>/admin/order-edits/${orderEditId}/request`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<SERVER_URL>/admin/order-edits/<ORDER_EDIT_ID>/request' \
curl -L -X POST '<BACKEND_URL>/admin/order-edits/<ORDER_EDIT_ID>/request' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -552,7 +566,7 @@ It returns the Order Edit object. You can access the following properties relate
:::tip
💡 This request triggers the event `order-edit.requested`. You can use a subscriber to send an email to the customer with a link to view the order edit on the storefront. You can learn more in the [Events reference](../backend/subscribers/events-list.md).
💡 This request triggers the event `order-edit.requested`. You can use a subscriber to send an email to the customer with a link to view the order edit on the storefront. You can learn more in the [Events reference](../../../development/events/events-list.md).
:::
@@ -607,8 +621,10 @@ export default OrderEdit
</TabItem>
<TabItem value="fetch" label="Fetch API">
<!-- eslint-disable max-len -->
```ts
fetch(`<YOUR_SERVER>/admin/order-edits/${orderEditId}/confirm`, {
fetch(`<BACKEND_URL>/admin/order-edits/${orderEditId}/confirm`, {
method: "POST",
credentials: "include",
})
@@ -622,7 +638,7 @@ fetch(`<YOUR_SERVER>/admin/order-edits/${orderEditId}/confirm`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<SERVER_URL>/admin/order-edits/<ORDER_EDIT_ID>/confirm' \
curl -L -X POST '<BACKEND_URL>/admin/order-edits/<ORDER_EDIT_ID>/confirm' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -673,7 +689,9 @@ medusa.admin.payments.capturePayment(paymentId)
import { useAdminPaymentsCapturePayment } from "medusa-react"
const OrderEditPayment = () => {
const capturePayment = useAdminPaymentsCapturePayment(paymentId)
const capturePayment = useAdminPaymentsCapturePayment(
paymentId
)
const handleCapturePayment = () => {
capturePayment.mutate()
@@ -689,7 +707,7 @@ export default OrderEditPayment
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<YOUR_SERVER>/admin/payments/${paymentId}/capture`, {
fetch(`<BACKEND_URL>/admin/payments/${paymentId}/capture`, {
method: "POST",
credentials: "include",
})
@@ -703,7 +721,7 @@ fetch(`<YOUR_SERVER>/admin/payments/${paymentId}/capture`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<SERVER_URL>/admin/payments/<PAYMENT_ID>/capture' \
curl -L -X POST '<BACKEND_URL>/admin/payments/<PAYMENT_ID>/capture' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -746,12 +764,13 @@ import { RefundReason } from "@medusajs/medusa"
const OrderEditPayment = () => {
const refundPayment = useAdminPaymentsRefundPayment(paymentId)
const handleRefundPayment = (amount: number, reason: RefundReason) => {
refundPayment.mutate({
amount,
reason,
})
}
const handleRefundPayment =
(amount: number, reason: RefundReason) => {
refundPayment.mutate({
amount,
reason,
})
}
// ...
}
@@ -763,7 +782,7 @@ export default OrderEditPayment
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<YOUR_SERVER>/admin/payments/${paymentId}/refund`, {
fetch(`<BACKEND_URL>/admin/payments/${paymentId}/refund`, {
method: "POST",
credentials: "include",
headers: {
@@ -784,7 +803,7 @@ fetch(`<YOUR_SERVER>/admin/payments/${paymentId}/refund`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<SERVER_URL>/admin/payments/<PAYMENT_ID>/refund' \
curl -L -X POST '<BACKEND_URL>/admin/payments/<PAYMENT_ID>/refund' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -820,5 +839,4 @@ It returns in the response the full Refund object.
## See Also
- [Handle order edits on the storefront](../storefront/handle-order-edits).
- [Order Edits API reference](/api/admin/#tag/OrderEdit).
- [Handle order edits on the storefront](../storefront/handle-order-edits.mdx)

View File

@@ -1,5 +1,5 @@
---
description: 'Learn how to handle the order claim event in the Medusa server. When the event is triggered, you can send an email to the customer to inform them about it.'
description: 'Learn how to handle the order claim event in the Medusa backend. When the event is triggered, you can send an email to the customer to inform them about it.'
addHowToData: true
---
@@ -13,11 +13,11 @@ When a guest customer places an order, the order is not associated with a custom
After the customer registers, later on, they can claim that order by providing the orders ID.
When the customer requests to claim the order, the event `order-update-token.created` is triggered on the Medusa server. This event should be used to send the customer a confirmation email.
When the customer requests to claim the order, the event `order-update-token.created` is triggered on the Medusa backend. This event should be used to send the customer a confirmation email.
### What Youll Learn
In this document, youll learn how to handle the `order-update-token.created` event on the server to send the customer a confirmation email.
In this document, youll learn how to handle the `order-update-token.created` event on the backend to send the customer a confirmation email.
---
@@ -25,17 +25,17 @@ In this document, youll learn how to handle the `order-update-token.created`
### Medusa Components
It's assumed that you already have a Medusa server installed and set up. If not, you can follow the [quickstart guide](../../quickstart/quick-start.mdx) to get started.
It's assumed that you already have a Medusa backend installed and set up. If not, you can follow the [quickstart guide](../../../development/backend/install.mdx) to get started.
### Redis
Redis is required for batch jobs to work. Make sure you [install Redis](../../tutorial/0-set-up-your-development-environment.mdx#redis) and [configure it with your Medusa server](../../usage/configurations.md#redis).
Redis is required for batch jobs to work. Make sure you [install Redis](../../../development/backend/prepare-environment.mdx#redis) and [configure it with the Medusa backend](../../../development/backend/configurations.md#redis).
### Notification Provider
To send an email or another type of notification method, you must have a notification provider installed or configured. You can either install an existing plugin or [create your own](../backend/notification/how-to-create-notification-provider.md).
To send an email or another type of notification method, you must have a notification provider installed or configured. You can either install an existing plugin or [create your own](../../../development/notification/create-notification-provider.md).
This document has an example using the [SendGrid](../../add-plugins/sendgrid.mdx) plugin.
This document has an example using the [SendGrid](../../../plugins/notifications/sendgrid.mdx) plugin.
---
@@ -45,7 +45,7 @@ To subscribe to and handle an event, you must create a subscriber.
:::tip
You can learn more about subscribers in the [Subscribers](../backend/subscribers/overview.md) documentation.
You can learn more about subscribers in the [Subscribers](../../../development/events/subscribers.mdx) documentation.
:::
@@ -69,7 +69,7 @@ Youll be adding in the next step the necessary dependencies to the subscriber
:::info
You can learn more about [dependency injection](../backend/dependency-container/index.md) in this documentation.
You can learn more about [dependency injection](../../../development/fundamentals/dependency-injection.md) in this documentation.
:::
@@ -108,7 +108,7 @@ Where `<NOTIFICATION_PROVIDER_IDENTIFIER>` is the identifier for your notificati
:::info
You can learn more about handling events with the Notification Service using [this documentation](../backend/notification/how-to-create-notification-provider.md).
You can learn more about handling events with the Notification Service using [this documentation](../../../development/notification/create-notification-provider.md).
:::
@@ -150,7 +150,7 @@ The `handleRequestClaimOrder` event receives a `data` object as a parameter. Thi
In this method, you should typically send an email to the customers old email. In the email, you should link to a page in your storefront and pass the `token` as a parameter.
The page would then send a request to the server to verify that the `token` is valid and associate the order with the customer. You can read more about how to implement this in your storefront in [this documentation](../storefront/implement-claim-order.mdx).
The page would then send a request to the backend to verify that the `token` is valid and associate the order with the customer. You can read more about how to implement this in your storefront in [this documentation](../storefront/implement-claim-order.mdx).
---
@@ -158,6 +158,8 @@ The page would then send a request to the server to verify that the `token` is v
For example, you can implement this subscriber to send emails using SendGrid:
<!-- eslint-disable max-len -->
```ts title=src/subscribers/claim-order.ts
import { EventBusService } from "@medusajs/medusa"
@@ -169,7 +171,10 @@ type InjectedDependencies = {
class ClaimOrderSubscriber {
protected sendGridService: any
constructor({ eventBusService, sendgridService }: InjectedDependencies) {
constructor({
eventBusService,
sendgridService,
}: InjectedDependencies) {
this.sendGridService = sendgridService
eventBusService.subscribe(
"order-update-token.created",

View File

@@ -0,0 +1,357 @@
---
description: "Customers place orders to purchase products from an ecommerce business. Learn about the available features and guides."
---
import DocCardList from '@theme/DocCardList';
import Icons from '@theme/Icon';
# Orders
Customers place orders to purchase products from an ecommerce business. This overview introduces the available features related to orders.
:::note
Not a developer? Check out the [Orders user guide](../../user-guide/orders/index.md).
:::
## Features
### Order Management
Admins can manage orders placed by customers, including capturing payment and fulfilling items in the order. Admins can also export orders into CSV files.
Customers can view their previous orders.
<DocCardList colSize={4} items={[
{
type: 'link',
href: '#',
label: 'Admin: Manage Orders',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to manage orders using Admin APIs.',
isSoon: true,
}
},
{
type: 'link',
href: '/user-guide/orders/manage',
label: 'User Guide: Manage Orders',
customProps: {
icon: Icons['users-solid'],
description: 'Manage orders in Medusa Admin.'
}
},
{
type: 'link',
href: '/user-guide/orders/export',
label: 'User Guide: Export Orders',
customProps: {
icon: Icons['users-solid'],
description: 'Export orders into CSV files in Medusa admin.'
}
},
]} />
<DocCardList colSize={4} items={[
{
type: 'link',
href: '/user-guide/orders/payments',
label: 'User Guide: Manage Payments',
customProps: {
icon: Icons['users-solid'],
description: 'Manage an order\'s payment in Medusa Admin.'
}
},
{
type: 'link',
href: '/user-guide/orders/fulfillments',
label: 'User Guide: Manage Fulfillment',
customProps: {
icon: Icons['users-solid'],
description: 'Manage an order\'s fulfillment in Medusa Admin.'
}
},
{
type: 'link',
href: '#',
label: 'Storefront: Manage Customer Orders',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to manage orders as a customer.',
isSoon: true,
}
},
]} />
### Edit Orders
Admins can perform edits on items in an order, such as add, remove, or update items. Admins can request confirmation from the customer or force apply the edit.
Customers can review order edit requests and authorize additional payments if necessary.
<DocCardList colSize={4} items={[
{
type: 'link',
href: '/modules/orders/admin/edit-order',
label: 'Admin: Edit an Order',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to edit an order using Admin APIs.'
}
},
{
type: 'link',
href: '/user-guide/orders/edit',
label: 'User Guide: Edit Order',
customProps: {
icon: Icons['users-solid'],
description: 'Edit an order in Medusa Admin.'
}
},
{
type: 'link',
href: '/modules/orders/storefront/handle-order-edits',
label: 'Storefront: Order Edits',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Handle order edits in a storefront.'
}
},
]} />
### Draft Orders
Admins can create draft orders that dont require involvement from a customer. They can specify all details including items in the order, payment method, and more.
<DocCardList colSize={4} items={[
{
type: 'link',
href: '#',
label: 'Admin: Manage Draft Orders',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to manage draft orders using Admin APIs.',
isSoon: true,
}
},
{
type: 'link',
href: '/user-guide/orders/edit',
label: 'User Guide: Draft Orders',
customProps: {
icon: Icons['users-solid'],
description: 'Manage draft orders in Medusa Admin.'
}
},
{
type: 'link',
href: '/api/admin#tag/Draft-Order',
label: 'Admin APIs: Draft Orders',
customProps: {
icon: Icons['server-solid'],
description: 'Check available Admin REST APIs for Draft Orders.'
}
},
]} />
### Returns, Swaps, and Claims
Admins can return order items, or create swaps to return an item to be replaced by a new one.
Customers can also request to return or swap items. This allows for implementing an automated Return Merchandise Authorization (RMA) flow.
<DocCardList colSize={4} items={[
{
type: 'link',
href: '#',
label: 'Admin: Manage Returns',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to manage returns using Admin APIs.',
isSoon: true,
}
},
{
type: 'link',
href: '#',
label: 'Admin: Manage Swaps',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to manage swaps using Admin APIs.',
isSoon: true,
}
},
{
type: 'link',
href: '#',
label: 'Admin: Manage Claims',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to manage claims using Admin APIs.',
isSoon: true,
}
},
{
type: 'link',
href: '/user-guide/orders/returns',
label: 'User Guide: Manage Returns',
customProps: {
icon: Icons['users-solid'],
description: 'Manage order returns in Medusa Admin.'
}
},
{
type: 'link',
href: '/user-guide/orders/exchange',
label: 'User Guide: Exchanges',
customProps: {
icon: Icons['users-solid'],
description: 'Manage order exchanges in Medusa Admin.'
}
},
{
type: 'link',
href: '/user-guide/orders/claims',
label: 'User Guide: Manage Claims',
customProps: {
icon: Icons['users-solid'],
description: 'Manage order claims in Medusa Admin.'
}
},
{
type: 'link',
href: '#',
label: 'Storefront: Create a Return',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create a return as a customer.',
isSoon: true,
}
},
{
type: 'link',
href: '#',
label: 'Storefront: Create a Swap',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create a swap as a customer.',
isSoon: true,
}
},
{
type: 'link',
href: '/api/store#tag/Return',
label: 'Storefront APIs: Returns',
customProps: {
icon: Icons['server-solid'],
description: 'Check available Storefront REST APIs for Returns.'
}
},
]} />
---
## Understand the Architecture
Learn how order-related entities are built, their relation to other modules, and more.
<DocCardList colSize={4} items={[
{
type: 'link',
href: '#',
label: 'Architecture: Order',
customProps: {
icon: Icons['circle-stack-solid'],
description: 'Learn about the Order architecture.',
isSoon: true,
}
},
{
type: 'link',
href: '#',
label: 'Architecture: Swap',
customProps: {
icon: Icons['circle-stack-solid'],
description: 'Learn about the Swap architecture.',
isSoon: true,
}
},
{
type: 'link',
href: '#',
label: 'Architecture: Return',
customProps: {
icon: Icons['circle-stack-solid'],
description: 'Learn about the Return architecture.',
isSoon: true,
}
},
{
type: 'link',
href: '#',
label: 'Architecture: Claim',
customProps: {
icon: Icons['circle-stack-solid'],
description: 'Learn about the Claim architecture.',
isSoon: true,
}
},
{
type: 'link',
href: '#',
label: 'Architecture: Draft Order',
customProps: {
icon: Icons['circle-stack-solid'],
description: 'Learn about the Draft Order architecture.',
isSoon: true,
}
},
{
type: 'link',
href: '#',
label: 'Architecture: Fulfillment',
customProps: {
icon: Icons['circle-stack-solid'],
description: 'Learn about the Fulfillment architecture.',
isSoon: true,
}
},
]} />
---
## Related Modules
Discover Orders relation to other modules in Medusa
<DocCardList colSize={4} items={[
{
type: 'link',
href: '/modules/carts-and-checkout/overview',
label: 'Carts and Checkout',
customProps: {
icon: Icons['shopping-cart-solid'],
description: 'Customers can place an order using a virtual cart.'
}
},
{
type: 'link',
href: '/modules/products/overview',
label: 'Products',
customProps: {
icon: Icons['tag-solid'],
description: 'Customers can browse products to purchase them.'
}
},
{
type: 'link',
href: '/modules/sales-channels/overview',
label: 'Sales Channels',
customProps: {
icon: Icons['channels-solid'],
description: 'Orders can be associated with specific channels.',
}
},
]} />

View File

@@ -22,7 +22,7 @@ This guide focuses on how to use the Storefront APIs to implement the flow that
:::note
You can check out how to implement order editing using the Admin APIs in [this documentation](../admin/order-edit.mdx).
You can check out how to implement order editing using the Admin APIs in [this documentation](../admin/edit-order.mdx).
:::
@@ -46,21 +46,21 @@ You can perform other functionalities related to order editing. To learn more, c
### Medusa Components
It's assumed that you already have a Medusa server installed and set up. If not, you can follow our [quickstart guide](../../quickstart/quick-start.mdx) to get started.
It's assumed that you already have a Medusa backend installed and set up. If not, you can follow our [quickstart guide](../../../development/backend/install.mdx) to get started.
It is also assumed you already have a storefront set up. It can be a custom storefront or one of Medusas storefronts. If you dont have a storefront set up, you can install either the [Next.js](../../starters/nextjs-medusa-starter.mdx) or [Gatsby](../../starters/gatsby-medusa-starter.mdx) storefronts.
It is also assumed you already have a storefront set up. It can be a custom storefront or one of Medusas storefronts. If you dont have a storefront set up, you can install the [Next.js starter storefront](../../../starters/nextjs-medusa-starter.mdx).
### JS Client
This guide includes code snippets to send requests to your Medusa server using Medusas JS Client and JavaScripts Fetch API.
This guide includes code snippets to send requests to your Medusa backend using Medusas JS Client and JavaScripts Fetch API.
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client installed](../../js-client/overview.md) and have [created an instance of the client](../../js-client/overview.md#configuration).
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client installed](../../../js-client/overview.md) and have [created an instance of the client](../../../js-client/overview.md#configuration).
### Medusa React
This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods.
This guide also includes code snippets to send requests to your Medusa backend using Medusa React, among other methods.
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage).
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../../medusa-react/overview.md#usage).
### Previous Steps
@@ -102,7 +102,7 @@ export default OrderEdit
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/order-edits/${orderEditId}`)
fetch(`<BACKEND_URL>/store/order-edits/${orderEditId}`)
.then((response) => response.json())
.then(({ order_edit }) => {
console.log(order_edit.changes)
@@ -161,7 +161,9 @@ Heres an example of how you can use this data to show the customer the reques
}
</strong>
{itemChange.type === "added" && <span>New Item</span>}
{itemChange.type === "removed" && <span>Removed Item</span>}
{itemChange.type === "removed" && (
<span>Removed Item</span>
)}
{itemChange.type === "edited" &&
<span>
Edited Item
@@ -201,6 +203,8 @@ If `difference_due` is greater than 0, then additional payment from the customer
<Tabs groupId="request-type" wrapperClassName="code-tabs">
<TabItem value="client" label="Medusa JS Client" default>
<!-- eslint-disable max-len -->
```ts
medusa.paymentCollections.managePaymentSession(paymentCollectionId, {
provider_id,
@@ -217,7 +221,9 @@ medusa.paymentCollections.managePaymentSession(paymentCollectionId, {
import { useManagePaymentSession } from "medusa-react"
const OrderEditPayment = () => {
const managePaymentSession = useManagePaymentSession(paymentCollectionId)
const managePaymentSession = useManagePaymentSession(
paymentCollectionId
)
// ...
const handleAdditionalPayment = (provider_id: string) => {
@@ -235,9 +241,11 @@ export default OrderEditPayment
</TabItem>
<TabItem value="fetch" label="Fetch API">
<!-- eslint-disable max-len -->
```ts
fetch(
`<SERVER_URL>/store/payment-collections/${paymentCollectionId}/sessions`,
`<BACKEND_URL>/store/payment-collections/${paymentCollectionId}/sessions`,
{
method: "POST",
credentials: "include",
@@ -265,8 +273,12 @@ fetch(
<TabItem value="client" label="Medusa JS Client" default>
```ts
medusa.paymentCollection
.authorizePaymentSession(paymentCollectionId, paymentSessionId)
medusa
.paymentCollection
.authorizePaymentSession(
paymentCollectionId,
paymentSessionId
)
.then(({ payment_session }) => {
console.log(payment_session.id)
})
@@ -297,9 +309,11 @@ export default OrderEditPayment
</TabItem>
<TabItem value="fetch" label="Fetch API">
<!-- eslint-disable max-len -->
```ts
fetch(
`<SERVER_URL>/store/payment-collection/${paymentCollectionId}` +
`<BACKEND_URL>/store/payment-collection/${paymentCollectionId}` +
`/sessions/${paymentSessionId}/authorize`,
{
method: "POST",
@@ -356,8 +370,10 @@ export default OrderEdit
</TabItem>
<TabItem value="fetch" label="Fetch API">
<!-- eslint-disable max-len -->
```ts
fetch(`<SERVER_URL>/store/order-edits/${orderEditId}/complete`, {
fetch(`<BACKEND_URL>/store/order-edits/${orderEditId}/complete`, {
method: "POST",
credentials: "include",
})
@@ -426,16 +442,19 @@ export default OrderEdit
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/order-edits/${orderEditId}/decline`, {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
decline_reason: "I am not satisfied",
}),
})
fetch(
`<BACKEND_URL>/store/order-edits/${orderEditId}/decline`,
{
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
decline_reason: "I am not satisfied",
}),
}
)
.then((response) => response.json())
.then(({ order_edit }) => {
console.log(order_edit.declined_at)
@@ -455,5 +474,4 @@ If the Order Edit is declined, the changes requested in the Order Edit aren't re
## See Also
- [Order Edit API reference](/api/store/#tag/OrderEdit)
- [Edit an order using Admin APIs](../admin/order-edit.mdx)
- [Edit an order using Admin APIs](../admin/edit-order.mdx)

View File

@@ -12,7 +12,7 @@ In this document, youll learn how to implement the claim order flow in a stor
:::note
This flow was added starting from Medusa v1.7. You can learn more about upgrading in the [upgrade guide](../backend/upgrade-guides/medusa-core/1-7-0.md).
This flow was added starting from Medusa v1.7. You can learn more about upgrading in the [upgrade guide](../../../upgrade-guides/medusa-core/1-7-0.md).
:::
@@ -28,7 +28,7 @@ The email should contain a link to a page in the storefront, and the link should
The customer must then click the link in the email they received. If the token is valid, the order will be associated with the customer.
![Claim Order Flow](https://res.cloudinary.com/dza7lstvk/image/upload/v1671040165/Medusa%20Docs/Diagrams/Claim_Order_Flow_ybf2ok.jpg)
![Claim Order Flow](https://res.cloudinary.com/dza7lstvk/image/upload/v1677782439/Medusa%20Docs/Diagrams/claim-order-workflow_m6oybo.jpg)
### What Youll Learn
@@ -43,31 +43,31 @@ In this document, youll learn how to implement two parts of this flow:
### Medusa Components
It's assumed that you already have a Medusa server installed and set up. If not, you can follow the [quickstart guide](../../quickstart/quick-start.mdx) to get started.
It's assumed that you already have a Medusa backend installed and set up. If not, you can follow the [quickstart guide](../../../development/backend/install.mdx) to get started.
It is also assumed you already have a storefront set up. It can be a custom storefront or one of Medusas storefronts. If you dont have a storefront set up, you can install either the [Next.js](../../starters/nextjs-medusa-starter.mdx) or [Gatsby](../../starters/gatsby-medusa-starter.mdx) storefronts.
It is also assumed you already have a storefront set up. It can be a custom storefront or one of Medusas storefronts. If you dont have a storefront set up, you can install the [Next.js starter storefront](../../../starters/nextjs-medusa-starter.mdx).
### JS Client
This guide includes code snippets to send requests to your Medusa server using Medusas JS Client, among other methods.
This guide includes code snippets to send requests to your Medusa backend using Medusas JS Client, among other methods.
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client installed](../../js-client/overview.md) and have [created an instance of the client](../../js-client/overview.md#configuration).
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client installed](../../../js-client/overview.md) and have [created an instance of the client](../../../js-client/overview.md#configuration).
### Medusa React
This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods.
This guide also includes code snippets to send requests to your Medusa backend using Medusa React, among other methods.
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage).
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../../medusa-react/overview.md#usage).
### Handle Order Claim Request Event
When the customer requests to claim the order, an event will be triggered. You should subscribe to this event to send a confirmation email to the customer when the event is triggered.
You can learn how to implement this flow in [this documentation](../ecommerce/handle-order-claim-event.md).
You can learn how to implement this flow in [this documentation](../backend/handle-order-claim-event.md).
### Previous Steps
It is assumed you already have an order placed by a guest customer. You can refer to the [Cart](../../guides/carts-in-medusa.mdx) and [Checkout](./how-to-implement-checkout-flow.mdx) implementation documentation to learn how to implement them in your storefront.
It is assumed you already have an order placed by a guest customer. You can refer to the [Cart](../../carts-and-checkout/storefront/implement-cart) and [Checkout](../../carts-and-checkout/storefront/implement-checkout-flow.mdx) implementation documentation to learn how to implement them in your storefront.
In addition, it is assumed you already have a logged-in customer before performing the steps in this document. You can refer to the [API reference](/api/store/#tag/Auth/operation/PostAuth) for more details on that.
@@ -100,7 +100,7 @@ medusa.orders.claimOrders({
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/orders/batch/customer/token`, {
fetch(`<BACKEND_URL>/store/orders/batch/customer/token`, {
method: "POST",
credentials: "include",
body: JSON.stringify({
@@ -178,7 +178,7 @@ export default ClaimOrder
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<SERVER_URL>/store/orders/customer/confirm`, {
fetch(`<BACKEND_URL>/store/orders/customer/confirm`, {
method: "POST",
credentials: "include",
body: JSON.stringify({
@@ -207,4 +207,4 @@ If the verification is successful, the order will now be associated with the cus
## See Also
- [Send a confirmation email to claim an order](../ecommerce/handle-order-claim-event.md)
- [Send a confirmation email to claim an order](../backend/handle-order-claim-event.md)

View File

@@ -0,0 +1,247 @@
---
description: 'Learn about the ecommerce features that Medusa provides including order management, product management, multi region and currency support, and more.'
hide_table_of_contents: true
---
import DocCardList from '@theme/DocCardList'
import Icons from '@theme/Icon'
import LargeCardList from '@site/src/components/LargeCardList'
import LargeCard from '@site/src/components/LargeCard'
# Commerce Modules
Medusa offers ecommerce features essential to all types of businesses as Commerce Modules. Starting from the basic products management and order management, to the more advanced automated return and exchange flows.
This part of the documentation covers Medusas ecommerce features and how they can be used. It also includes guides that help developers utilize these features to create unique digital experiences.
## Feature Highlights
This section gives an overview of the features available in Medusa. You can learn more about other available features by following the guides in this documentation.
### Optimized Shopping and Fulfillment Experience
Medusa provides the necessary features to build a customizable shopping experience for your customers. Medusa also offers features optimized for business operations to manage their orders effeciently.
<LargeCardList>
<LargeCard
Icon={Icons['check-circle-solid']}
title='Orders'
action={{
label: 'Learn more',
href: '/modules/orders/overview'
}}
>
- Process orders' payments and fulfillments with custom logic or third-party providers.
- Create one or multiple fulfillments for items in the order.
- Edit an order to add, update, or delete its items.
- Handle and automate order returns, exchanges, and refunds.
- Create draft orders without direct involvement from the customer.
</LargeCard>
<LargeCard
Icon={Icons['shopping-cart-solid']}
title='Cart and Checkout'
action={{
label: 'Learn more',
href: '/modules/carts-and-checkout/overview'
}}
>
- Accept payments with payment providers including Stripe and PayPal.
- Calculate taxes of a cart through custom logic or third-party tax providers.
- Allow customers to apply discount codes and gift cards during checkout.
- Fully customize the frontend experience of the checkout process.
</LargeCard>
<LargeCard
Icon={Icons['users-solid']}
title='Customers'
action={{
label: 'Learn more',
href: '/modules/customers/overview'
}}
>
- Allow orders from both registered and unregisterd customers.
- Allow customers to create return or exchange requests from the storefront for better customer experience.
- Assign customers different groups for segmentation and specify different pricing for customer groups.
</LargeCard>
</LargeCardList>
### Advanced Product Configurations and Management
Medusa's products configuration allows managing products of different types including products with options and gift cards. Medusa also includes advanced features related to pricing and discounts.
<LargeCardList>
<LargeCard
Icon={Icons['tag-solid']}
title='Products'
action={{
label: 'Learn more',
href: '/modules/products/overview'
}}
>
- Create products with unlimited variants and options.
- Organize products into nested categories of different heirarchies.
- Associate products with collections, types, and tags.
- Manage a products inventory, pricing, sales channels, and more.
- Import and export products to and from Medusa using CSV files.
</LargeCard>
<LargeCard
Icon={Icons['gift-solid']}
title='Gift Cards'
action={{
label: 'Learn more',
href: '/modules/gift-cards/overview'
}}
>
- Offer your customers a gift card with unlimited denominations.
- Set denomination prices per currency to cater for different regions.
- Send custom gift cards to specific customers for marketing purposes.
- Manage a custom gift card's balance amount.
</LargeCard>
<LargeCard
Icon={Icons['currency-dollar-solid']}
title='Price Lists and Discounts'
action={{
label: 'Learn more',
href: '/modules/price-lists/overview'
}}
>
- Create discounts and deals with advanced conditions and rules such as minimum cart quantity or specific products.
- Offer free shipping, fixed discount, or percentage discount.
- Override product prices using price lists and set special conditions such as specific customer groups.
- Import prices into a price list from a CSV file.
</LargeCard>
</LargeCardList>
### Ready Configurations for International Selling
Medusa's multi-region setup and sales channels allow businesses to sell internationally and sell across platforms. Medusa allows configuring regions differently to cater for different markets across the globe.
<LargeCardList>
<LargeCard
Icon={Icons['globe-europe-solid']}
title='Multi-Region'
action={{
label: 'Learn more',
href: '/modules/regions-and-currencies/overview'
}}
>
- Create an unlimited number of regions, each associated with a currency and at least one country.
- Manage each regions settings including payment providers, shipping options, and more.
- Set prices for products and shipping options specific to a currency or a region.
</LargeCard>
<LargeCard
Icon={Icons['cash-solid']}
title='Taxes'
action={{
label: 'Learn more',
href: '/modules/taxes/overview'
}}
>
- Specify different tax providers for different regions.
- Create tax providers using custom logic or third-party integrations.
- Customize tax configurations using tax rates and tax overrides.
- Enable tax-inclusive pricing for automatic tax-rate calculations during checkout.
</LargeCard>
<LargeCard
Icon={Icons['channels-solid']}
title='Sales Channels'
action={{
label: 'Learn more',
href: '/modules/sales-channels/overview'
}}
>
- Create sales channels for your different platforms such as web, mobile, or marketplaces.
- Specify the availability of products for each sales channel.
- Associate orders with each sales channel for better handling and logistics.
- Associate API keys with sales channels for easier development.
</LargeCard>
</LargeCardList>
## Get Additional Help
If you have any questions about Medusa, its features, and development with it, feel free to reach out to the core team and the community behind Medusa on [Discord](https://discord.gg/medusajs).
## Popular Guides
<DocCardList colSize={4} items={[
{
type: 'link',
href: '/modules/customers/storefront/implement-customer-profiles',
label: 'Implement Accounts',
customProps: {
icon: Icons['users-solid'],
description: 'Add customer profiles to the storefront.',
}
},
{
type: 'link',
href: '/modules/carts-and-checkout/storefront/implement-cart',
label: 'Implement Cart',
customProps: {
icon: Icons['shopping-cart-solid'],
description: 'Add cart functionality to the storefront.',
}
},
{
type: 'link',
href: '/modules/carts-and-checkout/backend/add-payment-provider',
label: 'Create a Payment Provider',
customProps: {
icon: Icons['credit-card-solid'],
description: 'Create a payment provider.',
},
},
{
type: 'link',
href: '/modules/orders/admin/edit-order',
label: 'Edit an Order',
customProps: {
icon: Icons['pencil-square-solid'],
description: 'Edit an order with the Admin APIs.',
}
},
{
type: 'link',
href: '/modules/price-lists/admin/import-prices',
label: 'Import Prices',
customProps: {
icon: Icons['currency-dollar-solid'],
description: 'Import prices to Medusa.',
}
},
{
type: 'link',
href: '/modules/sales-channels/admin/manage',
label: 'Manage Sales Channels',
customProps: {
icon: Icons['channels-solid'],
description: 'Manage sales channels.',
}
}
]} />

View File

@@ -12,7 +12,7 @@ In this document, youll learn how to bulk import prices into a price list usi
## Overview
Using Medusas [Batch Job Admin APIs](https://docs.medusajs.com/api/admin/#tag/Batch-Job), you can import prices into a price list.
Using Medusas [Batch Job Admin APIs](/api/admin/#tag/Batch-Job), you can import prices into a price list.
:::caution
@@ -26,46 +26,46 @@ Importing prices into a price list removes all existing prices in the price list
### Medusa Components
It is assumed that you already have a Medusa server installed and set up. If not, you can follow our [quickstart guide](../../quickstart/quick-start.mdx) to get started.
It is assumed that you already have a Medusa backend installed and set up. If not, you can follow our [quickstart guide](../../../development/backend/install.mdx) to get started.
### Redis
Redis is required for batch jobs to work. Make sure you [install Redis](../../tutorial/0-set-up-your-development-environment.mdx#redis) and [configure it with your Medusa server](./../../usage/configurations.md#redis).
Redis is required for batch jobs to work. Make sure you [install Redis](../../../development/backend/prepare-environment.mdx#redis) and [configure it with the Medusa backend](../../../development/backend/configurations.md#redis).
### File Service Plugin
Part of the process of importing prices is uploading a CSV file. This requires a file service plugin to be installed on your server. If you dont have any installed, you can install one of the following options:
Part of the process of importing prices is uploading a CSV file. This requires a file service plugin to be installed on your backend. If you dont have any installed, you can install one of the following options:
- [MinIO](../../add-plugins/minio.md) (At least version `1.1.0`)
- [Spaces](../../add-plugins/spaces.md)
- [MinIO](../../../plugins/file-service/minio.md) (At least version `1.1.0`)
- [Spaces](../../../plugins/file-service/spaces.md)
### CSV File
You must have a CSV file that you will use to import prices into your Medusa server. You can check [this CSV example file](https://medusa-doc-files.s3.amazonaws.com/price-list-import-template.csv) to see which format is required for your import.
You must have a CSV file that you will use to import prices into your Medusa backend. You can check [this CSV example file](https://medusa-doc-files.s3.amazonaws.com/price-list-import-template.csv) to see which format is required for your import.
### JS Client
This guide includes code snippets to send requests to your Medusa server using Medusas JS Client, among other methods.
This guide includes code snippets to send requests to your Medusa backend using Medusas JS Client, among other methods.
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client](../../js-client/overview.md) installed and have [created an instance of the client](../../js-client/overview.md#configuration).
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client](../../../js-client/overview.md) installed and have [created an instance of the client](../../../js-client/overview.md#configuration).
### Medusa React
This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods.
This guide also includes code snippets to send requests to your Medusa backend using Medusa React, among other methods.
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage).
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../../medusa-react/overview.md#usage).
### Authenticated Admin User
You must be an authenticated admin user before following along with the steps in the tutorial.
You can learn more about [authenticating as an admin user in the API reference](https://docs.medusajs.com/api/admin/#section/Authentication).
You can learn more about [authenticating as an admin user in the API reference](/api/admin/#section/Authentication).
### Created Price List
Before importing the prices, you must have a price list to import them to.
You can use the [Create Price List](https://docs.medusajs.com/api/admin/#tag/Price-List/operation/PostPriceListsPriceList) endpoint, or follow the [how-to guide to learn how to create and manage price lists using the Admin API](../backend/price-lists/use-api.mdx).
You can use the [Create Price List](/api/admin/#tag/Price-List/operation/PostPriceListsPriceList) endpoint, or follow the [how-to guide to learn how to create and manage price lists using the Admin API](./manage-price-lists.mdx).
---
@@ -73,7 +73,7 @@ You can use the [Create Price List](https://docs.medusajs.com/api/admin/#tag/Pri
The first step is to upload the CSV file to import prices from.
You can do that by sending the following request to the [Upload Files](https://docs.medusajs.com/api/admin/#tag/Upload/operation/PostUploads) endpoint:
You can do that by sending the following request to the [Upload Files](/api/admin/#tag/Upload/operation/PostUploads) endpoint:
<Tabs groupId="request-type" wrapperClassName="code-tabs">
<TabItem value="client" label="Medusa JS Client" default>
@@ -112,7 +112,7 @@ export default ImportPrices
const formData = new FormData()
formData.append("files", file) // file is an instance of File
fetch(`<YOUR_SERVER>/admin/uploads`, {
fetch(`<BACKEND_URL>/admin/uploads`, {
method: "POST",
credentials: "include",
headers: {
@@ -130,7 +130,7 @@ fetch(`<YOUR_SERVER>/admin/uploads`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<YOUR_SERVER>/admin/uploads' \
curl -L -X POST '<BACKEND_URL>/admin/uploads' \
-H 'Authorization: Bearer {api_token}' \
-H 'Content-Type: text/csv' \
-F 'files=@"<FILE_PATH_1>"'
@@ -147,7 +147,7 @@ This request returns an array of uploads. Each item in the array is an object th
To start a new price import, you must create a batch job.
You can do that by sending the following request to the [Create a Batch Job](https://docs.medusajs.com/api/admin/#tag/Batch-Job/operation/PostBatchJobs) endpoint:
You can do that by sending the following request to the [Create a Batch Job](/api/admin/#tag/Batch-Job/operation/PostBatchJobs) endpoint:
<Tabs groupId="request-type" wrapperClassName="code-tabs">
<TabItem value="client" label="Medusa JS Client" default>
@@ -196,7 +196,7 @@ export default ImportPrices
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<YOUR_SERVER>/admin/batch-jobs`, {
fetch(`<BACKEND_URL>/admin/batch-jobs`, {
method: "POST",
credentials: "include",
headers: {
@@ -221,7 +221,7 @@ fetch(`<YOUR_SERVER>/admin/batch-jobs`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<YOUR_SERVER>/admin/batch-jobs' \
curl -L -X POST '<BACKEND_URL>/admin/batch-jobs' \
-H 'Authorization: Bearer {api_token}' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -304,7 +304,7 @@ export default ImportPrices
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<YOUR_SERVER>/admin/batch-jobs/${batchJobId}`, {
fetch(`<BACKEND_URL>/admin/batch-jobs/${batchJobId}`, {
credentials: "include",
})
.then((response) => response.json())
@@ -317,7 +317,7 @@ fetch(`<YOUR_SERVER>/admin/batch-jobs/${batchJobId}`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X GET '<YOUR_SERVER>/admin/batch-jobs/<BATCH_JOB_ID>' \
curl -L -X GET '<BACKEND_URL>/admin/batch-jobs/<BATCH_JOB_ID>' \
-H 'Authorization: Bearer {api_token}'
# <BATCH_JOB_ID> is the ID of the batch job
```
@@ -387,7 +387,7 @@ export default ImportPrices
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<YOUR_SERVER>/admin/batch-jobs/${batchJobId}/confirm`, {
fetch(`<BACKEND_URL>/admin/batch-jobs/${batchJobId}/confirm`, {
method: "POST",
credentials: "include",
})
@@ -401,7 +401,7 @@ fetch(`<YOUR_SERVER>/admin/batch-jobs/${batchJobId}/confirm`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<YOUR_SERVER>/admin/batch-jobs/<BATCH_JOB_ID>/confirm' \
curl -L -X POST '<BACKEND_URL>/admin/batch-jobs/<BATCH_JOB_ID>/confirm' \
-H 'Authorization: Bearer {api_token}'
# <BATCH_JOB_ID> is the ID of the batch job
```
@@ -423,5 +423,5 @@ After confirming the batch job, you can check the status while it is processing
## See Also
- [Batch Jobs Overview](../backend/batch-jobs/index.md)
- [Batch Jobs API Reference](https://docs.medusajs.com/api/admin/#tag/Batch-Job)
- [Batch Jobs Overview](../../../development/batch-jobs/index.mdx)
- [Batch Jobs API Reference](/api/admin/#tag/Batch-Job)

View File

@@ -6,13 +6,13 @@ addHowToData: true
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
# How to Manage PriceLists
# How to Manage Price Lists
In this document, youll learn how to use the PriceList Admin APIs to create, update, and manage prices in a price list.
:::note
This document doesn't cover what price lists are and their basics. If youre interested to learn about that, check out [this documentation](./index.md) instead.
This document doesn't cover what price lists are and their basics. If youre interested to learn about that, check out [this documentation](../price-lists.md) instead.
:::
@@ -20,17 +20,17 @@ This document doesn't cover what price lists are and their basics. If youre i
### Medusa Components
It is assumed that you already have a Medusa server installed and set up. If not, you can follow our [quickstart guide](../../../quickstart/quick-start.mdx) to get started.
It is assumed that you already have a Medusa backend installed and set up. If not, you can follow our [quickstart guide](../../../development/backend/install.mdx) to get started.
### JS Client
This guide includes code snippets to send requests to your Medusa server using Medusas JS Client, JavaScripts Fetch API, or cURL.
This guide includes code snippets to send requests to your Medusa backend using Medusas JS Client, JavaScripts Fetch API, or cURL.
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client](../../../js-client/overview.md) installed and [have created an instance of the client](../../../js-client/overview.md#configuration).
### Medusa React
This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods.
This guide also includes code snippets to send requests to your Medusa backend using Medusa React, among other methods.
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../../medusa-react/overview.md#usage).
@@ -38,7 +38,7 @@ If you follow the Medusa React code blocks, it's assumed you already have [Medus
You must be an authenticated admin user before following along with the steps in the tutorial.
You can learn more about [authenticating as an admin user in the API reference](https://docs.medusajs.com/api/admin/#section/Authentication).
You can learn more about [authenticating as an admin user in the API reference](/api/admin/#section/Authentication).
---
@@ -80,7 +80,10 @@ For example, sending the following request creates a price list with two prices:
<TabItem value="client" label="Medusa JS Client" default>
```jsx
import { PriceListStatus, PriceListType } from "@medusajs/medusa"
import {
PriceListStatus,
PriceListType,
} from "@medusajs/medusa"
medusa.admin.priceLists.create({
name: "New Price List",
@@ -111,7 +114,10 @@ medusa.admin.priceLists.create({
<TabItem value="medusa-react" label="Medusa React">
```tsx
import { PriceListStatus, PriceListType } from "@medusajs/medusa"
import {
PriceListStatus,
PriceListType,
} from "@medusajs/medusa"
import { useAdminCreatePriceList } from "medusa-react"
const CreatePriceList = () => {
@@ -151,7 +157,7 @@ export default CreatePriceList
<TabItem value="fetch" label="Fetch API">
```jsx
fetch(`<SERVER_URL>/admin/price-lists`, {
fetch(`<BACKEND_URL>/admin/price-lists`, {
method: "POST",
credentials: "include",
headers: {
@@ -188,7 +194,7 @@ fetch(`<SERVER_URL>/admin/price-lists`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<YOUR_SERVER_URL>/admin/price-lists' \
curl -L -X POST '<YOUR_BACKEND_URL>/admin/price-lists' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -218,7 +224,7 @@ curl -L -X POST '<YOUR_SERVER_URL>/admin/price-lists' \
This request returns the created price list.
You can check the full list of request body parameters in the [API reference](https://docs.medusajs.com/api/admin/#tag/Price-List/operation/PostPriceListsPriceList).
You can check the full list of request body parameters in the [API reference](/api/admin/#tag/Price-List/operation/PostPriceListsPriceList).
---
@@ -244,7 +250,10 @@ import { CustomerGroup } from "@medusajs/medusa"
import { useAdminPriceList } from "medusa-react"
const PriceList = () => {
const { price_list, isLoading } = useAdminPriceList(priceListId)
const {
price_list,
isLoading,
} = useAdminPriceList(priceListId)
return (
<div>
@@ -261,7 +270,7 @@ export default PriceList
<TabItem value="fetch" label="Fetch API">
```jsx
fetch(`<SERVER_URL>/admin/price-lists/${priceListId}`, {
fetch(`<BACKEND_URL>/admin/price-lists/${priceListId}`, {
credentials: "include",
})
.then((response) => response.json())
@@ -274,7 +283,7 @@ fetch(`<SERVER_URL>/admin/price-lists/${priceListId}`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X GET '<SERVER_URL>/admin/price-lists/{id}' \
curl -L -X GET '<BACKEND_URL>/admin/price-lists/{id}' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -285,7 +294,7 @@ curl -L -X GET '<SERVER_URL>/admin/price-lists/{id}' \
## Update a Price List
After creating a price list, you can update all of its fields including its status, prices, and more using the [Update Price List](https://docs.medusajs.com/api/admin/#tag/Price-List/operation/PostPriceListsPriceListPriceList) endpoint.
After creating a price list, you can update all of its fields including its status, prices, and more using the [Update Price List](/api/admin/#tag/Price-List/operation/PostPriceListsPriceListPriceList) endpoint.
For example, by sending the following request the end date of the price list will be updated:
@@ -305,7 +314,10 @@ medusa.admin.priceLists.update(priceListId, {
<TabItem value="medusa-react" label="Medusa React">
```tsx
import { PriceListStatus, PriceListType } from "@medusajs/medusa"
import {
PriceListStatus,
PriceListType,
} from "@medusajs/medusa"
import { useAdminUpdatePriceList } from "medusa-react"
const CreatePriceList = () => {
@@ -328,7 +340,7 @@ export default CreatePriceList
<TabItem value="fetch" label="Fetch API">
```jsx
fetch(`<SERVER_URL>/admin/price-lists/${priceListId}`, {
fetch(`<BACKEND_URL>/admin/price-lists/${priceListId}`, {
method: "POST",
credentials: "include",
headers: {
@@ -348,7 +360,7 @@ fetch(`<SERVER_URL>/admin/price-lists/${priceListId}`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<SERVER_URL>/admin/price-lists/<PRICE_LIST_ID>' \
curl -L -X POST '<BACKEND_URL>/admin/price-lists/<PRICE_LIST_ID>' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -361,7 +373,7 @@ curl -L -X POST '<SERVER_URL>/admin/price-lists/<PRICE_LIST_ID>' \
This request returns the updated price list.
For a full list of request body parameters, check out the [API reference](https://docs.medusajs.com/api/admin/#tag/Price-List/operation/PostPriceListsPriceListPriceList).
For a full list of request body parameters, check out the [API reference](/api/admin/#tag/Price-List/operation/PostPriceListsPriceListPriceList).
---
@@ -369,7 +381,7 @@ For a full list of request body parameters, check out the [API reference](https:
### Add Prices
You can add prices to your price list after creating it using the [Update Prices](https://docs.medusajs.com/api/admin/#tag/Price-List/operation/PostPriceListsPriceListPricesBatch) endpoint.
You can add prices to your price list after creating it using the [Update Prices](/api/admin/#tag/Price-List/operation/PostPriceListsPriceListPricesBatch) endpoint.
You can also set the `override` request body parameter to `true` to replace the existing prices in the price list.
@@ -424,8 +436,10 @@ export default PriceList
</TabItem>
<TabItem value="fetch" label="Fetch API">
<!-- eslint-disable max-len -->
```jsx
fetch(`<SERVER_URL>/admin/price-lists/${priceListId}/prices/batch`, {
fetch(`<BACKEND_URL>/admin/price-lists/${priceListId}/prices/batch`, {
method: "POST",
credentials: "include",
headers: {
@@ -451,7 +465,7 @@ fetch(`<SERVER_URL>/admin/price-lists/${priceListId}/prices/batch`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<SERVER_URL>/admin/price-lists/<PRICE_LIST_ID>' \
curl -L -X POST '<BACKEND_URL>/admin/price-lists/<PRICE_LIST_ID>' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -470,27 +484,32 @@ curl -L -X POST '<SERVER_URL>/admin/price-lists/<PRICE_LIST_ID>' \
This request returns the price list with the updated prices.
For a full list of request body parameters, check out the [API reference](https://docs.medusajs.com/api/admin/#tag/Price-List/operation/PostPriceListsPriceListPricesBatch).
For a full list of request body parameters, check out the [API reference](/api/admin/#tag/Price-List/operation/PostPriceListsPriceListPricesBatch).
### Delete a Products Prices
You can delete all the prices of a products variants using the [Delete Product Prices](https://docs.medusajs.com/api/admin/#tag/Price-List/operation/DeletePriceListsPriceListProductsProductPrices) endpoint:
You can delete all the prices of a products variants using the [Delete Product Prices](/api/admin/#tag/Price-List/operation/DeletePriceListsPriceListProductsProductPrices) endpoint:
<Tabs groupId="request-type" wrapperClassName="code-tabs">
<TabItem value="client" label="Medusa JS Client" default>
```jsx
medusa.admin.priceLists.deleteProductPrices(priceListId, productId)
.then(({ ids, object, deleted }) => {
console.log(ids.length)
})
```tsx
medusa
.admin
.priceLists
.deleteProductPrices(priceListId, productId)
.then(({ ids, object, deleted }) => {
console.log(ids.length)
})
```
</TabItem>
<TabItem value="medusa-react" label="Medusa React">
```tsx
import { useAdminDeletePriceListProductPrices } from "medusa-react"
import {
useAdminDeletePriceListProductPrices,
} from "medusa-react"
const PriceList = () => {
const deletePrices = useAdminDeletePriceListProductPrices(
@@ -516,7 +535,7 @@ export default PriceList
```jsx
fetch(
`<SERVER_URL>/admin/price-lists/${priceListId}/products/${productId}/prices`,
`<BACKEND_URL>/admin/price-lists/${priceListId}/products/${productId}/prices`,
{
method: "DELETE",
credentials: "include",
@@ -532,7 +551,7 @@ fetch(
<TabItem value="curl" label="cURL">
```bash
curl -L -X DELETE '<SERVER_URL>/admin/price-lists/<PRICE_LIST_ID>/products/<PRODUCT_ID>/prices' \
curl -L -X DELETE '<BACKEND_URL>/admin/price-lists/<PRICE_LIST_ID>/products/<PRODUCT_ID>/prices' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -543,29 +562,35 @@ This request returns the IDs of the deleted prices.
### Delete a Variants Prices
You can delete all the prices of a variant using the [Delete Variant Prices](https://docs.medusajs.com/api/admin/#tag/Price-List/operation/DeletePriceListsPriceListVariantsVariantPrices) endpoint:
You can delete all the prices of a variant using the [Delete Variant Prices](/api/admin/#tag/Price-List/operation/DeletePriceListsPriceListVariantsVariantPrices) endpoint:
<Tabs groupId="request-type" wrapperClassName="code-tabs">
<TabItem value="client" label="Medusa JS Client" default>
```jsx
medusa.admin.priceLists.deleteVariantPrices(priceListId, variantId)
.then(({ ids, object, deleted }) => {
console.log(ids)
})
```tsx
medusa
.admin
.priceLists
.deleteVariantPrices(priceListId, variantId)
.then(({ ids, object, deleted }) => {
console.log(ids)
})
```
</TabItem>
<TabItem value="medusa-react" label="Medusa React">
```tsx
import { useAdminDeletePriceListVariantPrices } from "medusa-react"
import {
useAdminDeletePriceListVariantPrices,
} from "medusa-react"
const PriceList = () => {
const deleteVariantPrices = useAdminDeletePriceListVariantPrices(
priceListId,
variantId
)
const deleteVariantPrices =
useAdminDeletePriceListVariantPrices(
priceListId,
variantId
)
// ...
const handleDeletePrices = () => {
@@ -585,7 +610,7 @@ export default PriceList
```jsx
fetch(
`<SERVER_URL>/admin/price-lists/${priceListId}/variants/${variantId}/prices`,
`<BACKEND_URL>/admin/price-lists/${priceListId}/variants/${variantId}/prices`,
{
method: "DELETE",
credentials: "include",
@@ -601,7 +626,7 @@ fetch(
<TabItem value="curl" label="cURL">
```bash
curl -L -X DELETE '<SERVER_URL>/admin/price-lists/<PRICE_LIST_ID>/variants/<VARIANT_ID>/prices' \
curl -L -X DELETE '<BACKEND_URL>/admin/price-lists/<PRICE_LIST_ID>/variants/<VARIANT_ID>/prices' \
-H 'Authorization: Bearer <API_TOKEN>'
```
@@ -614,7 +639,7 @@ This request returns the IDs of the deleted prices.
## Delete Price List
You can delete a price list, and subsequently all prices defined in it, using the [Delete Price List](https://docs.medusajs.com/api/admin/#tag/Price-List/operation/DeletePriceListsPriceList) endpoint:
You can delete a price list, and subsequently all prices defined in it, using the [Delete Price List](/api/admin/#tag/Price-List/operation/DeletePriceListsPriceList) endpoint:
<Tabs groupId="request-type" wrapperClassName="code-tabs">
<TabItem value="client" label="Medusa JS Client" default>
@@ -650,7 +675,7 @@ export default PriceList
<TabItem value="fetch" label="Fetch API">
```jsx
fetch(`<SERVER_URL>/admin/price-lists/${priceListId}`, {
fetch(`<BACKEND_URL>/admin/price-lists/${priceListId}`, {
method: "DELETE",
credentials: "include",
})
@@ -664,18 +689,11 @@ fetch(`<SERVER_URL>/admin/price-lists/${priceListId}`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X DELETE '<SERVER_URL>/admin/price-lists/<PRICE_LIST_ID>' \
curl -L -X DELETE '<BACKEND_URL>/admin/price-lists/<PRICE_LIST_ID>' \
-H 'Authorization: Bearer <API_TOKEN>'
```
</TabItem>
</Tabs>
This request returns the ID of the deleted price list.
---
## See Also
- [Price Lists Overview](./index.md).
- [Price Selection Strategy Overview](../price-selection-strategy/index.md).
This request returns the ID of the deleted price list.

View File

@@ -9,13 +9,13 @@ In this document, youll learn how to override Medusas price selection stra
:::note
If youre interested in learning what a price selection strategy is and how it works, check out [this documentation](./index.md) instead.
If youre interested in learning what a price selection strategy is and how it works, check out [this documentation](../price-selection-strategy.md) instead.
:::
## 1. Create Class
Create a TypeScript or JavaScript file in `src/strategies` of your Medusa server project with a class that extends the `AbstractPriceSelectionStrategy` class:
Create a TypeScript or JavaScript file in `src/strategies` of your Medusa backend project with a class that extends the `AbstractPriceSelectionStrategy` class:
```ts title=src/strategies/price.ts
import {
@@ -27,22 +27,24 @@ import {
import { EntityManager } from "typeorm"
export default class MyStrategy extends AbstractPriceSelectionStrategy {
export default class MyStrategy extends
AbstractPriceSelectionStrategy {
withTransaction(
manager: EntityManager
): IPriceSelectionStrategy {
if (!manager) {
return this
}
withTransaction(manager: EntityManager): IPriceSelectionStrategy {
if (!manager) {
return this
return new MyStrategy()
}
return new MyStrategy()
}
async calculateVariantPrice(
variant_id: string,
context: PriceSelectionContext
): Promise<PriceSelectionResult> {
// TODO
}
async calculateVariantPrice(
variant_id: string,
context: PriceSelectionContext
): Promise<PriceSelectionResult> {
// TODO
}
}
```
@@ -57,26 +59,29 @@ import {
PriceSelectionResult,
} from "@medusajs/medusa"
export default class MyStrategy extends AbstractPriceSelectionStrategy {
private customerService: CustomerService
export default class MyStrategy extends
AbstractPriceSelectionStrategy {
private customerService: CustomerService
constructor({
customerService,
}) {
super()
this.customerService = customerService
}
withTransaction(manager: EntityManager): IPriceSelectionStrategy {
if (!manager) {
return this
constructor({
customerService,
}) {
super()
this.customerService = customerService
}
return new MyStrategy({
customerService: this.customerService,
})
}
// ...
withTransaction(
manager: EntityManager
): IPriceSelectionStrategy {
if (!manager) {
return this
}
return new MyStrategy({
customerService: this.customerService,
})
}
// ...
}
```
@@ -86,7 +91,7 @@ export default class MyStrategy extends AbstractPriceSelectionStrategy {
Implement the price selection strategy you want inside the `calculateVariantPrice` method.
This method accepts the variant ID as a first parameter and the [context](./index.md#context-object) object as a second parameter.
This method accepts the variant ID as a first parameter and the [context](../price-selection-strategy.md#context-object) object as a second parameter.
This method must return an object having the following fields:
@@ -98,7 +103,7 @@ This method must return an object having the following fields:
}
```
You can learn more about optional properties and the meaning behind every property [here](./index.md#calculatevariantprice-method).
You can learn more about optional properties and the meaning behind every property [here](../price-selection-strategy.md#calculatevariantprice-method).
---
@@ -114,16 +119,10 @@ npm run build
## Test it Out
Run your server to test it out:
Run your backend to test it out:
```bash npm2yarn
npm run start
```
Then, try out your strategy using any of the [Products](https://docs.medusajs.com/api/store/#tag/Product) or [Carts](https://docs.medusajs.com/api/store/#tag/Cart) endpoints which include retrieving product variants and line items respectively. You should then see the prices in the response based on your implemented strategy.
---
## See Also
- [Price List Selection Strategy Overview](./index.md)
Then, try out your strategy using any of the [Products](/api/store/#tag/Product) or [Carts](/api/store/#tag/Cart) endpoints which include retrieving product variants and line items respectively. You should then see the prices in the response based on your implemented strategy.

View File

@@ -0,0 +1,145 @@
---
description: "Price Lists are special prices applied to products based on a set of conditions. Learn about the available features and guides."
---
import DocCardList from '@theme/DocCardList';
import DocCard from '@theme/DocCard';
import Icons from '@theme/Icon';
# Price Lists
Price Lists are special prices applied to products based on a set of conditions. This overview introduces the available features related to price lists.
:::note
Looking for Discounts? You can find the [Discounts guide here](../discounts/overview.mdx).
:::
## Features
### Price Lists Management
Admins can manage price lists to add special prices for products based on defined conditions, such as the group of the customer viewing the product. The price list can be used for a sale or to override prices of some products.
Developers can change the default logic behind how prices are selected to be shown to the customer.
<DocCardList colSize={4} items={[
{
type: 'link',
href: '/modules/price-lists/admin/manage-price-lists',
label: 'Admin: Manage Price Lists',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to manage price lists using the Admin APIs.'
}
},
{
type: 'link',
href: '/user-guide/price-lists/manage',
label: 'User Guide: Manage Price Lists',
customProps: {
icon: Icons['users-solid'],
description: 'Learn how to manage price lists using Medusa Admin.'
}
},
{
type: 'link',
href: '/modules/price-lists/backend/override-price-selection-strategy',
label: 'Backend: Override Price Selection',
customProps: {
icon: Icons['users-solid'],
description: 'Learn how to override the price selection strategy.'
}
},
]} />
### Import Prices
Admins can import prices into a price list from CSV files.
Developers can import the prices from CSV files using the Admin APIs. They can also customize the import strategy.
<DocCardList colSize={4} items={[
{
type: 'link',
href: '/user-guide/price-lists/import',
label: 'User Guide: Import Prices',
customProps: {
icon: Icons['users-solid'],
description: 'Learn how to import prices using Medusa Admin.'
}
},
{
type: 'link',
href: '/modules/price-lists/admin/import-prices',
label: 'Admin: Import Prices',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to import prices using the Admin APIs.'
}
},
{
type: 'link',
href: '/development/batch-jobs/customize-import',
label: 'Core: Customize Import Strategy',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to customize the prices import strategy.'
}
},
]} />
---
## Understand the Architecture
Learn how price list-related entities and concepts are built, their relation to other modules, and more.
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/modules/price-lists',
label: 'Architecture: Price List',
customProps: {
icon: Icons['circle-stack-solid'],
description: 'Learn about the Price List architecture.'
}
},
{
type: 'link',
href: '/modules/price-lists/price-selection-strategy',
label: 'Architecture: Price Selection Strategy',
customProps: {
icon: Icons['circle-stack-solid'],
description: 'Learn about Price Selection Strategy.'
}
},
]} />
---
## Related Modules
Discover Price Lists relation to other modules in Medusa
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/modules/products/overview',
label: 'Product',
customProps: {
icon: Icons['tag-solid'],
description: 'Price lists are used to override products prices.'
}
},
{
type: 'link',
href: '/modules/customers/overview',
label: 'Customers',
customProps: {
icon: Icons['users-solid'],
description: 'Customer groups can be used as a price lists conditions.'
}
},
]} />

View File

@@ -1,5 +1,5 @@
---
description: 'Learn what price lists are and how they work in a Medusa server. Price Lists can be used to override product prices based on different conditions.'
description: 'Learn what price lists are and how they work in a Medusa backend. Price Lists can be used to override product prices based on different conditions.'
---
# Price Lists
@@ -20,7 +20,7 @@ Price lists can be used for a variety of use cases including:
### Price List Entity Overview
A price list is stored in the database as a [PriceList](../../../references/entities/classes/PriceList.md) entity. Some of its important attributes are:
A price list is stored in the database as a [PriceList](../../references/entities/classes/PriceList.md) entity. Some of its important attributes are:
- `type`: The price list's type. Can be either a `sale` or an `override`.
- `status`: The status of the price list. Can be `active` or `draft`. If a price list is a `draft`, its prices won't be applied even if its conditions are met.
@@ -45,7 +45,7 @@ You can use any of the following conditions:
## How are Price Lists Applied
When a product or a line item is retrieved or manipulated on the storefront, Medusa determines its price using a Price Selection Strategy. The price selection strategy determines the best price to apply in a given [context](../price-selection-strategy/index.md#context-object). Part of determining the price depends on the price list.
When a product or a line item is retrieved or manipulated on the storefront, Medusa determines its price using a Price Selection Strategy. The price selection strategy determines the best price to apply in a given [context](./price-selection-strategy.md#context-object). Part of determining the price depends on the price list.
:::info
@@ -59,9 +59,9 @@ When the strategy calculates the prices of a product variant, it retrieves both
The original price depends on the selected region or currency code in the current context, where the region has higher precedence.
The calculated price is the lowest price among all retrieved prices. Retrieved prices can include the original price and the price lists that can be applied. Prices are retrieved based on the [context](../price-selection-strategy/index.md#context-object).
The calculated price is the lowest price among all retrieved prices. Retrieved prices can include the original price and the price lists that can be applied. Prices are retrieved based on the [context](./price-selection-strategy.md#context-object).
In the [Get Product](https://docs.medusajs.com/api/store/#tag/Product/operation/GetProductsProduct) and [List Product](https://docs.medusajs.com/api/store/#tag/Product/operation/GetProducts) endpoints, you must pass either the `region_id` or `currency_code` to retrieve the correct prices, as they are part of the price selection strategy context.
In the [Get Product](/api/store/#tag/Product/operation/GetProductsProduct) and [List Product](/api/store/#tag/Product/operation/GetProducts) endpoints, you must pass either the `region_id` or `currency_code` to retrieve the correct prices, as they are part of the price selection strategy context.
Each variant in the response has the following properties:
@@ -87,5 +87,5 @@ Since the line item belongs to a cart, theres no need to pass the `region_id`
## See Also
- [Price Selection Strategy Overview](../price-selection-strategy/index.md).
- [Use the PriceList Admin APIs](./use-api.mdx).
- [Price Selection Strategy Overview](./price-selection-strategy.md)
- [Manage price lists using the admin APIs](./admin/manage-price-lists.mdx)

View File

@@ -1,5 +1,5 @@
---
description: 'Learn what the price selection strategy is in the Medusa server. The price selection strategy retrieves the best price for a product variant for a specific context.'
description: 'Learn what the price selection strategy is in the Medusa backend. The price selection strategy retrieves the best price for a product variant for a specific context.'
---
# Price Selection Strategy
@@ -8,7 +8,7 @@ In this document, youll learn what a price selection strategy is.
:::note
If youre interested to learn how to override the price selection strategy, check out [this documentation](./override.md) instead.
If youre interested to learn how to override the price selection strategy, check out [this documentation](./backend/override-price-selection-strategy.md) instead.
:::
@@ -46,7 +46,7 @@ It returns an object with the following properties:
:::info
You can learn more about price lists and how theyre used in [this documentation](../price-lists/index.md).
You can learn more about price lists and how theyre used in [this documentation](./price-lists.md).
:::
@@ -66,5 +66,4 @@ The context that is passed to the `calculateVariantPrice` method is an object th
## See Also
- [Override the Price Selection Strategy](./override.md)
- [Price Lists Overview](./../price-lists/index.md)
- [Override the Price Selection Strategy](./backend/override-price-selection-strategy.md)

View File

@@ -8,11 +8,11 @@ import TabItem from '@theme/TabItem';
# How to Bulk Import Products
In this document, youll learn how to use the Admin APIs to bulk import products into a Medusa server.
In this document, youll learn how to use the Admin APIs to bulk import products into a Medusa backend.
## Overview
Using Medusas [Batch Job Admin APIs](https://docs.medusajs.com/api/admin/#tag/Batch-Job), you can import products into your Medusa server. This will either add new products or update existing products.
Using Medusas [Batch Job Admin APIs](/api/admin/#tag/Batch-Job), you can import products into your Medusa backend. This will either add new products or update existing products.
---
@@ -20,40 +20,40 @@ Using Medusas [Batch Job Admin APIs](https://docs.medusajs.com/api/admin/#tag
### Medusa Components
It is assumed that you already have a Medusa server installed and set up. If not, you can follow the [quickstart guide](../../quickstart/quick-start.mdx) to get started.
It is assumed that you already have a Medusa backend installed and set up. If not, you can follow the [quickstart guide](../../../development/backend/install.mdx) to get started.
### Redis
Redis is required for batch jobs to work. Make sure you [install Redis](../../tutorial/0-set-up-your-development-environment.mdx#redis) and [configure it with your Medusa server](./../../usage/configurations.md#redis).
Redis is required for batch jobs to work. Make sure you [install Redis](../../../development/backend/prepare-environment.mdx#redis) and [configure it with the Medusa backend](../../../development/backend/configurations.md#redis).
### File Service Plugin
Part of the process of importing products is uploading a CSV file. This requires a file service plugin to be installed on your server. If you dont have any installed, you can install one of the following options:
Part of the process of importing products is uploading a CSV file. This requires a file service plugin to be installed on your backend. If you dont have any installed, you can install one of the following options:
- [MinIO](../../add-plugins/minio.md) (At least version `1.1.0`)
- [Spaces](../../add-plugins/spaces.md)
- [MinIO](../../../plugins/file-service/minio.md) (At least version `1.1.0`)
- [Spaces](../../../plugins/file-service/spaces.md)
### CSV File
You must have a CSV file that you will use to import products into your Medusa server. You can check [this CSV example file](https://medusa-doc-files.s3.amazonaws.com/product-import-1.3.8.csv) to see which format is required for your import.
You must have a CSV file that you will use to import products into your Medusa backend. You can check [this CSV example file](https://medusa-doc-files.s3.amazonaws.com/product-import-1.3.8.csv) to see which format is required for your import.
:::note
If you have Sales Channels enabled on your server, you must use [this CSV example file](https://medusa-doc-files.s3.amazonaws.com/product-import-sales-channels.csv) instead.
If you have Sales Channels enabled on your backend, you must use [this CSV example file](https://medusa-doc-files.s3.amazonaws.com/product-import-sales-channels.csv) instead.
:::
### JS Client
This guide includes code snippets to send requests to your Medusa server using Medusas JS Client, among other methods.
This guide includes code snippets to send requests to your Medusa backend using Medusas JS Client, among other methods.
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client](../../js-client/overview.md) installed and have [created an instance of the client](../../js-client/overview.md#configuration).
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client](../../../js-client/overview.md) installed and have [created an instance of the client](../../../js-client/overview.md#configuration).
### Medusa React
This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods.
This guide also includes code snippets to send requests to your Medusa backend using Medusa React, among other methods.
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage).
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../../medusa-react/overview.md#usage).
### Authenticated Admin User
@@ -67,7 +67,7 @@ You can learn more about [authenticating as an admin user in the API reference](
The first step is to upload the CSV file that you want to import products.
You can do that by sending the following request to the [Upload Files](https://docs.medusajs.com/api/admin/#tag/Upload/operation/PostUploads) endpoint:
You can do that by sending the following request to the [Upload Files](/api/admin/#tag/Upload/operation/PostUploads) endpoint:
<Tabs groupId="request-type" wrapperClassName="code-tabs">
<TabItem value="client" label="Medusa JS Client" default>
@@ -106,7 +106,7 @@ export default ImportProducts
const formData = new FormData()
formData.append("files", file) // file is an instance of File
fetch(`<YOUR_SERVER>/admin/uploads`, {
fetch(`<BACKEND_URL>/admin/uploads`, {
method: "POST",
credentials: "include",
headers: {
@@ -124,7 +124,7 @@ fetch(`<YOUR_SERVER>/admin/uploads`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<YOUR_SERVER>/admin/uploads' \
curl -L -X POST '<BACKEND_URL>/admin/uploads' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: text/csv' \
-F 'files=@"<FILE_PATH_1>"'
@@ -141,7 +141,7 @@ This request returns an array of uploads. Each item in the array is an object th
To start a new product import, you must create a batch job.
You can do that by sending the following request to the [Create a Batch Job](https://docs.medusajs.com/api/admin/#tag/Batch-Job/operation/PostBatchJobs) endpoint:
You can do that by sending the following request to the [Create a Batch Job](/api/admin/#tag/Batch-Job/operation/PostBatchJobs) endpoint:
<Tabs groupId="request-type" wrapperClassName="code-tabs">
<TabItem value="client" label="Medusa JS Client" default>
@@ -189,7 +189,7 @@ export default ImportProducts
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<YOUR_SERVER>/admin/batch-jobs`, {
fetch(`<BACKEND_URL>/admin/batch-jobs`, {
method: "POST",
credentials: "include",
headers: {
@@ -213,7 +213,7 @@ fetch(`<YOUR_SERVER>/admin/batch-jobs`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<YOUR_SERVER>/admin/batch-jobs' \
curl -L -X POST '<BACKEND_URL>/admin/batch-jobs' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
@@ -292,7 +292,7 @@ export default ImportProducts
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<YOUR_SERVER>/admin/batch-jobs/${batchJobId}`, {
fetch(`<BACKEND_URL>/admin/batch-jobs/${batchJobId}`, {
credentials: "include",
})
.then((response) => response.json())
@@ -305,7 +305,7 @@ fetch(`<YOUR_SERVER>/admin/batch-jobs/${batchJobId}`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X GET '<YOUR_SERVER>/admin/batch-jobs/<BATCH_JOB_ID>' \
curl -L -X GET '<BACKEND_URL>/admin/batch-jobs/<BATCH_JOB_ID>' \
-H 'Authorization: Bearer <API_TOKEN>'
# <BATCH_JOB_ID> is the ID of the batch job
```
@@ -337,7 +337,7 @@ Heres an example of the `result` property:
## 3. Confirm Batch Job
A batch job can be confirmed only once the batch job has the status `pre_processed`. Once you confirm a batch job, the product import will start which will create or update products on your server.
A batch job can be confirmed only once the batch job has the status `pre_processed`. Once you confirm a batch job, the product import will start which will create or update products on your backend.
To confirm a batch job send the following request:
@@ -375,7 +375,7 @@ export default ImportProducts
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<YOUR_SERVER>/admin/batch-jobs/${batchJobId}/confirm`, {
fetch(`<BACKEND_URL>/admin/batch-jobs/${batchJobId}/confirm`, {
method: "POST",
credentials: "include",
})
@@ -389,7 +389,7 @@ fetch(`<YOUR_SERVER>/admin/batch-jobs/${batchJobId}/confirm`, {
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<YOUR_SERVER>/admin/batch-jobs/<BATCH_JOB_ID>/confirm' \
curl -L -X POST '<BACKEND_URL>/admin/batch-jobs/<BATCH_JOB_ID>/confirm' \
-H 'Authorization: Bearer <API_TOKEN>'
# <BATCH_JOB_ID> is the ID of the batch job
```
@@ -411,5 +411,4 @@ After confirming the batch job, you can check the status while it is processing
## See Also
- [Batch Jobs Overview](../backend/batch-jobs/index.md)
- [Batch Jobs API Reference](https://docs.medusajs.com/api/admin/#tag/Batch-Job)
- [Batch Jobs Overview](../../../development/batch-jobs/index.mdx)

View File

@@ -0,0 +1,221 @@
---
description: "Products are items or services that businesses sell to their customers. Learn about the available features and guides."
---
import DocCardList from '@theme/DocCardList';
import Icons from '@theme/Icon';
# Products
Products are items or services that businesses sell to their customers. This overview introduces the available features related to products.
:::note
💡 Not a developer? Check out the [Products user guide](../../user-guide/products/manage.mdx).
:::
## Features
### Products Management
Admins can manage unlimited amount of products and their variants. They can manage the products details including their pricing, inventory, and more.
<DocCardList colSize={4} items={[
{
type: 'link',
href: '#',
label: 'Admin: Manage Products',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to manage products using Admin APIs.',
isSoon: true,
}
},
{
type: 'link',
href: '/user-guide/products/manage',
label: 'User Guide: Manage Products',
customProps: {
icon: Icons['users-solid'],
description: 'Manage products in Medusa Admin.'
}
},
{
type: 'link',
href: '#',
label: 'Storefront: Show Products',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to show products in a storefront.',
isSoon: true,
}
},
]} />
### Product Organization
Admins can organize products into collections, tags, types, and more.
Customers can use this organization to filter products while browsing them.
<DocCardList colSize={4} items={[
{
type: 'link',
href: '#',
label: 'Admin: Manage Collections',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to manage collections using Admin APIs.',
isSoon: true,
}
},
{
type: 'link',
href: '/user-guide/products/collections',
label: 'User Guide: Manage Collections',
customProps: {
icon: Icons['users-solid'],
description: 'Learn how to manage collections in Medusa Admin.'
}
},
{
type: 'link',
href: '#',
label: 'Storefront: Show Collections',
customProps: {
icon: Icons['server-solid'],
description: 'Learn how to show collections in a storefront.',
isSoon: true,
}
},
]} />
### Product Import and Export
Admins can bulk import and export products using CSV files. This facilitates moving data from other ecommerce platforms to Medusa.
<DocCardList colSize={4} items={[
{
type: 'link',
href: '/modules/products/admin/import-products',
label: 'Admin: Import Products',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to import products into Medusa using Admin APIs.'
}
},
{
type: 'link',
href: '/user-guide/products/import',
label: 'User Guide: Import',
customProps: {
icon: Icons['users-solid'],
description: 'Learn how to import products into Medusa Admin.'
}
},
{
type: 'link',
href: '/user-guide/products/export',
label: 'User Guide: Export',
customProps: {
icon: Icons['users-solid'],
description: 'Learn how to export products from Medusa Admin.'
}
},
]} />
---
## Understand the Architecture
Learn how product-related entities are build, their relation to other modules, and more.
<DocCardList colSize={6} items={[
{
type: 'link',
href: '#',
label: 'Architecture: Product',
customProps: {
icon: Icons['circle-stack-solid'],
description: 'Learn about the Product Architecture.',
isSoon: true,
}
},
{
type: 'link',
href: '#',
label: 'Architecture: Collection',
customProps: {
icon: Icons['circle-stack-solid'],
description: 'Learn about the Collection Architecture.',
isSoon: true,
}
},
]} />
---
## Related Modules
Discover Products relation to other modules in Medusa
<DocCardList colSize={4} items={[
{
type: 'link',
href: '/modules/sales-channels/overview',
label: 'Sales Channels',
customProps: {
icon: Icons['channels-solid'],
description: 'Products availability can be specific to sales channels.',
}
},
{
type: 'link',
href: '/modules/price-lists/overview',
label: 'Price Lists',
customProps: {
icon: Icons['currency-dollar'],
description: 'Override prices of products based on specific conditions.',
}
},
{
type: 'link',
href: '/modules/discounts/overview',
label: 'Discounts',
customProps: {
icon: Icons['receipt-percent'],
description: 'Discounts can be created for specific products or collections.',
}
},
]} />
<DocCardList colSize={4} items={[
{
type: 'link',
href: '/modules/gift-cards/overview',
label: 'Gift Cards',
customProps: {
icon: Icons['gift-solid'],
description: 'Gift cards can be sold as Products.',
}
},
{
type: 'link',
href: '/modules/carts-and-checkout/overview',
label: 'Carts and Checkout',
customProps: {
icon: Icons['shopping-cart-solid'],
description: 'Allow customers to purchase your products.'
}
},
{
type: 'link',
href: '/modules/orders/overview',
label: 'Orders',
customProps: {
icon: Icons['check-circle-solid'],
description: 'Product purchases can be managed as orders.'
}
},
]} />

Some files were not shown because too many files have changed in this diff Show More