[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79BYSC5JJ885SPSV98D5MHP":3,"skill-same:01M79BYSC5JJ885SPSV98D5MHP":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M79BYSC5JJ885SPSV98D5MHP","payment-gateways-stripe-adyen-integration",null,"Architect and implement secure, PCI-DSS compliant payment processing integrations with Stripe and Adyen, featuring idempotent webhook handling, tokenization, multi-currency processing, automatic retries, and ledger-based reconciliation.","hamzabellouch\u002Fagent-skills","hamzabellouch","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F237856042?v=4","01M79BRYW7XAMK3YDWQEMTWGWS","Hamza Bellouch","01M79BRYWXQV3JK2TGVTX8GN2A",8,"MIT","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FBusiness\u002FFintech_and_Accounting\u002FFinancial_and_Payment_Gateways\u002Fpayment-gateways-stripe-adyen-integration\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: payment-gateways-stripe-adyen-integration\ndescription: Architect and implement secure, PCI-DSS compliant payment processing integrations with Stripe and Adyen, featuring idempotent webhook handling, tokenization, multi-currency processing, automatic retries, and ledger-based reconciliation.\n---\n\n# Payment Gateways Integration Architecture (Stripe & Adyen)\n\nThis skill package provides enterprise-grade patterns, architectural principles, PCI-DSS v4.0 compliance guidelines, and production code implementations for orchestrating payment processing across **Stripe** and **Adyen**.\n\n---\n\n## 1. Core Architectural & Compliance Standards\n\n### PCI-DSS v4.0 Compliance & Tokenization\n- **Out-of-Scope Architecture (SAQ A \u002F SAQ A-EP)**: Never ingest, process, or store Raw Primary Account Numbers (PAN), Card Verification Values (CVV\u002FCVC), or PINs on your infrastructure. Use client-side SDKs (Stripe Elements \u002F Adyen Web Drop-in) to tokenization endpoints directly owned by payment service providers (PSPs).\n- **Network & Transport Layer Security**: All API endpoints and client SDK communications must enforce TLS 1.3 with strong cipher suites (e.g., `TLS_AES_256_GCM_SHA384`).\n- **Data Sanitization & Zero Logging**: Redact all sensitive fields from application logs, trace contexts, and error payloads. Never log header signatures, API tokens, raw webhook payloads with PII, or tokens susceptible to account takeover.\n\n### Webhook Idempotency & Replay Protection\n- **Idempotency Keying**: Webhook events must be processed exactly once using distributed locking (e.g., Redis `SET key value NX PX`) keyed by the unique Event ID (`event.id` for Stripe, `eventCode` + `pspReference` for Adyen).\n- **Time-Window & Signature Verification**: Reject webhooks missing cryptographic HMAC signatures or with timestamps older than 300 seconds to prevent replay attacks.\n- **Asynchronous Execution**: Webhook HTTP handlers must validate signatures, enqueue the event into an isolated message queue (e.g., Kafka \u002F RabbitMQ), and return an immediate HTTP `200 OK` within 500ms to avoid PSP retry loops.\n\n### Reconciliation & Ledger Architecture\n- **Double-Entry Bookkeeping**: Model payments as state transitions across double-entry ledger accounts (Asset: PSP Clearing, Revenue, Expense: Gateway Fees, Liability: Customer Balance).\n- **State Machine Integrity**: Enforce strict status transitions (`AUTHORIZED` -> `CAPTURED` -> `SETTLED` \u002F `REFUNDED` \u002F `DISPUTED`).\n\n---\n\n## 2. PSP Capabilities Comparison Matrix\n\n| Capability | Stripe Integration | Adyen Integration |\n| :--- | :--- | :--- |\n| **Client Tokenization** | Stripe Elements \u002F PaymentIntents API | Adyen Drop-in \u002F Components API |\n| **Webhook Verification** | HMAC-SHA256 (`Stripe-Signature` header) | HMAC-SHA256 Base64 encoded payload validation |\n| **Capture Model** | Immediate or Manual (`capture_method: 'manual'`) | Automatic, Manual, or Delayed Capture rules |\n| **Payout & Settlement** | Balance Transactions & Payouts API | Financial Reports (Settlement Detail Report) |\n| **Global Payment Methods** | iDEAL, SEPA, Klarna, Alipay via PaymentIntents | 250+ local payment methods via `\u002Fpayments` |\n\n---\n\n## 3. Production Code Implementations\n\n### Python Implementation: Production-Grade Webhook Handler with Redis Idempotency & HMAC Validation\n\n```python\nimport base64\nimport hashlib\nimport hmac\nimport json\nimport time\nimport logging\nfrom typing import Dict, Any, Optional\nimport redis\nimport stripe\n\nlogger = logging.getLogger(\"payment_orchestrator\")\nlogger.setLevel(logging.INFO)\n\nclass PaymentWebhookProcessor:\n    def __init__(self, stripe_webhook_secret: str, adyen_hmac_key: str, redis_client: redis.Redis):\n        self.stripe_webhook_secret = stripe_webhook_secret\n        self.adyen_hmac_key = adyen_hmac_key\n        self.redis = redis_client\n        self.lock_ttl_ms = 60000  # 60s processing lock\n\n    def process_stripe_webhook(self, raw_body: bytes, sig_header: str) -> Dict[str, Any]:\n        \"\"\"\n        Validates Stripe signature, enforces idempotency, and queues event.\n        \"\"\"\n        try:\n            event = stripe.Webhook.construct_event(\n                payload=raw_body,\n                sig_header=sig_header,\n                secret=self.stripe_webhook_secret,\n                tolerance=300\n            )\n        except stripe.error.SignatureVerificationError as e:\n            logger.error(\"Invalid Stripe webhook signature\", exc_info=True)\n            raise ValueError(\"Invalid signature\") from e\n\n        event_id = event[\"id\"]\n        event_type = event[\"type\"]\n\n        if not self._acquire_idempotency_lock(f\"stripe:{event_id}\"):\n            logger.info(f\"Duplicate Stripe event skipped: {event_id}\")\n            return {\"status\": \"already_processed\", \"event_id\": event_id}\n\n        try:\n            self._route_stripe_event(event_type, event[\"data\"][\"object\"])\n            return {\"status\": \"success\", \"event_id\": event_id}\n        except Exception as e:\n            # Release lock on processing error to allow retry\n            self.redis.delete(f\"stripe:{event_id}\")\n            raise e\n\n    def verify_adyen_hmac(self, notification_item: Dict[str, Any]) -> bool:\n        \"\"\"\n        Verifies Adyen HMAC signature according to Adyen HMAC validator specs.\n        \"\"\"\n        item = notification_item.get(\"NotificationRequestItem\", {})\n        hmac_signature = item.get(\"additionalData\", {}).get(\"hmacSignature\")\n        if not hmac_signature:\n            return False\n\n        keys = [\n            \"pspReference\", \"originalReference\", \"merchantAccountCode\", \"merchantReference\",\n            \"value\", \"currency\", \"eventCode\", \"success\"\n        ]\n        \n        # Format string to sign\n        signed_vals = []\n        for k in keys:\n            val = str(item.get(k, \"\") or \"\")\n            # Escape backslashes and colons\n            escaped_val = val.replace(\"\\\\\", \"\\\\\\\\\").replace(\":\", \"\\\\:\")\n            signed_vals.append(escaped_val)\n\n        payload_to_sign = \":\".join(signed_vals).encode(\"utf-8\")\n        hmac_key_bytes = bytes.fromhex(self.adyen_hmac_key)\n        \n        calculated_hmac = base64.b64encode(\n            hmac.new(hmac_key_bytes, payload_to_sign, hashlib.sha256).digest()\n        ).decode(\"utf-8\")\n\n        return hmac.compare_digest(calculated_hmac, hmac_signature)\n\n    def process_adyen_webhook(self, notification_payload: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"\n        Processes Adyen notification items with HMAC validation and idempotency.\n        \"\"\"\n        items = notification_payload.get(\"notificationItems\", [])\n        processed = []\n\n        for container in items:\n            item = container.get(\"NotificationRequestItem\", {})\n            if not self.verify_adyen_hmac(container):\n                logger.error(\"Adyen HMAC signature mismatch\")\n                continue\n\n            psp_ref = item.get(\"pspReference\")\n            event_code = item.get(\"eventCode\")\n            idempotency_key = f\"adyen:{psp_ref}:{event_code}\"\n\n            if not self._acquire_idempotency_lock(idempotency_key):\n                logger.info(f\"Duplicate Adyen notification skipped: {idempotency_key}\")\n                processed.append({\"pspReference\": psp_ref, \"status\": \"duplicate\"})\n                continue\n\n            # Process notification logic\n            self._route_adyen_event(event_code, item)\n            processed.append({\"pspReference\": psp_ref, \"status\": \"processed\"})\n\n        return {\"status\": \"ok\", \"processed\": processed}\n\n    def _acquire_idempotency_lock(self, lock_key: str) -> bool:\n        \"\"\"Atomic Redis distributed lock for idempotency enforcement.\"\"\"\n        return bool(self.redis.set(lock_key, \"1\", nx=True, px=self.lock_ttl_ms))\n\n    def _route_stripe_event(self, event_type: str, data_object: Dict[str, Any]):\n        if event_type == \"payment_intent.succeeded\":\n            payment_intent_id = data_object[\"id\"]\n            amount = data_object[\"amount\"]\n            currency = data_object[\"currency\"]\n            logger.info(f\"Stripe Payment Succeeded: {payment_intent_id} | {amount}{currency}\")\n            # Execute double-entry ledger settlement...\n        elif event_type == \"charge.dispute.created\":\n            dispute_id = data_object[\"id\"]\n            logger.warning(f\"Stripe Dispute Created: {dispute_id}\")\n\n    def _route_adyen_event(self, event_code: str, item: Dict[str, Any]):\n        if event_code == \"AUTHORISATION\" and item.get(\"success\") == \"true\":\n            psp_ref = item[\"pspReference\"]\n            val = item.get(\"value\", {}).get(\"value\")\n            currency = item.get(\"value\", {}).get(\"currency\")\n            logger.info(f\"Adyen Authorisation Succeeded: {psp_ref} | {val} {currency}\")\n```\n\n---\n\n### TypeScript Implementation: Modern Payment Intent & Checkout Orchestration\n\n```typescript\nimport stripe from 'stripe';\nimport crypto from 'crypto';\n\nexport interface PaymentRequest {\n  merchantReference: string;\n  amountCents: number;\n  currency: string;\n  paymentMethodToken: string;\n  customerId: string;\n}\n\nexport interface PaymentResult {\n  transactionId: string;\n  status: 'AUTHORIZED' | 'CAPTURED' | 'REQUIRES_ACTION' | 'FAILED';\n  clientSecret?: string;\n  rawResponse: Record\u003Cstring, unknown>;\n}\n\nexport class StripePaymentProvider {\n  private stripeClient: stripe;\n\n  constructor(apiKey: string) {\n    this.stripeClient = new stripe(apiKey, {\n      apiVersion: '2023-10-16',\n      typescript: true,\n    });\n  }\n\n  \u002F**\n   * Orchestrates PaymentIntent creation with 3D Secure 2.0 Strong Customer Authentication (SCA)\n   *\u002F\n  public async createPaymentIntent(req: PaymentRequest): Promise\u003CPaymentResult> {\n    const idempotencyKey = crypto\n      .createHash('sha256')\n      .update(`${req.merchantReference}-${req.amountCents}-${req.currency}`)\n      .digest('hex');\n\n    try {\n      const intent = await this.stripeClient.paymentIntents.create(\n        {\n          amount: req.amountCents,\n          currency: req.currency.toLowerCase(),\n          customer: req.customerId,\n          payment_method: req.paymentMethodToken,\n          confirm: true,\n          off_session: false,\n          capture_method: 'manual', \u002F\u002F Auth and capture separated for risk checks\n          confirmation_method: 'automatic',\n          metadata: {\n            merchant_reference: req.merchantReference,\n          },\n        },\n        {\n          idempotencyKey,\n        }\n      );\n\n      if (intent.status === 'requires_action' || intent.status === 'requires_source_action') {\n        return {\n          transactionId: intent.id,\n          status: 'REQUIRES_ACTION',\n          clientSecret: intent.client_secret ?? undefined,\n          rawResponse: intent as unknown as Record\u003Cstring, unknown>,\n        };\n      }\n\n      if (intent.status === 'requires_capture') {\n        return {\n          transactionId: intent.id,\n          status: 'AUTHORIZED',\n          rawResponse: intent as unknown as Record\u003Cstring, unknown>,\n        };\n      }\n\n      throw new Error(`Unexpected PaymentIntent status: ${intent.status}`);\n    } catch (err: any) {\n      throw new Error(`Stripe Payment Intent Execution Failed: ${err.message}`);\n    }\n  }\n\n  \u002F**\n   * Captures a previously authorized payment after manual anti-fraud review\n   *\u002F\n  public async captureAuthorizedPayment(paymentIntentId: string, amountToCaptureCents?: number): Promise\u003CPaymentResult> {\n    const captureOptions: stripe.PaymentIntentCaptureParams = {};\n    if (amountToCaptureCents) {\n      captureOptions.amount_to_capture = amountToCaptureCents;\n    }\n\n    const intent = await this.stripeClient.paymentIntents.capture(paymentIntentId, captureOptions);\n\n    return {\n      transactionId: intent.id,\n      status: 'CAPTURED',\n      rawResponse: intent as unknown as Record\u003Cstring, unknown>,\n    };\n  }\n}\n```\n\n---\n\n## 4. Anti-Patterns & Pitfalls\n\n### Critical Architectural Mistakes\n\n1. **Processing Webhooks Synchronously in HTTP Worker Threads**\n   - *Impact*: Gateways like Stripe\u002FAdyen time out after 5-10 seconds and re-send webhooks, causing cascading duplicate executions and worker thread starvation.\n   - *Remediation*: Accept payload, verify HMAC, publish event to broker (Kafka\u002FAWS SQS), return HTTP 200 immediately.\n\n2. **Using Floating-Point Numbers for Currency Operations**\n   - *Impact*: IEEE 754 floating-point rounding errors (`0.1 + 0.2 = 0.30000000000000004`) lead to balance mismatches in accounting ledgers.\n   - *Remediation*: Always store and compute amounts as 64-bit integers in minor currency units (cents, pence) or fixed-point decimal objects (`Decimal`).\n\n3. **Ignoring Client-Side 3D-Secure (3DS2) Challenge Flows**\n   - *Impact*: Soft-deletes and authorization rejections increase due to PSD2 SCA requirements in Europe and worldwide mandate compliance.\n   - *Remediation*: Correctly propagate `requires_action` states back to client SDKs to render 3DS authentication modals.\n\n4. **Storing API Keys or Webhook Secrets in Code Repositories**\n   - *Impact*: Secrets leak, leading to unauthorized refund triggers, customer data breach, or fraud.\n   - *Remediation*: Inject secrets using KMS (HashiCorp Vault, AWS Secrets Manager) and support seamless secret rotation.\n\n---\n\n## 5. Verification & Testing Playbook\n\n- **Stripe CLI Webhook Testing**:\n  ```bash\n  stripe listen --forward-to localhost:8080\u002Fapi\u002Fv1\u002Fwebhooks\u002Fstripe\n  stripe trigger payment_intent.succeeded\n  ```\n- **Adyen Mock Webhook Replay**: Test HMAC generation using official Adyen test payload fixtures and verify zero-drop idempotency under simulated concurrent execution.\n- **Chaos & Failure Testing**: Simulate network splits during capture API calls and verify double-entry ledger idempotency keys prevent double charging.\n","# Payment Gateways Integration Architecture (Stripe & Adyen)\n\nThis skill package provides enterprise-grade patterns, architectural principles, PCI-DSS v4.0 compliance guidelines, and production code implementations for orchestrating payment processing across **Stripe** and **Adyen**.\n\n---\n\n## 1. Core Architectural & Compliance Standards\n\n### PCI-DSS v4.0 Compliance & Tokenization\n- **Out-of-Scope Architecture (SAQ A \u002F SAQ A-EP)**: Never ingest, process, or store Raw Primary Account Numbers (PAN), Card Verification Values (CVV\u002FCVC), or PINs on your infrastructure. Use client-side SDKs (Stripe Elements \u002F Adyen Web Drop-in) to tokenization endpoints directly owned by payment service providers (PSPs).\n- **Network & Transport Layer Security**: All API endpoints and client SDK communications must enforce TLS 1.3 with strong cipher suites (e.g., `TLS_AES_256_GCM_SHA384`).\n- **Data Sanitization & Zero Logging**: Redact all sensitive fields from application logs, trace contexts, and error payloads. Never log header signatures, API tokens, raw webhook payloads with PII, or tokens susceptible to account takeover.\n\n### Webhook Idempotency & Replay Protection\n- **Idempotency Keying**: Webhook events must be processed exactly once using distributed locking (e.g., Redis `SET key value NX PX`) keyed by the unique Event ID (`event.id` for Stripe, `eventCode` + `pspReference` for Adyen).\n- **Time-Window & Signature Verification**: Reject webhooks missing cryptographic HMAC signatures or with timestamps older than 300 seconds to prevent replay attacks.\n- **Asynchronous Execution**: Webhook HTTP handlers must validate signatures, enqueue the event into an isolated message queue (e.g., Kafka \u002F RabbitMQ), and return an immediate HTTP `200 OK` within 500ms to avoid PSP retry loops.\n\n### Reconciliation & Ledger Architecture\n- **Double-Entry Bookkeeping**: Model payments as state transitions across double-entry ledger accounts (Asset: PSP Clearing, Revenue, Expense: Gateway Fees, Liability: Customer Balance).\n- **State Machine Integrity**: Enforce strict status transitions (`AUTHORIZED` -> `CAPTURED` -> `SETTLED` \u002F `REFUNDED` \u002F `DISPUTED`).\n\n---\n\n## 2. PSP Capabilities Comparison Matrix\n\n| Capability | Stripe Integration | Adyen Integration |\n| :--- | :--- | :--- |\n| **Client Tokenization** | Stripe Elements \u002F PaymentIntents API | Adyen Drop-in \u002F Components API |\n| **Webhook Verification** | HMAC-SHA256 (`Stripe-Signature` header) | HMAC-SHA256 Base64 encoded payload validation |\n| **Capture Model** | Immediate or Manual (`capture_method: 'manual'`) | Automatic, Manual, or Delayed Capture rules |\n| **Payout & Settlement** | Balance Transactions & Payouts API | Financial Reports (Settlement Detail Report) |\n| **Global Payment Methods** | iDEAL, SEPA, Klarna, Alipay via PaymentIntents | 250+ local payment methods via `\u002Fpayments` |\n\n---\n\n## 3. Production Code Implementations\n\n### Python Implementation: Production-Grade Webhook Handler with Redis Idempotency & HMAC Validation\n\n```python\nimport base64\nimport hashlib\nimport hmac\nimport json\nimport time\nimport logging\nfrom typing import Dict, Any, Optional\nimport redis\nimport stripe\n\nlogger = logging.getLogger(\"payment_orchestrator\")\nlogger.setLevel(logging.INFO)\n\nclass PaymentWebhookProcessor:\n    def __init__(self, stripe_webhook_secret: str, adyen_hmac_key: str, redis_client: redis.Redis):\n        self.stripe_webhook_secret = stripe_webhook_secret\n        self.adyen_hmac_key = adyen_hmac_key\n        self.redis = redis_client\n        self.lock_ttl_ms = 60000  # 60s processing lock\n\n    def process_stripe_webhook(self, raw_body: bytes, sig_header: str) -> Dict[str, Any]:\n        \"\"\"\n        Validates Stripe signature, enforces idempotency, and queues event.\n        \"\"\"\n        try:\n            event = stripe.Webhook.construct_event(\n                payload=raw_body,\n                sig_header=sig_header,\n                secret=self.stripe_webhook_secret,\n                tolerance=300\n            )\n        except stripe.error.SignatureVerificationError as e:\n            logger.error(\"Invalid Stripe webhook signature\", exc_info=True)\n            raise ValueError(\"Invalid signature\") from e\n\n        event_id = event[\"id\"]\n        event_type = event[\"type\"]\n\n        if not self._acquire_idempotency_lock(f\"stripe:{event_id}\"):\n            logger.info(f\"Duplicate Stripe event skipped: {event_id}\")\n            return {\"status\": \"already_processed\", \"event_id\": event_id}\n\n        try:\n            self._route_stripe_event(event_type, event[\"data\"][\"object\"])\n            return {\"status\": \"success\", \"event_id\": event_id}\n        except Exception as e:\n            # Release lock on processing error to allow retry\n            self.redis.delete(f\"stripe:{event_id}\")\n            raise e\n\n    def verify_adyen_hmac(self, notification_item: Dict[str, Any]) -> bool:\n        \"\"\"\n        Verifies Adyen HMAC signature according to Adyen HMAC validator specs.\n        \"\"\"\n        item = notification_item.get(\"NotificationRequestItem\", {})\n        hmac_signature = item.get(\"additionalData\", {}).get(\"hmacSignature\")\n        if not hmac_signature:\n            return False\n\n        keys = [\n            \"pspReference\", \"originalReference\", \"merchantAccountCode\", \"merchantReference\",\n            \"value\", \"currency\", \"eventCode\", \"success\"\n        ]\n        \n        # Format string to sign\n        signed_vals = []\n        for k in keys:\n            val = str(item.get(k, \"\") or \"\")\n            # Escape backslashes and colons\n            escaped_val = val.replace(\"\\\\\", \"\\\\\\\\\").replace(\":\", \"\\\\:\")\n            signed_vals.append(escaped_val)\n\n        payload_to_sign = \":\".join(signed_vals).encode(\"utf-8\")\n        hmac_key_bytes = bytes.fromhex(self.adyen_hmac_key)\n        \n        calculated_hmac = base64.b64encode(\n            hmac.new(hmac_key_bytes, payload_to_sign, hashlib.sha256).digest()\n        ).decode(\"utf-8\")\n\n        return hmac.compare_digest(calculated_hmac, hmac_signature)\n\n    def process_adyen_webhook(self, notification_payload: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"\n        Processes Adyen notification items with HMAC validation and idempotency.\n        \"\"\"\n        items = notification_payload.get(\"notificationItems\", [])\n        processed = []\n\n        for container in items:\n            item = container.get(\"NotificationRequestItem\", {})\n            if not self.verify_adyen_hmac(container):\n                logger.error(\"Adyen HMAC signature mismatch\")\n                continue\n\n            psp_ref = item.get(\"pspReference\")\n            event_code = item.get(\"eventCode\")\n            idempotency_key = f\"adyen:{psp_ref}:{event_code}\"\n\n            if not self._acquire_idempotency_lock(idempotency_key):\n                logger.info(f\"Duplicate Adyen notification skipped: {idempotency_key}\")\n                processed.append({\"pspReference\": psp_ref, \"status\": \"duplicate\"})\n                continue\n\n            # Process notification logic\n            self._route_adyen_event(event_code, item)\n            processed.append({\"pspReference\": psp_ref, \"status\": \"processed\"})\n\n        return {\"status\": \"ok\", \"processed\": processed}\n\n    def _acquire_idempotency_lock(self, lock_key: str) -> bool:\n        \"\"\"Atomic Redis distributed lock for idempotency enforcement.\"\"\"\n        return bool(self.redis.set(lock_key, \"1\", nx=True, px=self.lock_ttl_ms))\n\n    def _route_stripe_event(self, event_type: str, data_object: Dict[str, Any]):\n        if event_type == \"payment_intent.succeeded\":\n            payment_intent_id = data_object[\"id\"]\n            amount = data_object[\"amount\"]\n            currency = data_object[\"currency\"]\n            logger.info(f\"Stripe Payment Succeeded: {payment_intent_id} | {amount}{currency}\")\n            # Execute double-entry ledger settlement...\n        elif event_type == \"charge.dispute.created\":\n            dispute_id = data_object[\"id\"]\n            logger.warning(f\"Stripe Dispute Created: {dispute_id}\")\n\n    def _route_adyen_event(self, event_code: str, item: Dict[str, Any]):\n        if event_code == \"AUTHORISATION\" and item.get(\"success\") == \"true\":\n            psp_ref = item[\"pspReference\"]\n            val = item.get(\"value\", {}).get(\"value\")\n            currency = item.get(\"value\", {}).get(\"currency\")\n            logger.info(f\"Adyen Authorisation Succeeded: {psp_ref} | {val} {currency}\")\n```\n\n---\n\n### TypeScript Implementation: Modern Payment Intent & Checkout Orchestration\n\n```typescript\nimport stripe from 'stripe';\nimport crypto from 'crypto';\n\nexport interface PaymentRequest {\n  merchantReference: string;\n  amountCents: number;\n  currency: string;\n  paymentMethodToken: string;\n  customerId: string;\n}\n\nexport interface PaymentResult {\n  transactionId: string;\n  status: 'AUTHORIZED' | 'CAPTURED' | 'REQUIRES_ACTION' | 'FAILED';\n  clientSecret?: string;\n  rawResponse: Record\u003Cstring, unknown>;\n}\n\nexport class StripePaymentProvider {\n  private stripeClient: stripe;\n\n  constructor(apiKey: string) {\n    this.stripeClient = new stripe(apiKey, {\n      apiVersion: '2023-10-16',\n      typescript: true,\n    });\n  }\n\n  \u002F**\n   * Orchestrates PaymentIntent creation with 3D Secure 2.0 Strong Customer Authentication (SCA)\n   *\u002F\n  public async createPaymentIntent(req: PaymentRequest): Promise\u003CPaymentResult> {\n    const idempotencyKey = crypto\n      .createHash('sha256')\n      .update(`${req.merchantReference}-${req.amountCents}-${req.currency}`)\n      .digest('hex');\n\n    try {\n      const intent = await this.stripeClient.paymentIntents.create(\n        {\n          amount: req.amountCents,\n          currency: req.currency.toLowerCase(),\n          customer: req.customerId,\n          payment_method: req.paymentMethodToken,\n          confirm: true,\n          off_session: false,\n          capture_method: 'manual', \u002F\u002F Auth and capture separated for risk checks\n          confirmation_method: 'automatic',\n          metadata: {\n            merchant_reference: req.merchantReference,\n          },\n        },\n        {\n          idempotencyKey,\n        }\n      );\n\n      if (intent.status === 'requires_action' || intent.status === 'requires_source_action') {\n        return {\n          transactionId: intent.id,\n          status: 'REQUIRES_ACTION',\n          clientSecret: intent.client_secret ?? undefined,\n          rawResponse: intent as unknown as Record\u003Cstring, unknown>,\n        };\n      }\n\n      if (intent.status === 'requires_capture') {\n        return {\n          transactionId: intent.id,\n          status: 'AUTHORIZED',\n          rawResponse: intent as unknown as Record\u003Cstring, unknown>,\n        };\n      }\n\n      throw new Error(`Unexpected PaymentIntent status: ${intent.status}`);\n    } catch (err: any) {\n      throw new Error(`Stripe Payment Intent Execution Failed: ${err.message}`);\n    }\n  }\n\n  \u002F**\n   * Captures a previously authorized payment after manual anti-fraud review\n   *\u002F\n  public async captureAuthorizedPayment(paymentIntentId: string, amountToCaptureCents?: number): Promise\u003CPaymentResult> {\n    const captureOptions: stripe.PaymentIntentCaptureParams = {};\n    if (amountToCaptureCents) {\n      captureOptions.amount_to_capture = amountToCaptureCents;\n    }\n\n    const intent = await this.stripeClient.paymentIntents.capture(paymentIntentId, captureOptions);\n\n    return {\n      transactionId: intent.id,\n      status: 'CAPTURED',\n      rawResponse: intent as unknown as Record\u003Cstring, unknown>,\n    };\n  }\n}\n```\n\n---\n\n## 4. Anti-Patterns & Pitfalls\n\n### Critical Architectural Mistakes\n\n1. **Processing Webhooks Synchronously in HTTP Worker Threads**\n   - *Impact*: Gateways like Stripe\u002FAdyen time out after 5-10 seconds and re-send webhooks, causing cascading duplicate executions and worker thread starvation.\n   - *Remediation*: Accept payload, verify HMAC, publish event to broker (Kafka\u002FAWS SQS), return HTTP 200 immediately.\n\n2. **Using Floating-Point Numbers for Currency Operations**\n   - *Impact*: IEEE 754 floating-point rounding errors (`0.1 + 0.2 = 0.30000000000000004`) lead to balance mismatches in accounting ledgers.\n   - *Remediation*: Always store and compute amounts as 64-bit integers in minor currency units (cents, pence) or fixed-point decimal objects (`Decimal`).\n\n3. **Ignoring Client-Side 3D-Secure (3DS2) Challenge Flows**\n   - *Impact*: Soft-deletes and authorization rejections increase due to PSD2 SCA requirements in Europe and worldwide mandate compliance.\n   - *Remediation*: Correctly propagate `requires_action` states back to client SDKs to render 3DS authentication modals.\n\n4. **Storing API Keys or Webhook Secrets in Code Repositories**\n   - *Impact*: Secrets leak, leading to unauthorized refund triggers, customer data breach, or fraud.\n   - *Remediation*: Inject secrets using KMS (HashiCorp Vault, AWS Secrets Manager) and support seamless secret rotation.\n\n---\n\n## 5. Verification & Testing Playbook\n\n- **Stripe CLI Webhook Testing**:\n  ```bash\n  stripe listen --forward-to localhost:8080\u002Fapi\u002Fv1\u002Fwebhooks\u002Fstripe\n  stripe trigger payment_intent.succeeded\n  ```\n- **Adyen Mock Webhook Replay**: Test HMAC generation using official Adyen test payload fixtures and verify zero-drop idempotency under simulated concurrent execution.\n- **Chaos & Failure Testing**: Simulate network splits during capture API calls and verify double-entry ledger idempotency keys prevent double charging.\n",{"name":5,"description":7},"main","e905af21e5f1e1c3ca605e9656c3a7930360a84e","Business\u002FFintech_and_Accounting\u002FFinancial_and_Payment_Gateways\u002Fpayment-gateways-stripe-adyen-integration",1,"https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills","https:\u002F\u002Fhamzabellouch.github.io\u002F","https:\u002F\u002Fgithub.com\u002Fhamzabellouch","hamzabellouch.github.io","CEO & Founder of @tknoglobal | Researcher in Technology & Applied Sciences.","2026-10-17 03:20:19",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add hamzabellouch\u002Fagent-skills --skill payment-gateways-stripe-adyen-integration",{"tool":40,"command":41},"bunx","bunx skills add hamzabellouch\u002Fagent-skills --skill payment-gateways-stripe-adyen-integration",{"tool":43,"command":44},"pnpm","pnpm dlx skills add hamzabellouch\u002Fagent-skills --skill payment-gateways-stripe-adyen-integration","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FBusiness\u002FFintech_and_Accounting\u002FFinancial_and_Payment_Gateways\u002Fpayment-gateways-stripe-adyen-integration\u002FSKILL.md",true,[],[49,56,63,70,77,84],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M79FHH2H815A9TAP6WNKH4Q8","security-audit","Comprehensive security guidance, source code audit, vulnerability assessment, and penetration test review for codebases, APIs, microservices, CLI tools, libraries, and LLM-backed applications. Triggers on requests to audit a codebase, conduct security reviews, find vulnerabilities or flaws, pen-test source code, or when the user asks in Arabic (فحص أمني، تدقيق الكود أمنياً، مراجعة الثغرات، فحص أمان المشروع). Supports Guidance mode (focused review) and Full Audit mode (deterministic 6-phase harness).","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FSecurity_Audit_and_Code_Review\u002Fsecurity-audit\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M79FHBGXVBY6VQ1X7ETAZMF1","malware-analysis-reversing","Production malware analysis workflows, reverse engineering methodologies, isolated sandbox triage, static\u002Fdynamic binary analysis, memory forensics, and YARA detection rule authoring.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FOffensive_Security_and_Pentesting\u002Fmalware-analysis-reversing\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M79FH6EACDR801TZCE4R8SAC","application-security-pentesting","Production Application Security (AppSec) standards, OWASP Top 10 vulnerability remediation, SAST\u002FDAST pipeline integration, secure code review, threat modeling, and defensive security posture.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FOffensive_Security_and_Pentesting\u002Fapplication-security-pentesting\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M79FH0VKVT44FK923K520ZQA","oauth2-oidc-security-flows","Implement enterprise OAuth 2.1 and OpenID Connect (OIDC) authorization code flow with Proof Key for Code Exchange (PKCE), state and nonce verification, refresh token rotation, token revocation, and centralized IdP federation (Keycloak, Auth0, Okta). Trigger when building secure authentication, single sign-on (SSO), or third-party delegated authorization.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FIdentity_and_Access_Management_IAM\u002Foauth2-oidc-security-flows\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M79FGVVB3R4T88XXD8FRSV5B","jwt-session-management-hardening","Harden JWT-based authentication and session lifecycles using asymmetric signing (RS256\u002FEdDSA), JWKS rotation, strict claims validation, Redis-backed sliding window sessions, revocation lists, and secure HttpOnly cookie storage. Trigger when implementing token validation, session revocation, or hardening API authentication.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FIdentity_and_Access_Management_IAM\u002Fjwt-session-management-hardening\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M79FGNCPZ85CVEY0B3NE4H3B","soc2-compliance-automation","Best practices for implementing SOC 2 Type II compliance controls, continuous evidence collection, infrastructure policy-as-code, and automated security monitoring. Use when automating Trust Services Criteria (Security, Availability, Confidentiality, Processing Integrity, Privacy), audit logging, IAM least privilege, or CI\u002FCD security gates.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FGovernance_Compliance_and_Legal_Tech\u002Fsoc2-compliance-automation\u002FSKILL.md",[],[]]