К основному содержанию
скилл CX Codex

commerce-app-webhooks — скилл для Claude Code

Скилл commerce-app-webhooks добавляет перехватчики webhook в приложение Adobe Commerce. Позволяет валидировать данные, добавлять информацию или менять поведение операций до или после их выполнения.

Apache-2.0 330 установок ★ 335 обновлён 2026-11-14

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add adobe/skills --skill commerce-app-webhooks -a claude-code
Открыть на GitHub

Что делает commerce-app-webhooks

Скилл работает с конфигом app.commerce.config.ts и добавляет записи в массив webhooks. Каждый перехватчик привязан к операции Commerce (например, plugin.magento.catalog_product.save) и срабатывает до или после её выполнения. Обработчик живёт либо в самом приложении как runtime-действие в пакете my-app/validate-product, либо указывается внешним URL.

Перед добавлением webhook скилл проверит, что проект инициализирован: нужны одновременно файл app.commerce.config.ts, директория src/commerce-extensibility-1/ и установленные node_modules. Если конфиг есть, но проект не инициализирован, скилл запустит npx @adobe/aio-commerce-lib-app init.

Для каждого перехватчика нужно задать имя операции, тип (before или after), категорию (валидация, добавление или изменение данных), имена batch и hook (только буквы, цифры и подчёркивание). Если обработчик — runtime-действие, создаётся файл в src/actions/ и регистрируется в src/commerce-extensibility-1/ext.config.yaml.

Какие задачи решает

  • валидировать данные продукта перед сохранением в каталог
  • перехватить создание заказа и отправить данные во внешний сервис
  • добавить вычисленные значения к операции перед выполнением
  • заблокировать операцию, если данные не прошли проверку
  • логировать и отслеживать все изменения в Commerce

Примеры запросов агенту

  • Добавь webhook, который валидирует цену товара перед сохранением
  • Создай перехватчик для проверки мошеннических заказов перед их размещением
  • Настрой webhook, чтобы добавлять метаданные к товарам при сохранении

Как установить commerce-app-webhooks

1Через Skills CLI (Vercel)

npx skills add adobe/skills --skill commerce-app-webhooks -a claude-code

2Вручную: положить файлы

~/.claude/skills/commerce-app-webhooks/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/commerce-app-webhooks/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о commerce-app-webhooks

Как установить commerce-app-webhooks в Claude Code?

Выполни команду npx skills add adobe/skills --skill commerce-app-webhooks -a claude-code, затем открой файл ~/.claude/skills/commerce-app-webhooks/SKILL.md.

Что такое webhook и зачем он нужен?

Webhook — это перехватчик, который срабатывает на операцию в Commerce до или после её выполнения. Используется для валидации данных, добавления информации или изменения поведения операции.

Какие требования для работы скилла?

Нужны Node.js 22+, aio CLI и @adobe/aio-commerce-lib-app. Приложение должно быть инициализировано с помощью скилла commerce-app-init — это создаст app.commerce.config.ts и директорию src/commerce-extensibility-1/.

Исходный текст

SKILL.md · Apache-2.0
---
name: commerce-app-webhooks
description: >
  Add or modify webhook interceptors in an Adobe Commerce app. Use when the
  user wants to intercept Commerce operations to validate input, append data,
  or modify behavior — before or after execution. Requires a base app
  initialized with commerce-app-init.
license: Apache-2.0
compatibility: >
  Requires Node.js 22+, aio CLI, and @adobe/aio-commerce-lib-app.
  Requires a base app initialized with commerce-app-init.
metadata:
  author: adobe
---

# Configure Commerce App Webhooks

Adds or modifies webhook interceptors in an existing `app.commerce.config.ts`.
Webhooks intercept Commerce operations — you can validate input, append data, or modify behavior before or after an operation executes.
Other extensibility domains (events, business config) are added separately via their own skills.

## Prerequisites

- Verify the app is **scaffolded and initialized**, not merely that the config exists. Require **both**:
  - `app.commerce.config.ts` present in the project root, **and**
  - the project initialized — signalled by the generated `src/commerce-extensibility-1/` directory and installed `node_modules` (the `@adobe/aio-commerce-lib-app` dependency).
- If `app.commerce.config.ts` is **missing**, stop and invoke `commerce-app-init` first (it writes the config, then runs init).
- If the config is **present but the project is not initialized** (no `src/commerce-extensibility-1/` or `node_modules`), run `npx @adobe/aio-commerce-lib-app init` before continuing. Init is idempotent — it finds the existing config, skips the interactive prompts, installs dependencies, and generates the project files.
- Actions can be authored in TypeScript only once the project has the TypeScript build setup (`webpack-config.cjs` + root `tsconfig.json`) that `init` scaffolds for a TypeScript Commerce config — see `commerce-app-init`. Otherwise, author actions in JavaScript.

## Step 1 — Understand intent

Ask the user what they want to intercept and how:

- **What operation**: the `webhook_method` (the Commerce operation, e.g., `plugin.magento.catalog_product.save`) and `webhook_type` (`before` or `after`)
- **How the handler is reached**: either a **runtime action** in this app (`runtimeAction: "<package>/<action>"`) or an **explicit external URL** (`webhook.url`) — these are mutually exclusive
- **Category** (optional): `validation` (block if invalid), `append` (add data), or `modification` (alter data) — used for conflict detection
- **Batch and hook identifiers**: `batch_name` groups related hooks; `hook_name` uniquely identifies this hook within the batch

## Step 2 — Derive config values

Apply the following validation rules before writing. Surface any issues to the user before proceeding.

| Field                      | Constraint                                                                            |
| -------------------------- | ------------------------------------------------------------------------------------- |
| `batch_name`               | `[a-zA-Z0-9_]+` only — no hyphens, dots, or spaces                                    |
| `hook_name`                | `[a-zA-Z0-9_]+` only — no hyphens, dots, or spaces                                    |
| `category`                 | Optional; must be `validation`, `append`, or `modification`                           |
| `runtimeAction`            | `<package>/<action>` format; mutually exclusive with `webhook.url`                    |
| `webhook.url`              | Must be a valid absolute URL (`https://...`); mutually exclusive with `runtimeAction` |
| `label`                    | Required, non-empty                                                                   |
| `description`              | Required, non-empty                                                                   |
| `webhook_type`             | Required; must be `before` or `after`                                                 |
| `method`                   | Required; must be `POST`, `PUT`, `DELETE`, or `GET`                                   |
| `timeout` / `soft_timeout` | Optional; positive integer (milliseconds)                                             |
| `priority` / `batch_order` | Optional; positive integer                                                            |

## Step 3 — Update `app.commerce.config.ts`

Add entries to the top-level `webhooks` array (or create it), preserving all other domains. If the config already has a `webhooks` key, append to it rather than replacing it.

Minimal examples:

```ts
// Runtime action handler (handler lives in this app)
webhooks: [
  {
    label: "Validate Product Save",
    description: "Validates product data before saving.",
    category: "validation", // optional
    runtimeAction: "my-package/validate-product", // <package>/<action>
    webhook: {
      webhook_method: "plugin.magento.catalog_product.save",
      webhook_type: "before",
      batch_name: "my_app", // [a-zA-Z0-9_]+ only
      hook_name: "validate_product", // [a-zA-Z0-9_]+ only
      method: "POST",
    },
  },
];

// URL handler (external endpoint)
webhooks: [
  {
    label: "Fraud Check",
    description: "Calls external fraud service before order placement.",
    webhook: {
      webhook_method: "plugin.magento.sales_order.place",
      webhook_type: "before",
      batch_name: "my_app",
      hook_name: "fraud_check",
      method: "POST",
      url: "https://fraud.example.com/check", // inside webhook object, not top level
    },
  },
];
```

Each entry also accepts an optional `env` array (`"paas"` / `"saas"`) to scope it to specific Commerce environments. When omitted, the webhook applies to all environments; when set, it is only subscribed at install time on the listed environments.

See [assets/webhooks-config.ts](assets/webhooks-config.ts) for the full annotated reference.

## Creating the handler action

For webhook entries that use `runtimeAction`, create the action file under `src/actions/` and register it in `app.config.yaml`.

### Register the action

Add a user-defined package to `src/commerce-extensibility-1/ext.config.yaml` alongside the existing `app-management` package. Use any name except `app-management` (reserved by the framework):

```yaml
# src/commerce-extensibility-1/ext.config.yaml
# (add below the auto-generated app-management package)
runtimeManifest:
  packages:
    app-management:
      # ... auto-generated — do not edit
    my-app: # your package name — any name except "app-management"
      actions:
        validate-product:
          function: actions/validate-product/index.js # relative to src/commerce-extensibility-1/
          web: "yes"
          runtime: nodejs:26
          annotations:
            require-adobe-auth: true
```

The `<package>/<action>` format in `runtimeAction` maps directly: `my-app/validate-product` → package `my-app`, action `validate-product`.

### Handler skeleton

```typescript
// src/commerce-extensibility-1/actions/validate-product/index.ts
import {
  ok,
  successOperation,
  exceptionOperation,
  addOperation,
  replaceOperation,
  removeOperation,
} from "@adobe/aio-commerce-lib-webhooks/responses";

export async function main(params: Record<string, unknown>) {
  // params contains the Commerce operation payload

  // Allow the operation to proceed
  return ok(successOperation());

  // Block the operation (validation failure)
  // return ok(exceptionOperation("Product SKU is required"));

  // Append data to the operation result
  // return ok(addOperation("result/custom_field", { value: "appended" }));

  // Modify a field in the result
  // return ok(replaceOperation("result/price", 99.99));

  // Remove a field from the result
  // return ok(removeOperation("result/unwanted_field"));
}
```

Operation types:

| Response                        | Effect                                          |
| ------------------------------- | ----------------------------------------------- |
| `successOperation()`            | Allow — operation proceeds unchanged            |
| `exceptionOperation(message)`   | Block — operation is rejected with this message |
| `addOperation(path, value)`     | Append data at `path` in the result             |
| `replaceOperation(path, value)` | Replace the value at `path` in the result       |
| `removeOperation(path)`         | Remove the field at `path` from the result      |

## Step 4 — Regenerate the `installation` action

If `webhooks` is the first install-requiring domain in the config (the others are `eventing.commerce`, `eventing.external`, `adminUi`, `installation.customInstallationSteps`), re-run:

```sh
npx @adobe/aio-commerce-lib-app init
```

This is what adds the `installation` action to `ext.config.yaml`'s `app-management` package — `aio app build`/`aio app deploy` only read the existing file, they never regenerate it. Skip this and Commerce has no endpoint to call, so the webhook builds and deploys fine but never actually gets installed. Safe to re-run even when the action already exists.

## Step 5 — Validate

Build the project to confirm the updated config is valid:

```sh
aio app build
```

A build failure with a validation error points directly to the offending config field. If this webhook needed Step 4, also check that `ext.config.yaml` now has `actions.installation` under `app-management`.

## Common Issues

- **`batch_name` or `hook_name` rejected**: Use underscores as separators (`my_app`, `validate_product_save`) — hyphens, dots, and spaces are not accepted.
- **Both `runtimeAction` and `webhook.url` set**: These are mutually exclusive — use `runtimeAction` when the handler lives in this app; `webhook.url` for an external endpoint.
- **`url` at wrong level**: For URL-based entries, `url` must be inside the nested `webhook` object, not at the top level alongside `label`.
- **`app-management` package name conflict**: The framework generates this package in `ext.config.yaml` on every build. Use any other name for your own actions.
- **Function path is relative to `src/commerce-extensibility-1/`**: Do not use `src/...` or project-root-relative paths. `actions/validate-product/index.js` resolves correctly; `src/commerce-extensibility-1/actions/validate-product/index.js` does not.
- **`defineConfig` not found**: Ensure `@adobe/aio-commerce-lib-app` is installed and `defineConfig` is imported from `@adobe/aio-commerce-lib-app/config`.
- **Webhook deployed but Commerce never calls it**: `init` wasn't re-run after adding the first install-requiring domain (Step 4) — no `installation` action, no install endpoint.

## Quality Bar

- `aio app build` completes without errors
- `installation` action present in `ext.config.yaml` when this webhook requires it

## Chaining

After `aio app build` passes:

- **Add merchant settings** — invoke `commerce-app-business-config` to expose configurable settings in Commerce Admin
- **Add event subscriptions** — invoke `commerce-app-eventing` to subscribe to Commerce or external events
- **Extend the Admin UI** — invoke `commerce-app-admin-ui` to add custom columns, mass actions, order view buttons, or menu entries in Commerce Admin
- **Add persistent storage** — invoke `commerce-app-storage` to back webhook handlers with queryable DB storage

## References

- [assets/webhooks-config.ts](assets/webhooks-config.ts) — Reference config showing both runtime action and URL-based webhook entry shapes

© adobe · Apache-2.0 · adobe/skills

Похожие скиллы

Все скиллы по теме «Бэкенд и API» →
deepgram-webhooks hookdeck Скилл deepgram-webhooks для Claude Code принимает и проверяет вебхуки Deepgram. Обрабатывает асинхронные результаты транскрипции и колбэки завершённых запросов. CX Codex +1 200установок github-webhooks hookdeck Скилл github-webhooks для приёма и проверки вебхуков GitHub: подсказывает, как разобрать подпись и обработать события push, pull_request, issues и release. CX Codex +1 512установок adobe-commerce membrane Интегрирует агента с Adobe Commerce через Membrane CLI для управления заказами, товарами, счетами и автоматизации интернет-магазина. CX Codex +1 167установок setup-zoom-webhooks официальный anthropics Скилл setup-zoom-webhooks для Claude Code, Codex, Cursor, GitHub Copilot и Gemini CLI с эталонной документацией по Zoom webhooks. Включается при реализации подписок на события, проверки подписи x-zm-signature и обработки доставки. CX Codex +1 2 200установок rc-webhooks RevenueCat Скилл rc-webhooks помогает подключить RevenueCat Webhooks к серверу: проверяет запросы, разбирает события и обновляет доступ через повторное чтение клиента. CX Codex +1 785установок pipefy-members-email-webhooks pipefy Скилл pipefy-members-email-webhooks для Claude Code управляет участниками пайпов Pipefy, письмами из карточного инбокса и вебхуками. Включается для приглашения пользователя, отправки письма или регистрации endpoint. CX Codex +1 782установок

Из того же набора108

Весь набор →
commerce-app-business-config Скилл commerce-app-business-config добавляет типизированные поля бизнес-конфигурации в приложение Adobe Commerce через businessConfig.schema. Мерчант настраивает их в Commerce Admin, приложение читает значения в рантайме. CX Codex +1 334установок link-rot-scanner Скилл link-rot-scanner находит и проверяет внутренние и внешние ссылки на сайтах AEM Edge Delivery Services. Помогает найти битые URL перед релизом или после миграции контента. CX Codex +1 334установок commerce-app-eventing Скилл commerce-app-eventing настраивает подписки на события Adobe Commerce и внешних систем, правила фильтрации и вызов экшенов App Builder. CX Codex +1 332установок commerce-app-storage Скилл commerce-app-storage для Claude Code, Cursor, Codex и других платформ — встраивает App Builder Database Storage в существующее Adobe Commerce-приложение и создаёт runtime action для чтения и записи документов. CX Codex +1 331установок rollout Скилл rollout разворачивает целиком мигрированный сайт в AEM Edge Delivery Services за один прогон. Инвентаризирует дерево страниц, дедуплицирует блоки, запускает deploy на каждую страницу и отслеживает, что развёрнуто, а что осталось. CX Codex +1 318установок adobe-edit-quick-cut Скилл adobe-edit-quick-cut собирает из видео один короткий highlight cut, выбирая подходящие фрагменты по смыслу. Подходит для тизера или визуального пересказа. CX Codex +1 308установок cwv-optimizer Скилл cwv-optimizer для Claude Code находит причины просадки Core Web Vitals на сайтах AEM Edge Delivery Services и рассчитывает точечные правки. CX Codex +1 306установок adobe-resize-photos-and-videos Скилл adobe-resize-photos-and-videos для Claude Code меняет разрешение фото и видео в пикселях или пропорциях через инструменты Adobe. Готовит ассеты к печати, YouTube и веб-страницам. CX Codex +1 303установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой