sf-integration

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

sf-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

核心职责

  1. Named Credential Generation: Create Named Credentials with OAuth 2.0, JWT Bearer, Certificate, or Custom authentication
  2. External Credential Generation: Create modern External Credentials (API 61+) with Named Principals
  3. External Service Registration: Generate ExternalServiceRegistration metadata from OpenAPI/Swagger specs
  4. REST Callout Patterns: Synchronous and asynchronous HTTP callout implementations (details)
  5. SOAP Callout Patterns: WSDL2Apex guidance and WebServiceCallout patterns (details)
  6. Platform Events: Event definitions, publishers, and subscriber triggers (details)
  7. Change Data Capture: CDC enablement and subscriber patterns (details)
  8. Validation & Scoring: Score integrations against 6 categories (0-120 points)
  1. Named Credential生成:创建采用OAuth 2.0、JWT Bearer、证书或自定义认证方式的Named Credential
  2. External Credential生成:创建支持Named Principal的现代External Credential(API 61+版本)
  3. External Service注册:从OpenAPI/Swagger规范生成ExternalServiceRegistration元数据
  4. REST调用模式:同步和异步HTTP调用实现(详情
  5. SOAP调用模式:WSDL2Apex指导和WebServiceCallout模式(详情
  6. Platform Event:事件定义、发布者和订阅者触发器(详情
  7. Change Data Capture:CDC启用和订阅者模式(详情
  8. 验证与评分:从6个维度对集成方案进行评分(0-120分)

Key Insights

关键洞察

InsightDetailsAction
Named Credential ArchitectureLegacy (pre-API 61) vs External Credentials (API 61+)Check org API version first
Callouts in TriggersSynchronous callouts NOT allowed in triggersAlways use async (Queueable, @future)
Governor Limits100 callouts per transaction, 120s timeout maxBatch callouts, use async patterns
External ServicesAuto-generates Apex from OpenAPI specsRequires 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

FeatureLegacy Named CredentialExternal Credential (API 61+)
API VersionPre-API 61API 61+ (Winter '24+)
Principal ConceptSingle principal per credentialNamed Principal + Per-User Principal
OAuth SupportBasic OAuth 2.0Full OAuth 2.0 + PKCE, JWT
PermissionsProfile-basedPermission Set + Named Principal
RecommendationLegacy orgs onlyUse for all new development
特性旧版Named CredentialExternal 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
AskUserQuestion
to gather:
  1. Integration Type: Outbound REST/SOAP, Inbound REST, Event-driven (Platform Events, CDC)
  2. Authentication Method: OAuth 2.0 (Client Credentials, JWT Bearer, Authorization Code), Certificate-based, API Key/Basic Auth
  3. External System Details: Base endpoint URL, API version, rate limits, required headers
  4. Sync vs Async Requirements: Real-time response needed → Sync | Fire-and-forget or DML-triggered → Async (Queueable)
使用
AskUserQuestion
收集以下信息:
  1. 集成类型:出站REST/SOAP、入站REST、事件驱动(Platform Event、CDC)
  2. 认证方式:OAuth 2.0(客户端凭证、JWT Bearer、授权码)、基于证书、API密钥/基础认证
  3. 外部系统详情:基础端点URL、API版本、速率限制、必填请求头
  4. 同步/异步需求:需要实时响应 → 同步 | 触发即忘或DML触发 → 异步(Queueable)

Phase 2: Template Selection

阶段2:模板选择

Integration NeedTemplateLocation
Named Credentials
oauth-client-credentials.namedCredential-meta.xml
templates/named-credentials/
External Credentials
oauth-external-credential.externalCredential-meta.xml
templates/external-credentials/
External Services
openapi-registration.externalServiceRegistration-meta.xml
templates/external-services/
REST Callouts
rest-sync-callout.cls
,
rest-queueable-callout.cls
templates/callouts/
SOAP Callouts
soap-callout-service.cls
templates/soap/
Platform Events
platform-event-definition.object-meta.xml
templates/platform-events/
CDC Subscribers
cdc-subscriber-trigger.trigger
templates/cdc/
集成需求模板路径
Named Credential
oauth-client-credentials.namedCredential-meta.xml
templates/named-credentials/
External Credential
oauth-external-credential.externalCredential-meta.xml
templates/external-credentials/
External Service
openapi-registration.externalServiceRegistration-meta.xml
templates/external-services/
REST调用
rest-sync-callout.cls
,
rest-queueable-callout.cls
templates/callouts/
SOAP调用
soap-callout-service.cls
templates/soap/
Platform Event
platform-event-definition.object-meta.xml
templates/platform-events/
CDC订阅者
cdc-subscriber-trigger.trigger
templates/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 subscribers
Validate 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:测试与验证

  1. Test Named Credential: Setup → Named Credentials → Test Connection
  2. Test External Service: Invoke generated Apex methods
  3. Test Callout: Anonymous Apex or test class with
    Test.setMock()
  4. Test Events: Publish and verify subscriber execution

  1. 测试Named Credential:设置 → Named Credential → 测试连接
  2. 测试External Service:调用生成的Apex方法
  3. 测试调用:匿名Apex或使用
    Test.setMock()
    的测试类
  4. 测试事件:发布事件并验证订阅者执行情况

Named Credentials

Named Credential

Auth TypeUse CaseTemplateKey Config
OAuth 2.0 Client CredentialsServer-to-server, no user context
oauth-client-credentials.namedCredential-meta.xml
scope, tokenEndpoint
OAuth 2.0 JWT BearerCI/CD, backend services
oauth-jwt-bearer.namedCredential-meta.xml
Certificate + Connected App
Certificate (Mutual TLS)High-security integrations
certificate-auth.namedCredential-meta.xml
Client cert required
Custom (API Key/Basic)Simple APIs
custom-auth.namedCredential-meta.xml
username/password
Templates in
templates/named-credentials/
. ⚠️ NEVER hardcode credentials - always use Named Credentials!

认证类型使用场景模板关键配置
OAuth 2.0客户端凭证服务器到服务器,无用户上下文
oauth-client-credentials.namedCredential-meta.xml
scope、tokenEndpoint
OAuth 2.0 JWT BearerCI/CD、后端服务
oauth-jwt-bearer.namedCredential-meta.xml
证书 + Connected App
证书(双向TLS)高安全要求的集成
certificate-auth.namedCredential-meta.xml
需要客户端证书
自定义(API密钥/基础认证)简单API
custom-auth.namedCredential-meta.xml
用户名/密码
模板位于
templates/named-credentials/
。⚠️ 绝对不要硬编码凭证 - 始终使用Named Credential!

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.xml
Key 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:
  1. Obtain OpenAPI 2.0 (Swagger) or 3.0 spec from external API
  2. Create Named Credential for authentication
  3. Register External Service in Salesforce (Setup → External Services OR via metadata)
  4. Salesforce auto-generates Apex classes:
    ExternalService.{{ServiceName}}
Template:
templates/external-services/openapi-registration.externalServiceRegistration-meta.xml
CLI 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);

流程:
  1. 从外部API获取OpenAPI 2.0(Swagger)或3.0规范
  2. 创建用于认证的Named Credential
  3. 在Salesforce中注册External Service(设置 → External Service 或通过元数据)
  4. Salesforce自动生成Apex类:
    ExternalService.{{ServiceName}}
模板
templates/external-services/openapi-registration.externalServiceRegistration-meta.xml
CLI替代方案:
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

快速参考

PatternUse CaseTemplate
SynchronousUser-initiated, need immediate response
rest-sync-callout.cls
Asynchronous (Queueable)Triggered from DML (triggers), fire-and-forget
rest-queueable-callout.cls
Retry HandlerHandle transient failures with exponential backoff
callout-retry-handler.cls
Key Points:
  • Use Named Credentials:
    req.setEndpoint('callout:{{NamedCredentialName}}/{{path}}')
  • Set timeout:
    req.setTimeout(120000)
    (120s max)
  • 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
模式使用场景模板
同步用户发起,需要即时响应
rest-sync-callout.cls
异步(Queueable)由DML(触发器)触发,触发即忘
rest-queueable-callout.cls
重试处理器处理瞬时故障,支持指数退避
callout-retry-handler.cls
关键点:
  • 使用Named Credential:
    req.setEndpoint('callout:{{NamedCredentialName}}/{{path}}')
  • 设置超时:
    req.setTimeout(120000)
    (最大120秒)
  • 处理状态码: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:
  1. Setup → Apex Classes → Generate from WSDL
  2. Upload WSDL file
  3. 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流程:
  1. 设置 → Apex类 → 从WSDL生成
  2. 上传WSDL文件
  3. 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:
{{ObjectAPIName}}ChangeEvent
(e.g.,
AccountChangeEvent
)
Subscriber 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}}ChangeEvent
(例如:
AccountChangeEvent
订阅者模板:
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

维度细分

CategoryPointsEvaluation Criteria
Security30Named Credentials used (no hardcoded secrets), OAuth scopes minimized, certificate auth where applicable
Error Handling25Retry logic present, timeout handling (120s max), specific exception types, logging implemented
Bulkification20Batch callouts considered, CDC bulk handling, event batching for Platform Events
Architecture20Async patterns for DML-triggered callouts, proper service layer separation, single responsibility
Best Practices15Governor limit awareness, proper HTTP methods, idempotency for retries
Documentation10Clear intent documented, endpoint versioning noted, API contract documented
维度分值评估标准
安全性30使用Named Credential(无硬编码密钥),OAuth范围最小化,适用场景使用证书认证
错误处理25包含重试逻辑,处理超时(最大120秒),捕获特定异常类型,实现日志记录
批量处理20考虑批量调用,支持CDC批量处理,Platform Event事件批量发送
架构设计20DML触发的调用使用异步模式,合理分离服务层,遵循单一职责原则
最佳实践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 SkillWhen to Use
sf-connected-appsOAuth Connected App for Named Credential
sf-apexCustom callout service beyond templates
sf-metadataQuery existing Named Credentials
sf-deployDeploy to org
sf-ai-agentscriptAgent action using External Service
sf-flowHTTP 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-integration
→ Named Credential + External Service →
sf-flow
→ HTTP Callout wrapper →
sf-ai-agentscript
→ Agent with
flow://
target →
sf-deploy
→ Deploy all

sf-integration
→ Named Credential + External Service →
sf-flow
→ HTTP调用封装 →
sf-ai-agentscript
→ 带
flow://
目标的Agent →
sf-deploy
→ 部署所有资源

CLI Commands Reference

CLI命令参考

Named Credentials

Named Credential

bash
undefined
bash
undefined

List 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}}
undefined
sf project retrieve start --metadata NamedCredential:{{Name}} --target-org {{alias}}
undefined

External Services

External Service

bash
undefined
bash
undefined

List 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}}
undefined
sf project deploy start --metadata ExternalServiceRegistration:{{Name}} --target-org {{alias}}
undefined

Platform Events

Platform Event

bash
undefined
bash
undefined

List 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}}
undefined
sf project deploy start --metadata CustomObject:{{EventName}}__e --target-org {{alias}}
undefined

API Requests (Beta)

API请求(Beta版)

Execute REST and GraphQL API calls directly via
sf
CLI, without
curl
:
bash
undefined
直接通过
sf
CLI执行REST和GraphQL API调用,无需使用
curl
:
bash
undefined

REST 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}}
sf api request rest /services/data/v62.0/sobjects/Account --method POST
--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

可用脚本

ScriptPurposeUsage
configure-named-credential.sh
Set API keys via ConnectApi (Enhanced NC)
./scripts/configure-named-credential.sh <org-alias>
set-api-credential.sh
Store keys in Custom Settings (legacy)
./scripts/set-api-credential.sh <name> - <org-alias>
脚本用途使用方式
configure-named-credential.sh
通过ConnectApi设置API密钥(增强型NC)
./scripts/configure-named-credential.sh <org-alias>
set-api-credential.sh
将密钥存储到自定义设置(旧版)
./scripts/set-api-credential.sh <name> - <org-alias>

Auto-Run Behavior

自动运行逻辑

When you create credential metadata files, Claude automatically suggests running the appropriate script:
File PatternSuggested Action
*.namedCredential-meta.xml
Run
configure-named-credential.sh
*.externalCredential-meta.xml
Run
configure-named-credential.sh
*.cspTrustedSite-meta.xml
Deploy endpoint security
当你创建凭证元数据文件时,Claude会自动建议运行对应的脚本:
文件模式建议操作
*.namedCredential-meta.xml
运行
configure-named-credential.sh
*.externalCredential-meta.xml
运行
configure-named-credential.sh
*.cspTrustedSite-meta.xml
部署端点安全配置

Example Workflow

示例工作流程

bash
undefined
bash
undefined

1. 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
sf project deploy start --metadata ExternalCredential:WeatherAPI
--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密钥(安全隐藏输入)

undefined
undefined

Prerequisites

前置条件

  • Salesforce CLI v2+:
    sf
    command available
  • 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-PatternProblemCorrect Pattern
Hardcoded credentialsSecurity vulnerability, credential rotation nightmareUse Named Credentials
Sync callout in trigger
CalloutException: Uncommitted work pending
Use Queueable with
Database.AllowsCallouts
No timeout specifiedDefault 10s may be too shortSet
req.setTimeout(120000)
(max 120s)
No retry logicTransient failures cause data lossImplement exponential backoff
Ignoring status codesSilent failuresCheck
statusCode
and handle 4xx/5xx
100+ callouts per transactionGovernor limit exceededBatch callouts, use async
No loggingCan't debug production issuesLog all callout requests/responses
Exposing API errors to usersSecurity risk, poor UXCatch and wrap in user-friendly messages

反模式问题正确模式
硬编码凭证安全漏洞,凭证轮换困难使用Named Credential
触发器中同步调用
CalloutException: Uncommitted work pending
异常
使用带
Database.AllowsCallouts
的Queueable
未指定超时默认10秒可能过短设置
req.setTimeout(120000)
(最大120秒)
无重试逻辑瞬时故障导致数据丢失实现指数退避重试
忽略状态码静默故障检查
statusCode
并处理4xx/5xx
单事务调用超过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:
  • templates/named-credentials/
    - Authentication templates
  • templates/external-credentials/
    - External Credential templates (API 61+)
  • templates/external-services/
    - OpenAPI registration templates
  • templates/callouts/
    - REST/SOAP callout patterns
  • templates/platform-events/
    - Event definitions and publishers
  • templates/cdc/
    - Change Data Capture triggers

📚 详细文档:
  • 调用模式 - REST和SOAP调用实现
  • 事件模式 - Platform Event和Change Data Capture
  • Messaging API v2 - 新增:MIAW自定义客户端架构(Agentforce外部聊天)
📁 模板:
  • templates/named-credentials/
    - 认证模板
  • templates/external-credentials/
    - External Credential模板(API 61+)
  • templates/external-services/
    - OpenAPI注册模板
  • templates/callouts/
    - REST/SOAP调用模式
  • templates/platform-events/
    - 事件定义和发布者
  • templates/cdc/
    - Change Data Capture触发器

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文件。