b2c-custom-api-development

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Custom API Development Skill

自定义API开发技能

This skill guides you through developing Custom APIs for Salesforce B2C Commerce. Custom APIs let you expose custom script code as REST endpoints under the SCAPI framework.
Tip: If
b2c
CLI is not installed globally, use
npx @salesforce/b2c-cli
instead (e.g.,
npx @salesforce/b2c-cli code deploy
).
本技能将指导你为Salesforce B2C Commerce开发自定义API。自定义API允许你将自定义脚本代码作为SCAPI框架下的REST端点对外暴露。
提示: 如果未全局安装
b2c
CLI,请改用
npx @salesforce/b2c-cli
(例如:
npx @salesforce/b2c-cli code deploy
)。

Overview

概述

A Custom API URL has this structure:
https://{shortCode}.api.commercecloud.salesforce.com/custom/{apiName}/{apiVersion}/organizations/{organizationId}/{endpointPath}
Three components are required to create a Custom API:
  1. API Contract - An OAS 3.0 schema file (YAML)
  2. API Implementation - A script using the B2C Commerce Script API
  3. API Mapping - An
    api.json
    file binding endpoints to implementations
自定义API的URL结构如下:
https://{shortCode}.api.commercecloud.salesforce.com/custom/{apiName}/{apiVersion}/organizations/{organizationId}/{endpointPath}
创建自定义API需要三个核心组件:
  1. API契约 - 一份OAS 3.0 schema文件(YAML格式)
  2. API实现 - 使用B2C Commerce脚本API编写的脚本
  3. API映射 - 一份
    api.json
    文件,用于将端点绑定到对应的实现逻辑

Cartridge Structure

Cartridge结构

/my-cartridge
    /cartridge
        package.json
        /rest-apis
            /my-api-name              # API name (lowercase alphanumeric and hyphens only)
                api.json              # Mapping file
                schema.yaml           # OAS 3.0 contract
                script.js             # Implementation
Important: API directory names can only contain alphanumeric lowercase characters and hyphens.
/my-cartridge
    /cartridge
        package.json
        /rest-apis
            /my-api-name              # API名称,仅可使用小写字母数字和连字符
                api.json              # 映射文件
                schema.yaml           # OAS 3.0契约文件
                script.js             # 实现逻辑
重要提示: API目录名称仅可包含小写字母数字和连字符。

Component 1: API Contract (schema.yaml)

组件1:API契约(schema.yaml)

Minimal example:
yaml
openapi: 3.0.0
info:
  version: 1.0.0
  title: My Custom API
components:
  securitySchemes:
    ShopperToken:
      type: oauth2
      flows:
        clientCredentials:
          tokenUrl: https://{shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/{organizationId}/oauth2/token
          scopes:
            c_my_scope: My custom scope
  parameters:
    siteId:
      name: siteId
      in: query
      required: true
      schema:
        type: string
        minLength: 1
paths:
  /my-endpoint:
    get:
      operationId: getMyData
      parameters:
        - $ref: '#/components/parameters/siteId'
      responses:
        '200':
          description: Success
security:
  - ShopperToken: ['c_my_scope']
Key requirements:
  • Use
    ShopperToken
    for Shopper APIs (requires siteId),
    AmOAuth2
    for Admin APIs
  • Custom scopes must start with
    c_
    , max 25 chars
  • Custom parameters must have
    c_
    prefix
See Contract Reference for full schema examples and Shopper vs Admin API differences.
最小示例:
yaml
openapi: 3.0.0
info:
  version: 1.0.0
  title: My Custom API
components:
  securitySchemes:
    ShopperToken:
      type: oauth2
      flows:
        clientCredentials:
          tokenUrl: https://{shortCode}.api.commercecloud.salesforce.com/shopper/auth/v1/organizations/{organizationId}/oauth2/token
          scopes:
            c_my_scope: My custom scope
  parameters:
    siteId:
      name: siteId
      in: query
      required: true
      schema:
        type: string
        minLength: 1
paths:
  /my-endpoint:
    get:
      operationId: getMyData
      parameters:
        - $ref: '#/components/parameters/siteId'
      responses:
        '200':
          description: Success
security:
  - ShopperToken: ['c_my_scope']
核心要求:
  • shopper端API使用
    ShopperToken
    (需要siteId参数),管理端API使用
    AmOAuth2
  • 自定义作用域必须以
    c_
    开头,最长25个字符
  • 自定义参数必须带
    c_
    前缀
完整schema示例以及Shopper/Admin API的差异请参考契约参考文档

Component 2: Implementation (script.js)

组件2:实现逻辑(script.js)

javascript
var RESTResponseMgr = require('dw/system/RESTResponseMgr');

exports.getMyData = function() {
    var myParam = request.getHttpParameterMap().get('c_my_param').getStringValue();
    var result = { data: 'my data', param: myParam };
    RESTResponseMgr.createSuccess(result).render();
};
exports.getMyData.public = true;  // Required
Key requirements:
  • Mark exported functions with
    .public = true
  • Use
    RESTResponseMgr.createSuccess()
    for responses
  • Use
    RESTResponseMgr.createError()
    for error responses (RFC 9457 format)
See Implementation Reference for caching, remote includes, and external service calls.
javascript
var RESTResponseMgr = require('dw/system/RESTResponseMgr');

exports.getMyData = function() {
    var myParam = request.getHttpParameterMap().get('c_my_param').getStringValue();
    var result = { data: 'my data', param: myParam };
    RESTResponseMgr.createSuccess(result).render();
};
exports.getMyData.public = true;  // 必要配置
核心要求:
  • 导出的函数必须标记
    .public = true
  • 响应使用
    RESTResponseMgr.createSuccess()
    生成
  • 错误响应使用
    RESTResponseMgr.createError()
    生成(符合RFC 9457格式)
缓存、远程引入、外部服务调用的相关说明请参考实现参考文档

Component 3: Mapping (api.json)

组件3:映射配置(api.json)

json
{
  "endpoints": [
    {
      "endpoint": "getMyData",
      "schema": "schema.yaml",
      "implementation": "script"
    }
  ]
}
Important: Implementation name must NOT include file extension.
json
{
  "endpoints": [
    {
      "endpoint": "getMyData",
      "schema": "schema.yaml",
      "implementation": "script"
    }
  ]
}
重要提示: 实现名称不能包含文件扩展名。

Development Workflow

开发工作流

  1. Create cartridge with
    rest-apis/{api-name}/
    structure
  2. Define contract (schema.yaml) with endpoints and security
  3. Implement logic (script.js) with exported functions
  4. Create mapping (api.json) binding endpoints to implementation
  5. Deploy and activate to register endpoints
  6. Check registration status and test
  1. 按照
    rest-apis/{api-name}/
    结构创建cartridge
  2. 在schema.yaml中定义契约,包含端点和安全配置
  3. 在script.js中编写逻辑,导出对应的函数
  4. 创建api.json文件,绑定端点和实现逻辑
  5. 部署并激活代码完成端点注册
  6. 检查注册状态并测试接口

Deployment

部署

bash
undefined
bash
undefined

Deploy and activate to register endpoints

部署并激活代码完成端点注册

b2c code deploy ./my-cartridge --reload
b2c code deploy ./my-cartridge --reload

Check registration status

检查注册状态

b2c scapi custom status --tenant-id zzpq_013
b2c scapi custom status --tenant-id zzpq_013

Show failed registrations with error reasons

查看注册失败的条目及错误原因

b2c scapi custom status --tenant-id zzpq_013 --status not_registered --columns apiName,endpointPath,errorReason
undefined
b2c scapi custom status --tenant-id zzpq_013 --status not_registered --columns apiName,endpointPath,errorReason
undefined

Authentication Setup

身份验证配置

For Shopper APIs

Shopper端API

  1. Create a SLAS client with your custom scope(s):
    bash
    b2c slas client create --default-scopes --scopes "c_my_scope"
  2. Obtain token via SLAS client credentials
  3. Include
    siteId
    in all requests
  1. 创建包含自定义作用域的SLAS客户端:
    bash
    b2c slas client create --default-scopes --scopes "c_my_scope"
  2. 通过SLAS客户端凭证获取token
  3. 所有请求携带
    siteId
    参数

For Admin APIs

管理端API

  1. Configure custom scope in Account Manager
  2. Obtain token via Account Manager OAuth
  3. Omit
    siteId
    from requests
See Testing Reference for curl examples and authentication setup.
  1. 在账户管理器中配置自定义作用域
  2. 通过账户管理器OAuth获取token
  3. 请求无需携带
    siteId
    参数
curl示例和身份验证配置详情请参考测试参考文档

Troubleshooting

问题排查

ErrorCauseSolution
400 Bad RequestInvalid/unknown paramsDefine all params in schema
401 UnauthorizedInvalid tokenCheck token validity
403 ForbiddenMissing scopeVerify scope in token
404 Not FoundNot registeredCheck
b2c scapi custom status
500 Internal ErrorScript errorCheck
b2c logs get --level ERROR
503 Service UnavailableCircuit breaker openFix errors, wait for reset
错误原因解决方案
400 Bad Request参数无效/未知在schema中定义所有参数
401 Unauthorizedtoken无效检查token有效性
403 Forbidden缺少作用域验证token中的作用域配置
404 Not Found端点未注册执行
b2c scapi custom status
检查状态
500 Internal Error脚本执行错误执行
b2c logs get --level ERROR
查看日志
503 Service Unavailable熔断器开启修复错误后等待重置

Registration Issues

注册相关问题

  • Endpoint not appearing: Verify cartridge is in site's cartridge path, re-activate code version
  • Check logs: Use
    b2c logs get
    or filter Log Center with
    CustomApiRegistry
  • 端点未展示: 确认cartridge在站点的cartridge路径中,重新激活代码版本
  • 日志排查: 使用
    b2c logs get
    或在日志中心过滤
    CustomApiRegistry
    关键词

Related Skills

相关技能

  • b2c-cli:b2c-code
    - Deploying cartridges and activating code versions
  • b2c-cli:b2c-scapi-custom
    - Checking Custom API registration status
  • b2c-cli:b2c-slas
    - Creating SLAS clients for testing Shopper APIs
  • b2c:b2c-webservices
    - Service configuration for external calls
  • b2c-cli:b2c-code
    - 部署cartridge与激活代码版本
  • b2c-cli:b2c-scapi-custom
    - 检查自定义API注册状态
  • b2c-cli:b2c-slas
    - 创建用于测试Shopper API的SLAS客户端
  • b2c:b2c-webservices
    - 外部调用的服务配置

Reference Documentation

参考文档

  • Contract Reference - Full schema.yaml examples, Shopper vs Admin APIs
  • Implementation Reference - script.js patterns, caching, remote includes
  • Testing Reference - Authentication setup, curl examples
  • 契约参考文档 - 完整schema.yaml示例、Shopper与Admin API差异
  • 实现参考文档 - script.js开发模式、缓存、远程引入
  • 测试参考文档 - 身份验证配置、curl示例