fix: merge conflicts with master

This commit is contained in:
olivermrbl
2022-04-27 14:21:03 +02:00
69 changed files with 8240 additions and 3476 deletions

View File

@@ -14,11 +14,7 @@ Create an account on Algolia and grab your Application ID and Admin API Key from
In your Medusa project, install the plugin using your favourite package manager:
```jsx
yarn add medusa-plugin-algolia@canary
// or
```bash npm2yarn
npm install medusa-plugin-algolia@canary
```

View File

@@ -36,18 +36,21 @@ For a full guide to how to set up your development environment for Medusa please
In order to get you started with your Gatsby, Contentful, Medusa store you must complete a couple of installations:
- Install the Medusa CLI
```bash npm2yarn
npm install @medusajs/medusa-cli -g
```
yarn global add @medusajs/medusa-cli
npm install -g @medusajs/medusa-cli
```
- Install the Gatsby CLI
```bash npm2yarn
npm install gatsby-cli -g
```
yarn global add gatsby-cli
npm install -g gatsby-cli
```
- [Create a Contentful account](https://www.contentful.com/sign-up/)
- [Install Redis](https://redis.io/topics/quickstart)
```
```bash
brew install redis
brew services start redis
```
@@ -144,7 +147,14 @@ In the `/src` directory there are 4 special subdirectories that are added for yo
#### `/data`
We will be using two seed scripts to kickstart your development, namely `yarn seed:contentful` and `yarn seed`. Data for these seed scripts are contained in the `/data` directory.
We will be using two seed scripts to kickstart your development, namely:
```bash npm2yarn
npm run seed:contentful
npm run seed
```
Data for these seed scripts are contained in the `/data` directory.
When the seed scripts have been executed you will have a Contentful space that holds all the data for your website; this includes content for Pages, Navigtion Menu, etc.
@@ -227,8 +237,8 @@ Now that we have collected your credentials we are ready to migrate the Contentf
You can now run:
```shell
yarn migrate:contentful
```bash npm2yarn
npm run migrate:contentful
```
This script will run each of the migrations in the `contentful-migrations` directory. After it has completed navigate to your Contentful space and click "Content model" in the top navigation bar. You will see that the content types will be imported into your space. Feel free to familiarize yourself with the different types by clicking them and inspecting the different fields that they hold.
@@ -237,8 +247,8 @@ This script will run each of the migrations in the `contentful-migrations` direc
The next step is to seed the Contentful space with some data that can be used to display your ecommerce store's pages and navigation. To seed the database open up your command line and run:
```shell
yarn seed:contentful
```bash npm2yarn
npm run seed:contentful
```
In your Contentful space navigate to "Content" and you will be able to see the different entries in your space. You can filter the entries by type to, for example, only view Pages:
@@ -249,9 +259,9 @@ You will notice that there are not any Products in your store yet and this is be
To do this open your command line and run:
```shell
yarn seed
yarn start
```bash npm2yarn
npm run seed
npm run start
```
This will seed your Medusa database, which will result in `medusa-plugin-contentful` synchronizing data to your Contentful space. Everytime you add or update a product the data will be copied into your Contentful space for further enrichment.
@@ -287,7 +297,11 @@ Once `gatsby new` is complete you should rename the `.env.template` file to `.en
To get your token go to **Settings** > **API Keys** > **Add API key**. Now click save and copy the token specified in the field "Content Delivery API - access token".
After you have copied the token and your space ID to your `.env`, you can run `yarn start` which will start your Gatsby development server on port 8000.
After you have copied the token and your space ID to your `.env`, you can start your Gatsby development server on port 8000 by running:
```bash npm2yarn
npm run start
```
You can now go to https://localhost:8000 to check out your new Medusa store.

View File

@@ -0,0 +1,183 @@
# Mailchimp
In this document, youll learn about the Mailchimp plugin, what it does, and how to use it.
## Overview
[Mailchimp](https://mailchimp.com) is an email marketing service that can be used to create newsletters and subscriptions.
By integrating Mailchimp with Medusa, customers will be able to subscribe from Medusa to your Mailchimp newsletter and will be automatically added to your Mailchimp subscribers list.
:::note
This plugin is only used to allow your customers to subscribe but does not actually do any email sending. If you want to send emails to customers based on specific events, for example, when an order is placed, you should check out our [SendGrid plugin](./sendgrid.mdx) instead.
:::
## Prerequisites
Before going further with this guide make sure you have a Medusa server set up. You can follow our [Quickstart guide](https://docs.medusajs.com/quickstart/quick-start).
You also need a Mailchimp account, so please [create one](https://mailchimp.com/signup) before you start.
## Obtain Mailchimp Keys
To integrate the plugin into Medusa you need 2 keys: The API Key and the Newsletter list or Audience ID. The API Key acts as a credential for your account, whereas the Newsletter list ID determines which audience should the subscribed customers be added to.
You can follow [this guide](https://mailchimp.com/help/about-api-keys/#Find_or_generate_your_API_key) from Mailchimps documentation to obtain an API Key.
You can follow [this guide](https://mailchimp.com/help/find-audience-id/) from Mailchimps documentation to obtain your Newsletter list or Audience ID.
## Install the Plugin
In the directory of your Medusa server, run the following command to install the Mailchimp plugin:
```bash npm2yarn
npm install medusa-plugin-mailchimp
```
### Add Keys
Open `.env` and add the following keys:
```bash
MAILCHIMP_API_KEY=<YOUR_API_KEY>
MAILCHIMP_NEWSLETTER_LIST_ID=<YOUR_NEWSLETTER_LIST_ID>
```
Make sure to replace `<YOUR_API_KEY>` with your API Key and `<YOUR_NEWSLETTER_LIST_ID>` with your Newsletter list or Audience ID.
### Add Plugin to Medusa Config
Open `medusa-config.js` and add the new plugin into the `plugins` array:
```js
const plugins = [
...,
{
resolve: `medusa-plugin-mailchimp`,
options: {
api_key: process.env.MAILCHIMP_API_KEY,
newsletter_list_id: process.env.MAILCHIMP_NEWSLETTER_LIST_ID
}
}
};
```
## Test it Out
This plugin adds a new `POST` endpoint at `/mailchimp/subscribe`. This endpoint requires in the body of the request an `email` field. You can also optionally include a `data` object that holds any additional data you want to send to Mailchimp. You can check out [Mailchimps subscription documentation](https://mailchimp.com/developer/marketing/api/list-members/add-member-to-list/) for more details on the data you can send.
### Without Additional Data
Try sending a `POST` request to `/mailchimp/subscribe` with the following JSON body:
```json
{
"email": "example@gmail.com"
}
```
If the subscription is successful, a `200` response code will be returned with `OK` message.
![Postman](https://i.imgur.com/tpr7uCF.png)
If you check your Mailchimp dashboard, you should find the email added to your Audience list.
![Email Added](https://i.imgur.com/ALz6WUq.png)
### With Additional Data
Heres an example of sending additional data with the subscription:
```json
{
"email": "example@gmail.com",
"data": {
"tags": ["customer"]
}
}
```
All fields inside `data` will be sent to Mailchimps API along with the email.
## Use Mailchimp Service
If you want to subscribe to users without using this endpoint or at a specific place in your code, you can use Mailchimps service `mailchimpService` in your endpoints, services, or subscribers. This service has a method `subscribeNewsletter` which lets you use the subscribe functionality.
Heres an example of using the `mailchimpService` inside an endpoint:
```jsx
const mailchimpService = req.scope.resolve("mailchimpService")
mailchimpService.subscribeNewsletter(
"example@gmail.com",
{ tags: ["customer"] } // optional
)
```
:::tip
You can learn more about how you can use services in your endpoints, services, and subscribers in the [Services documentation](https://docs.medusajs.com/advanced/backend/services/create-service#using-your-custom-service).
:::
## Add Subscription Form
This section has a simple example of adding a subscription form in your storefront. The code is for React-based frameworks but you can use the same logic for your storefronts regardless of the framework you are using.
Youll need to use [axios](https://www.google.com/search?client=safari&rls=en&q=axios+github&ie=UTF-8&oe=UTF-8) to send API requests, so if you dont have it installed make sure you install it first:
```bash npm2yarn
npm install axios
```
Then, in the component you want to add the subscription form add the following code:
```jsx
import axios from 'axios'
import { useState } from "react";
export default function NewsletterForm() {
const [email, setEmail] = useState("")
function subscribe(e) {
e.preventDefault();
if (!email) {
return;
}
axios.post('http://localhost:9000/mailchimp/subscribe', {
email
})
.then((e) => {
alert("Subscribed sucessfully!")
setEmail("")
})
.catch((e) => {
console.error(e);
alert("An error occurred");
})
}
return (
<form onSubmit={subscribe}>
<h2>Sign Up for our newsletter</h2>
<input type="email" name="email" id="email" placeholder="example@gmail.com"
value={email} onChange={(e) => setEmail(e.target.value)} />
<button type="submit">Subscribe</button>
</form>
)
}
```
This will result in a subscription form similar to the following:
![Subscription Form](https://i.imgur.com/JHIFEwe.png)
If you try entering an email and clicking Subscribe, the email will be subscribed to your Mailchimp newsletter successfully.
## Whats Next 🚀
- Check out SendGrid plugin for more Email functionalities.
- [Learn more about plugins.](https://docs.medusajs.com/guides/plugins)

View File

@@ -26,11 +26,7 @@ For other installation alternatives, you can head over to Meilisearch's [install
In order to add the plugin to your medusa project, you will need to first install the plugin using your favorite package manager:
```bash
# yarn
yarn add medusa-plugin-meilisearch
# npm
```bash npm2yarn
npm install medusa-plugin-meilisearch
```
@@ -83,11 +79,8 @@ The Medusa + MeiliSearch integration opens up a lot of capabilities for creating
In order to leverage this functionality, you'll need to install the corresponding packages by running:
```bash
# npm
```bash npm2yarn
npm install react-instantsearch-dom @meilisearch/instant-meilisearch
# yarn
yarn add react-instantsearch-dom @meilisearch/instant-meilisearch
```
You can then use the MeiliSearch client in your react app:

View File

@@ -26,8 +26,8 @@ Navigate to users and perform the following steps:
First, install the plugin using your preferred package manager:
```
yarn add medusa-file-minio
```bash npm2yarn
npm install medusa-file-minio
```
Then configure your `medusa-config.js` to include the plugin alongside the required options:

View File

@@ -51,8 +51,8 @@ Upon successfull creation of the user, you are presented with an **Access key ID
First, install the plugin using your preferred package manager:
```
yarn add medusa-file-s3
```bash npm2yarn
npm install medusa-file-s3
```
Then configure your `medusa-config.js` to include the plugin alongside the required options:

View File

@@ -25,8 +25,8 @@ Common integration use cases that can be implemented with Segment include:
Plugins in Medusa's ecosystem come as separate npm packages, that can be installed from the npm registry.
```bash
yarn add medusa-plugin-segment
```bash npm2yarn
npm install medusa-plugin-segment
```
After installation open `medusa-config.js` to configure the Segment plugin, by adding it to your project's plugin array and providing the options required by the plugin, namely the write key obtained from the Segment dashboard.

View File

@@ -1,9 +0,0 @@
# SendGrid (Documentation coming soon)
[View plugin here](https://github.com/medusajs/medusa/tree/master/packages/medusa-plugin-sendgrid)
<div>
<video width="100%" height="100%" playsinline autoplay muted controls>
<source src="https://user-images.githubusercontent.com/59018053/154807282-1e72671f-1936-411d-b914-e05c6597693a.mp4" type="video/mp4" />
</video>
</div>

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +1,101 @@
# Slack (Documentation coming soon)
# Slack
[View plugin here](https://github.com/medusajs/medusa/tree/master/packages/medusa-plugin-slack-notification)
In this documentation, you'll learn how to add the [Slack plugin](https://github.com/medusajs/medusa/tree/master/packages/medusa-plugin-slack-notification) to your Medusa server to start receiving order notifications.
## Overview
When you add this plugin, the store owner can receive order notifications into their Slack workspace.
The notification contains details about the order including:
- Customer's details and address
- Items ordered, their quantity, and the price
- Order totals including Tax amount.
- Promotion details if there are any (this is optional and can be turned off).
The plugin registers a subscriber to the `order.placed` event. When an order is placed, the subscriber handler method uses the ID of the order to retrieve order details mentioned above.
Then, the order notificaiton is sent to Slack using Webhooks. So, you'll need to create a Slack App, add it into your workspace, and activate Incoming Webhooks.
## Prerequisites
### Slack Account
To follow along with this guide, you need to have a Slack account with a connected workspace. If you dont have one, you can [create a free account on Slack](https://slack.com/).
### Medusa Server
This tutorial assumes you already have a Medusa server installed. If you dont, please follow along with the [quickstart guide](../quickstart/quick-start.md).
### Redis
Medusa's event system works by pushing data into a queue that is based on [Redis](https://redis.io/). This queue then notifies handlers of different events of this data that is pushed into the queue. The handlers then use this data to perform a certain action.
As the Slack plugin will listen to the `order.placed` event to know when to send notifications, you'll need to have Redis installed and configured with your Medusa server.
You can read the [Set up your development enviornment guideline](https://docs.medusajs.com/tutorial/set-up-your-development-environment) to learn more about how you can install and setup Redis.
## Create Slack App
The first step is to create a Slack app. This app will be connected to your workspace and will have Incoming Webhooks activated to receive notifications from the Medusa server using a Webhook URL.
Go to [Slack API](https://api.slack.com/) and click Create app. This will take you to a new page with a pop-up. In the pop-up, choose From scratch.
![Create Slack App](https://i.imgur.com/liVfwF8.png)
Youll then need to enter some info like the App name and the workspace it will be connected to. Once youre done, the app will be created.
### Activate Incoming Webhooks
To activate Incoming Webhooks, choose Features > Incoming Webhooks from the sidebar. At first, it will be disabled so make sure to enable it by switching the toggle.
![Incoming Webhooks](https://i.imgur.com/5Y0nv4p.png)
### Add New Webhook
After activating Incoming Webhooks, on the same page scroll down and click on the Add New Webhook to Workspace button.
![Add New Webhook](https://i.imgur.com/sejdIqH.png)
After that, choose the channel to send the notifications to. You can also choose a DM to send the notifications to. Once youre done click Allow.
![Choose channel or DM](https://i.imgur.com/Zw3f5uF.png)
This will create a new Webhook with a URL which you can see in the table at the end of the Incoming Webhooks page. Copy the URL as youll use it in the next section.
## Install Slack Plugin
The next step is to install Medusas [Slack plugin](https://github.com/medusajs/medusa/tree/master/packages/medusa-plugin-slack-notification) into your Medusa server.
Open the terminal in the Medusa servers directory and run the following command:
```bash npm2yarn
npm install medusa-plugin-slack-notification
```
After that, open `medusa-config.js` and add the new plugin with its configurations in the `plugins` array:
```jsx
const plugins = [
...,
{
resolve: `medusa-plugin-slack-notification`,
options: {
show_discount_code: false,
slack_url: `<WEBHOOK_URL>`,
admin_orders_url: `http://localhost:7001/a/orders`
}
}
];
```
- Make sure to change `<WEBHOOK_URL>` with the Webhook URL you copied after creating the Slack app.
- The `show_discount_code` option enables or disables showing the discount code in the notification sent to Slack.
- The `admin_orders_url` is the prefix of the URL of the order detail pages on your admin panel. If youre using Medusas Admin locally, it should be `http://localhost:7001/a/orders`. This will result in a URL like `http://localhost:7001/a/orders/order_01FYP7DM7PS43H9VQ1PK59ZR5G`.
Thats all you need to do to integrate Slack into Medusa!
## What's Next :rocket:
- Install [Medusa's Admin](https://github.com/medusajs/admin) for the full order-management experience.
- Add a Storefront to your Medusa server using [the Next.js starter](https://docs.medusajs.com/starters/nextjs-medusa-starter) or [the Gatsby starter](https://docs.medusajs.com/starters/gatsby-medusa-starter).

View File

@@ -26,8 +26,8 @@ Navigate to API in the left sidebar. Generate a new Spaces access key. This shou
First, install the plugin using your preferred package manager:
```
yarn add medusa-file-spaces
```bash npm2yarn
npm install medusa-file-spaces
```
Then configure your `medusa-config.js` to include the plugin alongside the required options:

View File

@@ -28,26 +28,27 @@ First, create a Medusa project using your favorite package manager. You can go a
`npx create-medusa-app` will allow you to create a Medusa store engine, a storefront, and Medusa admin in a single command
```bash
# using npx
npx create-medusa-app
```
# using yarn
Alternatively, using Yarn:
```bash
yarn create medusa-app
```
> When choosing `npx` you are shown different store engine options as part of the setup. For this Strapi tutorial, you should choose `medusa-starter-default`. Optionally, pick a storefront.
**Use `medusa-cli`**
`@medusajs/medusa-cli` is our Command Line Tool for creating the Medusa store engine (alongside many other powerful commands). Use it as such:
`@medusajs/medusa-cli` is our Command Line Tool for creating the Medusa store engine (alongside many other powerful commands). First, install it:
```bash npm2yarn
npm install @medusajs/medusa-cli -g
```
Then, initialize a Medusa project:
```bash
# using yarn
yarn global add @medusajs/medusa-cli
# using npm
npm install -g @medusajs/medusa-cli
# initialise a Medusa project
medusa new my-medusa-store
```
@@ -87,22 +88,14 @@ Additionally, add Strapi to your list of plugins:
And finally, install the plugin using your package manager:
```bash
#using yarn
yarn add medusa-plugin-strapi
# using npm
```bash npm2yarn
npm install medusa-plugin-strapi
```
You've now successfully installed and configured your Medusa store engine. Seed it with data and start it up by running:
```bash
# using npm
npm run seed && npm start
# using yarn
yarn seed && yarn start
```bash npm2yarn
npm run seed && npm run start
```
We'll now turn to the Strapi side of things.
@@ -111,13 +104,16 @@ We'll now turn to the Strapi side of things.
Similar to how you installed Medusa, you can install Strapi using your favorite package manager. Use the `strapi-medusa-template` to create your project. The template is a custom Strapi implementation required for the two systems to work together.
You can use NPX:
```bash
# using npx
npx create-strapi-app@3.6.8 strapi-medusa --template https://github.com/Deathwish98/strapi-medusa-template.git
```
# using yarn
Alternatively, using Yarn:
```bash
yarn global add create-strapi-app@3.6.8
create-strapi-app strapi-medusa --template https://github.com/Deathwish98/strapi-medusa-template.git
```

View File

@@ -1,6 +1,10 @@
# Stripe
[View plugin here](https://github.com/medusajs/medusa/tree/master/packages/medusa-payment-stripe)
This document guides you through setting up Stripe payments in your Medusa server, admin, and storefront using the [Stripe Plugin](https://github.com/medusajs/medusa/tree/master/packages/medusa-payment-stripe).
## Video Guide
You can also follow our video guide to learn how the setup works:
<div>
<video width="100%" height="100%" playsinline autoplay muted controls>
@@ -8,114 +12,364 @@
</video>
</div>
### Introduction
## Overview
Handling payments is at the core of every commerce system; it allows us to run our businesses. Consequently, a vast landscape of payment providers has developed, each with varying cost models, implementational specifications, and analytical capabilities.
[Stripe](https://stripe.com/) is a battle-tested and unified platform for transaction handling. Stripe supplies you with the technical components needed to handle transactions safely and all the analytical features necessary to gain insight into your sales. These features are also available in a safe test environment which allows for a concern-free development process.
As a consequence, one might ask, which one(s) should I choose? Medusa makes exchanging enabled payment providers easy through its unified payment API. Here, one may select payment provider plugins already existing ([PayPal](https://docs.medusajs.com/add-plugins/paypal), [Klarna](https://docs.medusajs.com/add-plugins/klarna), and Stripe), or develop new ones.
Using the `medusa-payment-stripe` plugin, this guide shows you how to set up your Medusa project with Stripe as a payment provider.
Using the `medusa-payment-stripe` plugin, this guide will show you how to set up your Medusa project with Stripe as a payment provider.
## Prerequisites
[Stripe](https://stripe.com) is a battle-tested and unified platform for transaction handling. Stripe supplies you with the technical components needed to handle transactions safely and all the analytical features necessary to gain insight into your sales. These features are also available in a safe test environment which allows for a concern free development process.
Before you proceed with this guide, make sure you create a [Stripe account](https://stripe.com). Youll later retrieve the API Keys and secrets from your account to connect Medusa to your Stripe account.
### Prerequisites
## Medusa Server
This guide assumes that you have set up a medusa project (See [this guide](https://docs.medusajs.com/tutorial/creating-your-medusa-server)). Furthermore, this guide will be using the Gatsby starter as our storefront (See [this guide](https://docs.medusajs.com/starters/gatsby-medusa-starter)) and the Admin panel to manage our store (See the github installation guide [here](https://github.com/medusajs/admin)).
This section guides you over the steps necessary to add Stripe as a payment provider to your Medusa server.
### Installation
If you dont have a Medusa server installed yet, you must follow our [quickstart guide](../quickstart/quick-start) first.
The first step is to install the `medusa-payment-stripe` plugin in your Medusa project using your favorite package manager:
### Plugin Installation
```bash
# yarn
yarn add medusa-payment-stripe
In the root of your Medusa server, run the following command to install the stripe plugin:
# npm
```bash npm2yarn
npm install medusa-payment-stripe
```
Then in your `medusa-config.js` , add the plugin to your `plugins` array:
### Plugin Configuration
```javascript
module.exports = {
// ... other options
plugins: [
// ... other plugins
{
resolve: `medusa-payment-stripe`,
options: {
api_key: STRIPE_API_KEY,
webhook_secret: STRIPE_WEBHOOK_SECRET,
},
},
];
Next, you need to add configurations for your stripe plugin.
In `medusa-config.js` add the following at the end of the `plugins` array:
```jsx
const plugins = [
...,
{
resolve: `medusa-payment-stripe`,
options: {
api_key: STRIPE_API_KEY,
webhook_secret: STRIPE_WEBHOOK_SECRET,
},
},
];
```
:::note
You might find that this code is already available but commented out. You can proceed with removing the comments instead of adding the code again.
:::
The Stripe plugin uses 2 configuration options. The `api_key` is essential to both your development and production environments. As for the `webhook_secret`, its essential for your production environment. So, if youre only using Stripe for development you can skip adding the value for this option at the moment.
### Retrieving The Keys
On the [dashboard](https://dashboard.stripe.com) of your Stripe account click on the Developers link at the top right. This will take you to the developer dashboard.
Youll first retrieve the API key. You can find it by choosing API Keys from the sidebar and copying the Secret key.
Next, you need to add the key to your environment variables. In your Medusa server, create `.env` if it doesnt already exist and add the Stripe key:
```jsx
STRIPE_API_KEY=sk_...
```
:::note
If you store environment variables differently on your server, for example, using the hosting providers UI, then you dont need to add it in `.env`. Add the environment variables in a way relevant to your server.
:::
Next, if youre installing this plugin for production use, you need to retrieve the Webhook secret. Webhooks allows you to track different events on your Medusa server, such as failed payments.
Go to Webhooks on Stripes developer dashboard. Then, choose the Add an Endpoint button.
The endpoint for Stripes webhook on your Medusa server is `{SERVER_URL}/stripe/hooks`. So, add that endpoint in its field. Make sure to replace `{SERVER_URL}` with the URL to your server.
Then, you can add a description. You must select at least one event to listen to. Once youre done, click “Add endpoint”.
After the Webhook is created, youll see a key at the top right that starts with `we_...`. Copy that key and in your Medusa server add the Webhook secret environment variable:
```jsx
STRIPE_WEBHOOK_SECRET=we_...
```
## Admin Setup
This section will guide you through adding Stripe as a payment provider in a region using your Medusa admin dashboard.
This step is required for you to be able to use Stripe as a payment provider in your storefront.
### Prerequisites
If you dont have a Medusa admin installed, make sure to follow along with [the guide on how to install it](https://github.com/medusajs/admin#-quickstart) before continuing with this section.
### Adding Stripe
First, make sure that both your Medusa server and Medusa Admin are running.
Then, in your Medusa Admin, log in and choose Settings from the Sidebar. Then, choose Regions.
![Settings](https://i.imgur.com/wRkmbLY.png)
Then, choose the regions you want to add Stripe as a payment provider. In the right-side settings, scroll down to “Payment Providers” and choose Stripe.
![Choose Stripe](https://i.imgur.com/FH5vgWh.png)
Once youre done, click Save. Stripe is now a payment provider in your store in the regions you selected.
## Storefront Setup
This guide will take you through how to set up Stripe payments in your Medusa storefront. It includes the steps necessary when using one of Medusas official storefronts as well as your own custom React-based storefront.
### Prerequisites
All storefronts require that you obtain your Stripes Publishable Key. You can retrieve it from your Stripes developer dashboard by choosing API Keys and then copying the Publishable Key.
### Next.js Storefront
Medusa has a Next.js storefront that you can easily use with your Medusa server. If you dont have the storefront installed, you can follow [this quickstart guide](../starters/nextjs-medusa-starter).
In your `.env` file, add the following variable with its value set to the Publishable Key:
```jsx
NEXT_PUBLIC_STRIPE_KEY=pk_...
```
:::note
This variable might be available in your `.env` file but commented out. You can instead remove the comment and change its value.
:::
Now, if you run your Medusa server and your storefront, on checkout youll be able to use Stripe.
![Next.js Stripe Form](https://i.imgur.com/1XvW776.png)
### Gatsby Storefront
Medusa also has a Gatsby storefront that you can use as your ecommerce store. If you dont have the storefront installed, you can follow [this quickstart guide](../starters/gatsby-medusa-starter).
In your `.env.development` file (or the file youre using for your environment variables) add the following variable with the value set to the Publishable Key:
```jsx
GATSBY_STRIPE_KEY=pk_
```
:::note
You might find this environment variable already available so you can just replace its value with your Publishable Key.
:::
Now, if you run your Medusa server and your storefront, on checkout youll be able to use Stripe.
![Gatsby Stripe Form](https://i.imgur.com/1XvW776.png)
### Custom Storefront
This section will go over how to add Stripe into a React-based framework. The instructions are general instructions that you can use in your storefront.
#### Workflow Overview
The integration with stripe must have the following workflow:
1. During checkout when the user reaches the payment section, you should [create payment sessions](https://docs.medusajs.com/api/store/cart/initialize-payment-sessions). This will initialize the `payment_sessions` array in the `cart` object received. The `payment_sessions` is an array of available payment providers.
2. If Stripe is available as a payment provider, you should select Stripe as [the payment session](https://docs.medusajs.com/api/store/cart/select-a-payment-session) for the current cart. This will initialize the `payment_session` object in the `cart` object to include data related to Stripe and the current payment session. This includes the payment intent and client secret.
3. After the user enters their card details and submits the form, confirm the payment with Stripe.
4. If the payment is confirmed successfully, [complete the order](https://docs.medusajs.com/api/store/cart/complete-a-cart) in Medusa. Otherwise show an error.
#### Installing Dependencies
Before you start the implementations you need to install the necessary dependencies. Youll be using Stripes React libraries to show the UI and handle the payment confirmation:
```bash npm2yarn
npm install --save @stripe/react-stripe-js @stripe/stripe-js
```
Youll also use Medusas JS Client to easily call Medusas REST APIs:
```bash npm2yarn
npm install @medusajs/medusa-js
```
#### Initialize Stripe
In this section, youll initialize Stripe without Medusas checkout workflow. Please note that this is one approach to add Stripe into your React project. You can check out [Stripes React documentation](https://stripe.com/docs/stripe-js/react) for other methods or components.
Create a container component that will hold the payment card component:
```jsx
import { useState } from 'react';
import {Elements} from '@stripe/react-stripe-js';
import Form from './Form';
import {loadStripe} from '@stripe/stripe-js';
const stripePromise = loadStripe('pk_...');
export default function Container() {
const [clientSecret, setClientSecret] = useState()
//TODO set clientSecret
return (
<div>
{clientSecret && (
<Elements stripe={stripePromise} options={{
clientSecret
}}>
<Form clientSecret={clientSecret} cartId={cartId} />
</Elements>
)}
</div>
);
};
```
In this component, you need to use Stripes `loadStripe` function outside of the components implementation to ensure that Stripe doesnt re-load with every change. The function accepts the Publishable Key.
:::note
Youll probably store this Publishable Key in an environment variable depending on your framework. Its hard-coded here for simplicity.
:::
Then, inside the components implementation, you add a state variable `clientSecret` which youll retrieve in the next section.
Once the clientSecret is set, the `Elements` Stripe component will wrap a `Form` component youll create next. This is necessary because the `Elements` component allows child elements to get access to the cards inputs and their data using Stripes `useElements` hook.
Create a new file for the `Form` component with the following content:
```jsx
import {CardElement, useElements, useStripe} from '@stripe/react-stripe-js';
export default function Form({clientSecret, cartId}) {
const stripe = useStripe();
const elements = useElements();
async function handlePayment(e) {
e.preventDefault()
//TODO handle payment
}
return (
<form>
<CardElement />
<button onClick={handlePayment}>Submit</button>
</form>
);
};
```
This component shows a CardElement component from Stripes React library. You can use `stripe` to be able to confirm the payment later. The `elements` variable will be used to retrieve the entered card details safely.
#### Implement the Workflow
Youll now implement the workflow explained earlier. Youll use Medusas JS Client, so make sure to import it and initialize it in your `Container` component:
```jsx
import Medusa from "@medusajs/medusa-js"
export default function Container() {
const client = new Medusa();
...
}
```
Now head over to [Stripe](https://stripe.com/) and create your account. You can then click API Keys on your dashboard, and here you will see two keys. We suggest using the test environment during development, and therefore you should make sure that you are seeing the keys to the test environment (These keys start with `pk_test_` and `sk_test_` respectively).
:::note
Now open your `.env` file for the Medusa project and store your _secret key_ in the `STRIPE_API_KEY` variable:
In your storefront, youll probably be managing the Medusa client through a context for better performance.
```bash
# .env
STRIPE_API_KEY=<your key here>
:::
Then, in the place of the `//TODO` inside the `Container` element, initialize the payment sessions and create a payment session if Stripe is available:
```jsx
client.carts.createPaymentSessions(cart.id)
.then(({cart}) => {
//check if stripe is selected
const isStripeAvailable = cart.payment_sessions?.some((session) => session.provider_id === 'stripe');
if (!isStripeAvailable) {
return;
}
//select stripe payment session
client.carts.setPaymentSession(cart.id, {
provider_id: 'stripe'
}).then(({cart}) => {
setClientSecret(cart.payment_session.data.client_secret);
});
})
```
> Note: For production you should also create a webhook on Stripe (also available on your dashboard) and store its secret in the `STRIPE_WEBHOOK_SECRET` variable. We will go into detail with this in a later guide.
:::note
Then navigate to your Gatsby starter project and open the `.env.development` file and store your _publishable key_ in the `GATSBY_STRIPE_KEY` variable:
Notice that here its assumed you have access to the `cart` object throughout your storefront. Ideally, the `cart` should be managed through a context. So, every time the cart is updated, for example, when the `createPaymentSessions` or `setPaymentSession` are called, the cart should be updated in the context to be accessed from other elements. In this case, you probably wouldnt need a `clientSecret` state variable as you can use the client secret directly from the `cart` object.
```bash
# .env
GATSBY_STRIPE_KEY=<your key here>
:::
Once the client secret is set, the form will be shown to the user.
The last step in the workflow is confirming the payment with Stripe and if its done successfully, completing the users order. This part is done in the `Form` component.
As youll use Medusas client again make sure to import it and initialize it:
```jsx
import Medusa from "@medusajs/medusa-js"
export default function Form() {
const client = new Medusa();
...
}
```
### Whats next?
Then, replace the `//TODO` in the `handlePayment` function with the following content:
At this point we have set everything up, and the Stripe payment provider is now enabled in your Medusa project. So, go ahead and start up your medusa project, the gatsby starter, and the admin panel!
```jsx
return stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: elements.getElement(CardElement),
billing_details: {
name,
email,
phone,
address: {
city,
country,
line1,
line2,
postal_code,
}
}
}
}).then(({ error, paymentIntent }) => {
//TODO handle errors
client.carts.complete(cartId).then(resp => console.log(resp))
})
```
However, as Medusa allows for different payment providers in different regions (and multiple providers in each) we should first make Stripe a valid payment option in our default region. To do so, open the admin panel (`http://localhost:7000`) login, and navigate to `Settings > Region settings > Edit Default Region`. Here you should now be able to select Stripe as a payment provider:
You use the `confirmCardPayment` method in the `stripe` object. Youll need to pass it the client secret, which you can have access to from the cart object if its available through the context.
<center>
This method also requires the customers information like `name`, `email`, and their address. Make sure to place the values for each based on your implementation.
![Change payment provider](https://i.imgur.com/mVIDYz4.png)
Once the promise resolves you can handle the errors, if there are any. If not, you can complete the customers order using `complete` from Medusas client. This request expects the cart ID which you should have access to as well.
</center>
If you run your server and storefront now, youll see the Stripe UI element and youll be able to make orders.
After doing this, and clicking save, we are ready to accept payments using Stripe. So, navigate to your storefront (`http://localhost:8000`) and go through the checkout process:
![Stripe Form](https://i.imgur.com/NOi8THw.png)
<center>
## Capturing Payment
![Checkout process](https://i.imgur.com/qhanISL.gif)
After the customer places an order, youll be able to see the order on the admin panel. In the payment information under the “Payment” section, you should see a “Capture” button.
</center>
After doing so, you should be able to see an uncaptured payment in Stripe. Here, you navigate to the payments tab, where you should see the following (depending on your choices during the checkout process):
![Capture Payment](https://i.imgur.com/Iz55PVZ.png)
<center>
Clicking this button allows you to capture the payment for an order. You can also refund payments if an order has captured payments.
![Uncaptured payment](https://i.imgur.com/LX6UR40.png)
Refunding or Capturing payments is reflected in your Stripes dashboard as well. This gives you access to all of Stripes analytical capabilities.
</center>
## Whats Next 🚀
To then capture the payment, navigate back to the admin panel (`http://localhost:7000/`), and dig into the relevant order, and capture the payment:
<center>
![Capture payment](https://i.imgur.com/y5UxxpS.gif)
</center>
The capture is then reflected in the payment overview in Stripe as well, giving you access to all of Stripe's analytical capabilities:
<center>
![Captured payment](https://i.imgur.com/edv84Nq.png)
</center>
### Summary
In this guide we have setup Stripe as a payment provider giving you a fully functioning ecommerce experience! Interested in learning more? Check out the other guides and tutorials or head over to our [Discord channel](https://discord.gg/xpCwq3Kfn8) if you have any questions or want to become part of our community!
[View plugin here](https://github.com/medusajs/medusa/tree/master/packages/medusa-payment-stripe)
- Check out [more plugins](https://github.com/medusajs/medusa/tree/master/packages) you can add to your store.

View File

@@ -0,0 +1,128 @@
# Twilio SMS
In this document, youll learn about the Twilio SMS Plugin, what it does, and how to use it in Medusa.
## Overview
[Twilios SMS API](https://www.twilio.com/sms) can be used to send users SMS messages instantly. It has a lot of additional features such as Whatsapp messaging and conversations.
By integrating Twilio SMS into Medusa, youll have easy access to Twilios SMS API to send SMS messages to your users and customers. You can use it to send Order confirmations, verification codes, reset password messages, and more.
:::note
This plugin only gives you access to the Twilio SMS API but does not implement sending messages at any given point. Youll have to add this yourself where you need it. You can look at the [example later in this tutorial](#example-usage-of-the-plugin) to check how you can send an SMS for a new order.
:::
## Prerequisites
Before going further with this guide make sure you have a Medusa server set up. You can follow our [Quickstart guide](../quickstart/quick-start.md) if you dont.
You also must have a [Twilio account created](https://www.twilio.com/sms) so if you dont already please go ahead and create one.
## Retrieve Credentials
For the [Twilio SMS plugin](https://github.com/medusajs/medusa/tree/master/packages/medusa-plugin-twilio-sms), you need three credentials from your Twilio account: Account SID, Auth Token, and a Twilio phone number to send from. You can find these 3 from your [Twilio Consoles homepage](https://console.twilio.com).
## Install Plugin
In the directory of your Medusa server, run the following command to install [Twilio SMS plugin](https://github.com/medusajs/medusa/tree/master/packages/medusa-plugin-twilio-sms):
```bash npm2yarn
npm install medusa-plugin-twilio-sms
```
Then, youll need to add your credentials in `.env`:
```bash
TWILIO_SMS_ACCOUNT_SID=<YOUR_ACCOUNT_SID>
TWILIO_SMS_AUTH_TOKEN=<YOUR_AUTH_TOKEN>
TWILIO_SMS_FROM_NUMBER=<YOUR_TWILIO_NUMBER>
```
Make sure to replace `<YOUR_ACCOUNT_SID>`, `<YOUR_AUTH_TOKEN>`, and `<YOUR_TWILIO_NUMBER>` with the credentials you obtained from your Twilio Console.
Finally, add the plugin and its options in the `medusa-config.js` file to the `plugins` array:
```jsx
const plugins = [
...,
{
resolve: `medusa-plugin-twilio-sms`,
options: {
account_sid: process.env.TWILIO_SMS_ACCOUNT_SID,
auth_token: process.env.TWILIO_SMS_AUTH_TOKEN,
from_number: process.env.TWILIO_SMS_FROM_NUMBER
}
}
];
```
## Example Usage of the Plugin
This plugin adds the service `twilioSmsService` to your Medusa server. To send SMS using it, all you have to do is resolve it in your file as explained in the [Services](../advanced/backend/services/create-service.md#using-your-custom-service) documentation.
In this example, youll create a subscriber that listens to the `order.placed` event and sends an SMS to the customer to confirm their order.
:::tip
For this example to work, youll need to install and configure Redis on your server. You can refer to the [development guide](../tutorial/0-set-up-your-development-environment.md#redis) to learn how to do that.
:::
Create the file `src/services/sms.js` in your Medusa server with the following content:
```jsx
class SmsSubscriber {
constructor({ twilioSmsService, orderService, eventBusService }) {
this.twilioSmsService_ = twilioSmsService;
this.orderService = orderService;
eventBusService.subscribe("order.placed", this.sendSMS);
}
sendSMS = async (data) => {
const order = await this.orderService.retrieve(data.id, {
relations: ['shipping_address']
});
if (order.shipping_address.phone) {
this.twilioSmsService_.sendSms({
to: order.shipping_address.phone,
body: 'We have received your order #' + data.id,
})
}
};
}
export default SmsSubscriber;
```
In the `constructor`, you resolve the `twilioSmsService` and `orderService` using dependency injection to use it later in the `sendSMS` method.
You also subscribe to the event `order.placed` and sets the event handler to be `sendSMS`.
In `sendSMS`, you first retrieve the order with its relation to `shipping_address` which contains a `phone` field. If the phone is set, you send an SMS to the customer using the method `sendSms` in the `twilioSmsService`.
This method accepts an object of parameters. These parameters are based on Twilios SMS APIs. You can check their [API documentation](https://www.twilio.com/docs/sms/api/message-resource#create-a-message-resource) for more fields that you can add.
If you create an order now on your storefront, you should receive a message from Twilio on the phone number you entered in the shipping address.
:::tip
If you dont have a storefront set up yet, you can install one of our [Next.js](../starters/nextjs-medusa-starter.md) or [Gatsby](../starters/gatsby-medusa-starter.md) storefronts.
:::
:::caution
If youre on a Twilio trial make sure that the phone number you entered on checkout is a [verified Twilio number on your console](https://console.twilio.com/us1/develop/phone-numbers/manage/verified).
:::
![Twilio Dashboard](https://i.imgur.com/MXtQMiL.png)
## Whats Next 🚀
- Learn more about how [Notifications work in Medusa](../how-to/notification-api).
- Install the [Medusa admin](../admin/quickstart.md) for functionalities like Gift Cards creation, swaps, claims, order return requests, and more.