Hyperse
  • Pricing
  • FAQs
Newsletter

Subscribe to our newsletter

Receive weekly updates with latest collections and exclusive offers, straight to your inbox.

Hyperse

Headless commerce solutions for brands, developers, and modern ecommerce teams.

Explore

  • Home
  • About Us
  • Partners
  • FAQs

Legal & resources

  • Proposal
  • Privacy Policy
  • Terms & Conditions

© 2026 Hyperse. All rights reserved.


  1. Home
  2. Vendure Plugins
  3. hps-plugin-email-marketing
hps-plugin-email-marketing

hps-plugin-email-marketing

By Yingchun Tian

hps-plugin-email-marketing is a Email Marketing plugin in the Hub Growth group.hps-plugin-email-marketing provides Email Marketing plugin capabilities for Hub Growth. Growth, campaigns, loyalty, and customer engagement features. It is especially useful for growth, core workflows.

CoreVendure Plugins

Specifications

Technical details and package information for this product.

Package

@hyperse-hub/hps-plugin-email-marketing

Support by

Yingchun Tian

Support languages

TypeScript, JavaScript, CSS, Prolog, Shell

Integration type

Core

Category

Vendure Plugins

Compatible with

^3.0.0

Latest version

1.0.11

Downloads

0

Repository

https://github.com/hyperse-hub/hub-growth

Last published

July 14, 2026

Description
Changelog
loading...

On this page

  • @hyperse-hub/hps-plugin-email-marketing
    • 功能概览
    • 架构
    • 依赖
    • 快速开始(Klaviyo)
      • 1. 安装
      • 2. 获取 Klaviyo Private API Key
      • 3. 配置 Vendure
    • 配置选项
      • urlDefaults 与 defaultBrand
        • Order Placed 预加载的 relations
      • 按 Channel 启用 / 多 Provider
    • Shop GraphQL API
      • 弃购(Checkout Started)
      • 缺货通知(Klaviyo)
      • 与 plugin-subscribe 集成(示例,非内置)
    • 商品 Feed(已迁移至 plugin-feed)
    • 内置 Event Handlers
      • 注册退款事件
      • Klaviyo 订单事件说明
    • 自定义 Event Handler
      • 自定义 Order Placed 数据
    • 扩展新的 Provider(Strategy)
    • 失败监控
    • 开发与测试
    • 主要导出
    • 从 Pinelab Klaviyo 插件迁移
    • License

@hyperse-hub/hps-plugin-email-marketing

Vendure 插件:将电商行为、订单与商品数据同步到第三方邮件/营销平台(ESP)。

采用 Strategy 策略模式 抽象 Provider 无关能力,当前内置 Klaviyo 实现,后续可扩展 Mailchimp、Brevo 等。

功能概览

能力说明
订单同步下单后发送 Order Placed 及行级商品事件
弃购挽回Storefront 触发 Checkout Started
退款通知可选 Refund Created 事件
列表同步EmailMarketingService.subscribeToList(服务端调用;与 subscribe 的集成见下方示例)
缺货通知Back-in-stock 订阅(Klaviyo Catalog)
自定义事件通过 Event Handler 扩展任意 Vendure 事件
失败监控FailedToSendMarketingEvent 供业务监听

架构

职责划分:

  • Core:EventBus 监听、Job Queue 异步发送、Shop GraphQL
  • Event Handler:Vendure 领域事件 → 通用营销事件(各 Provider 共享)
  • Strategy:通用营销事件 → 具体 Provider API(Provider 特有逻辑在此)

与 hub-growth 其他插件的边界:

插件职责
plugin-subscribe站内订阅收集、Topic、双 opt-in 验证
plugin-email事务邮件(SMTP)
plugin-feed商品目录 Feed(Google/Facebook/Klaviyo 等)
本插件将营销数据 推送到 第三方 ESP

本插件不依赖 plugin-subscribe,也不提供内置 Newsletter bridge handler。若同时使用两者,请在 vendure-config / 自定义 Plugin 里用 EventBus 接线(见下方示例)。

推荐:Storefront 经 plugin-subscribe 收集并验证订阅 → 监听 SubscribeEmailVerifiedEvent → 调用 EmailMarketingService.subscribeToList 同步到 ESP。


依赖

包用途
@hyperse-hub/hps-plugin-coreShop API 缺货订阅的 RecaptchaInput 与 reCAPTCHA 校验(与 plugin-subscribe 相同)
@hyperse-hub/hps-plugin-feedKlaviyo 缺货通知所需的商品 Catalog Feed(可选)

快速开始(Klaviyo)

1. 安装

yarn add @hyperse-hub/hps-plugin-email-marketing

2. 获取 Klaviyo Private API Key

在 Klaviyo 控制台创建 Private API Key。

3. 配置 Vendure

默认已启用以下 Event Handler:

  • defaultOrderPlacedEventHandler — 订单完成 → Order Placed
  • checkoutStartedEventHandler — 弃购 → Checkout Started(需 Storefront 调用 mutation)

配置选项

注意: 同一 Vendure 事件不要注册多个 handler(例如两个 OrderPlacedEvent),否则会重复入队、重复发送到 ESP。启动时若检测到重复会输出 warn 日志。

urlDefaults 与 defaultBrand

字段说明
storefrontDomain商品链接域名;可为 (ctx) => string 按 channel 返回
productUrlPathTemplate默认 product/{slug}/{variantId}
assetBaseUrl / assetUrlTemplateCDN 绝对图片 URL
productUrlBuilder自定义商品 URL;优先于 productUrlPathTemplate(签名与 plugin-feed 相近)
assetUrlBuilder自定义图片 URL;优先于 assetBaseUrl / assetUrlTemplate

解析顺序:builder → 模板 → 内置默认(与 plugin-feed 行内 URL 一致)。

| defaultBrand | 无 brand facet 时的 fallback(内置 handler 已预加载 facet,见下方) |

默认 defaultOrderPlacedEventHandler 会映射 collection → categories、brand facet → brand、coupon → discountCode。

Order Placed 预加载的 relations

defaultOrderPlacedEventHandler 通过 OrderService.findOne 加载订单时,下列 relation 已 join,映射行项目时可直接使用,无需再查询:

导出常量:ORDER_PLACED_LOAD_RELATIONS(类型为 RelationPaths<Order>,与 Vendure OrderService.findOne 的 relations 参数一致)。

路径用途
lines.productVariant.product.facetValues + .facet + .translationsproduct facet brand → orderItems[].brand(按 channel 语言取翻译)
lines.productVariant.product.translations商品 slug → productUrl
lines.productVariant.collections + .translationscollection 名称 → orderItems[].categories
lines.productVariant.featuredAsset / lines.featuredAsset行图 preview → imageUrl

在自定义 MarketingEventHandler 中若需相同字段,请自行 findOne / EntityHydrator.hydrate 并包含 ORDER_PLACED_LOAD_RELATIONS(或其中子集)。productUrlBuilder / assetUrlBuilder 收到的 product / variant 即上述已加载实体。

未加载(需自行 join):variant 级 facetValues、product collections、variant options 等。

按 Channel 启用 / 多 Provider

strategy 支持函数,按 channel 返回不同实现或未启用:

Klaviyo API Key 也支持按 channel 动态返回:


Shop GraphQL API

弃购(Checkout Started)

前端在进入结账页时调用:

mutation { marketingCheckoutStarted }

需存在 active order 且 有效 Session;插件会发布 CheckoutStartedEvent,经 Handler 映射后异步发送到 ESP。

缺货通知(Klaviyo)

需先在 Klaviyo 账户连接商品 Feed(由 @hyperse-hub/hps-plugin-feed 的 klaviyo 平台生成,见该插件 README)。

  • 需要 recaptcha(reCAPTCHA v3),不需要 Shop Session — 商品页访客可直接留邮箱
  • 须注册 HpsPluginCore 以提供 RecaptchaInput 并完成校验

catalogItemId 通常为 @hyperse-hub/hps-plugin-feed Klaviyo Feed 中的 variant id(数字字符串,如 "1")。

与 plugin-subscribe 集成(示例,非内置)

Shop 不再暴露列表订阅 mutation。本插件不会自动监听 subscribe 事件;下列代码应放在你的 Vendure 配置或业务 Plugin 中(需同时安装 @hyperse-hub/hps-plugin-subscribe 与 @hyperse-hub/hps-plugin-email-marketing):


商品 Feed(已迁移至 plugin-feed)

Klaviyo 等 ESP 所需的 JSON 商品目录由 @hyperse-hub/hps-plugin-feed 生成,不再由本插件提供。

在 Vendure 中同时注册两个插件:

Feed URL(Klaviyo 后台填写):

单条 JSON 结构(Klaviyo 兼容):


内置 Event Handlers

HandlerVendure 事件营销事件名默认启用
defaultOrderPlacedEventHandlerOrderPlacedEventOrder Placed✅
checkoutStartedEventHandlerCheckoutStartedEventCheckout Started✅
createRefundEventHandler()RefundEventRefund Created❌ 需手动注册

注册退款事件

Klaviyo 订单事件说明

Order Placed 在 Klaviyo Strategy 中会发送:

  1. 一条 Placed Order(Klaviyo 原生电商事件)
  2. 每个 order line 一条 Ordered Product(可逐行排除)

自定义 Event Handler

将任意 Vendure 事件同步到 ESP,例如账户验证后发送欢迎流:

注册:

mapToMarketingEvent 返回 false 则跳过发送。

自定义 Order Placed 数据

返回 OrderPlacedEvent(eventName: 'Order Placed')即可;若完全自定义,请 移除 defaultOrderPlacedEventHandler,避免重复发送。

import type { OrderPlacedEvent } from '@hyperse-hub/hps-plugin-email-marketing'; // mapToMarketingEvent 返回 OrderPlacedEvent,可附加 customProperties、brand、categories 等

行级 Ordered Product 可通过 excludeFromLineItemEvent: true 排除。


扩展新的 Provider(Strategy)

实现 EmailMarketingStrategy 接口:

建议:

  • Event Handler 留在 Core,不要放进 Strategy
  • Provider 特有语义(如 Klaviyo Placed Order + Ordered Product)只在对应 Strategy 内处理
  • 重度 SDK 依赖可拆成独立包,例如 @hyperse-hub/hps-plugin-email-marketing-klaviyo

失败监控

Job 发送失败(含重试耗尽)时会:

  1. 写入 marketing_send_failure 表(Admin 模块 Marketing send failures 看板可查询)
  2. 发布 FailedToSendMarketingEvent 供业务监听

Admin GraphQL(需 AllowEmailMarketingPermission):

  • Queries: marketingSendFailures, marketingSendFailure
  • Mutations: resolveMarketingSendFailure, deleteMarketingSendFailure

Job Queue 名称:email-marketing,默认重试 10 次。仅在最后一次重试失败时写入失败表并发布 FailedToSendMarketingEvent。

升级后需同步数据库 schema(新建 marketing_send_failure 表),例如运行 Vendure migration 或在开发环境启用 synchronize。


开发与测试

环境变量(config/dev-server.ts):

变量说明
KLAVIYO_API_KEYKlaviyo Private API Key

E2E 排错: 若出现 no such table: module,删除 __data__/ 目录后重跑(sqljs 缓存了不完整的数据库快照)。


主要导出

导出用途
HpsPluginEmailMarketing插件入口
createKlaviyoEmailMarketingStrategyKlaviyo Strategy 工厂
defaultOrderPlacedEventHandler默认下单 Handler
checkoutStartedEventHandler弃购 Handler
createRefundEventHandler退款 Handler 工厂
CheckoutStartedEvent弃购内部事件
FailedToSendMarketingEvent发送失败事件
MarketingSendFailureService失败记录持久化服务
emailMarketingPermissionAdmin 看板权限
toMarketingMoney分 → 元(ESP 金额格式)

从 Pinelab Klaviyo 插件迁移

本插件由 @pinelab/vendure-plugin-klaviyo 重构而来。

Pinelab Klaviyo本插件
KlaviyoPluginHpsPluginEmailMarketing
KlaviyoEventHandlerMarketingEventHandler
KlaviyoGenericEventMarketingEvent
KlaviyoOrderPlacedEventOrderPlacedEvent
toKlaviyoMoneytoMarketingMoney
klaviyoCheckoutStartedmarketingCheckoutStarted
subscribeToKlaviyoList

License

MIT

Vendure Event
↓
MarketingEventHandler(Core,可扩展)
↓
Canonical Event(MarketingEvent / OrderPlacedEvent)
↓
EmailMarketingStrategy(Provider 实现,如 Klaviyo)
↓
第三方 ESP API
import { HpsPluginCore } from '@hyperse-hub/hps-plugin-core';
import {
HpsPluginEmailMarketing,
createKlaviyoEmailMarketingStrategy,
} from '@hyperse-hub/hps-plugin-email-marketing';
export const config: VendureConfig = {
plugins: [
HpsPluginCore.init({
reCaptchaV3SecretKey: process.env.RECAPTCHA_SECRET_KEY,
}),
HpsPluginEmailMarketing.init({
strategy: createKlaviyoEmailMarketingStrategy({
apiKey: process.env.KLAVIYO_API_KEY!,
}),
}),
],
};
HpsPluginEmailMarketing.init({
/** 营销 Provider 策略,见下文 Strategy */
strategy: createKlaviyoEmailMarketingStrategy({ apiKey: '...' }),
/** Vendure 事件 → 营销事件映射,默认含 order placed + checkout started */
eventHandlers: [defaultOrderPlacedEventHandler, checkoutStartedEventHandler],
/** 订单行 productUrl / imageUrl(与 plugin-feed 保持一致) */
urlDefaults: {
storefrontDomain: 'https://www.example.com/',
productUrlPathTemplate: 'product/{slug}/{variantId}',
assetBaseUrl: 'https://file.example.com',
},
defaultBrand: 'MyBrand',
});
HpsPluginEmailMarketing.init({
urlDefaults: {
storefrontDomain: 'https://www.example.com/',
productUrlPathTemplate: 'product/{slug}/{variantId}',
productUrlBuilder: ({ domain, slug, variantId, ctx }) =>
`${domain}${ctx.languageCode}/product/${slug}/${variantId}`,
assetUrlBuilder: ({ preview }) =>
`https://cdn.example.com/${preview.replace(/^\/+/, '')}`,
},
});
shippingLines.shippingMethod配送方式(profile / 订单上下文)
customer.addresses.country / customer.user客户地址与账号
import {
ORDER_PLACED_LOAD_RELATIONS,
productBrandName,
} from '@hyperse-hub/hps-plugin-email-marketing';
// 自定义 handler 示例:复用相同 relations
await orderService.findOne(ctx, orderId, [...ORDER_PLACED_LOAD_RELATIONS]);
const brand = productBrandName(
product,
ctx.languageCode,
ctx.channel.defaultLanguageCode
);
HpsPluginEmailMarketing.init({
strategy: (ctx) => {
if (ctx.channel.code === 'us-store') {
return createKlaviyoEmailMarketingStrategy({
apiKey: process.env.KLAVIYO_US_KEY!,
});
}
if (ctx.channel.code === 'eu-store') {
return createMailchimpStrategy({/* ... */}); // 未来扩展
}
return undefined; // 该 channel 不发送
},
});
createKlaviyoEmailMarketingStrategy({
apiKey: (ctx) =>
ctx.channel.code === 'default' ? process.env.KLAVIYO_API_KEY : undefined,
/** Ordered Product 并行发送数,默认 5 */
orderedProductConcurrency: 5,
/** Back-in-stock catalog variant id,默认 `$custom:::$default:::{catalogItemId}` */
catalogVariantId: (catalogItemId) => `$custom:::$default:::${catalogItemId}`,
});
mutation {
subscribeToMarketingBackInStock(
input: {
emailAddress: "user@example.com"
catalogItemId: "1"
recaptcha: { token: "<recaptcha-v3-token>" }
}
)
}
import { EmailMarketingService } from '@hyperse-hub/hps-plugin-email-marketing';
import {
SubscribeEmailVerifiedEvent,
SubscribeEvent,
} from '@hyperse-hub/hps-plugin-subscribe';
// 在自定义 Plugin 的 onApplicationBootstrap 或 vendure-config 插件工厂中:
// const emailMarketingService = injector.get(EmailMarketingService);
// Shop 邮箱双 opt-in 完成
eventBus.ofType(SubscribeEmailVerifiedEvent).subscribe(async (event) => {
const topicToListId: Record<string, string> = {
newsletter: 'WpeFJd',
};
for (const topic of event.entity.subscribeTopics) {
const listId = topicToListId[topic.code];
if (listId) {
await emailMarketingService.subscribeToList(
event.ctx,
event.entity.value,
listId
);
}
}
});
// Admin 直接创建已验证订阅
eventBus
.ofType(SubscribeEvent)
.filter(
(e) =>
e.type === 'created' &&
e.entity.emailVerifiedAt != null &&
e.entity.type === 'email'
)
.subscribe(async (event) => {
const topicToListId: Record<string, string> = {
newsletter: 'WpeFJd',
};
for (const topic of event.entity.subscribeTopics) {
const listId = topicToListId[topic.code];
if (listId) {
await emailMarketingService.subscribeToList(
event.ctx,
event.entity.value,
listId
);
}
}
});
import { HpsPluginFeed } from '@hyperse-hub/hps-plugin-feed';
import {
HpsPluginEmailMarketing,
createKlaviyoEmailMarketingStrategy,
} from '@hyperse-hub/hps-plugin-email-marketing';
HpsPluginFeed.init({
urlDefaults: {
productUrlPathTemplate: 'product/{slug}/{variantId}',
assetBaseUrl: 'https://file.example.com',
},
feedConfigs: [
{
siteName: 'my-store',
domain: 'https://www.example.com/',
limit: 5000,
languageCode: LanguageCode.en,
channelToken: 'default-channel',
currencyCode: CurrencyCode.USD,
platforms: ['klaviyo'],
onlyEnabledProducts: true,
accessPassword: process.env.MARKETING_FEED_PASSWORD,
},
],
});
HpsPluginEmailMarketing.init({
strategy: createKlaviyoEmailMarketingStrategy({ apiKey: '...' }),
});
https://www.example.com/feeds/my-store/klaviyo/products.json?password=your-secret
{
"id": "123",
"title": "Product name",
"link": "https://store.example/product/slug",
"description": "...",
"price": 19.99,
"image_link": "https://cdn.example/image.jpg",
"categories": ["Electronics"],
"inventory_quantity": 100,
"inventory_policy": 1
}
import { createRefundEventHandler } from '@hyperse-hub/hps-plugin-email-marketing';
HpsPluginEmailMarketing.init({
strategy: klaviyoStrategy,
eventHandlers: [
defaultOrderPlacedEventHandler,
checkoutStartedEventHandler,
createRefundEventHandler({
getPaymentMethodName: (payment) => payment?.metadata?.method ?? 'unknown',
}),
],
});
import { AccountVerifiedEvent } from '@vendure/core';
import type {
MarketingEventHandler,
MarketingEvent,
} from '@hyperse-hub/hps-plugin-email-marketing';
export const accountVerifiedHandler: MarketingEventHandler<AccountVerifiedEvent> =
{
vendureEvent: AccountVerifiedEvent,
mapToMarketingEvent: async (event) => {
const { customer } = event;
return {
uniqueId: `account-verified-${customer.id}`,
eventName: 'Account Verified',
profile: {
emailAddress: customer.emailAddress,
externalId: customer.id.toString(),
firstName: customer.firstName,
lastName: customer.lastName,
},
customProperties: {
verifiedAt: new Date().toISOString(),
},
} satisfies MarketingEvent;
},
};
HpsPluginEmailMarketing.init({
strategy: klaviyoStrategy,
eventHandlers: [defaultOrderPlacedEventHandler, accountVerifiedHandler],
});
import type {
EmailMarketingStrategy,
MarketingEvent,
OrderPlacedEvent,
} from '@hyperse-hub/hps-plugin-email-marketing';
export class MailchimpEmailMarketingStrategy implements EmailMarketingStrategy {
readonly code = 'mailchimp';
isEnabled(ctx: RequestContext): boolean {
return !!this.getApiKey(ctx);
}
async sendEvent(
ctx: RequestContext,
event: MarketingEvent | OrderPlacedEvent
) {
// 映射并调用 Mailchimp API
}
async subscribeToList(ctx: RequestContext, input: ListSubscriptionInput) {
// ...
}
// subscribeToBackInStock 为可选,不支持则勿实现
}
import { FailedToSendMarketingEvent } from '@hyperse-hub/hps-plugin-email-marketing';
eventBus.ofType(FailedToSendMarketingEvent).subscribe((event) => {
console.error('Marketing event failed:', event.data.eventName);
console.error('Profile:', event.data.profile.emailAddress);
console.error('Reason:', (event.error as Error)?.message);
});
cd packages/plugin-email-marketing
# 单元测试
yarn test-unit
# E2E(含 nock mock Klaviyo API)
yarn test-e2e
# 全部
yarn test
# 本地 dev server
yarn serve
ORDER_PLACED_LOAD_RELATIONS
下单 Handler 预加载的 RelationPaths<Order>
productBrandName / variantCategoryNames行项目 brand / categories 辅助函数
MarketingEventHandler自定义 Handler 类型
EmailMarketingStrategy自定义 Strategy 类型
已移除 Shop API;在应用层用 plugin-subscribe + EmailMarketingService.subscribeToList(见 README 集成示例)
subscribeToKlaviyoBackInStocksubscribeToMarketingBackInStock
klaviyoProductFeed@hyperse-hub/hps-plugin-feed → klaviyo/products.json
FailedToSendToKlaviyoEventFailedToSendMarketingEvent
apiKey 插件选项createKlaviyoEmailMarketingStrategy({ apiKey })