Skip to content

Instantly share code, notes, and snippets.

@kmelve
Created December 8, 2020 23:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmelve/35d470f27ad8a5c5022eeb46bd3bad71 to your computer and use it in GitHub Desktop.
Save kmelve/35d470f27ad8a5c5022eeb46bd3bad71 to your computer and use it in GitHub Desktop.
Create Mailchimp campaign document action proof of concept
const fetch = require('got');
const client = require('../client');
const HTML = require('../lib/newsletter-template');
const MAILCHIMP_URL = 'https://us3.api.mailchimp.com/3.0/campaigns';
const API_TOKEN = process.env.MAILCHIMP_TOKEN;
const QUERY = `//groq
*[
_type == "post"
&& newsletter == true
&& (defined(publishedAt) &&publishedAt < now())
][0]|order(publishedAt asc)
`;
module.exports = async function(req, res) {
const { title, subject_line, secret } = req.body;
if (secret !== process.env.WEBHOOK_SECRET) {
// Return 401 if the secret doesn't match.
return 401;
}
const campaign = await fetch
.post(MAILCHIMP_URL, {
headers: {
Authorization: API_TOKEN,
},
body: JSON.stringify({
type: 'regular',
recipients: {
list_id: '',
},
settings: {
title,
subject_line,
preview_text: 'News from the community',
from_name: 'Knut @ Sanity.io',
template_id: ,
},
}),
responseType: 'json',
})
.catch(error =>
console.error(
'create campaign',
JSON.stringify(error.body.errors, null, 2)
)
);
if (!campaign) {
return res.status(404);
}
const { id, web_id } = JSON.parse(campaign.body);
await fetch
.put(`${MAILCHIMP_URL}/${id}/content`, {
headers: {
Authorization: API_TOKEN,
},
responseType: 'json',
body: JSON.stringify({
html: HTML,
}),
})
.catch(error =>
console.error(
'update campaign',
JSON.stringify(error.body.errors, null, 2)
)
);
console.log('prepared campaign', id);
return res.status(200).json({ web_id });
import { useDocumentOperation } from '@sanity/react-hooks'
const HOST = ''
const URL = `${HOST}/api/create-community-newsletter`
const secret = ''
export function NewsletterAction (props) {
const { type, id, onComplete, draft, published } = props
const doc = draft || published
if (!doc) {
return null
}
const { newsLetterCampaign } = doc
const { patch, commit } = useDocumentOperation(id, type)
return {
label: newsLetterCampaign ? 'Open Newsletter' : 'Create newsletter',
icon: () => '🐒',
onHandle: async () => {
if (!doc.newsletter) {
onComplete()
return null
}
if (newsLetterCampaign) {
const MCURL = `https://us3.admin.mailchimp.com/campaigns/edit?id=${
newsLetterCampaign
}`
window.open(MCURL, '_blank')
onComplete()
return null
}
const campaign = await fetch(URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: doc.title,
subject_line: doc.excerpt,
secret
})
}).then(res => console.log(res) || res.json()).catch(error => console.error(error))
patch.execute([
{
set: {
newsLetterCampaign: campaign.web_id
}
}
])
commit.execute()
onComplete()
}
}
}
module.exports = `
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- NAME: VERY PLAIN TEXT -->
<meta name="viewport" content="width=device-width">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>*|MC:SUBJECT|*</title>
<style>
body {
font-family: Helvetica, Arial, sans-serfif;
font-size: 18px;
}
img {max-width: 100%; height: auto;}
</style>
</head>
<body>
<p mc:edit="header">Header section</p>
<div mc:edit="body"><p>Here is your mail body.</p></div>
<div mc:edit="footer">
<br><br>*|IFNOT:ARCHIVE_PAGE|* *|LIST:DESCRIPTION|* *|END:IF|*<br><br>
<a href="*|UNSUB|*">unsubscribe</a> |
<a href="*|UPDATE_PROFILE|*">edit preferences</a><br>
<br>
*|IF:REWARDS|* *|HTML:REWARDS|* *|END:IF|*
</div>
</body>
</html>
`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment