sf-integration
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesesf-integration: Salesforce Integration Patterns Expert
sf-integration: Salesforce集成模式专家
Expert integration architect specializing in secure callout patterns, event-driven architecture, and external service registration for Salesforce.
专注于Salesforce安全调用模式、事件驱动架构和外部服务注册的集成架构专家。
Core Responsibilities
核心职责
- Named Credential Generation: Create Named Credentials with OAuth 2.0, JWT Bearer, Certificate, or Custom authentication
- External Credential Generation: Create modern External Credentials (API 61+) with Named Principals
- External Service Registration: Generate ExternalServiceRegistration metadata from OpenAPI/Swagger specs
- REST Callout Patterns: Synchronous and asynchronous HTTP callout implementations (details)
- SOAP Callout Patterns: WSDL2Apex guidance and WebServiceCallout patterns (details)
- Platform Events: Event definitions, publishers, and subscriber triggers (details)
- Change Data Capture: CDC enablement and subscriber patterns (details)
- Validation & Scoring: Score integrations against 6 categories (0-120 points)
- Named Credential生成:创建采用OAuth 2.0、JWT Bearer、证书或自定义认证方式的Named Credential
- External Credential生成:创建支持Named Principal的现代External Credential(API 61+版本)
- External Service注册:从OpenAPI/Swagger规范生成ExternalServiceRegistration元数据
- REST调用模式:同步和异步HTTP调用实现(详情)
- SOAP调用模式:WSDL2Apex指导和WebServiceCallout模式(详情)
- Platform Event:事件定义、发布者和订阅者触发器(详情)
- Change Data Capture:CDC启用和订阅者模式(详情)
- 验证与评分:从6个维度对集成方案进行评分(0-120分)
Key Insights
关键洞察
| Insight | Details | Action |
|---|---|---|
| Named Credential Architecture | Legacy (pre-API 61) vs External Credentials (API 61+) | Check org API version first |
| Callouts in Triggers | Synchronous callouts NOT allowed in triggers | Always use async (Queueable, @future) |
| Governor Limits | 100 callouts per transaction, 120s timeout max | Batch callouts, use async patterns |
| External Services | Auto-generates Apex from OpenAPI specs | Requires Named Credential for auth |
| 关键洞察 | 详情 | 操作建议 |
|---|---|---|
| Named Credential架构 | 旧版(API 61之前)与External Credential(API 61+)对比 | 先检查组织的API版本 |
| 触发器中的调用 | 触发器中不允许同步调用 | 始终使用异步方式(Queueable、@future) |
| Governor限制 | 每个事务最多100次调用,超时上限120秒 | 批量调用,使用异步模式 |
| External Service | 从OpenAPI规范自动生成Apex代码 | 需要依赖Named Credential进行认证 |
⚠️ CRITICAL: Named Credential Architecture (API 61+)
⚠️ 重要提示:Named Credential架构(API 61+)
Legacy Named Credentials vs External Credentials
旧版Named Credential vs External Credential
| Feature | Legacy Named Credential | External Credential (API 61+) |
|---|---|---|
| API Version | Pre-API 61 | API 61+ (Winter '24+) |
| Principal Concept | Single principal per credential | Named Principal + Per-User Principal |
| OAuth Support | Basic OAuth 2.0 | Full OAuth 2.0 + PKCE, JWT |
| Permissions | Profile-based | Permission Set + Named Principal |
| Recommendation | Legacy orgs only | Use for all new development |
| 特性 | 旧版Named Credential | External Credential(API 61+) |
|---|---|---|
| API版本 | API 61之前 | API 61+(Winter '24及以后) |
| 主体概念 | 每个凭证对应单个主体 | 支持Named Principal + 按用户主体 |
| OAuth支持 | 基础OAuth 2.0 | 完整OAuth 2.0 + PKCE、JWT |
| 权限控制 | 基于配置文件 | 基于权限集 + Named Principal |
| 推荐场景 | 仅适用于旧版组织 | 所有新开发项目均推荐使用 |
Decision Matrix
决策矩阵
┌─────────────────────────────────────────────────────────────────────────────┐
│ WHEN TO USE WHICH CREDENTIAL TYPE │
├─────────────────────────────────────────────────────────────────────────────┤
│ Use LEGACY Named Credential if: │
│ • Org API version < 61 │
│ • Migrating existing integrations (maintain compatibility) │
│ • Simple API key / Basic Auth (quick setup) │
│ │
│ Use EXTERNAL Credential (API 61+) if: │
│ • New development (recommended) │
│ • OAuth 2.0 with PKCE required │
│ • Per-user authentication needed │
│ • Fine-grained permission control required │
│ • JWT Bearer flow for server-to-server │
└─────────────────────────────────────────────────────────────────────────────┘┌─────────────────────────────────────────────────────────────────────────────┐
│ 何时使用对应凭证类型 │
├─────────────────────────────────────────────────────────────────────────────┤
│ 使用旧版Named Credential的场景: │
│ • 组织API版本 < 61 │
│ • 迁移现有集成(保持兼容性) │
│ • 简单API密钥 / 基础认证(快速配置) │
│ │
│ 使用External Credential(API 61+)的场景: │
│ • 新开发项目(推荐) │
│ • 需要支持带PKCE的OAuth 2.0 │
│ • 需要按用户认证 │
│ • 需要细粒度权限控制 │
│ • 服务器到服务器的JWT Bearer流 │
└─────────────────────────────────────────────────────────────────────────────┘Workflow (5-Phase Pattern)
工作流程(5阶段模式)
Phase 1: Requirements Gathering
阶段1:需求收集
Use to gather:
AskUserQuestion- Integration Type: Outbound REST/SOAP, Inbound REST, Event-driven (Platform Events, CDC)
- Authentication Method: OAuth 2.0 (Client Credentials, JWT Bearer, Authorization Code), Certificate-based, API Key/Basic Auth
- External System Details: Base endpoint URL, API version, rate limits, required headers
- Sync vs Async Requirements: Real-time response needed → Sync | Fire-and-forget or DML-triggered → Async (Queueable)
使用收集以下信息:
AskUserQuestion- 集成类型:出站REST/SOAP、入站REST、事件驱动(Platform Event、CDC)
- 认证方式:OAuth 2.0(客户端凭证、JWT Bearer、授权码)、基于证书、API密钥/基础认证
- 外部系统详情:基础端点URL、API版本、速率限制、必填请求头
- 同步/异步需求:需要实时响应 → 同步 | 触发即忘或DML触发 → 异步(Queueable)
Phase 2: Template Selection
阶段2:模板选择
| Integration Need | Template | Location |
|---|---|---|
| Named Credentials | | |
| External Credentials | | |
| External Services | | |
| REST Callouts | | |
| SOAP Callouts | | |
| Platform Events | | |
| CDC Subscribers | | |
| 集成需求 | 模板 | 路径 |
|---|---|---|
| Named Credential | | |
| External Credential | | |
| External Service | | |
| REST调用 | | |
| SOAP调用 | | |
| Platform Event | | |
| CDC订阅者 | | |
Phase 3: Generation & Validation
阶段3:生成与验证
File Locations:
force-app/main/default/
├── namedCredentials/ # Legacy Named Credentials
├── externalCredentials/ # External Credentials (API 61+)
├── externalServiceRegistrations/
├── classes/ # Callout services, handlers
├── objects/{{EventName}}__e/ # Platform Events
└── triggers/ # Event/CDC subscribersValidate using scoring system (see Scoring System below)
文件路径:
force-app/main/default/
├── namedCredentials/ # 旧版Named Credential
├── externalCredentials/ # External Credential(API 61+)
├── externalServiceRegistrations/
├── classes/ # 调用服务、处理器
├── objects/{{EventName}}__e/ # Platform Event
└── triggers/ # 事件/CDC订阅者使用评分体系进行验证(见下方评分体系)
Phase 4: Deployment
阶段4:部署
Deployment Order (CRITICAL):
1. Named Credentials / External Credentials FIRST
2. External Service Registrations (depends on Named Credentials)
3. Apex classes (callout services, handlers)
4. Platform Events / CDC configuration
5. Triggers (depends on events being deployed)Use sf-deploy skill:
Skill(skill="sf-deploy")CLI Commands: See CLI Commands Reference
部署顺序(至关重要):
1. 先部署Named Credential / External Credential
2. 部署External Service Registration(依赖Named Credential)
3. 部署Apex类(调用服务、处理器)
4. 部署Platform Event / CDC配置
5. 部署触发器(依赖已部署的事件)使用sf-deploy技能:
Skill(skill="sf-deploy")CLI命令:见CLI命令参考
Phase 5: Testing & Verification
阶段5:测试与验证
- Test Named Credential: Setup → Named Credentials → Test Connection
- Test External Service: Invoke generated Apex methods
- Test Callout: Anonymous Apex or test class with
Test.setMock() - Test Events: Publish and verify subscriber execution
- 测试Named Credential:设置 → Named Credential → 测试连接
- 测试External Service:调用生成的Apex方法
- 测试调用:匿名Apex或使用的测试类
Test.setMock() - 测试事件:发布事件并验证订阅者执行情况
Named Credentials
Named Credential
| Auth Type | Use Case | Template | Key Config |
|---|---|---|---|
| OAuth 2.0 Client Credentials | Server-to-server, no user context | | scope, tokenEndpoint |
| OAuth 2.0 JWT Bearer | CI/CD, backend services | | Certificate + Connected App |
| Certificate (Mutual TLS) | High-security integrations | | Client cert required |
| Custom (API Key/Basic) | Simple APIs | | username/password |
Templates in . ⚠️ NEVER hardcode credentials - always use Named Credentials!
templates/named-credentials/| 认证类型 | 使用场景 | 模板 | 关键配置 |
|---|---|---|---|
| OAuth 2.0客户端凭证 | 服务器到服务器,无用户上下文 | | scope、tokenEndpoint |
| OAuth 2.0 JWT Bearer | CI/CD、后端服务 | | 证书 + Connected App |
| 证书(双向TLS) | 高安全要求的集成 | | 需要客户端证书 |
| 自定义(API密钥/基础认证) | 简单API | | 用户名/密码 |
模板位于。⚠️ 绝对不要硬编码凭证 - 始终使用Named Credential!
templates/named-credentials/External Credentials (API 61+)
External Credential(API 61+)
Use Case: Modern OAuth 2.0 with per-user or named principal authentication
Template:
templates/external-credentials/oauth-external-credential.externalCredential-meta.xmlKey Features:
- Named Principal vs Per-User Principal support
- OAuth 2.0 with PKCE
- JWT Bearer flow
- Permission Set-based access control
Quick Start:
xml
<ExternalCredential xmlns="http://soap.sforce.com/2006/04/metadata">
<label>{{CredentialLabel}}</label>
<authenticationProtocol>Oauth</authenticationProtocol>
<principals>
<principalName>{{PrincipalName}}</principalName>
<principalType>NamedPrincipal</principalType>
</principals>
</ExternalCredential>使用场景:支持按用户或Named Principal认证的现代OAuth 2.0集成
模板:
templates/external-credentials/oauth-external-credential.externalCredential-meta.xml核心特性:
- 支持Named Principal与按用户主体
- 支持带PKCE的OAuth 2.0
- 支持JWT Bearer流
- 基于权限集的访问控制
快速开始:
xml
<ExternalCredential xmlns="http://soap.sforce.com/2006/04/metadata">
<label>{{CredentialLabel}}</label>
<authenticationProtocol>Oauth</authenticationProtocol>
<principals>
<principalName>{{PrincipalName}}</principalName>
<principalType>NamedPrincipal</principalType>
</principals>
</ExternalCredential>External Services (OpenAPI/Swagger)
External Service(OpenAPI/Swagger)
Process:
- Obtain OpenAPI 2.0 (Swagger) or 3.0 spec from external API
- Create Named Credential for authentication
- Register External Service in Salesforce (Setup → External Services OR via metadata)
- Salesforce auto-generates Apex classes:
ExternalService.{{ServiceName}}
Template:
templates/external-services/openapi-registration.externalServiceRegistration-meta.xmlCLI Alternative:
bash
sf api request rest /services/data/v62.0/externalServiceRegistrations \
--method POST \
--body '{"label":"{{Label}}","namedCredential":"{{NC}}","schemaUrl":"{{URL}}"}'Usage Example:
apex
ExternalService.Stripe stripe = new ExternalService.Stripe();
ExternalService.Stripe_createCustomer_Request req = new ExternalService.Stripe_createCustomer_Request();
req.email = 'customer@example.com';
ExternalService.Stripe_createCustomer_Response resp = stripe.createCustomer(req);流程:
- 从外部API获取OpenAPI 2.0(Swagger)或3.0规范
- 创建用于认证的Named Credential
- 在Salesforce中注册External Service(设置 → External Service 或通过元数据)
- Salesforce自动生成Apex类:
ExternalService.{{ServiceName}}
模板:
templates/external-services/openapi-registration.externalServiceRegistration-meta.xmlCLI替代方案:
bash
sf api request rest /services/data/v62.0/externalServiceRegistrations \
--method POST \
--body '{"label":"{{Label}}","namedCredential":"{{NC}}","schemaUrl":"{{URL}}"}'使用示例:
apex
ExternalService.Stripe stripe = new ExternalService.Stripe();
ExternalService.Stripe_createCustomer_Request req = new ExternalService.Stripe_createCustomer_Request();
req.email = 'customer@example.com';
ExternalService.Stripe_createCustomer_Response resp = stripe.createCustomer(req);Callout Patterns
调用模式
REST Callouts
REST调用
For detailed REST callout patterns, see resources/callout-patterns.md
详细REST调用模式请参考resources/callout-patterns.md
Quick Reference
快速参考
| Pattern | Use Case | Template |
|---|---|---|
| Synchronous | User-initiated, need immediate response | |
| Asynchronous (Queueable) | Triggered from DML (triggers), fire-and-forget | |
| Retry Handler | Handle transient failures with exponential backoff | |
Key Points:
- Use Named Credentials:
req.setEndpoint('callout:{{NamedCredentialName}}/{{path}}') - Set timeout: (120s max)
req.setTimeout(120000) - Handle status codes: 2xx success, 4xx client error (don't retry), 5xx server error (retry)
Detailed Examples:
- Synchronous REST Callout
- Asynchronous Queueable Callout
- Retry Handler with Exponential Backoff
| 模式 | 使用场景 | 模板 |
|---|---|---|
| 同步 | 用户发起,需要即时响应 | |
| 异步(Queueable) | 由DML(触发器)触发,触发即忘 | |
| 重试处理器 | 处理瞬时故障,支持指数退避 | |
关键点:
- 使用Named Credential:
req.setEndpoint('callout:{{NamedCredentialName}}/{{path}}') - 设置超时:(最大120秒)
req.setTimeout(120000) - 处理状态码:2xx成功,4xx客户端错误(不重试),5xx服务器错误(重试)
详细示例:
- 同步REST调用
- 异步Queueable REST调用
- 带指数退避的重试处理器
SOAP Callouts
SOAP调用
For detailed SOAP callout patterns, see resources/callout-patterns.md#soap-callout-patterns
详细SOAP调用模式请参考resources/callout-patterns.md#soap-callout-patterns
Quick Reference
快速参考
WSDL2Apex Process:
- Setup → Apex Classes → Generate from WSDL
- Upload WSDL file
- Salesforce generates stub classes
Usage:
apex
{{WsdlGeneratedClass}}.{{PortType}} stub = new {{WsdlGeneratedClass}}.{{PortType}}();
stub.endpoint_x = 'callout:{{NamedCredentialName}}';
stub.timeout_x = 120000;
return stub.{{OperationName}}(request);Detailed Examples:
- WSDL2Apex Process
- SOAP Service Implementation
WSDL2Apex流程:
- 设置 → Apex类 → 从WSDL生成
- 上传WSDL文件
- Salesforce生成存根类
使用示例:
apex
{{WsdlGeneratedClass}}.{{PortType}} stub = new {{WsdlGeneratedClass}}.{{PortType}}();
stub.endpoint_x = 'callout:{{NamedCredentialName}}';
stub.timeout_x = 120000;
return stub.{{OperationName}}(request);详细示例:
- WSDL2Apex流程
- SOAP服务实现
Event-Driven Patterns
事件驱动模式
Platform Events
Platform Event
For detailed Platform Event patterns, see resources/event-patterns.md#platform-events
详细Platform Event模式请参考resources/event-patterns.md#platform-events
Quick Reference
快速参考
Event Types:
- Standard Volume: ~2,000 events/hour, 3-day retention
- High Volume: Millions/day, 24-hour retention, at-least-once delivery
Templates:
- Event Definition:
templates/platform-events/platform-event-definition.object-meta.xml - Publisher:
templates/platform-events/event-publisher.cls - Subscriber:
templates/platform-events/event-subscriber-trigger.trigger
Publishing:
apex
List<Database.SaveResult> results = EventBus.publish(events);Subscribing:
apex
trigger {{EventName}}Subscriber on {{EventName}}__e (after insert) {
for ({{EventName}}__e event : Trigger.new) {
{{EventName}}Handler.processEvent(event);
}
}Detailed Examples:
- Platform Event Definition
- Event Publisher
- Event Subscriber Trigger
事件类型:
- 标准容量:约2000事件/小时,保留3天
- 高容量:数百万事件/天,保留24小时,至少一次交付
模板:
- 事件定义:
templates/platform-events/platform-event-definition.object-meta.xml - 发布者:
templates/platform-events/event-publisher.cls - 订阅者:
templates/platform-events/event-subscriber-trigger.trigger
发布事件:
apex
List<Database.SaveResult> results = EventBus.publish(events);订阅事件:
apex
trigger {{EventName}}Subscriber on {{EventName}}__e (after insert) {
for ({{EventName}}__e event : Trigger.new) {
{{EventName}}Handler.processEvent(event);
}
}详细示例:
- Platform Event定义
- 事件发布者
- 事件订阅者触发器
Change Data Capture (CDC)
Change Data Capture(CDC)
For detailed CDC patterns, see resources/event-patterns.md#change-data-capture-cdc
详细CDC模式请参考resources/event-patterns.md#change-data-capture-cdc
Quick Reference
快速参考
Enablement: Setup → Integrations → Change Data Capture
Channel Naming: (e.g., )
{{ObjectAPIName}}ChangeEventAccountChangeEventSubscriber Template:
apex
trigger {{ObjectName}}CDCSubscriber on {{ObjectName}}ChangeEvent (after insert) {
for ({{ObjectName}}ChangeEvent event : Trigger.new) {
EventBus.ChangeEventHeader header = event.ChangeEventHeader;
String changeType = header.getChangeType(); // CREATE, UPDATE, DELETE, UNDELETE
List<String> changedFields = header.getChangedFields();
String recordId = header.getRecordIds()[0];
switch on changeType {
when 'CREATE' { {{ObjectName}}CDCHandler.handleCreate(event); }
when 'UPDATE' { {{ObjectName}}CDCHandler.handleUpdate(event, changedFields); }
when 'DELETE' { {{ObjectName}}CDCHandler.handleDelete(recordId); }
when 'UNDELETE' { {{ObjectName}}CDCHandler.handleUndelete(event); }
}
}
}Detailed Examples:
- CDC Enablement
- CDC Subscriber Trigger
- CDC Handler Service
启用方式:设置 → 集成 → Change Data Capture
通道命名:(例如:)
{{ObjectAPIName}}ChangeEventAccountChangeEvent订阅者模板:
apex
trigger {{ObjectName}}CDCSubscriber on {{ObjectName}}ChangeEvent (after insert) {
for ({{ObjectName}}ChangeEvent event : Trigger.new) {
EventBus.ChangeEventHeader header = event.ChangeEventHeader;
String changeType = header.getChangeType(); // CREATE, UPDATE, DELETE, UNDELETE
List<String> changedFields = header.getChangedFields();
String recordId = header.getRecordIds()[0];
switch on changeType {
when 'CREATE' { {{ObjectName}}CDCHandler.handleCreate(event); }
when 'UPDATE' { {{ObjectName}}CDCHandler.handleUpdate(event, changedFields); }
when 'DELETE' { {{ObjectName}}CDCHandler.handleDelete(recordId); }
when 'UNDELETE' { {{ObjectName}}CDCHandler.handleUndelete(event); }
}
}
}详细示例:
- CDC启用
- CDC订阅者触发器
- CDC处理器服务
Scoring System (120 Points)
评分体系(120分)
Category Breakdown
维度细分
| Category | Points | Evaluation Criteria |
|---|---|---|
| Security | 30 | Named Credentials used (no hardcoded secrets), OAuth scopes minimized, certificate auth where applicable |
| Error Handling | 25 | Retry logic present, timeout handling (120s max), specific exception types, logging implemented |
| Bulkification | 20 | Batch callouts considered, CDC bulk handling, event batching for Platform Events |
| Architecture | 20 | Async patterns for DML-triggered callouts, proper service layer separation, single responsibility |
| Best Practices | 15 | Governor limit awareness, proper HTTP methods, idempotency for retries |
| Documentation | 10 | Clear intent documented, endpoint versioning noted, API contract documented |
| 维度 | 分值 | 评估标准 |
|---|---|---|
| 安全性 | 30 | 使用Named Credential(无硬编码密钥),OAuth范围最小化,适用场景使用证书认证 |
| 错误处理 | 25 | 包含重试逻辑,处理超时(最大120秒),捕获特定异常类型,实现日志记录 |
| 批量处理 | 20 | 考虑批量调用,支持CDC批量处理,Platform Event事件批量发送 |
| 架构设计 | 20 | DML触发的调用使用异步模式,合理分离服务层,遵循单一职责原则 |
| 最佳实践 | 15 | 考虑Governor限制,使用正确HTTP方法,重试实现幂等性 |
| 文档 | 10 | 记录清晰的设计意图,标注端点版本,文档化API契约 |
Scoring Thresholds
评分阈值
Score: XX/120 Rating
├─ ⭐⭐⭐⭐⭐ Excellent (108-120): Production-ready, follows all best practices
├─ ⭐⭐⭐⭐ Very Good (90-107): Minor improvements suggested
├─ ⭐⭐⭐ Good (72-89): Acceptable with noted improvements
├─ ⭐⭐ Needs Work (54-71): Address issues before deployment
└─ ⭐ Block (<54): CRITICAL issues, do not deploy评分: XX/120 评级
├─ ⭐⭐⭐⭐⭐ 优秀(108-120):可用于生产环境,遵循所有最佳实践
├─ ⭐⭐⭐⭐ 良好(90-107):建议进行小幅优化
├─ ⭐⭐⭐ 合格(72-89):可接受,但需按建议改进
├─ ⭐⭐ 需要改进(54-71):部署前需解决相关问题
└─ ⭐ 阻塞(<54):存在严重问题,禁止部署Scoring Output Format
评分输出格式
📊 INTEGRATION SCORE: XX/120 ⭐⭐⭐⭐ Rating
════════════════════════════════════════════════════
🔐 Security XX/30 ████████░░ XX%
├─ Named Credentials used: ✅
├─ No hardcoded secrets: ✅
└─ OAuth scopes minimal: ✅
⚠️ Error Handling XX/25 ████████░░ XX%
├─ Retry logic: ✅
├─ Timeout handling: ✅
└─ Logging: ✅
📦 Bulkification XX/20 ████████░░ XX%
├─ Batch callouts: ✅
└─ Event batching: ✅
🏗️ Architecture XX/20 ████████░░ XX%
├─ Async patterns: ✅
└─ Service separation: ✅
✅ Best Practices XX/15 ████████░░ XX%
├─ Governor limits: ✅
└─ Idempotency: ✅
📝 Documentation XX/10 ████████░░ XX%
├─ Clear intent: ✅
└─ API versioning: ✅
════════════════════════════════════════════════════📊 集成评分: XX/120 ⭐⭐⭐⭐ 评级
════════════════════════════════════════════════════
🔐 安全性 XX/30 ████████░░ XX%
├─ 使用Named Credential: ✅
├─ 无硬编码密钥: ✅
└─ OAuth范围最小化: ✅
⚠️ 错误处理 XX/25 ████████░░ XX%
├─ 重试逻辑: ✅
├─ 超时处理: ✅
└─ 日志记录: ✅
📦 批量处理 XX/20 ████████░░ XX%
├─ 批量调用: ✅
└─ 事件批量发送: ✅
🏗️ 架构设计 XX/20 ████████░░ XX%
├─ 异步模式: ✅
└─ 服务层分离: ✅
✅ 最佳实践 XX/15 ████████░░ XX%
├─ 考虑Governor限制: ✅
└─ 幂等性: ✅
📝 文档 XX/10 ████████░░ XX%
├─ 设计意图清晰: ✅
└─ API版本标注: ✅
════════════════════════════════════════════════════Cross-Skill Integration
跨技能集成
| To Skill | When to Use |
|---|---|
| sf-connected-apps | OAuth Connected App for Named Credential |
| sf-apex | Custom callout service beyond templates |
| sf-metadata | Query existing Named Credentials |
| sf-deploy | Deploy to org |
| sf-ai-agentscript | Agent action using External Service |
| sf-flow | HTTP Callout Flow for agent |
| 关联技能 | 使用场景 |
|---|---|
| sf-connected-apps | 为Named Credential配置OAuth Connected App |
| sf-apex | 编写超出模板范围的自定义调用服务 |
| sf-metadata | 查询现有Named Credential |
| sf-deploy | 部署到组织 |
| sf-ai-agentscript | 使用External Service的Agent动作 |
| sf-flow | 为Agent封装HTTP调用的Flow |
Agentforce Integration Flow
Agentforce集成流程
sf-integrationsf-flowsf-ai-agentscriptflow://sf-deploysf-integrationsf-flowsf-ai-agentscriptflow://sf-deployCLI Commands Reference
CLI命令参考
Named Credentials
Named Credential
bash
undefinedbash
undefinedList Named Credentials
列出Named Credential
sf org list metadata --metadata-type NamedCredential --target-org {{alias}}
sf org list metadata --metadata-type NamedCredential --target-org {{alias}}
Deploy Named Credential
部署Named Credential
sf project deploy start --metadata NamedCredential:{{Name}} --target-org {{alias}}
sf project deploy start --metadata NamedCredential:{{Name}} --target-org {{alias}}
Retrieve Named Credential
拉取Named Credential
sf project retrieve start --metadata NamedCredential:{{Name}} --target-org {{alias}}
undefinedsf project retrieve start --metadata NamedCredential:{{Name}} --target-org {{alias}}
undefinedExternal Services
External Service
bash
undefinedbash
undefinedList External Service Registrations
列出External Service Registration
sf org list metadata --metadata-type ExternalServiceRegistration --target-org {{alias}}
sf org list metadata --metadata-type ExternalServiceRegistration --target-org {{alias}}
Deploy External Service
部署External Service
sf project deploy start --metadata ExternalServiceRegistration:{{Name}} --target-org {{alias}}
undefinedsf project deploy start --metadata ExternalServiceRegistration:{{Name}} --target-org {{alias}}
undefinedPlatform Events
Platform Event
bash
undefinedbash
undefinedList Platform Events
列出Platform Event
sf org list metadata --metadata-type CustomObject --target-org {{alias}} | grep "__e"
sf org list metadata --metadata-type CustomObject --target-org {{alias}} | grep "__e"
Deploy Platform Event
部署Platform Event
sf project deploy start --metadata CustomObject:{{EventName}}__e --target-org {{alias}}
undefinedsf project deploy start --metadata CustomObject:{{EventName}}__e --target-org {{alias}}
undefinedAPI Requests (Beta)
API请求(Beta版)
Execute REST and GraphQL API calls directly via CLI, without :
sfcurlbash
undefined直接通过 CLI执行REST和GraphQL API调用,无需使用:
sfcurlbash
undefinedREST API request
REST API请求
sf api request rest /services/data/v62.0/sobjects/Account/describe --target-org {{alias}}
sf api request rest /services/data/v62.0/sobjects/Account/describe --target-org {{alias}}
REST with POST body
带POST请求体的REST调用
sf api request rest /services/data/v62.0/sobjects/Account --method POST
--body '{"Name":"Test Account"}' --target-org {{alias}}
--body '{"Name":"Test Account"}' --target-org {{alias}}
sf api request rest /services/data/v62.0/sobjects/Account --method POST
--body '{"Name":"Test Account"}' --target-org {{alias}}
--body '{"Name":"Test Account"}' --target-org {{alias}}
GraphQL query
GraphQL查询
sf api request graphql --body '{"query":"{ uiapi { query { Account { edges { node { Name { value } } } } } } }"}' --target-org {{alias}}
> **[Beta]** These commands simplify API exploration. For production integration code, use Named Credentials and Apex callouts.
---sf api request graphql --body '{"query":"{ uiapi { query { Account { edges { node { Name { value } } } } } } }"}' --target-org {{alias}}
> **[Beta版]** 这些命令简化了API探索流程。生产环境的集成代码请使用Named Credential和Apex调用。
---🔧 Helper Scripts
🔧 辅助脚本
sf-integration includes automation scripts to configure credentials without manual UI steps.
sf-integration包含自动化脚本,无需手动通过UI配置凭证。
Available Scripts
可用脚本
| Script | Purpose | Usage |
|---|---|---|
| Set API keys via ConnectApi (Enhanced NC) | |
| Store keys in Custom Settings (legacy) | |
| 脚本 | 用途 | 使用方式 |
|---|---|---|
| 通过ConnectApi设置API密钥(增强型NC) | |
| 将密钥存储到自定义设置(旧版) | |
Auto-Run Behavior
自动运行逻辑
When you create credential metadata files, Claude automatically suggests running the appropriate script:
| File Pattern | Suggested Action |
|---|---|
| Run |
| Run |
| Deploy endpoint security |
当你创建凭证元数据文件时,Claude会自动建议运行对应的脚本:
| 文件模式 | 建议操作 |
|---|---|
| 运行 |
| 运行 |
| 部署端点安全配置 |
Example Workflow
示例工作流程
bash
undefinedbash
undefined1. Claude generates credential metadata files
1. Claude生成凭证元数据文件
2. Hook detects and suggests next steps
2. 钩子检测并建议下一步操作
3. Deploy metadata first
3. 先部署元数据
sf project deploy start --metadata ExternalCredential:WeatherAPI
--metadata NamedCredential:WeatherAPI
--target-org MyOrg
--metadata NamedCredential:WeatherAPI
--target-org MyOrg
sf project deploy start --metadata ExternalCredential:WeatherAPI
--metadata NamedCredential:WeatherAPI
--target-org MyOrg
--metadata NamedCredential:WeatherAPI
--target-org MyOrg
4. Run automation script
4. 运行自动化脚本
./scripts/configure-named-credential.sh MyOrg
./scripts/configure-named-credential.sh MyOrg
Enter API key when prompted (secure, hidden input)
提示时输入API密钥(安全隐藏输入)
undefinedundefinedPrerequisites
前置条件
- Salesforce CLI v2+: command available
sf - Authenticated org:
sf org login web -a <alias> - Deployed metadata: External Credential and Named Credential deployed
📚 Documentation: See docs/named-credentials-automation.md for complete guide.
- Salesforce CLI v2+:确保命令可用
sf - 已认证组织:
sf org login web -a <alias> - 已部署元数据:已部署External Credential和Named Credential
📚 文档:完整指南请参考docs/named-credentials-automation.md。
Anti-Patterns
反模式
| Anti-Pattern | Problem | Correct Pattern |
|---|---|---|
| Hardcoded credentials | Security vulnerability, credential rotation nightmare | Use Named Credentials |
| Sync callout in trigger | | Use Queueable with |
| No timeout specified | Default 10s may be too short | Set |
| No retry logic | Transient failures cause data loss | Implement exponential backoff |
| Ignoring status codes | Silent failures | Check |
| 100+ callouts per transaction | Governor limit exceeded | Batch callouts, use async |
| No logging | Can't debug production issues | Log all callout requests/responses |
| Exposing API errors to users | Security risk, poor UX | Catch and wrap in user-friendly messages |
| 反模式 | 问题 | 正确模式 |
|---|---|---|
| 硬编码凭证 | 安全漏洞,凭证轮换困难 | 使用Named Credential |
| 触发器中同步调用 | | 使用带 |
| 未指定超时 | 默认10秒可能过短 | 设置 |
| 无重试逻辑 | 瞬时故障导致数据丢失 | 实现指数退避重试 |
| 忽略状态码 | 静默故障 | 检查 |
| 单事务调用超过100次 | 触发Governor限制 | 批量调用,使用异步模式 |
| 无日志记录 | 无法调试生产问题 | 记录所有调用请求/响应 |
| 向用户暴露API错误 | 安全风险,用户体验差 | 捕获错误并包装为友好提示信息 |
Additional Resources
额外资源
📚 Detailed Documentation:
- Callout Patterns - REST and SOAP callout implementations
- Event Patterns - Platform Events and Change Data Capture
- Messaging API v2 - NEW: MIAW custom client architecture (Agentforce external chat)
📁 Templates:
- - Authentication templates
templates/named-credentials/ - - External Credential templates (API 61+)
templates/external-credentials/ - - OpenAPI registration templates
templates/external-services/ - - REST/SOAP callout patterns
templates/callouts/ - - Event definitions and publishers
templates/platform-events/ - - Change Data Capture triggers
templates/cdc/
📚 详细文档:
- 调用模式 - REST和SOAP调用实现
- 事件模式 - Platform Event和Change Data Capture
- Messaging API v2 - 新增:MIAW自定义客户端架构(Agentforce外部聊天)
📁 模板:
- - 认证模板
templates/named-credentials/ - - External Credential模板(API 61+)
templates/external-credentials/ - - OpenAPI注册模板
templates/external-services/ - - REST/SOAP调用模式
templates/callouts/ - - 事件定义和发布者
templates/platform-events/ - - Change Data Capture触发器
templates/cdc/
Notes & Dependencies
注意事项与依赖
- API Version: 62.0+ (Winter '25) recommended for External Credentials
- Required Permissions: API Enabled, External Services access
- Optional Skills: sf-connected-apps (OAuth setup), sf-apex (custom callout code), sf-deploy (deployment)
- Scoring Mode: Strict (block deployment if score < 54)
- API版本:推荐使用62.0+(Winter '25)以支持External Credential
- 所需权限:API启用、External Service访问权限
- 可选技能:sf-connected-apps(OAuth配置)、sf-apex(自定义调用代码)、sf-deploy(部署)
- 评分模式:严格模式(评分<54分时阻止部署)
License
许可证
MIT License - See LICENSE file for details.
MIT许可证 - 详情请查看LICENSE文件。