api-billing-service-onboarding

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API Billing Service Onboarding

API账单服务接入流程

Automates the complete process of adding a new third-party API service to the AWS Lambda-based billing and quota monitoring system.
自动完成将新的第三方API服务添加到基于AWS Lambda的账单和配额监控系统的完整流程。

Purpose

用途

This skill provides a step-by-step workflow for integrating new API services into an existing AWS monitoring infrastructure that tracks account balances, quotas, and usage across multiple third-party services. The system monitors services every 30 minutes, pushes metrics to CloudWatch, triggers alerts via SNS to Feishu, and visualizes data on a centralized dashboard.
此Skill提供了将新API服务集成到现有AWS监控基础设施的分步工作流,该基础设施可跨多个第三方服务跟踪账户余额、配额和使用情况。系统每30分钟监控一次服务,将指标推送到CloudWatch,通过SNS触发飞书(Feishu)告警,并在集中式仪表盘上可视化数据。

When to Use

适用场景

Use this skill when the user requests to:
  • Add monitoring for a new API service's balance, quota, or credits
  • Set up alerts for low balance/quota on a third-party service
  • Integrate a new service into the billing dashboard
  • Monitor remaining usage or spending on an external API
Common trigger phrases:
  • "Add [Service] to monitoring"
  • "Monitor [Service] API balance"
  • "Set up quota alerts for [Service]"
  • "Track [Service] credits in dashboard"
当用户提出以下请求时使用此Skill:
  • 为新API服务的余额、配额或额度添加监控
  • 为第三方服务设置低余额/配额告警
  • 将新服务集成到账单仪表盘
  • 监控外部API的剩余使用量或支出
常见触发语句:
  • "将[服务]添加到监控"
  • "监控[服务] API余额"
  • "为[服务]设置配额告警"
  • "在仪表盘中跟踪[服务]额度"

Project Context

项目背景

The monitoring system is located in
/Users/cdd/Code/all-code-in-mba/source-code/lambda-function/
and consists of:
  • Runtime: Node.js 18.x (TypeScript)
  • Cloud Platform: AWS Lambda + CloudWatch + Secrets Manager + EventBridge + SNS
  • Commands: Managed via
    just
    (see
    justfile
    )
  • Architecture: EventBridge (30min) → Lambda → CloudWatch Metrics → Alarms → SNS → Feishu
Key Files:
  • adapters/*.ts
    - API service adapters
  • adapters/index.ts
    - Adapter registry
  • src/handler.ts
    - Lambda entry point
  • src/types.ts
    - BillingMetric interface
  • src/metrics.ts
    - CloudWatch metric publishing
  • CLAUDE.md
    - Project documentation
监控系统位于
/Users/cdd/Code/all-code-in-mba/source-code/lambda-function/
,包含以下组件:
  • 运行时:Node.js 18.x(TypeScript)
  • 云平台:AWS Lambda + CloudWatch + Secrets Manager + EventBridge + SNS
  • 命令管理:通过
    just
    (详见
    justfile
  • 架构:EventBridge(每30分钟)→ Lambda → CloudWatch指标 → 告警 → SNS → 飞书(Feishu)
关键文件
  • adapters/*.ts
    - API服务适配器
  • adapters/index.ts
    - 适配器注册表
  • src/handler.ts
    - Lambda入口文件
  • src/types.ts
    - BillingMetric接口
  • src/metrics.ts
    - CloudWatch指标发布逻辑
  • CLAUDE.md
    - 项目文档

Workflow

工作流

Step 1: Gather Service Information

步骤1:收集服务信息

Before starting implementation, collect the following information from the user:
  1. Service name (e.g., "resend", "sendgrid")
  2. API documentation URL (especially balance/quota endpoints)
  3. API Key/Token (will be stored in Secrets Manager)
  4. Alert threshold (absolute value or percentage)
  5. Service display name (for Dashboard labels)
Questions to ask:
  • "What is the API endpoint for checking balance/quota?"
  • "How does the API authenticate? (Bearer token, API key header, query param?)"
  • "What response format does the API return? (JSON structure)"
  • "What threshold should trigger an alert? (e.g., remaining < 100, or < 5%)"
  • "What unit does the service use? (USD, credits, emails, requests?)"
开始实施前,从用户处收集以下信息:
  1. 服务名称(例如:"resend"、"sendgrid")
  2. API文档URL(尤其是余额/配额相关的端点)
  3. API密钥/令牌(将存储在Secrets Manager中)
  4. 告警阈值(绝对值或百分比)
  5. 服务显示名称(用于仪表盘标签)
需询问的问题
  • "查询余额/配额的API端点是什么?"
  • "API如何进行身份验证?(Bearer令牌、API密钥头、查询参数?)"
  • "API返回什么格式的响应?(JSON结构)"
  • "触发告警的阈值是多少?(例如:剩余量<100,或<5%)"
  • "服务使用什么单位?(美元、额度、邮件数、请求数?)"

Step 2: Create API Adapter

步骤2:创建API适配器

Create a new TypeScript adapter file at
adapters/<service_name>.ts
.
Refer to:
references/adapter-templates.md
for three common adapter patterns:
  • Standard JSON response with balance fields
  • Response headers containing quota information
  • Prepaid credits with no total amount
The adapter must:
  1. Call the service's API to retrieve balance/quota
  2. Mask the API key (show first 6 and last 6 characters)
  3. Return a
    BillingMetric
    object with:
    • service
      : lowercase service identifier
    • apiKeyMask
      : masked API key
    • total
      : total quota/balance
    • remaining
      : remaining quota/balance
    • remainingRatio
      : remaining/total (0-1)
    • currency
      (optional): "USD", "CNY", etc.
    • unit
      (optional): "credits", "emails", "requests"
Use the Read tool to examine existing adapters for reference:
  • adapters/resend.ts
    - Response header quota pattern
  • adapters/serper.ts
    - Prepaid credits pattern
  • adapters/scrapedo.ts
    - Standard JSON response pattern
adapters/<service_name>.ts
路径下创建新的TypeScript适配器文件。
参考文档
references/adapter-templates.md
中的三种常见适配器模式:
  • 包含余额字段的标准JSON响应
  • 包含配额信息的响应头
  • 无总额度的预付费额度模式
适配器必须满足:
  1. 调用服务API以获取余额/配额
  2. 对API密钥进行掩码处理(显示前6位和后6位字符)
  3. 返回一个
    BillingMetric
    对象,包含:
    • service
      :小写的服务标识符
    • apiKeyMask
      :掩码后的API密钥
    • total
      :总配额/余额
    • remaining
      :剩余配额/余额
    • remainingRatio
      :剩余量/总量(0-1)
    • currency
      (可选):"USD"、"CNY"等
    • unit
      (可选):"credits"、"emails"、"requests"
使用Read工具查看现有适配器作为参考:
  • adapters/resend.ts
    - 响应头配额模式
  • adapters/serper.ts
    - 预付费额度模式
  • adapters/scrapedo.ts
    - 标准JSON响应模式

Step 3: Register Adapter

步骤3:注册适配器

Edit
adapters/index.ts
:
  1. Import the new adapter function
  2. Add entry to the
    adapters
    object
Example:
typescript
import { fetchServiceName } from "./service_name";

export const adapters = {
  // ... existing adapters
  service_name: fetchServiceName,
};
编辑
adapters/index.ts
  1. 导入新的适配器函数
  2. adapters
    对象中添加条目
示例:
typescript
import { fetchServiceName } from "./service_name";

export const adapters = {
  // ... 现有适配器
  service_name: fetchServiceName,
};

Step 4: Update Lambda Handler

步骤4:更新Lambda处理器

Edit
src/handler.ts
to add the service call logic.
Location: Insert before
console.log("✅ Billing check completed")
Pattern:
typescript
// <Service Display Name>
if (apiKeys.<service_name>) {
  try {
    console.log("🔍 Fetching <Service> quota...");
    const metric = await adapters.<service_name>(apiKeys.<service_name>);
    await pushMetrics(metric);
    results.push({
      service: "<service_name>",
      status: "success",
      remaining: metric.remaining,
      total: metric.total,
      ratio: metric.remainingRatio
    });
  } catch (error: any) {
    console.error("❌ <Service> error:", error.message);
    results.push({ service: "<service_name>", status: "error", error: error.message });
  }
}
编辑
src/handler.ts
以添加服务调用逻辑。
位置:插入到
console.log("✅ Billing check completed")
之前
代码模式
typescript
// <Service Display Name>
if (apiKeys.<service_name>) {
  try {
    console.log("🔍 Fetching <Service> quota...");
    const metric = await adapters.<service_name>(apiKeys.<service_name>);
    await pushMetrics(metric);
    results.push({
      service: "<service_name>",
      status: "success",
      remaining: metric.remaining,
      total: metric.total,
      ratio: metric.remainingRatio
    });
  } catch (error: any) {
    console.error("❌ <Service> error:", error.message);
    results.push({ service: "<service_name>", status: "error", error: error.message });
  }
}

Step 5: Add API Key to Secrets Manager

步骤5:向Secrets Manager添加API密钥

Use the helper script to safely add the API key:
bash
scripts/add-secret-key.sh <service_name> <api_key>
Manual alternative:
bash
undefined
使用辅助脚本安全添加API密钥:
bash
scripts/add-secret-key.sh <service_name> <api_key>
手动替代方案
bash
undefined

Get current secrets

获取当前密钥

aws secretsmanager get-secret-value
--secret-id api-billing-monitor/keys
--query SecretString --output text > /tmp/secrets.json
aws secretsmanager get-secret-value
--secret-id api-billing-monitor/keys
--query SecretString --output text > /tmp/secrets.json

Edit /tmp/secrets.json to add: "<service_name>": "<api_key>"

编辑/tmp/secrets.json添加:"<service_name>": "<api_key>"

Update secrets

更新密钥

aws secretsmanager update-secret
--secret-id api-billing-monitor/keys
--secret-string file:///tmp/secrets.json
undefined
aws secretsmanager update-secret
--secret-id api-billing-monitor/keys
--secret-string file:///tmp/secrets.json
undefined

Step 6: Build and Deploy

步骤6:构建与部署

bash
undefined
bash
undefined

Quick deployment (recommended)

快速部署(推荐)

just deploy-quick
just deploy-quick

Or full deployment with verbose output

或带详细输出的完整部署

just deploy

Verify deployment:
```bash
just deploy

验证部署:
```bash

Trigger Lambda manually

手动触发Lambda

just invoke
just invoke

Check logs for the new service

检查新服务的日志

just logs | grep <service_name>
undefined
just logs | grep <service_name>
undefined

Step 7: Create CloudWatch Alarm

步骤7:创建CloudWatch告警

Choose the appropriate alarm strategy:
Strategy A: Absolute Value Threshold (for fixed quotas):
bash
aws cloudwatch put-metric-alarm \
  --alarm-name "<Service>-Low-Balance" \
  --namespace "ThirdPartyAPIBilling" \
  --metric-name "Remaining" \
  --dimensions Name=Service,Value=<service_name> \
  --statistic Average \
  --period 1800 \
  --evaluation-periods 1 \
  --threshold <absolute_value> \
  --comparison-operator LessThanThreshold \
  --alarm-actions "arn:aws:sns:us-east-1:830101142436:CloudWatchAlarmsToFeishu" \
  --alarm-description "<Service> remaining balance below <threshold>"
Strategy B: Percentage Threshold (for variable quotas):
bash
aws cloudwatch put-metric-alarm \
  --alarm-name "<Service>-Low-Ratio" \
  --namespace "ThirdPartyAPIBilling" \
  --metric-name "RemainingRatio" \
  --dimensions Name=Service,Value=<service_name> \
  --statistic Average \
  --period 1800 \
  --evaluation-periods 1 \
  --threshold 0.05 \
  --comparison-operator LessThanThreshold \
  --alarm-actions "arn:aws:sns:us-east-1:830101142436:CloudWatchAlarmsToFeishu" \
  --alarm-description "<Service> remaining ratio below 5%"
Verify alarm creation:
bash
just alarms | grep <Service>
选择合适的告警策略:
策略A:绝对值阈值(适用于固定配额):
bash
aws cloudwatch put-metric-alarm \
  --alarm-name "<Service>-Low-Balance" \
  --namespace "ThirdPartyAPIBilling" \
  --metric-name "Remaining" \
  --dimensions Name=Service,Value=<service_name> \
  --statistic Average \
  --period 1800 \
  --evaluation-periods 1 \
  --threshold <absolute_value> \
  --comparison-operator LessThanThreshold \
  --alarm-actions "arn:aws:sns:us-east-1:830101142436:CloudWatchAlarmsToFeishu" \
  --alarm-description "<Service> remaining balance below <threshold>"
策略B:百分比阈值(适用于可变配额):
bash
aws cloudwatch put-metric-alarm \
  --alarm-name "<Service>-Low-Ratio" \
  --namespace "ThirdPartyAPIBilling" \
  --metric-name "RemainingRatio" \
  --dimensions Name=Service,Value=<service_name> \
  --statistic Average \
  --period 1800 \
  --evaluation-periods 1 \
  --threshold 0.05 \
  --comparison-operator LessThanThreshold \
  --alarm-actions "arn:aws:sns:us-east-1:830101142436:CloudWatchAlarmsToFeishu" \
  --alarm-description "<Service> remaining ratio below 5%"
验证告警创建:
bash
just alarms | grep <Service>

Step 8: Update CloudWatch Dashboard

步骤8:更新CloudWatch仪表盘

Use the helper script to automatically add the service to the dashboard:
bash
scripts/add-to-dashboard.sh <service_name> "<Service Display Name>" "<masked_api_key>"
Manual alternative:
  1. Get current dashboard configuration:
    bash
    aws cloudwatch get-dashboard \
      --dashboard-name "API-Billing-Monitor" \
      --query "DashboardBody" \
      --output text > /tmp/dashboard.json
  2. Edit
    /tmp/dashboard.json
    to add the service in 4 locations:
    • "所有服务剩余比例趋势" metrics array
    • "当前剩余比例" metrics array
    • Create a new widget (optional, for detailed service chart)
    • "当前剩余额度/Credits" metrics array
  3. Update dashboard:
    bash
    aws cloudwatch put-dashboard \
      --dashboard-name "API-Billing-Monitor" \
      --dashboard-body file:///tmp/dashboard.json
Refer to:
references/dashboard-widget-template.json
for widget JSON structure examples.
使用辅助脚本自动将服务添加到仪表盘:
bash
scripts/add-to-dashboard.sh <service_name> "<Service Display Name>" "<masked_api_key>"
手动替代方案
  1. 获取当前仪表盘配置:
    bash
    aws cloudwatch get-dashboard \
      --dashboard-name "API-Billing-Monitor" \
      --query "DashboardBody" \
      --output text > /tmp/dashboard.json
  2. 编辑
    /tmp/dashboard.json
    ,在4个位置添加服务:
    • "所有服务剩余比例趋势"指标数组
    • "当前剩余比例"指标数组
    • 创建新的小部件(可选,用于服务详情图表)
    • "当前剩余额度/Credits"指标数组
  3. 更新仪表盘:
    bash
    aws cloudwatch put-dashboard \
      --dashboard-name "API-Billing-Monitor" \
      --dashboard-body file:///tmp/dashboard.json
参考文档
references/dashboard-widget-template.json
中的小部件JSON结构示例。

Step 9: Update Project Documentation

步骤9:更新项目文档

Edit
CLAUDE.md
to add the new service to the "已接入服务" table:
markdown
| <service_name> | <unit> | <threshold> | <description> |
编辑
CLAUDE.md
,将新服务添加到“已接入服务”表格:
markdown
| <service_name> | <unit> | <threshold> | <description> |

Step 10: Verification

步骤10:验证

Run the complete verification checklist:
bash
undefined
运行完整的验证检查清单:
bash
undefined

1. Trigger monitoring

1. 触发监控

just invoke
just invoke

2. Check logs for successful execution

2. 检查日志确认执行成功

just logs | grep "<service_name>"
just logs | grep "<service_name>"

Expected: "✅ Metrics pushed for <service_name>"

预期输出:"✅ Metrics pushed for <service_name>"

3. Verify metrics in CloudWatch

3. 在CloudWatch中验证指标

aws cloudwatch list-metrics
--namespace ThirdPartyAPIBilling
--dimensions Name=Service,Value=<service_name>
aws cloudwatch list-metrics
--namespace ThirdPartyAPIBilling
--dimensions Name=Service,Value=<service_name>

4. Check alarm status

4. 检查告警状态

just alarms | grep "<Service>"
just alarms | grep "<Service>"

5. View current status

5. 查看当前状态

just status
just status

6. Visit dashboard

6. 访问仪表盘


**Success criteria**:
- ✅ Lambda logs show successful metric push
- ✅ CloudWatch metrics exist for the service
- ✅ Alarm is in OK or ALARM state (not INSUFFICIENT_DATA)
- ✅ Dashboard displays the service in all charts
- ✅ Service appears in `just status` output

**成功标准**:
- ✅ Lambda日志显示指标推送成功
- ✅ CloudWatch中存在该服务的指标
- ✅ 告警处于OK或ALARM状态(而非INSUFFICIENT_DATA)
- ✅ 仪表盘的所有图表中均显示该服务
- ✅ 服务出现在`just status`的输出中

Troubleshooting

故障排除

Lambda execution fails:
  • Check logs:
    just logs
  • Verify API key in Secrets Manager:
    just secrets-full
  • Test API endpoint manually with curl/Postman
Metrics not appearing in CloudWatch:
  • Confirm Lambda executed successfully:
    just invoke
  • Check for errors in adapter code
  • Verify metric push logic in logs
Dashboard shows no data:
  • Wait 30 minutes for first execution cycle
  • Confirm metrics exist:
    aws cloudwatch list-metrics --namespace ThirdPartyAPIBilling
  • Verify Dashboard JSON syntax
Alarm not triggering:
  • Check alarm configuration:
    aws cloudwatch describe-alarms --alarm-names "<Service>-Low-Balance"
  • Verify metric data points exist
  • Test alarm:
    just test-alarm <Service>-Low-Balance
Lambda执行失败
  • 检查日志:
    just logs
  • 验证Secrets Manager中的API密钥:
    just secrets-full
  • 使用curl/Postman手动测试API端点
指标未出现在CloudWatch中
  • 确认Lambda执行成功:
    just invoke
  • 检查适配器代码中的错误
  • 在日志中验证指标推送逻辑
仪表盘无数据显示
  • 等待30分钟以完成首次执行周期
  • 确认指标存在:
    aws cloudwatch list-metrics --namespace ThirdPartyAPIBilling
  • 验证仪表盘JSON语法
告警未触发
  • 检查告警配置:
    aws cloudwatch describe-alarms --alarm-names "<Service>-Low-Balance"
  • 确认存在指标数据点
  • 测试告警:
    just test-alarm <Service>-Low-Balance

Notes

注意事项

  • The system runs on a 30-minute schedule via EventBridge
  • All API keys are stored securely in AWS Secrets Manager
  • Alarms notify via SNS to Feishu webhook
  • The CloudWatch namespace is
    ThirdPartyAPIBilling
  • Common dimension:
    Service=<service_name>
    ,
    APIKey=<masked_key>
For detailed examples and edge cases, refer to
references/service-integration-examples.md
.
  • 系统通过EventBridge按30分钟的周期运行
  • 所有API密钥均安全存储在AWS Secrets Manager中
  • 告警通过SNS发送到飞书(Feishu)Webhook
  • CloudWatch命名空间为
    ThirdPartyAPIBilling
  • 通用维度:
    Service=<service_name>
    APIKey=<masked_key>
如需详细示例和边缘案例参考,请查看
references/service-integration-examples.md