wix-cli-service-plugin

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Wix Service Plugin (SPI) Builder

Wix Service Plugin (SPI) 构建工具

Creates service plugin extensions for Wix CLI applications. Service plugins are a set of APIs defined by Wix that you can use to inject custom logic into the existing backend flows of Wix business solutions or to introduce entirely new flows to Wix sites.
When you implement a service plugin, Wix calls your custom functions during specific flows. Common use cases include eCommerce customization (shipping, fees, taxes, validations), but service plugins can extend any Wix business solution that exposes SPIs.
为Wix CLI应用程序创建服务插件扩展。服务插件是Wix定义的一组API,您可以使用它们向Wix商业解决方案的现有后端流程中注入自定义逻辑,或为Wix站点引入全新流程。
当您实现服务插件后,Wix会在特定流程中调用您的自定义函数。常见用例包括电商定制(配送、费用、税费、验证),但服务插件可以扩展任何暴露SPI的Wix商业解决方案。

Quick Start Checklist

快速开始清单

Follow these steps in order when creating a service plugin:
  1. Read the reference doc for your SPI type (REQUIRED before implementation)
  2. Create plugin folder:
    src/backend/service-plugins/<service-type>/<plugin-name>/
  3. Create
    plugin.ts
    with correct imports and
    provideHandlers()
    call
  4. Implement all required handler functions with complete business logic
  5. Create
    extensions.ts
    with appropriate builder method and unique UUID
  6. Update
    src/extensions.ts
    to import and use the new extension
  7. Run
    npx tsc --noEmit
    to verify TypeScript compiles
  8. Run
    npx wix build
    to verify build succeeds
  9. Test by triggering the relevant site action (e.g., add to cart for fees)
创建服务插件时,请按以下顺序执行步骤:
  1. 阅读对应SPI类型的参考文档(实现前必须完成)
  2. 创建插件文件夹:
    src/backend/service-plugins/<service-type>/<plugin-name>/
  3. 创建
    plugin.ts
    文件,包含正确的导入语句和
    provideHandlers()
    调用
  4. 实现所有必需的处理函数,并完善业务逻辑
  5. 创建
    extensions.ts
    文件,包含合适的构建器方法和唯一UUID
  6. 更新
    src/extensions.ts
    文件,导入并使用新扩展
  7. 运行
    npx tsc --noEmit
    验证TypeScript编译通过
  8. 运行
    npx wix build
    验证构建成功
  9. 通过触发相关站点操作进行测试(例如,添加商品到购物车以测试费用插件)

References

参考资料

You MUST read the relevant reference document before implementing a relevant SPI. Each reference contains the correct imports, handler signatures, response structures, and working examples.
SPI TypeReference
Additional FeesADDITIONAL-FEES.md
Discount TriggersDISCOUNT-TRIGGERS.md
Gift CardsGIFT-CARDS.md
Shipping RatesSHIPPING-RATES.md
Tax CalculationTAX-CALCULATION.md
ValidationsVALIDATIONS.md
在实现对应SPI之前,您必须阅读相关参考文档。 每个参考文档都包含正确的导入语句、处理函数签名、响应结构和可用示例。
SPI类型参考文档
附加费用ADDITIONAL-FEES.md
折扣触发器DISCOUNT-TRIGGERS.md
礼品卡GIFT-CARDS.md
配送费率SHIPPING-RATES.md
税费计算TAX-CALCULATION.md
验证VALIDATIONS.md

Output Structure

输出结构

Service plugins consist of two files that work together. Registration of plugins requires an extension builder file.
src/backend/service-plugins/
└── {service-type}/
    └── {plugin-name}/
        ├── plugin.ts           # Handler logic with provideHandlers()
        └── extensions.ts       # Builder configuration (id, name, source)
服务插件由两个协同工作的文件组成。插件注册需要一个扩展构建器文件。
src/backend/service-plugins/
└── {service-type}/
    └── {plugin-name}/
        ├── plugin.ts           # 包含provideHandlers()的处理逻辑
        └── extensions.ts       # 构建器配置(ID、名称、源文件路径)

File Descriptions

文件说明

FilePurpose
plugin.ts
Contains the service plugin handler logic with
provideHandlers()
- this is where you implement your custom business logic
extensions.ts
Contains the service plugin builder configuration with id (GUID), name, description, and source path
文件用途
plugin.ts
包含服务插件的处理逻辑和
provideHandlers()
调用——这是您实现自定义业务逻辑的地方
extensions.ts
包含服务插件的构建器配置,包括ID(GUID)、名称、描述和源文件路径

Implementation Requirements

实现要求

Generation Requirements

生成要求

  1. Implement ALL required handler functions with complete business logic
  2. Include proper TypeScript types and error handling
  3. Focus on implementing the EXACT business logic described in the user prompt
  1. 实现所有必需的处理函数,并完善业务逻辑
  2. 包含正确的TypeScript类型和错误处理
  3. 专注于实现用户需求中描述的精确业务逻辑

Implementation Patterns

实现模式

  • If capabilities are undocumented/unavailable, explicitly state the gap and proceed only with documented minimal logic
  • Implement all required handler functions according to Wix specifications
  • Never use placeholders - always implement complete, working functionality
  • 如果功能未被文档化/不可用,明确说明差距,仅基于已文档化的最小逻辑进行开发
  • 根据Wix规范实现所有必需的处理函数
  • 绝不使用占位符——始终实现完整、可运行的功能

Data Validation

数据验证

All service plugins must include comprehensive data validation:
  • Validate all input data from Wix requests
  • Ensure required fields are present and properly formatted
  • Handle missing or malformed data gracefully
  • Validate business logic constraints (e.g., minimum order amounts, valid addresses)
所有服务插件必须包含全面的数据验证:
  • 验证来自Wix请求的所有输入数据
  • 确保必需字段存在且格式正确
  • 优雅处理缺失或格式错误的数据
  • 验证业务逻辑约束(例如,最低订单金额、有效地址)

Implementation Pattern

实现模式

The handler file (
plugin.ts
) contains the service plugin logic. It must:
  1. Import the relevant service plugin from
    @wix/ecom/service-plugins
  2. Call
    provideHandlers()
    with an object containing handler functions
  3. Each handler function receives a payload with
    request
    and
    metadata
  4. Return the expected response structure for that SPI type
typescript
import { shippingRates } from "@wix/ecom/service-plugins";

shippingRates.provideHandlers({
  getShippingRates: async (payload) => {
    const { request, metadata } = payload;

    // Implement custom logic based on request data
    // - request contains cart items, shipping address, etc.
    // - metadata contains currency, locale, etc.

    return {
      shippingRates: [
        {
          code: "custom-shipping",
          title: "Custom Shipping",
          logistics: {
            deliveryTime: "3-5 business days",
          },
          cost: {
            price: "9.99",
            currency: metadata.currency || "USD",
          },
        },
      ],
    };
  },
});
Handler functions are called automatically by Wix when the relevant site action triggers them. Your custom logic should be placed inside each handler function.
处理文件(
plugin.ts
)包含服务插件逻辑。它必须:
  1. @wix/ecom/service-plugins
    导入相关的服务插件
  2. 调用
    provideHandlers()
    并传入包含处理函数的对象
  3. 每个处理函数接收包含
    request
    metadata
    的负载
  4. 返回对应SPI类型的预期响应结构
typescript
import { shippingRates } from "@wix/ecom/service-plugins";

shippingRates.provideHandlers({
  getShippingRates: async (payload) => {
    const { request, metadata } = payload;

    // 根据请求数据实现自定义逻辑
    // - request包含购物车商品、配送地址等信息
    // - metadata包含货币、区域设置等信息

    return {
      shippingRates: [
        {
          code: "custom-shipping",
          title: "Custom Shipping",
          logistics: {
            deliveryTime: "3-5 business days",
          },
          cost: {
            price: "9.99",
            currency: metadata.currency || "USD",
          },
        },
      ],
    };
  },
});
处理函数会在相关站点操作触发时由Wix自动调用。您的自定义逻辑应放在每个处理函数内部。

Elevating Permissions for API Calls

提升API调用权限

When making Wix API calls from service plugins, you must elevate permissions using
auth.elevate
from
@wix/essentials
.
typescript
import { auth } from "@wix/essentials";
import { items } from "@wix/data";

export const myFunction = async () => {
  const elevatedFunction = auth.elevate(items.query);
  const elevatedResponse = await elevatedFunction("myCollection");
  return elevatedResponse;
};
typescript
import { auth } from "@wix/essentials";
import { cart } from "@wix/ecom";

export const myFunction = async () => {
  const elevatedFunction = auth.elevate(cart.getCart);
  const elevatedResponse = await elevatedFunction("cart-id");
  return elevatedResponse;
};
typescript
import { auth } from "@wix/essentials";
import { products } from "@wix/stores";

export const myFunction = async () => {
  const elevatedFunction = auth.elevate(products.deleteCollection);
  const elevatedResponse = await elevatedFunction("collection-id");
  return elevatedResponse;
};
从服务插件中调用Wix API时,您必须使用
@wix/essentials
中的
auth.elevate
提升权限。
typescript
import { auth } from "@wix/essentials";
import { items } from "@wix/data";

export const myFunction = async () => {
  const elevatedFunction = auth.elevate(items.query);
  const elevatedResponse = await elevatedFunction("myCollection");
  return elevatedResponse;
};
typescript
import { auth } from "@wix/essentials";
import { cart } from "@wix/ecom";

export const myFunction = async () => {
  const elevatedFunction = auth.elevate(cart.getCart);
  const elevatedResponse = await elevatedFunction("cart-id");
  return elevatedResponse;
};
typescript
import { auth } from "@wix/essentials";
import { products } from "@wix/stores";

export const myFunction = async () => {
  const elevatedFunction = auth.elevate(products.deleteCollection);
  const elevatedResponse = await elevatedFunction("collection-id");
  return elevatedResponse;
};

Best Practices

最佳实践

Development Workflow

开发工作流

  • Always implement complete, working functionality - never use placeholders
  • Handle all required fields according to Wix documentation
  • Implement proper validation for all input data
  • Return responses in exact format expected by Wix
  • Add comprehensive error handling for all failure scenarios
  • Use meaningful variable names and clear code structure
  • Test thoroughly with different input combinations
  • 始终实现完整、可运行的功能——绝不使用占位符
  • 根据Wix文档处理所有必需字段
  • 为所有输入数据实现适当的验证
  • 返回Wix预期的精确格式响应
  • 为所有故障场景添加全面的错误处理
  • 使用有意义的变量名和清晰的代码结构
  • 使用不同的输入组合进行全面测试

Implementation Guidelines

实现指南

  • Validate all input: Check required fields are present and properly formatted
  • Handle errors gracefully: Return appropriate error responses, don't throw unhandled exceptions
  • Return exact format: Responses must match Wix documented structure exactly
  • Use TypeScript types: Leverage SDK types for better type safety
  • Test edge cases: Empty carts, missing addresses, invalid data
  • Performance: Keep calculations efficient - these run on every checkout
  • Logging: Add console.log for debugging but keep production logs minimal
  • 验证所有输入: 检查必需字段是否存在且格式正确
  • 优雅处理错误: 返回合适的错误响应,不要抛出未处理的异常
  • 返回精确格式: 响应必须完全匹配Wix文档中描述的结构
  • 使用TypeScript类型: 利用SDK类型提升类型安全性
  • 测试边缘情况: 空购物车、缺失地址、无效数据
  • 性能: 保持计算高效——这些逻辑会在每次结账时运行
  • 日志: 添加console.log用于调试,但生产环境日志要尽量精简

Extension Registration

扩展注册

Extension registration is MANDATORY and has TWO required steps.
扩展注册是必须的,且包含两个必需步骤。

Step 1: Create Plugin-Specific Extension File

步骤1:创建插件专属扩展文件

Each service plugin requires an
extensions.ts
file in its folder with the appropriate builder method for the SPI type:
typescript
import { extensions } from "@wix/astro/builders";

export const ecomshippingratesMyShipping = extensions.ecomShippingRates({
  id: "{{GENERATE_UUID}}",
  name: "My Shipping Rates",
  description: "Calculates custom shipping rates based on order weight",
  source: "./backend/service-plugins/ecom-shipping-rates/my-shipping/plugin.ts",
});
CRITICAL: UUID Generation
The
id
must be a unique, static UUID v4 string. Generate a fresh UUID for each extension - do NOT use
randomUUID()
or copy UUIDs from examples. Replace
{{GENERATE_UUID}}
with a freshly generated UUID like
"a1b2c3d4-e5f6-7890-abcd-ef1234567890"
.
每个服务插件在其文件夹中都需要一个
extensions.ts
文件,包含对应SPI类型的构建器方法:
typescript
import { extensions } from "@wix/astro/builders";

export const ecomshippingratesMyShipping = extensions.ecomShippingRates({
  id: "{{GENERATE_UUID}}",
  name: "My Shipping Rates",
  description: "Calculates custom shipping rates based on order weight",
  source: "./backend/service-plugins/ecom-shipping-rates/my-shipping/plugin.ts",
});
重要提示:UUID生成
The
id
must be a unique, static UUID v4 string. Generate a fresh UUID for each extension - do NOT use
randomUUID()
or copy UUIDs from examples. Replace
{{GENERATE_UUID}}
with a freshly generated UUID like
"a1b2c3d4-e5f6-7890-abcd-ef1234567890"
.

Builder Configuration Fields

构建器配置字段

FieldTypeDescription
id
stringService plugin ID as a GUID. Must be unique across all extensions in the project.
name
stringThe service plugin name (visible in app dashboard when developing an app).
description
stringA short description of what the service plugin does.
source
stringPath to the service plugin handler file that contains the plugin logic.
Additional fields may be required or optional depending on the specific service plugin type.
Builder methods by SPI type:
SPI TypeBuilder Method
Shipping Rates
ecomShippingRates()
Additional Fees
ecomAdditionalFees()
Validations
ecomValidations()
Discount Triggers
ecomDiscountTriggers()
Gift Cards
ecomGiftCards()
Payment Settings
ecomPaymentSettings()
字段类型描述
id
字符串服务插件ID,为GUID。在项目的所有扩展中必须唯一。
name
字符串服务插件名称(开发应用时在应用仪表板中可见)。
description
字符串服务插件的简短描述。
source
字符串包含插件逻辑的服务插件处理文件的路径。
根据具体的服务插件类型,可能需要或可选其他字段。

Step 2: Register in Main Extensions File

按SPI类型分类的构建器方法:

CRITICAL: After creating the plugin-specific extension file, you MUST read wix-cli-extension-registration and follow the "App Registration" section to update
src/extensions.ts
.
Without completing Step 2, the service plugin will not be active in the eCommerce system.
SPI类型构建器方法
配送费率
ecomShippingRates()
附加费用
ecomAdditionalFees()
验证
ecomValidations()
折扣触发器
ecomDiscountTriggers()
礼品卡
ecomGiftCards()
支付设置
ecomPaymentSettings()

Testing Service Plugins

步骤2:在主扩展文件中注册

To test your service plugin extension:
  1. Release a version with your changes - new service plugins or changes to existing ones won't take effect until you've built and released your project
  2. Trigger the call to your service plugin by performing the relevant action (e.g., add items to cart and view cart to test Additional Fees)
For example, to test an Additional Fees service plugin that adds a $5 packaging fee:
  1. Go to your site's store in the local development environment
  2. Select any product and add it to the cart, then view the cart
  3. Check if the additional fee is listed in the order summary
重要提示: 创建插件专属扩展文件后,您必须阅读wix-cli-extension-registration并按照“应用注册”部分的说明更新
src/extensions.ts
如果未完成步骤2,服务插件将无法在电商系统中生效。

Verification

测试服务插件

After implementation, use wix-cli-app-validation to validate TypeScript compilation, build, preview, and runtime behavior.
要测试您的服务插件扩展:
  1. 发布包含更改的版本——新服务插件或对现有插件的更改必须在构建并发布项目后才会生效
  2. 触发调用——执行相关操作触发服务插件(例如,添加商品到购物车并查看购物车以测试附加费用插件)
例如,要测试添加5美元包装费的附加费用服务插件:
  1. 进入本地开发环境中的站点商店
  2. 选择任意商品并添加到购物车,然后查看购物车
  3. 检查订单摘要中是否列出了附加费用

验证

实现完成后,使用wix-cli-app-validation验证TypeScript编译、构建、预览和运行时行为。