Files
medusa-store/www/docs/content/plugins/notifications/mailchimp.md
Shahed Nasser 914d773d3a api-ref: custom API reference (#4770)
* initialized next.js project

* finished markdown sections

* added operation schema component

* change page metadata

* eslint fixes

* fixes related to deployment

* added response schema

* resolve max stack issue

* support for different property types

* added support for property types

* added loading for components

* added more loading

* type fixes

* added oneOf type

* removed console

* fix replace with push

* refactored everything

* use static content for description

* fixes and improvements

* added code examples section

* fix path name

* optimizations

* fixed tag navigation

* add support for admin and store references

* general enhancements

* optimizations and fixes

* fixes and enhancements

* added search bar

* loading enhancements

* added loading

* added code blocks

* added margin top

* add empty response text

* fixed oneOf parameters

* added path and query parameters

* general fixes

* added base path env variable

* small fix for arrays

* enhancements

* design enhancements

* general enhancements

* fix isRequired

* added enum values

* enhancements

* general fixes

* general fixes

* changed oas generation script

* additions to the introduction section

* added copy button for code + other enhancements

* fix response code block

* fix metadata

* formatted store introduction

* move sidebar logic to Tags component

* added test env variables

* fix code block bug

* added loading animation

* added expand param + loading

* enhance operation loading

* made responsive + improvements

* added loading provider

* fixed loading

* adjustments for small devices

* added sidebar label for endpoints

* added feedback component

* fixed analytics

* general fixes

* listen to scroll for other headings

* added sample env file

* update api ref files + support new fields

* fix for external docs link

* added new sections

* fix last item in sidebar not showing

* move docs content to www/docs

* change redirect url

* revert change

* resolve build errors

* configure rewrites

* changed to environment variable url

* revert changing environment variable name

* add environment variable for API path

* fix links

* fix tailwind settings

* remove vercel file

* reconfigured api route

* move api page under api

* fix page metadata

* fix external link in navigation bar

* update api spec

* updated api specs

* fixed google lint error

* add max-height on request samples

* add padding before loading

* fix for one of name

* fix undefined types

* general fixes

* remove response schema example

* redesigned navigation bar

* redesigned sidebar

* fixed up paddings

* added feedback component + report issue

* fixed up typography, padding, and general styling

* redesigned code blocks

* optimization

* added error timeout

* fixes

* added indexing with algolia + fixes

* fix errors with algolia script

* redesign operation sections

* fix heading scroll

* design fixes

* fix padding

* fix padding + scroll issues

* fix scroll issues

* improve scroll performance

* fixes for safari

* optimization and fixes

* fixes to docs + details animation

* padding fixes for code block

* added tab animation

* fixed incorrect link

* added selection styling

* fix lint errors

* redesigned details component

* added detailed feedback form

* api reference fixes

* fix tabs

* upgrade + fixes

* updated documentation links

* optimizations to sidebar items

* fix spacing in sidebar item

* optimizations and fixes

* fix endpoint path styling

* remove margin

* final fixes

* change margin on small devices

* generated OAS

* fixes for mobile

* added feedback modal

* optimize dark mode button

* fixed color mode useeffect

* minimize dom size

* use new style system

* radius and spacing design system

* design fixes

* fix eslint errors

* added meta files

* change cron schedule

* fix docusaurus configurations

* added operating system to feedback data

* change content directory name

* fixes to contribution guidelines

* revert renaming content

* added api-reference to documentation workflow

* fixes for search

* added dark mode + fixes

* oas fixes

* handle bugs

* added code examples for clients

* changed tooltip text

* change authentication to card

* change page title based on selected section

* redesigned mobile navbar

* fix icon colors

* fix key colors

* fix medusa-js installation command

* change external regex in algolia

* change changeset

* fix padding on mobile

* fix hydration error

* update depedencies
2023-08-15 18:07:54 +03:00

6.7 KiB
Raw Blame History

description, addHowToData
description addHowToData
Learn how to integrate Mailchimp with the Medusa backend. Learn how to install the plugin on the Medusa backend and how to add a subscription form. true

Mailchimp

In this document, youll learn about the Mailchimp plugin, what it does, and how to use it.

Overview

Mailchimp 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 the SendGrid plugin instead.

:::


Prerequisites

Before going further with this guide make sure you have a Medusa backend set up. You can follow the Quickstart guide.

You also need a Mailchimp account, so please create one before you start.


Obtain Mailchimp Keys

To integrate the plugin into Medusa you need two 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 from Mailchimps documentation to obtain an API Key.

You can follow this guide from Mailchimps documentation to obtain your Newsletter list or Audience ID.


Install the Plugin

In the directory of your Medusa backend, run the following command to install the Mailchimp plugin:

npm install medusa-plugin-mailchimp

Add Keys

Open .env and add the following keys:

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:

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 new POST and PUT endpoints at /mailchimp/subscribe. These endpoints require in the body of the request an email field. You can also optionally include a data object that holds any additional data you want to send to Mailchimp. You can check out Mailchimps subscription documentation for more details on the data you can send.

Without Additional Data

Try sending a POST or PUT request to /mailchimp/subscribe with the following JSON body:

{
  "email": "example@gmail.com"
}

If the subscription is successful, a 200 response code will be returned with OK message. If the same email address is used again in the POST, a 400 response will be returned with an error page. If this can occur in your usecase, use the PUT endpoint to prevent this.

Postman

If you check your Mailchimp dashboard, you should find the email added to your Audience list.

Email Added

With Additional Data

Heres an example of sending additional data with the subscription:

{
    "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:

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.

:::


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 to send API requests, so if you dont have it installed make sure you install it first:

npm install axios

Then, in the component you want to add the subscription form add the following code:

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

If you try entering an email and clicking Subscribe, the email will be subscribed to your Mailchimp newsletter successfully.


See Also