[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M719FDHC2YSQ3STD1K5JYV6N":3,"skill-same:01M719FDHC2YSQ3STD1K5JYV6N":60},{"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":34,"linkOnly":35,"markdownContent":36,"markdownBody":37,"frontMatter":38,"refName":40,"commitSha":41,"skillDirectory":42,"forksCount":14,"repositoryHtmlUrl":43,"repositoryHomepageUrl":6,"ownerHtmlUrl":44,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":45,"install":46,"resources":59},"01M719FDHC2YSQ3STD1K5JYV6N","paypal-integration",null,"Master PayPal payment integration including Express Checkout, IPN handling, recurring billing, and refund workflows.","sapsapshen\u002Fai-memory-router","sapsapshen","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F20347959?v=4","01M6XDQEF1DP50DKF37H81J3J5","shenmian","01M6XDQEJPE41Y3DT2763X8ZJN",0,"MIT","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fglobal\u002Fpaypal-integration\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33],"integration","paypal integration","paypal","workflows","recurring","payment integration","master","community","payment","express","checkout","billing","unknown","refund","2026","2026-11-10 10:12:30",false,"---\nname: paypal-integration\ndescription: \"Master PayPal payment integration including Express Checkout, IPN handling, recurring billing, and refund workflows.\"\nrisk: unknown\nsource: community\ndate_added: \"2026-02-27\"\n---\n\n# PayPal Integration\n\nMaster PayPal payment integration including Express Checkout, IPN handling, recurring billing, and refund workflows.\n\n## Do not use this skill when\n\n- The task is unrelated to paypal integration\n- You need a different domain or tool outside this scope\n\n## Instructions\n\n- Clarify goals, constraints, and required inputs.\n- Apply relevant best practices and validate outcomes.\n- Provide actionable steps and verification.\n- If detailed examples are required, open `resources\u002Fimplementation-playbook.md`.\n\n## Use this skill when\n\n- Integrating PayPal as a payment option\n- Implementing express checkout flows\n- Setting up recurring billing with PayPal\n- Processing refunds and payment disputes\n- Handling PayPal webhooks (IPN)\n- Supporting international payments\n- Implementing PayPal subscriptions\n\n## Core Concepts\n\n### 1. Payment Products\n**PayPal Checkout**\n- One-time payments\n- Express checkout experience\n- Guest and PayPal account payments\n\n**PayPal Subscriptions**\n- Recurring billing\n- Subscription plans\n- Automatic renewals\n\n**PayPal Payouts**\n- Send money to multiple recipients\n- Marketplace and platform payments\n\n### 2. Integration Methods\n**Client-Side (JavaScript SDK)**\n- Smart Payment Buttons\n- Hosted payment flow\n- Minimal backend code\n\n**Server-Side (REST API)**\n- Full control over payment flow\n- Custom checkout UI\n- Advanced features\n\n### 3. IPN (Instant Payment Notification)\n- Webhook-like payment notifications\n- Asynchronous payment updates\n- Verification required\n\n## Quick Start\n\n```javascript\n\u002F\u002F Frontend - PayPal Smart Buttons\n\u003Cdiv id=\"paypal-button-container\">\u003C\u002Fdiv>\n\n\u003Cscript src=\"https:\u002F\u002Fwww.paypal.com\u002Fsdk\u002Fjs?client-id=YOUR_CLIENT_ID&currency=USD\">\u003C\u002Fscript>\n\u003Cscript>\n  paypal.Buttons({\n    createOrder: function(data, actions) {\n      return actions.order.create({\n        purchase_units: [{\n          amount: {\n            value: '25.00'\n          }\n        }]\n      });\n    },\n    onApprove: function(data, actions) {\n      return actions.order.capture().then(function(details) {\n        \u002F\u002F Payment successful\n        console.log('Transaction completed by ' + details.payer.name.given_name);\n\n        \u002F\u002F Send to backend for verification\n        fetch('\u002Fapi\u002Fpaypal\u002Fcapture', {\n          method: 'POST',\n          headers: {'Content-Type': 'application\u002Fjson'},\n          body: JSON.stringify({orderID: data.orderID})\n        });\n      });\n    }\n  }).render('#paypal-button-container');\n\u003C\u002Fscript>\n```\n\n```python\n# Backend - Verify and capture order\nfrom paypalrestsdk import Payment\nimport paypalrestsdk\n\npaypalrestsdk.configure({\n    \"mode\": \"sandbox\",  # or \"live\"\n    \"client_id\": \"YOUR_CLIENT_ID\",\n    \"client_secret\": \"YOUR_CLIENT_SECRET\"\n})\n\ndef capture_paypal_order(order_id):\n    \"\"\"Capture a PayPal order.\"\"\"\n    payment = Payment.find(order_id)\n\n    if payment.execute({\"payer_id\": payment.payer.payer_info.payer_id}):\n        # Payment successful\n        return {\n            'status': 'success',\n            'transaction_id': payment.id,\n            'amount': payment.transactions[0].amount.total\n        }\n    else:\n        # Payment failed\n        return {\n            'status': 'failed',\n            'error': payment.error\n        }\n```\n\n## Express Checkout Implementation\n\n### Server-Side Order Creation\n```python\nimport requests\nimport json\n\nclass PayPalClient:\n    def __init__(self, client_id, client_secret, mode='sandbox'):\n        self.client_id = client_id\n        self.client_secret = client_secret\n        self.base_url = 'https:\u002F\u002Fapi-m.sandbox.paypal.com' if mode == 'sandbox' else 'https:\u002F\u002Fapi-m.paypal.com'\n        self.access_token = self.get_access_token()\n\n    def get_access_token(self):\n        \"\"\"Get OAuth access token.\"\"\"\n        url = f\"{self.base_url}\u002Fv1\u002Foauth2\u002Ftoken\"\n        headers = {\"Accept\": \"application\u002Fjson\", \"Accept-Language\": \"en_US\"}\n\n        response = requests.post(\n            url,\n            headers=headers,\n            data={\"grant_type\": \"client_credentials\"},\n            auth=(self.client_id, self.client_secret)\n        )\n\n        return response.json()['access_token']\n\n    def create_order(self, amount, currency='USD'):\n        \"\"\"Create a PayPal order.\"\"\"\n        url = f\"{self.base_url}\u002Fv2\u002Fcheckout\u002Forders\"\n        headers = {\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {self.access_token}\"\n        }\n\n        payload = {\n            \"intent\": \"CAPTURE\",\n            \"purchase_units\": [{\n                \"amount\": {\n                    \"currency_code\": currency,\n                    \"value\": str(amount)\n                }\n            }]\n        }\n\n        response = requests.post(url, headers=headers, json=payload)\n        return response.json()\n\n    def capture_order(self, order_id):\n        \"\"\"Capture payment for an order.\"\"\"\n        url = f\"{self.base_url}\u002Fv2\u002Fcheckout\u002Forders\u002F{order_id}\u002Fcapture\"\n        headers = {\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {self.access_token}\"\n        }\n\n        response = requests.post(url, headers=headers)\n        return response.json()\n\n    def get_order_details(self, order_id):\n        \"\"\"Get order details.\"\"\"\n        url = f\"{self.base_url}\u002Fv2\u002Fcheckout\u002Forders\u002F{order_id}\"\n        headers = {\n            \"Authorization\": f\"Bearer {self.access_token}\"\n        }\n\n        response = requests.get(url, headers=headers)\n        return response.json()\n```\n\n## IPN (Instant Payment Notification) Handling\n\n### IPN Verification and Processing\n```python\nfrom flask import Flask, request\nimport requests\nfrom urllib.parse import parse_qs\n\napp = Flask(__name__)\n\n@app.route('\u002Fipn', methods=['POST'])\ndef handle_ipn():\n    \"\"\"Handle PayPal IPN notifications.\"\"\"\n    # Get IPN message\n    ipn_data = request.form.to_dict()\n\n    # Verify IPN with PayPal\n    if not verify_ipn(ipn_data):\n        return 'IPN verification failed', 400\n\n    # Process IPN based on transaction type\n    payment_status = ipn_data.get('payment_status')\n    txn_type = ipn_data.get('txn_type')\n\n    if payment_status == 'Completed':\n        handle_payment_completed(ipn_data)\n    elif payment_status == 'Refunded':\n        handle_refund(ipn_data)\n    elif payment_status == 'Reversed':\n        handle_chargeback(ipn_data)\n\n    return 'IPN processed', 200\n\ndef verify_ipn(ipn_data):\n    \"\"\"Verify IPN message authenticity.\"\"\"\n    # Add 'cmd' parameter\n    verify_data = ipn_data.copy()\n    verify_data['cmd'] = '_notify-validate'\n\n    # Send back to PayPal for verification\n    paypal_url = 'https:\u002F\u002Fipnpb.sandbox.paypal.com\u002Fcgi-bin\u002Fwebscr'  # or production URL\n\n    response = requests.post(paypal_url, data=verify_data)\n\n    return response.text == 'VERIFIED'\n\ndef handle_payment_completed(ipn_data):\n    \"\"\"Process completed payment.\"\"\"\n    txn_id = ipn_data.get('txn_id')\n    payer_email = ipn_data.get('payer_email')\n    mc_gross = ipn_data.get('mc_gross')\n    item_name = ipn_data.get('item_name')\n\n    # Check if already processed (prevent duplicates)\n    if is_transaction_processed(txn_id):\n        return\n\n    # Update database\n    # Send confirmation email\n    # Fulfill order\n    print(f\"Payment completed: {txn_id}, Amount: ${mc_gross}\")\n\ndef handle_refund(ipn_data):\n    \"\"\"Handle refund.\"\"\"\n    parent_txn_id = ipn_data.get('parent_txn_id')\n    mc_gross = ipn_data.get('mc_gross')\n\n    # Process refund in your system\n    print(f\"Refund processed: {parent_txn_id}, Amount: ${mc_gross}\")\n\ndef handle_chargeback(ipn_data):\n    \"\"\"Handle payment reversal\u002Fchargeback.\"\"\"\n    txn_id = ipn_data.get('txn_id')\n    reason_code = ipn_data.get('reason_code')\n\n    # Handle chargeback\n    print(f\"Chargeback: {txn_id}, Reason: {reason_code}\")\n```\n\n## Subscription\u002FRecurring Billing\n\n### Create Subscription Plan\n```python\ndef create_subscription_plan(name, amount, interval='MONTH'):\n    \"\"\"Create a subscription plan.\"\"\"\n    client = PayPalClient(CLIENT_ID, CLIENT_SECRET)\n\n    url = f\"{client.base_url}\u002Fv1\u002Fbilling\u002Fplans\"\n    headers = {\n        \"Content-Type\": \"application\u002Fjson\",\n        \"Authorization\": f\"Bearer {client.access_token}\"\n    }\n\n    payload = {\n        \"product_id\": \"PRODUCT_ID\",  # Create product first\n        \"name\": name,\n        \"billing_cycles\": [{\n            \"frequency\": {\n                \"interval_unit\": interval,\n                \"interval_count\": 1\n            },\n            \"tenure_type\": \"REGULAR\",\n            \"sequence\": 1,\n            \"total_cycles\": 0,  # Infinite\n            \"pricing_scheme\": {\n                \"fixed_price\": {\n                    \"value\": str(amount),\n                    \"currency_code\": \"USD\"\n                }\n            }\n        }],\n        \"payment_preferences\": {\n            \"auto_bill_outstanding\": True,\n            \"setup_fee\": {\n                \"value\": \"0\",\n                \"currency_code\": \"USD\"\n            },\n            \"setup_fee_failure_action\": \"CONTINUE\",\n            \"payment_failure_threshold\": 3\n        }\n    }\n\n    response = requests.post(url, headers=headers, json=payload)\n    return response.json()\n\ndef create_subscription(plan_id, subscriber_email):\n    \"\"\"Create a subscription for a customer.\"\"\"\n    client = PayPalClient(CLIENT_ID, CLIENT_SECRET)\n\n    url = f\"{client.base_url}\u002Fv1\u002Fbilling\u002Fsubscriptions\"\n    headers = {\n        \"Content-Type\": \"application\u002Fjson\",\n        \"Authorization\": f\"Bearer {client.access_token}\"\n    }\n\n    payload = {\n        \"plan_id\": plan_id,\n        \"subscriber\": {\n            \"email_address\": subscriber_email\n        },\n        \"application_context\": {\n            \"return_url\": \"https:\u002F\u002Fyourdomain.com\u002Fsubscription\u002Fsuccess\",\n            \"cancel_url\": \"https:\u002F\u002Fyourdomain.com\u002Fsubscription\u002Fcancel\"\n        }\n    }\n\n    response = requests.post(url, headers=headers, json=payload)\n    subscription = response.json()\n\n    # Get approval URL\n    for link in subscription.get('links', []):\n        if link['rel'] == 'approve':\n            return {\n                'subscription_id': subscription['id'],\n                'approval_url': link['href']\n            }\n```\n\n## Refund Workflows\n\n```python\ndef create_refund(capture_id, amount=None, note=None):\n    \"\"\"Create a refund for a captured payment.\"\"\"\n    client = PayPalClient(CLIENT_ID, CLIENT_SECRET)\n\n    url = f\"{client.base_url}\u002Fv2\u002Fpayments\u002Fcaptures\u002F{capture_id}\u002Frefund\"\n    headers = {\n        \"Content-Type\": \"application\u002Fjson\",\n        \"Authorization\": f\"Bearer {client.access_token}\"\n    }\n\n    payload = {}\n    if amount:\n        payload[\"amount\"] = {\n            \"value\": str(amount),\n            \"currency_code\": \"USD\"\n        }\n\n    if note:\n        payload[\"note_to_payer\"] = note\n\n    response = requests.post(url, headers=headers, json=payload)\n    return response.json()\n\ndef get_refund_details(refund_id):\n    \"\"\"Get refund details.\"\"\"\n    client = PayPalClient(CLIENT_ID, CLIENT_SECRET)\n\n    url = f\"{client.base_url}\u002Fv2\u002Fpayments\u002Frefunds\u002F{refund_id}\"\n    headers = {\n        \"Authorization\": f\"Bearer {client.access_token}\"\n    }\n\n    response = requests.get(url, headers=headers)\n    return response.json()\n```\n\n## Error Handling\n\n```python\nclass PayPalError(Exception):\n    \"\"\"Custom PayPal error.\"\"\"\n    pass\n\ndef handle_paypal_api_call(api_function):\n    \"\"\"Wrapper for PayPal API calls with error handling.\"\"\"\n    try:\n        result = api_function()\n        return result\n    except requests.exceptions.RequestException as e:\n        # Network error\n        raise PayPalError(f\"Network error: {str(e)}\")\n    except Exception as e:\n        # Other errors\n        raise PayPalError(f\"PayPal API error: {str(e)}\")\n\n# Usage\ntry:\n    order = handle_paypal_api_call(lambda: client.create_order(25.00))\nexcept PayPalError as e:\n    # Handle error appropriately\n    log_error(e)\n```\n\n## Testing\n\n```python\n# Use sandbox credentials\nSANDBOX_CLIENT_ID = \"...\"\nSANDBOX_SECRET = \"...\"\n\n# Test accounts\n# Create test buyer and seller accounts at developer.paypal.com\n\ndef test_payment_flow():\n    \"\"\"Test complete payment flow.\"\"\"\n    client = PayPalClient(SANDBOX_CLIENT_ID, SANDBOX_SECRET, mode='sandbox')\n\n    # Create order\n    order = client.create_order(10.00)\n    assert 'id' in order\n\n    # Get approval URL\n    approval_url = next((link['href'] for link in order['links'] if link['rel'] == 'approve'), None)\n    assert approval_url is not None\n\n    # After approval (manual step with test account)\n    # Capture order\n    # captured = client.capture_order(order['id'])\n    # assert captured['status'] == 'COMPLETED'\n```\n\n## Resources\n\n- **references\u002Fexpress-checkout.md**: Express Checkout implementation guide\n- **references\u002Fipn-handling.md**: IPN verification and processing\n- **references\u002Frefund-workflows.md**: Refund handling patterns\n- **references\u002Fbilling-agreements.md**: Recurring billing setup\n- **assets\u002Fpaypal-client.py**: Production PayPal client\n- **assets\u002Fipn-processor.py**: IPN webhook processor\n- **assets\u002Frecurring-billing.py**: Subscription management\n\n## Best Practices\n\n1. **Always Verify IPN**: Never trust IPN without verification\n2. **Idempotent Processing**: Handle duplicate IPN notifications\n3. **Error Handling**: Implement robust error handling\n4. **Logging**: Log all transactions and errors\n5. **Test Thoroughly**: Use sandbox extensively\n6. **Webhook Backup**: Don't rely solely on client-side callbacks\n7. **Currency Handling**: Always specify currency explicitly\n\n## Common Pitfalls\n\n- **Not Verifying IPN**: Accepting IPN without verification\n- **Duplicate Processing**: Not checking for duplicate transactions\n- **Wrong Environment**: Mixing sandbox and production URLs\u002Fcredentials\n- **Missing Webhooks**: Not handling all payment states\n- **Hardcoded Values**: Not making configurable for different environments\n","# PayPal Integration\n\nMaster PayPal payment integration including Express Checkout, IPN handling, recurring billing, and refund workflows.\n\n## Do not use this skill when\n\n- The task is unrelated to paypal integration\n- You need a different domain or tool outside this scope\n\n## Instructions\n\n- Clarify goals, constraints, and required inputs.\n- Apply relevant best practices and validate outcomes.\n- Provide actionable steps and verification.\n- If detailed examples are required, open `resources\u002Fimplementation-playbook.md`.\n\n## Use this skill when\n\n- Integrating PayPal as a payment option\n- Implementing express checkout flows\n- Setting up recurring billing with PayPal\n- Processing refunds and payment disputes\n- Handling PayPal webhooks (IPN)\n- Supporting international payments\n- Implementing PayPal subscriptions\n\n## Core Concepts\n\n### 1. Payment Products\n**PayPal Checkout**\n- One-time payments\n- Express checkout experience\n- Guest and PayPal account payments\n\n**PayPal Subscriptions**\n- Recurring billing\n- Subscription plans\n- Automatic renewals\n\n**PayPal Payouts**\n- Send money to multiple recipients\n- Marketplace and platform payments\n\n### 2. Integration Methods\n**Client-Side (JavaScript SDK)**\n- Smart Payment Buttons\n- Hosted payment flow\n- Minimal backend code\n\n**Server-Side (REST API)**\n- Full control over payment flow\n- Custom checkout UI\n- Advanced features\n\n### 3. IPN (Instant Payment Notification)\n- Webhook-like payment notifications\n- Asynchronous payment updates\n- Verification required\n\n## Quick Start\n\n```javascript\n\u002F\u002F Frontend - PayPal Smart Buttons\n\u003Cdiv id=\"paypal-button-container\">\u003C\u002Fdiv>\n\n\u003Cscript src=\"https:\u002F\u002Fwww.paypal.com\u002Fsdk\u002Fjs?client-id=YOUR_CLIENT_ID&currency=USD\">\u003C\u002Fscript>\n\u003Cscript>\n  paypal.Buttons({\n    createOrder: function(data, actions) {\n      return actions.order.create({\n        purchase_units: [{\n          amount: {\n            value: '25.00'\n          }\n        }]\n      });\n    },\n    onApprove: function(data, actions) {\n      return actions.order.capture().then(function(details) {\n        \u002F\u002F Payment successful\n        console.log('Transaction completed by ' + details.payer.name.given_name);\n\n        \u002F\u002F Send to backend for verification\n        fetch('\u002Fapi\u002Fpaypal\u002Fcapture', {\n          method: 'POST',\n          headers: {'Content-Type': 'application\u002Fjson'},\n          body: JSON.stringify({orderID: data.orderID})\n        });\n      });\n    }\n  }).render('#paypal-button-container');\n\u003C\u002Fscript>\n```\n\n```python\n# Backend - Verify and capture order\nfrom paypalrestsdk import Payment\nimport paypalrestsdk\n\npaypalrestsdk.configure({\n    \"mode\": \"sandbox\",  # or \"live\"\n    \"client_id\": \"YOUR_CLIENT_ID\",\n    \"client_secret\": \"YOUR_CLIENT_SECRET\"\n})\n\ndef capture_paypal_order(order_id):\n    \"\"\"Capture a PayPal order.\"\"\"\n    payment = Payment.find(order_id)\n\n    if payment.execute({\"payer_id\": payment.payer.payer_info.payer_id}):\n        # Payment successful\n        return {\n            'status': 'success',\n            'transaction_id': payment.id,\n            'amount': payment.transactions[0].amount.total\n        }\n    else:\n        # Payment failed\n        return {\n            'status': 'failed',\n            'error': payment.error\n        }\n```\n\n## Express Checkout Implementation\n\n### Server-Side Order Creation\n```python\nimport requests\nimport json\n\nclass PayPalClient:\n    def __init__(self, client_id, client_secret, mode='sandbox'):\n        self.client_id = client_id\n        self.client_secret = client_secret\n        self.base_url = 'https:\u002F\u002Fapi-m.sandbox.paypal.com' if mode == 'sandbox' else 'https:\u002F\u002Fapi-m.paypal.com'\n        self.access_token = self.get_access_token()\n\n    def get_access_token(self):\n        \"\"\"Get OAuth access token.\"\"\"\n        url = f\"{self.base_url}\u002Fv1\u002Foauth2\u002Ftoken\"\n        headers = {\"Accept\": \"application\u002Fjson\", \"Accept-Language\": \"en_US\"}\n\n        response = requests.post(\n            url,\n            headers=headers,\n            data={\"grant_type\": \"client_credentials\"},\n            auth=(self.client_id, self.client_secret)\n        )\n\n        return response.json()['access_token']\n\n    def create_order(self, amount, currency='USD'):\n        \"\"\"Create a PayPal order.\"\"\"\n        url = f\"{self.base_url}\u002Fv2\u002Fcheckout\u002Forders\"\n        headers = {\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {self.access_token}\"\n        }\n\n        payload = {\n            \"intent\": \"CAPTURE\",\n            \"purchase_units\": [{\n                \"amount\": {\n                    \"currency_code\": currency,\n                    \"value\": str(amount)\n                }\n            }]\n        }\n\n        response = requests.post(url, headers=headers, json=payload)\n        return response.json()\n\n    def capture_order(self, order_id):\n        \"\"\"Capture payment for an order.\"\"\"\n        url = f\"{self.base_url}\u002Fv2\u002Fcheckout\u002Forders\u002F{order_id}\u002Fcapture\"\n        headers = {\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {self.access_token}\"\n        }\n\n        response = requests.post(url, headers=headers)\n        return response.json()\n\n    def get_order_details(self, order_id):\n        \"\"\"Get order details.\"\"\"\n        url = f\"{self.base_url}\u002Fv2\u002Fcheckout\u002Forders\u002F{order_id}\"\n        headers = {\n            \"Authorization\": f\"Bearer {self.access_token}\"\n        }\n\n        response = requests.get(url, headers=headers)\n        return response.json()\n```\n\n## IPN (Instant Payment Notification) Handling\n\n### IPN Verification and Processing\n```python\nfrom flask import Flask, request\nimport requests\nfrom urllib.parse import parse_qs\n\napp = Flask(__name__)\n\n@app.route('\u002Fipn', methods=['POST'])\ndef handle_ipn():\n    \"\"\"Handle PayPal IPN notifications.\"\"\"\n    # Get IPN message\n    ipn_data = request.form.to_dict()\n\n    # Verify IPN with PayPal\n    if not verify_ipn(ipn_data):\n        return 'IPN verification failed', 400\n\n    # Process IPN based on transaction type\n    payment_status = ipn_data.get('payment_status')\n    txn_type = ipn_data.get('txn_type')\n\n    if payment_status == 'Completed':\n        handle_payment_completed(ipn_data)\n    elif payment_status == 'Refunded':\n        handle_refund(ipn_data)\n    elif payment_status == 'Reversed':\n        handle_chargeback(ipn_data)\n\n    return 'IPN processed', 200\n\ndef verify_ipn(ipn_data):\n    \"\"\"Verify IPN message authenticity.\"\"\"\n    # Add 'cmd' parameter\n    verify_data = ipn_data.copy()\n    verify_data['cmd'] = '_notify-validate'\n\n    # Send back to PayPal for verification\n    paypal_url = 'https:\u002F\u002Fipnpb.sandbox.paypal.com\u002Fcgi-bin\u002Fwebscr'  # or production URL\n\n    response = requests.post(paypal_url, data=verify_data)\n\n    return response.text == 'VERIFIED'\n\ndef handle_payment_completed(ipn_data):\n    \"\"\"Process completed payment.\"\"\"\n    txn_id = ipn_data.get('txn_id')\n    payer_email = ipn_data.get('payer_email')\n    mc_gross = ipn_data.get('mc_gross')\n    item_name = ipn_data.get('item_name')\n\n    # Check if already processed (prevent duplicates)\n    if is_transaction_processed(txn_id):\n        return\n\n    # Update database\n    # Send confirmation email\n    # Fulfill order\n    print(f\"Payment completed: {txn_id}, Amount: ${mc_gross}\")\n\ndef handle_refund(ipn_data):\n    \"\"\"Handle refund.\"\"\"\n    parent_txn_id = ipn_data.get('parent_txn_id')\n    mc_gross = ipn_data.get('mc_gross')\n\n    # Process refund in your system\n    print(f\"Refund processed: {parent_txn_id}, Amount: ${mc_gross}\")\n\ndef handle_chargeback(ipn_data):\n    \"\"\"Handle payment reversal\u002Fchargeback.\"\"\"\n    txn_id = ipn_data.get('txn_id')\n    reason_code = ipn_data.get('reason_code')\n\n    # Handle chargeback\n    print(f\"Chargeback: {txn_id}, Reason: {reason_code}\")\n```\n\n## Subscription\u002FRecurring Billing\n\n### Create Subscription Plan\n```python\ndef create_subscription_plan(name, amount, interval='MONTH'):\n    \"\"\"Create a subscription plan.\"\"\"\n    client = PayPalClient(CLIENT_ID, CLIENT_SECRET)\n\n    url = f\"{client.base_url}\u002Fv1\u002Fbilling\u002Fplans\"\n    headers = {\n        \"Content-Type\": \"application\u002Fjson\",\n        \"Authorization\": f\"Bearer {client.access_token}\"\n    }\n\n    payload = {\n        \"product_id\": \"PRODUCT_ID\",  # Create product first\n        \"name\": name,\n        \"billing_cycles\": [{\n            \"frequency\": {\n                \"interval_unit\": interval,\n                \"interval_count\": 1\n            },\n            \"tenure_type\": \"REGULAR\",\n            \"sequence\": 1,\n            \"total_cycles\": 0,  # Infinite\n            \"pricing_scheme\": {\n                \"fixed_price\": {\n                    \"value\": str(amount),\n                    \"currency_code\": \"USD\"\n                }\n            }\n        }],\n        \"payment_preferences\": {\n            \"auto_bill_outstanding\": True,\n            \"setup_fee\": {\n                \"value\": \"0\",\n                \"currency_code\": \"USD\"\n            },\n            \"setup_fee_failure_action\": \"CONTINUE\",\n            \"payment_failure_threshold\": 3\n        }\n    }\n\n    response = requests.post(url, headers=headers, json=payload)\n    return response.json()\n\ndef create_subscription(plan_id, subscriber_email):\n    \"\"\"Create a subscription for a customer.\"\"\"\n    client = PayPalClient(CLIENT_ID, CLIENT_SECRET)\n\n    url = f\"{client.base_url}\u002Fv1\u002Fbilling\u002Fsubscriptions\"\n    headers = {\n        \"Content-Type\": \"application\u002Fjson\",\n        \"Authorization\": f\"Bearer {client.access_token}\"\n    }\n\n    payload = {\n        \"plan_id\": plan_id,\n        \"subscriber\": {\n            \"email_address\": subscriber_email\n        },\n        \"application_context\": {\n            \"return_url\": \"https:\u002F\u002Fyourdomain.com\u002Fsubscription\u002Fsuccess\",\n            \"cancel_url\": \"https:\u002F\u002Fyourdomain.com\u002Fsubscription\u002Fcancel\"\n        }\n    }\n\n    response = requests.post(url, headers=headers, json=payload)\n    subscription = response.json()\n\n    # Get approval URL\n    for link in subscription.get('links', []):\n        if link['rel'] == 'approve':\n            return {\n                'subscription_id': subscription['id'],\n                'approval_url': link['href']\n            }\n```\n\n## Refund Workflows\n\n```python\ndef create_refund(capture_id, amount=None, note=None):\n    \"\"\"Create a refund for a captured payment.\"\"\"\n    client = PayPalClient(CLIENT_ID, CLIENT_SECRET)\n\n    url = f\"{client.base_url}\u002Fv2\u002Fpayments\u002Fcaptures\u002F{capture_id}\u002Frefund\"\n    headers = {\n        \"Content-Type\": \"application\u002Fjson\",\n        \"Authorization\": f\"Bearer {client.access_token}\"\n    }\n\n    payload = {}\n    if amount:\n        payload[\"amount\"] = {\n            \"value\": str(amount),\n            \"currency_code\": \"USD\"\n        }\n\n    if note:\n        payload[\"note_to_payer\"] = note\n\n    response = requests.post(url, headers=headers, json=payload)\n    return response.json()\n\ndef get_refund_details(refund_id):\n    \"\"\"Get refund details.\"\"\"\n    client = PayPalClient(CLIENT_ID, CLIENT_SECRET)\n\n    url = f\"{client.base_url}\u002Fv2\u002Fpayments\u002Frefunds\u002F{refund_id}\"\n    headers = {\n        \"Authorization\": f\"Bearer {client.access_token}\"\n    }\n\n    response = requests.get(url, headers=headers)\n    return response.json()\n```\n\n## Error Handling\n\n```python\nclass PayPalError(Exception):\n    \"\"\"Custom PayPal error.\"\"\"\n    pass\n\ndef handle_paypal_api_call(api_function):\n    \"\"\"Wrapper for PayPal API calls with error handling.\"\"\"\n    try:\n        result = api_function()\n        return result\n    except requests.exceptions.RequestException as e:\n        # Network error\n        raise PayPalError(f\"Network error: {str(e)}\")\n    except Exception as e:\n        # Other errors\n        raise PayPalError(f\"PayPal API error: {str(e)}\")\n\n# Usage\ntry:\n    order = handle_paypal_api_call(lambda: client.create_order(25.00))\nexcept PayPalError as e:\n    # Handle error appropriately\n    log_error(e)\n```\n\n## Testing\n\n```python\n# Use sandbox credentials\nSANDBOX_CLIENT_ID = \"...\"\nSANDBOX_SECRET = \"...\"\n\n# Test accounts\n# Create test buyer and seller accounts at developer.paypal.com\n\ndef test_payment_flow():\n    \"\"\"Test complete payment flow.\"\"\"\n    client = PayPalClient(SANDBOX_CLIENT_ID, SANDBOX_SECRET, mode='sandbox')\n\n    # Create order\n    order = client.create_order(10.00)\n    assert 'id' in order\n\n    # Get approval URL\n    approval_url = next((link['href'] for link in order['links'] if link['rel'] == 'approve'), None)\n    assert approval_url is not None\n\n    # After approval (manual step with test account)\n    # Capture order\n    # captured = client.capture_order(order['id'])\n    # assert captured['status'] == 'COMPLETED'\n```\n\n## Resources\n\n- **references\u002Fexpress-checkout.md**: Express Checkout implementation guide\n- **references\u002Fipn-handling.md**: IPN verification and processing\n- **references\u002Frefund-workflows.md**: Refund handling patterns\n- **references\u002Fbilling-agreements.md**: Recurring billing setup\n- **assets\u002Fpaypal-client.py**: Production PayPal client\n- **assets\u002Fipn-processor.py**: IPN webhook processor\n- **assets\u002Frecurring-billing.py**: Subscription management\n\n## Best Practices\n\n1. **Always Verify IPN**: Never trust IPN without verification\n2. **Idempotent Processing**: Handle duplicate IPN notifications\n3. **Error Handling**: Implement robust error handling\n4. **Logging**: Log all transactions and errors\n5. **Test Thoroughly**: Use sandbox extensively\n6. **Webhook Backup**: Don't rely solely on client-side callbacks\n7. **Currency Handling**: Always specify currency explicitly\n\n## Common Pitfalls\n\n- **Not Verifying IPN**: Accepting IPN without verification\n- **Duplicate Processing**: Not checking for duplicate transactions\n- **Wrong Environment**: Mixing sandbox and production URLs\u002Fcredentials\n- **Missing Webhooks**: Not handling all payment states\n- **Hardcoded Values**: Not making configurable for different environments\n",{"name":5,"risk":31,"source":26,"date_added":39,"description":7},"2026-02-27","main","7a38d8e7073e61c16eda85681cb32fb68a8657a5","skills-store\u002Fglobal\u002Fpaypal-integration","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router","https:\u002F\u002Fgithub.com\u002Fsapsapshen","2026-04-14 21:12:12",{"source":8,"skillName":5,"commands":47,"prompt":57,"zipAvailable":58},[48,51,54],{"tool":49,"command":50},"npx","npx skills add sapsapshen\u002Fai-memory-router --skill paypal-integration",{"tool":52,"command":53},"bunx","bunx skills add sapsapshen\u002Fai-memory-router --skill paypal-integration",{"tool":55,"command":56},"pnpm","pnpm dlx skills add sapsapshen\u002Fai-memory-router --skill paypal-integration","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fglobal\u002Fpaypal-integration\u002FSKILL.md",true,[],[61,85,111,121,134,153],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":72,"publishedAt":34},"01M71ATQRKG48SH06FQ697T5G9","wechat-search","Search WeChat Official Account articles using OpenClaw's web search and fetch capabilities with compliance-focused design.","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fopenclaw\u002Fwechat-search-release\u002FSKILL.md",[67],{"categoryNo":68,"categoryName":69,"taxonomyType":70,"taxonomyTypeDesc":71},"01JBSEEDCAT000000000000037","律师与法务","PROFESSION","适用职业",[73,74,75,76,77,78,79,80,81,82,83,84],"wechat search","wechat","search","capabilities","openclaw","design","web search","compliance","web","official","fetch","with",{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":34},"01M71ATNAVGZB35PFYM2GC5N00","trend-tap","Real-time trending topics aggregator across 7 platforms (X\u002FTwitter, Reddit, Google Trends, Hacker News, Zhihu, Bilibili, Weibo). Trigger: when user says 'trend', 'trends', 'trend tap', '热点', '热搜', or asks what is trending\u002Fhot. Do NOT use web_search — this skill already fetches live data from all platforms with zero API keys.","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fopenclaw\u002Ftrend-tap\u002FSKILL.md",[],[92,93,94,95,96,97,75,98,99,100,101,102,103,104,105,106,107,108,109,110],"trend","trend tap","tap","api keys","Bash","time","trending","hacker","aggregator","do","when","brew","live","data","google","install","read","across","api",{"skillNo":112,"name":113,"nameZh":6,"description":114,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":115,"categories":116,"keywords":117,"publishedAt":34},"01M71ATJ9AM5KM15AA8PS302EB","trend-radar","Real-time trending topics aggregator across 7 platforms (X\u002FTwitter, Reddit, Google Trends, Hacker News, Zhihu, Bilibili, Weibo). Trigger: when user says 'trend', 'trends', 'trend pulse', '热点', '热搜', or asks what is trending\u002Fhot. Do NOT use web_search — this skill already fetches live data from all platforms with zero API keys.","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fopenclaw\u002Ftrend-radar\u002FSKILL.md",[],[118,119,92,103,104,105,106,96,75,108,120,109,110,102,100,99,98,107,97,95],"trend radar","radar","pulse",{"skillNo":122,"name":123,"nameZh":6,"description":124,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":125,"categories":126,"keywords":127,"publishedAt":34},"01M71ATGF095N3EJM9G8SD0BB5","tech-news-daily","每日科技新闻汇——从全球多个 RSS 源抓取最新科技新闻，翻译（英→中）、去重、排版成每日简报。当用户询问科技新闻、科技新鲜事、每日科技、技术动态、Daily Tech News 或类似表达时触发此技能。","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fopenclaw\u002Ftech-news-daily\u002FSKILL.md",[],[128,129,130,131,132,133],"news","tech","tech news daily","daily","rss","翻译",{"skillNo":135,"name":136,"nameZh":6,"description":137,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":138,"categories":139,"keywords":145,"publishedAt":34},"01M71ATFAEAMQ17M70NQNY7SR8","summarize","Summarize URLs or files with the summarize CLI (web, PDFs, images, audio, YouTube).","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fopenclaw\u002Fsummarize\u002FSKILL.md",[140],{"categoryNo":141,"categoryName":142,"taxonomyType":143,"taxonomyTypeDesc":144},"01JBSEEDCAT000000000000021","资料检索与研究","SCENARIO","使用场景",[136,81,146,147,148,84,103,149,150,151,94,152,107],"Audio","cli","youtube","images","https","files","pdfs",{"skillNo":154,"name":155,"nameZh":6,"description":156,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":157,"categories":158,"keywords":159,"publishedAt":34},"01M71ATDNS3R0M4H936PACQAWZ","sonoscli","Control Sonos speakers (discover\u002Fstatus\u002Fplay\u002Fvolume\u002Fgroup).","https:\u002F\u002Fgithub.com\u002Fsapsapshen\u002Fai-memory-router\u002Fblob\u002Fmain\u002Fskills-store\u002Fopenclaw\u002Fsonoscli\u002FSKILL.md",[],[155,160,161,162,107,163,150,164,165,166,167,168],"status","play","go","latest","github","discover","control","cmd","volume"]