b2c-custom-api-development
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCustom 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: IfCLI is not installed globally, useb2cinstead (e.g.,npx @salesforce/b2c-cli).npx @salesforce/b2c-cli code deploy
本技能将指导你为Salesforce B2C Commerce开发自定义API。自定义API允许你将自定义脚本代码作为SCAPI框架下的REST端点对外暴露。
提示: 如果未全局安装CLI,请改用b2c(例如: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:
- API Contract - An OAS 3.0 schema file (YAML)
- API Implementation - A script using the B2C Commerce Script API
- API Mapping - An file binding endpoints to implementations
api.json
自定义API的URL结构如下:
https://{shortCode}.api.commercecloud.salesforce.com/custom/{apiName}/{apiVersion}/organizations/{organizationId}/{endpointPath}创建自定义API需要三个核心组件:
- API契约 - 一份OAS 3.0 schema文件(YAML格式)
- API实现 - 使用B2C Commerce脚本API编写的脚本
- 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 # ImplementationImportant: 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 for Shopper APIs (requires siteId),
ShopperTokenfor Admin APIsAmOAuth2 - Custom scopes must start with , max 25 chars
c_ - Custom parameters must have prefix
c_
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使用(需要siteId参数),管理端API使用
ShopperTokenAmOAuth2 - 自定义作用域必须以开头,最长25个字符
c_ - 自定义参数必须带前缀
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; // RequiredKey requirements:
- Mark exported functions with
.public = true - Use for responses
RESTResponseMgr.createSuccess() - Use for error responses (RFC 9457 format)
RESTResponseMgr.createError()
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() - 错误响应使用生成(符合RFC 9457格式)
RESTResponseMgr.createError()
缓存、远程引入、外部服务调用的相关说明请参考实现参考文档。
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
开发工作流
- Create cartridge with structure
rest-apis/{api-name}/ - Define contract (schema.yaml) with endpoints and security
- Implement logic (script.js) with exported functions
- Create mapping (api.json) binding endpoints to implementation
- Deploy and activate to register endpoints
- Check registration status and test
- 按照结构创建cartridge
rest-apis/{api-name}/ - 在schema.yaml中定义契约,包含端点和安全配置
- 在script.js中编写逻辑,导出对应的函数
- 创建api.json文件,绑定端点和实现逻辑
- 部署并激活代码完成端点注册
- 检查注册状态并测试接口
Deployment
部署
bash
undefinedbash
undefinedDeploy 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
undefinedb2c scapi custom status --tenant-id zzpq_013 --status not_registered --columns apiName,endpointPath,errorReason
undefinedAuthentication Setup
身份验证配置
For Shopper APIs
Shopper端API
- Create a SLAS client with your custom scope(s):
bash
b2c slas client create --default-scopes --scopes "c_my_scope" - Obtain token via SLAS client credentials
- Include in all requests
siteId
- 创建包含自定义作用域的SLAS客户端:
bash
b2c slas client create --default-scopes --scopes "c_my_scope" - 通过SLAS客户端凭证获取token
- 所有请求携带参数
siteId
For Admin APIs
管理端API
- Configure custom scope in Account Manager
- Obtain token via Account Manager OAuth
- Omit from requests
siteId
See Testing Reference for curl examples and authentication setup.
- 在账户管理器中配置自定义作用域
- 通过账户管理器OAuth获取token
- 请求无需携带参数
siteId
curl示例和身份验证配置详情请参考测试参考文档。
Troubleshooting
问题排查
| Error | Cause | Solution |
|---|---|---|
| 400 Bad Request | Invalid/unknown params | Define all params in schema |
| 401 Unauthorized | Invalid token | Check token validity |
| 403 Forbidden | Missing scope | Verify scope in token |
| 404 Not Found | Not registered | Check |
| 500 Internal Error | Script error | Check |
| 503 Service Unavailable | Circuit breaker open | Fix errors, wait for reset |
| 错误 | 原因 | 解决方案 |
|---|---|---|
| 400 Bad Request | 参数无效/未知 | 在schema中定义所有参数 |
| 401 Unauthorized | token无效 | 检查token有效性 |
| 403 Forbidden | 缺少作用域 | 验证token中的作用域配置 |
| 404 Not Found | 端点未注册 | 执行 |
| 500 Internal Error | 脚本执行错误 | 执行 |
| 503 Service Unavailable | 熔断器开启 | 修复错误后等待重置 |
Registration Issues
注册相关问题
- Endpoint not appearing: Verify cartridge is in site's cartridge path, re-activate code version
- Check logs: Use or filter Log Center with
b2c logs getCustomApiRegistry
- 端点未展示: 确认cartridge在站点的cartridge路径中,重新激活代码版本
- 日志排查: 使用或在日志中心过滤
b2c logs get关键词CustomApiRegistry
Related Skills
相关技能
- - Deploying cartridges and activating code versions
b2c-cli:b2c-code - - Checking Custom API registration status
b2c-cli:b2c-scapi-custom - - Creating SLAS clients for testing Shopper APIs
b2c-cli:b2c-slas - - Service configuration for external calls
b2c:b2c-webservices
- - 部署cartridge与激活代码版本
b2c-cli:b2c-code - - 检查自定义API注册状态
b2c-cli:b2c-scapi-custom - - 创建用于测试Shopper API的SLAS客户端
b2c-cli:b2c-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示例