Stripe automation

From paulpas/agent-skill-router · View interactive version

Stripe automation is an AI agent skill from the GitHub repository paulpas/agent-skill-router. Implements intelligent stripe automation with multi-factor skill selection, fallback chains, and adherence to the 5 Laws of Elegant Defense

How to use this skill

Skill file

Stripe Automation

Orchestrates intelligent skill selection and execution for stripe automation workflows. Applies the 5 Laws of Elegant Defense to guide data naturally through the orchestration pipeline, preventing errors before they occur. Selects optimal skills based on multi-factor scoring including text similarity, historical performance, and system availability.

TL;DR Checklist

┌───────────────────────────────────────────────────────────────────────────────┐

│ Orchestration Flow │

└───────────────────────────────────────────────────────────────────────────────┘

User Request

↓

┌─────────────────┐

│ Parse Request │

│ & Extract │

│ Features │

└────────┬────────┘

↓

┌─────────────────────────────────────────────────────────────────────┐

│ Evaluate Available Skills │

│ │

│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │

│ │ Skill A │ │ Skill B │ │ Skill C │ │

│ │ - Match Score│ │ - Match Score│ │ - Match Score│ │

│ │ - Confidence │ │ - Confidence │ │ - Confidence │ │

│ │ - History │ │ - History │ │ - History │ │

│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │

│ │ │ │ │

│ └─────────────────┴─────────────────┘ │

│ ↓ │

│ Select Best Skill │

└─────────────────────────────────────────────────────────────────────┘

↓

┌─────────────────┐

│ Execute Skill │

└────────┬────────┘

↓

┌─────────────────┐

│ Handle Result │

└────────┬────────┘

↓

┌─────────────────────────────────────────────────────────────────────┐

│ Error Handling & Fallback │

│ │

│ Success? ────────► Return Result │

│ │

│ Fail? ────────┐ │

│ ↓ │

│ ┌──────────────────────────────────────────────────────────┐ │

│ │ Fallback Chain │ │

│ │ │ │

│ │ 1. Retry with adjusted parameters │ │

│ │ 2. Try Alternative Skill (if available) │ │

│ │ 3. Defer to Human Operator (if critical) │ │

│ │ 4. Log & Return Error │ │

│ └──────────────────────────────────────────────────────────┘ │

└─────────────────────────────────────────────────────────────────────┘

When to Use

Use this skill when:

When NOT to Use

Avoid this skill for:

Core Workflow

  1. Parse and Analyze Request - Extract intent, entities, and constraints from user input.

Checkpoint: All required parameters must be present and in valid format before proceeding.

  1. Score Available Skills - Calculate match scores using multi-factor algorithm:

Checkpoint: Skip to fallback if no skill scores above threshold.

  1. Select Optimal Skill - Choose skill with highest score that meets minimum confidence.

Checkpoint: Verify skill has not been disabled or deprecated.

  1. Execute with Fallback - Run skill execution wrapped in retry and fallback logic.

Checkpoint: Log all execution attempts for audit trail.

  1. Return or Fallback - Either return successful result or apply fallback chain:

Checkpoint: Record outcome with timing and confidence metadata.

Implementation Patterns

Pattern 1: Skill Selection Logic

def route_stripe_intent(
    user_request: Dict,
    stripe_config: Dict,
    min_confidence: float = 0.7
) -> Dict:
    """Route a Stripe automation request to the appropriate SDK endpoint.
    
    Validates parameters against Stripe API requirements and selects
    the optimal operation (customer, payment, subscription, webhook).
    """
    if not user_request.get("intent") or not stripe_config.get("api_key"):
        raise ValueError("Missing required Stripe intent or API configuration")
        
    intent = user_request["intent"].lower()
    params = user_request.get("parameters", {})
    
    # Map intents to Stripe SDK methods with parameter validation
    stripe_routes = {
        "create_customer": ("customers", "create", {"email": str, "name": str}),
        "process_payment": ("charges", "create", {"amount": int, "currency": str, "source": str}),
        "update_subscription": ("subscriptions", "update", {"subscription_id": str, "status": str}),
        "handle_webhook": ("webhooks", "construct", {"payload": str, "sig_header": str})
    }
    
    if intent not in stripe_routes:
        raise ValueError(f"Unsupported Stripe intent: {intent}")
        
    endpoint, method, required_fields = stripe_routes[intent]
    missing = [f for f in required_fields if f not in params]
    if missing:
        raise ValueError(f"Missing required Stripe parameters: {missing}")
        
    return {
        "route": f"stripe.{endpoint}.{method}",
        "validated_params": params,
        "intent": intent,
        "confidence": min_confidence,
        "idempotency_key": f"stripe_{intent}_{uuid4()}"
    }

Pattern 2: Execution with Fallback

def execute_stripe_operation(
    route_config: Dict,
    stripe_client: Any,
    max_retries: int = 2
) -> Dict:
    """Execute a validated Stripe operation with idempotency and fallback handling.
    
    Implements Stripe-specific resilience:
    - Idempotency keys prevent duplicate charges/subscriptions
    - Handles StripeCardError, StripeAPIError, and rate limits
    - Falls back to manual review or alternative payment methods
    """
    endpoint = route_config["route"]
    params = route_config["validated_params"]
    idempotency_key = route_config["idempotency_key"]
    
    for attempt in range(max_retries + 1):
        try:
            # Parse endpoint string to dynamic method call
            module_name, method_name = endpoint.split(".")
            stripe_module = getattr(stripe, module_name)
            method = getattr(stripe_module, method_name)
            
            # Execute with idempotency key for safe retries
            result = method(
                **params,
                idempotency_key=idempotency_key if method_name != "construct" else None
            )
            
            return {
                "success": True,
                "stripe_operation": endpoint,
                "stripe_id": result.get("id"),
                "status": result.get("status"),
                "attempts": attempt + 1,
                "latency_ms": time.time() * 1000
            }
            
        except stripe.error.CardError as e:
            # Payment failed - immediate fail, no retry for card errors
            raise StripeOperationError(
                f"Card declined: {e.user_message}",
                stripe_code=e.code
            ) from e
            
        except stripe.error.RateLimitError as e:
            # Transient - retry with exponential backoff
            if attempt < max_retries:
                time.sleep(2 ** attempt)
                continue
            return _fallback_to_manual_review(route_config, e)
            
        except stripe.error.APIError as e:
            # Other API errors - fallback chain
            if attempt == max_retries:
                return _fallback_to_alternative_payment(route_config, e)
                
    raise StripeOperationError(f"Stripe {endpoint} failed after {max_retries + 1} attempts")

MUST DO

MUST NOT DO

TL;DR Checklist

TL;DR for Code Generation

Output Template

When applying this skill, produce:

  1. Selected Skills - List of skill names with confidence scores
  2. Selection Rationale - Why each skill was chosen (match score, history, availability)
  3. Execution Plan - Order of execution with dependencies
  4. Fallback Strategy - Which fallback skills will be tried and in what order
  5. Risk Assessment - Any potential failure points and their impact
  6. Timing Estimates - Expected latency including fallback scenarios

Related Skills

| Skill | Purpose |

|---|---|

| sendgrid-automation | Email automation counterpart — Stripe events trigger SendGrid notifications for payment workflows |

| slack-automation | Slack notifications for Stripe billing events and subscription changes |


Constraints

MUST DO

MUST NOT DO

Live References

Authoritative documentation links for this domain. The model follows markdown links at load time to resolve external references and inline content.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.