@godaddy/gd-commerce-server

中文文档
0.4.1发布于 2026/11/07MITTypeScriptES Module零依赖构建来源已验证近 30 天下载 1.1万

Opinionated Express server integration for GoDaddy Commerce

原始使用文档
文档目录6 节
  1. Host configuration
  2. Routers and helpers
  3. Product channel visibility
  4. Checkout return destinations
  5. Connection state
  6. Errors

@godaddy/gd-commerce-server

An opinionated Express router for GoDaddy Commerce catalog, cart, and hosted checkout APIs.

import express from 'express';
import { createCommerceRouter, createRuntimeCommerceConfiguration } from '@godaddy/gd-commerce-server';

const app = express();
app.use(express.json());
app.use('/api/commerce', createCommerceRouter({
  configuration: createRuntimeCommerceConfiguration(),
  checkoutReturnUrls: {
    returnUrls: ['https://shop.example.com/shop'],
    successUrls: ['https://shop.example.com/checkout/success'],
  },
}));

The default configuration reads these server-only environment variables on each request:

  • GODADDY_OAUTH_CLIENT_ID and GODADDY_OAUTH_CLIENT_SECRET
  • GODADDY_STORE_ID and GODADDY_CHANNEL_ID
  • GODADDY_CURRENCY_CODE
  • Optional GODADDY_CHECKOUT_CONFIGURATION: JSON with boolean enablePromotionCodes, enableTaxCollection, and enableShipping fields. All three default to false when this variable is absent or malformed so configuration discovery cannot prevent checkout creation. Optional shipping accepts the checkout API's originAddress or fulfillmentLocationId; omit it to use store configuration.

See Checkout configuration for the temporary build-time synchronization flow and its eventual-consistency limitation.

The API origin defaults to https://api.godaddy.com. The package does not load files, provision merchants, or assign application attribution. Hosts own these concerns and any readiness checks or retries before invoking Commerce.

Host configuration

For an alternate API origin, pass an explicit server-controlled option. It must be an HTTPS origin without credentials, a path, query, or fragment. The host is responsible for trusting the destination, which receives OAuth credentials. Request bodies never select the API origin or attribution.

const configuration = createRuntimeCommerceConfiguration({
  apiBaseUrl: process.env.COMMERCE_API_ORIGIN, // undefined uses production
  sourceApp: process.env.COMMERCE_SOURCE_APP,
  owner: process.env.COMMERCE_ORDER_OWNER,
});

apiBaseUrl controls catalog, order, and OAuth requests; checkout uses the corresponding checkout.commerce. subdomain. There is no built-in list of alternate environments. sourceApp and owner are optional host-owned attribution values: checkout uses both, while draft orders use owner. Supply values required by your Commerce integration; the package omits them by default.

Hosts with their own configuration service can implement CommerceConfiguration directly. read() returns clientId, clientSecret, storeId, channelId, currencyCode, apiBaseUrl, and optional attribution. readCheckout() returns the checkout flags and optional shipping settings. Return validated, ready-to-use settings from one consistent binding. Both functions run on the server; credentials must never reach browser code.

Routers and helpers

createCommerceCatalogRouter(configuration) installs catalog, public configuration, and cart routes. createGoDaddyPaymentsRouter(configuration, checkoutReturnUrls) installs checkout and read-only order-status routes without requiring catalog UI. createCommerceRouter({ configuration }) installs both by default or accepts explicit feature flags.

The HTTP checkout route accepts an existing draftOrderId or a direct skuId; Commerce resolves catalog prices. It rejects lineItemData. For non-catalog charges such as fixed-price deposits, calculate the amount on the server and call createCheckoutSession(params, configuration) directly. Never forward browser-supplied prices to this trusted helper. Server callers can also use getOrderStatus(orderId, configuration) without an HTTP loopback.

Product channel visibility

GET /products and GET /products/:id use the channel from the server configuration and request only ACTIVE products. Search, category filters, and explicit product IDs retain that channel filter. Product-detail requests for products unavailable on that channel return 404. Browser query parameters cannot select a different channel. Products configured for all channels remain available when the configured channel is active and registered to the store.

If a configured GODADDY_CHANNEL_ID is inactive or is not registered to the configured store, the Catalog API returns an empty product list and product-detail requests return 404. These are successful empty results from the Catalog API, not configuration errors. When an expected catalog is empty, verify that the channel is active and registered to GODADDY_STORE_ID, then check product status and channel assignments. A missing GODADDY_CHANNEL_ID is different: the default configuration reader rejects it with 503 not_configured.

The Catalog API resolves active store channels through the paginated /v1/commerce/channels endpoint when evaluating a channel filter. Those lookups are not currently cached by the Catalog API, so channel-filtered catalog requests can add upstream calls and latency.

These checks control product browsing. GET /skus/:id, cart creation (POST /cart), and item addition (POST /cart/:id/items) forward SKU IDs without this package checking whether their products are available on the configured channel. A 404 from product details does not establish that a SKU lookup or cart write will be rejected. Hosts that require channel-based restrictions on these operations must enforce them before forwarding the SKU IDs; browsing filters are not an authorization boundary.

Checkout return destinations

Configure checkoutReturnUrls on the router using trusted deployment settings. Both lists contain complete absolute HTTPS URLs; scheme, origin, port, path, and configured query parameters must match. Success URLs may add a single orderId query parameter. Additional query parameters, fragments, credentials, relative URLs, and unlisted destinations are rejected. Configure separate cancel and success destinations as shown above; do not derive the allowlist from request headers or request bodies.

Without this policy, HTTP checkout returns 503 before creating a session. Invalid request destinations return 400. This applies to both router presets that expose checkout. Trusted in-process callers of createCheckoutSession() own their return URLs and must construct or validate them server-side.

A return from hosted checkout is not proof of payment. The order-status route uses the authorized Orders REST API, which supports completed orders, and returns its payment status (for example PAID or PENDING; the exported ORDER_STATUS_UNKNOWN, 'unknown', if absent). Show it only as display enrichment and never present an unconfirmed payment as paid. The server OAuth client must be granted commerce.order:read. The helper verifies the returned order ID, store, and channel and returns a limited summary without customer contact data. The route returns 400 for a missing, blank, padded, ., or .. order ID (padded IDs are rejected, not trimmed) or one the Orders API rejects as malformed (422 VALIDATION_FAILED), and 404 when the Orders API reports the order missing (404 NOT_FOUND) or the order belongs to another store or channel. A 404 without that code, such as from a misconfigured API base URL, is an upstream failure. Token and other Commerce failures, including a response for a different order ID, return 502 and unreadable configuration returns 503 (see Errors). Hosts must authenticate callers and authorize access to each requested order before exposing this route.

Connection state

Hosts can implement the optional synchronous CommerceConfiguration.readConnectionState() method. Its return type is exported as CommerceConnectionState (unbound | connecting | ready). Returning undefined keeps the existing behavior. Throw when the state is unknown or cannot be read. The default environment configuration does not implement this method, so missing credentials never count as unbound.

GET /config returns { state: 'unbound' } or { state: 'connecting' } without reading store credentials. ready includes the usual opaque cartScope and currencyCode after read() succeeds. Without this method, the successful response shape is unchanged. All responses are uncached; a malformed state or unavailable configuration returns 503. Data and checkout routes, and the in-process checkout and order helpers, reject any state other than ready before upstream calls.

The host owns the connection lifecycle. Report ready only after the store connection is complete. Lost configuration is an error, never evidence of unbound. After a store connects, report unbound again only after it is deliberately disconnected. The storefront package owns the generic sample products and local sample cart; this server never creates sample Commerce records or simulates checkout.

A site before its store connects

A template that shows the storefront's sample products before a store connects needs the catalog routes and an explicit connection state. Here COMMERCE_CONNECTION_STATE is a host-owned setting, set to unbound when the site is created and to ready by the host's connection flow. Read it from whatever records the connection; never derive it from missing GODADDY_* variables.

import express from 'express';
import { createCommerceCatalogRouter, createRuntimeCommerceConfiguration } from '@godaddy/gd-commerce-server';

const runtime = createRuntimeCommerceConfiguration();
const configuration = {
  ...runtime,
  readConnectionState() {
    const state = process.env.COMMERCE_CONNECTION_STATE;
    if (state === 'unbound' || state === 'connecting' || state === 'ready') return state;
    throw new Error('COMMERCE_CONNECTION_STATE must be unbound, connecting, or ready.');
  },
};

const app = express();
app.use(express.json());
// Before static files and any single-page app or SSR fallback, which would answer /api/commerce with HTML.
app.use('/api/commerce', createCommerceCatalogRouter(configuration));
app.use(express.static('dist'));

createCommerceCatalogRouter exposes no checkout routes, so a site without checkout needs no checkoutReturnUrls. GET /api/commerce/config should return {"state":"unbound"} as JSON. If it returns the app's HTML page, the router is not mounted, or a fallback route runs before it.

Errors

Every route reports failures the same way. The body is { "error": "<customer-facing message>", "code": "<code>", "requestId": "<id>" } (order-status also includes success: false). The same id is passed to the logger. Bodies never contain upstream messages, configuration details, or credentials.

StatuscodeMeaning
400invalid_requestMissing or invalid input.
404not_foundMissing order or product, or a write to an existing cart (/cart/:id/...) that is missing, expired, or completed. Cart reads keep returning 200 { "cart": null }. Checkout with a stale or completed draftOrderId is not yet distinguished and returns 502.
409scope_mismatchX-Commerce-Scope no longer matches the configured store binding.
502upstream_unauthorizedCommerce rejected this server's OAuth client or requested scope (HTTP 401/403, or an OAuth 400 with invalid_client, invalid_grant, unauthorized_client, or invalid_scope). It concerns server credentials, not the caller, so it is never reported as 401/403.
502upstream_errorCommerce failed, returned an unexpected response, or could not be reached.
503not_configuredConfiguration is missing or unreadable, the host reports a connection state other than ready, or checkout return URLs are not configured.
500internal_errorAn unexpected error in this package.

Upstream errors without a specific mapping stay 502; business errors such as invalid discount codes are not yet distinguished. 5xx detail, including upstream status and GraphQL error codes, goes to the logger:

createCommerceRouter({
  configuration,
  logger: { error: (message, context) => log.error(context, message) },
  // Use the host's request id when its edge sets one; unsafe or missing ids fall back to a UUID.
  getRequestId: (req) => req.get('x-request-id'),
});

createCommerceCatalogRouter and createGoDaddyPaymentsRouter accept the same { logger, getRequestId } as their last argument. The logger defaults to console.error. In-process helpers throw the exported CommerceError subclasses (InvalidRequestError, NotFoundError, CommerceNotConfiguredError, UpstreamError), including when a host configuration throws while being read. Check error.code (for example 'not_found') rather than instanceof, which fails when a host has more than one copy of this package.

版本与发布记录

@godaddy/gd-commerce-server 共发布 6 个版本,首次发布于 2026/09/29;过去 12 个月发布了 6 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.4.1latest2026/11/0710 天前
0.4.02026/10/2225 天前
0.3.02026/10/2027 天前
0.2.02026/10/091 个月前
0.1.12026/10/021 个月前
0.1.02026/09/291 个月前

关于 @godaddy/gd-commerce-server 的常见问题

@godaddy/gd-commerce-server 是什么?

Opinionated Express server integration for GoDaddy Commerce

如何安装 @godaddy/gd-commerce-server?

在项目目录运行 npm install @godaddy/gd-commerce-server,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:express(^5.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@godaddy/gd-commerce-server 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@godaddy/gd-commerce-server 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@godaddy/gd-commerce-server 可以商用吗?

@godaddy/gd-commerce-server 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@godaddy/gd-commerce-server 的下载量有多少?

根据 npm 官方下载统计,@godaddy/gd-commerce-server 在 2026/10/17 – 2026/11/15 这 30 天内被下载 10,515 次,日均约 351 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@godaddy/gd-commerce-server 还在维护吗?

最新版本 0.4.1 发布于 2026/11/07(10 天前);至今共发布 6 个版本,其中过去 12 个月发布了 6 个;首次发布于 2026/09/29。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。