[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77R844ECVMDPJ2E99WP4EFZ":3,"skill-same:01M77R844ECVMDPJ2E99WP4EFZ":59},{"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":37,"commitSha":38,"skillDirectory":39,"forksCount":40,"repositoryHtmlUrl":41,"repositoryHomepageUrl":42,"ownerHtmlUrl":43,"ownerBlogUrl":6,"ownerDescription":44,"updatedAt":45,"install":46,"resources":58},"01M77R844ECVMDPJ2E99WP4EFZ","telegram-bot-payments",null,"Add paywall to OpenClaw Telegram bots. Covers Stripe external link (94% margin), Telegram Stars (65% margin, required for iOS), and TON Wallet Pay (99% margin). Includes webhook server, credits system, and AGENTS.md behavior.","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fp\u002Fphy-telegram-bot-payments\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: telegram-bot-payments\ndescription: Add paywall to OpenClaw Telegram bots. Covers Stripe external link (94% margin), Telegram Stars (65% margin, required for iOS), and TON Wallet Pay (99% margin). Includes webhook server, credits system, and AGENTS.md behavior.\nlicense: MIT\nhomepage: https:\u002F\u002Fcanlah.ai\nmetadata:\n  author: Canlah AI\n  version: \"1.0.2\"\n  tags: [\"telegram\", \"payments\", \"stripe\", \"stars\", \"openclaw\", \"monetization\"]\nallowed-tools: Bash Read Edit Write Grep Glob Agent\nuser-invocable: true\n---\n\n# Telegram Bot Payments — Paywall Implementation\n\nAdd paid credits to any OpenClaw Telegram bot. Supports three payment methods with a hybrid approach to maximize developer margin.\n\n## When to Use\n\n- Adding a paywall to an OpenClaw Telegram bot\n- Implementing per-image or per-use quota with paid top-ups\n- Choosing the right payment method for your user base\n- Setting up Stripe, Telegram Stars, or TON payments\n\n---\n\n## Payment Method Decision\n\n| Method | User pays $10 → You receive | When to use |\n|--------|------------------------------|-------------|\n| **Stripe (external link)** | **~$9.41 (94%)** | Android, Desktop, Web users — best margin |\n| **TON Wallet Pay** | **~$9.90 (99%)** | Crypto-savvy users — best margin, zero fees |\n| **Telegram Stars** | **~$6.50 (65%)** | iOS users ONLY — legally required for in-app digital goods on iOS |\n\n### Why NOT Stars-only\n\nStars = two fees back-to-back:\n```\nUser pays $10\n  → Apple\u002FGoogle takes ~30% (mandatory IAP)\n  → Telegram takes ~5%\n  → You receive ~$6.50\n```\n\nFor image generation at $0.03–$0.08\u002Fimage, Stars makes most packages unprofitable.\n\n### The Hybrid Rule\n\n```\nUser on iOS?   → Stars (no choice — Apple policy)\nUser on Android\u002FDesktop\u002FWeb? → Stripe external link (9x better margin)\n```\n\nTelegram does NOT currently ban external payment links. Risk is low-medium.\nIf enforced in future, fall back to Stars or TON.\n\n---\n\n## Architecture\n\n```\nQuota exhausted\n    ↓\nAgent detects (check_quota.py returns allowed=false)\n    ↓\nAgent sends payment options message + buttons\n    ↓\n    ├─ [Pay with Card ⭐] → Stripe Payment Link (external browser)\n    ├─ [Pay with Stars ⭐] → Telegram Stars invoice (iOS compliance)\n    └─ [Pay with TON 💎] → TON Wallet Pay link (optional)\n    ↓\nPayment completed → Stripe\u002FStars webhook fires\n    ↓\npayment_server.py updates \u002Fworkspaces\u002F{USER_ID}\u002Fusage.json credits\n    ↓\nUser continues generating\n```\n\n---\n\n## Implementation: Stripe External Link (Primary Method)\n\n### Step 1: Create Stripe Payment Links\n\nIn Stripe Dashboard → Payment Links → Create:\n\n```\nProduct: \"20 Image Credits\"   Price: $2.00  → copy link e.g. https:\u002F\u002Fbuy.stripe.com\u002Fxxx\nProduct: \"50 Image Credits\"   Price: $4.00  → copy link e.g. https:\u002F\u002Fbuy.stripe.com\u002Fyyy\nProduct: \"100 Image Credits\"  Price: $7.00  → copy link e.g. https:\u002F\u002Fbuy.stripe.com\u002Fzzz\n```\n\n**Critical:** Add a metadata field `telegram_user_id` — but Payment Links don't support dynamic metadata natively. Two options:\n\n**Option A (Simple) — URL with client_reference_id:**\nStripe Payment Links support `?client_reference_id=USER_ID` as a query param. Append the user's Telegram ID:\n```\nhttps:\u002F\u002Fbuy.stripe.com\u002Fxxx?client_reference_id=697391377\n```\nThe `client_reference_id` appears in the webhook payload.\n\n**Option B (Proper) — Stripe Checkout Session:**\nCreate a dynamic session per user via API (see `create_checkout.py` below). More control, supports pre-filling email, adding metadata.\n\n---\n\n### Step 2: `payment_server.py` (FastAPI, runs on port 8001)\n\n```python\n\"\"\"\nUnified payment webhook server.\nHandles: Stripe webhooks + Telegram Stars pre_checkout_query + successful_payment\nRun: uvicorn payment_server:app --host 0.0.0.0 --port 8001\n\"\"\"\nimport json\nimport os\nimport pathlib\nimport httpx\nfrom fastapi import FastAPI, Request, HTTPException\nimport stripe\n\napp = FastAPI()\nWORKSPACES = pathlib.Path(os.environ.get(\"WORKSPACES_DIR\", \"\u002Fworkspaces\"))\nBOT_TOKEN = os.environ[\"TELEGRAM_BOT_TOKEN\"]\nSTRIPE_WEBHOOK_SECRET = os.environ.get(\"STRIPE_WEBHOOK_SECRET\", \"\")\nstripe.api_key = os.environ.get(\"STRIPE_SECRET_KEY\", \"\")\n\nCREDIT_PACKAGES = {\n    \"price_20\":  {\"credits\": 20,  \"price_id\": \"price_xxx\"},  # replace with real Stripe price IDs\n    \"price_50\":  {\"credits\": 50,  \"price_id\": \"price_yyy\"},\n    \"price_100\": {\"credits\": 100, \"price_id\": \"price_zzz\"},\n}\n\n\ndef add_credits(user_id: str, credits: int):\n    \"\"\"Add credits to user's usage.json.\"\"\"\n    usage_file = WORKSPACES \u002F user_id \u002F \"usage.json\"\n    if usage_file.exists():\n        usage = json.loads(usage_file.read_text())\n    else:\n        usage = {\"daily_count\": 0, \"credits\": 0, \"tier\": \"free\"}\n    usage[\"credits\"] = usage.get(\"credits\", 0) + credits\n    usage_file.write_text(json.dumps(usage, indent=2))\n    return usage[\"credits\"]\n\n\ndef notify_user(user_id: str, credits_added: int, total_credits: int):\n    \"\"\"Send Telegram message to user after successful payment.\"\"\"\n    httpx.post(\n        f\"https:\u002F\u002Fapi.telegram.org\u002Fbot{BOT_TOKEN}\u002FsendMessage\",\n        json={\n            \"chat_id\": user_id,\n            \"text\": f\"✅ 充值成功！\\n\\n+{credits_added} 张图片额度\\n剩余总额度：{total_credits} 张\\n\\n直接告诉我你想要什么吧 👇\",\n        },\n        timeout=10,\n    )\n\n\n# ── Stripe Webhook ──────────────────────────────────────────────────────────\n\n@app.post(\"\u002Fwebhook\u002Fstripe\")\nasync def stripe_webhook(request: Request):\n    payload = await request.body()\n    sig = request.headers.get(\"stripe-signature\", \"\")\n\n    try:\n        event = stripe.Webhook.construct_event(payload, sig, STRIPE_WEBHOOK_SECRET)\n    except stripe.error.SignatureVerificationError:\n        raise HTTPException(status_code=400, detail=\"Invalid signature\")\n\n    if event[\"type\"] == \"checkout.session.completed\":\n        session = event[\"data\"][\"object\"]\n        user_id = session.get(\"client_reference_id\") or session.get(\"metadata\", {}).get(\"telegram_user_id\")\n        credits = int(session.get(\"metadata\", {}).get(\"credits\", 0))\n\n        if user_id and credits:\n            total = add_credits(user_id, credits)\n            notify_user(user_id, credits, total)\n\n    return {\"ok\": True}\n\n\n# ── Telegram Stars Webhook ───────────────────────────────────────────────────\n\n@app.post(\"\u002Fwebhook\u002Ftelegram\")\nasync def telegram_webhook(request: Request):\n    data = await request.json()\n\n    # Must answer pre_checkout_query within 10 seconds\n    pq = data.get(\"pre_checkout_query\")\n    if pq:\n        httpx.post(\n            f\"https:\u002F\u002Fapi.telegram.org\u002Fbot{BOT_TOKEN}\u002FanswerPreCheckoutQuery\",\n            json={\"pre_checkout_query_id\": pq[\"id\"], \"ok\": True},\n            timeout=8,\n        )\n        return {\"ok\": True}\n\n    msg = data.get(\"message\", {})\n    payment = msg.get(\"successful_payment\")\n    if payment:\n        # payload format: \"credits_20_697391377\"\n        parts = payment.get(\"invoice_payload\", \"\").split(\"_\")\n        if len(parts) == 3 and parts[0] == \"credits\":\n            credits = int(parts[1])\n            user_id = parts[2]\n            total = add_credits(user_id, credits)\n            notify_user(user_id, credits, total)\n\n    return {\"ok\": True}\n```\n\n---\n\n### Step 3: `buy_credits.py` (agent calls this to send payment options)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nSend payment options to user when quota is exhausted.\nUsage: python3 buy_credits.py \u003Cuser_id> [stars|stripe|both]\n\"\"\"\nimport sys\nimport os\nimport httpx\n\nBOT_TOKEN = os.environ[\"TELEGRAM_BOT_TOKEN\"]\nUSER_ID = sys.argv[1]\nMODE = sys.argv[2] if len(sys.argv) > 2 else \"both\"\n\n# Replace these with your actual Stripe Payment Links\nSTRIPE_LINKS = {\n    \"20\":  \"https:\u002F\u002Fbuy.stripe.com\u002Fxxx?client_reference_id=\" + USER_ID,\n    \"50\":  \"https:\u002F\u002Fbuy.stripe.com\u002Fyyy?client_reference_id=\" + USER_ID,\n    \"100\": \"https:\u002F\u002Fbuy.stripe.com\u002Fzzz?client_reference_id=\" + USER_ID,\n}\n\n# Stars packages (currency XTR, 1 star ≈ $0.013 received by developer)\nSTARS_PACKAGES = {\n    \"20\":  {\"stars\": 200, \"credits\": 20},   # ~$2.60 retail → ~$1.69 to you\n    \"50\":  {\"stars\": 450, \"credits\": 50},   # ~$5.85 retail → ~$3.80 to you\n    \"100\": {\"stars\": 800, \"credits\": 100},  # ~$10.40 retail → ~$6.76 to you\n}\n\nif MODE in (\"stripe\", \"both\"):\n    # Send external link buttons\n    httpx.post(\n        f\"https:\u002F\u002Fapi.telegram.org\u002Fbot{BOT_TOKEN}\u002FsendMessage\",\n        json={\n            \"chat_id\": USER_ID,\n            \"text\": \"今天的免费额度用完了！\\n\\n💳 用银行卡充值（推荐）：\",\n            \"reply_markup\": {\n                \"inline_keyboard\": [\n                    [{\"text\": \"20张 $2.00\", \"url\": STRIPE_LINKS[\"20\"]},\n                     {\"text\": \"50张 $4.00\", \"url\": STRIPE_LINKS[\"50\"]}],\n                    [{\"text\": \"100张 $7.00 🔥\", \"url\": STRIPE_LINKS[\"100\"]}],\n                ]\n            },\n        },\n        timeout=10,\n    )\n\nif MODE in (\"stars\", \"both\"):\n    # Send Stars invoice for the most popular package\n    httpx.post(\n        f\"https:\u002F\u002Fapi.telegram.org\u002Fbot{BOT_TOKEN}\u002FsendInvoice\",\n        json={\n            \"chat_id\": USER_ID,\n            \"title\": \"50张图片额度\",\n            \"description\": \"购买50张图片生成额度，不过期\",\n            \"payload\": f\"credits_50_{USER_ID}\",\n            \"currency\": \"XTR\",\n            \"prices\": [{\"label\": \"50张图片\", \"amount\": STARS_PACKAGES[\"50\"][\"stars\"]}],\n        },\n        timeout=10,\n    )\n\nprint(\"PAYMENT_OPTIONS_SENT\")\n```\n\n---\n\n### Step 4: `entrypoint.sh` additions\n\n```bash\n# Install dependencies\npip3 install fastapi uvicorn stripe httpx\n\n# Start payment server in background\nuvicorn payment_server:app --host 0.0.0.0 --port 8001 &\n\n# Register Telegram webhook for Stars payments\npython3 - \u003C\u003C 'EOF'\nimport httpx, os\ntoken = os.environ[\"TELEGRAM_BOT_TOKEN\"]\n# Replace with your server's public IP\u002Fdomain\nserver = os.environ.get(\"SERVER_PUBLIC_URL\", \"https:\u002F\u002Fyour-server.com\")\nhttpx.post(\n    f\"https:\u002F\u002Fapi.telegram.org\u002Fbot{token}\u002FsetWebhook\",\n    json={\"url\": f\"{server}\u002Fwebhook\u002Ftelegram\"}\n)\nprint(\"Telegram webhook set\")\nEOF\n```\n\n### Step 5: `AGENTS.md` payment behavior\n\n```markdown\n## 付费引导（额度用完时）\n\n当 check_quota.py 输出 `allowed=false` 时：\n1. 如果本次请求已生成图片，先发出图片\n2. 运行：exec python3 \u002Fworkspaces-shared\u002Fskills\u002Fpayments\u002Fbuy_credits.py {PEER_ID} both\n3. 不要多说，让按钮说话\n\n严格禁止：\n- 不要解释定价逻辑\n- 不要提到 Stripe、Stars 是什么\n- 不要说「我无法生成了」——说「今天的免费额度用完了」\n\n文字聊天、问题回答即使额度=0也继续正常进行。只有生成图片时才触发付费引导。\n```\n\n---\n\n## Stripe Setup Checklist\n\n```\n□ Stripe 账号创建并验证身份（需要护照\u002FID）\n□ 创建三个 Payment Links（20\u002F50\u002F100张）\n□ 每个 Product 的 metadata 里加 credits 字段（如 credits=20）\n□ Webhook endpoint 添加：https:\u002F\u002Fyour-server\u002Fwebhook\u002Fstripe\n□ 选择监听事件：checkout.session.completed\n□ 复制 Webhook Signing Secret → 填入 STRIPE_WEBHOOK_SECRET env var\n□ 测试：用 Stripe test card 4242 4242 4242 4242 付款，确认 credits 更新\n```\n\n---\n\n## Pricing Strategy\n\nGoal: cover API cost + profit. Using Seedream ($0.03\u002Fimage):\n\n| Package | Price | Stripe到手 | 成本(Seedream) | 利润 | 利润率 |\n|---------|-------|------------|----------------|------|--------|\n| 20张    | $2.00 | $1.41      | $0.60          | $0.81 | 57% |\n| 50张    | $4.00 | $3.41      | $1.50          | $1.91 | 56% |\n| 100张   | $7.00 | $6.41      | $3.00          | $3.41 | 53% |\n\nUsing NB2 ($0.08\u002Fimage) — not recommended for paid packages, only free tier:\n\n| Package | Price | Stripe到手 | 成本(NB2) | 利润 | 利润率 |\n|---------|-------|------------|-----------|------|--------|\n| 20张    | $2.00 | $1.41      | $1.60     | **-$0.19** | **亏损** |\n| 50张    | $4.00 | $3.41      | $4.00     | **-$0.59** | **亏损** |\n\n**结论：付费包只用 Seedream。NB2 限制在免费试用。**\n\n---\n\n## Soft Paywall UX Rules\n\nFrom `bot-ux-checklist.md`:\n\n```\n✅ 先出图，再提示额度用完（软 paywall）\n✅ 渐进式提示：「还剩2张」→「最后1张」→「用完了，充值继续」\n✅ 即使额度=0，文字对话继续正常进行\n✅ 付款成功后立即发确认消息（payment_server 里已实现）\n❌ 不要在生成前弹付款提示\n❌ 不要重复推送付款按钮\n```\n\n---\n\n## Known Issues \u002F Gotchas\n\n1. **Stripe Payment Links 无法动态注入 metadata** — 用 `client_reference_id` 传 user ID。如果需要 credits 数量，在 Stripe Dashboard 的 Product metadata 里提前设好，webhook 里从 `line_items` 读取。\n\n2. **Telegram webhook 和 OpenClaw 不能共用同一个 port** — OpenClaw 用 8815，payment server 用 8001，分开。\n\n3. **setWebhook 会覆盖 OpenClaw 的 Telegram 轮询** — 如果 OpenClaw 用 long-polling（默认），设了 webhook 后 OpenClaw 会收不到消息。解决：OpenClaw 配置 webhook 模式，或者 payment server 用独立 bot token（推荐创建一个独立的 @YourBotPaymentBot 专门处理支付回调）。\n\n4. **中国用户** — Stripe 支持中国发行的 Visa\u002FMastercard，但不支持支付宝\u002F微信支付（需要 Stripe China 账号）。如果主要是中国用户：考虑用 TON 或接入 Creem（支持更多支付方式）。\n\n5. **Stars 21天 hold** — 提现要等21天，且只能提 TON。Stars 做为 iOS 合规保底，不作为主要收入。\n\n---\n\n## Author\n\n**[Canlah AI](https:\u002F\u002Fcanlah.ai)** — Run performance marketing without breaking your brand.\n\n- GitHub: [github.com\u002FPHY041](https:\u002F\u002Fgithub.com\u002FPHY041)\n- All Skills: [clawhub.ai\u002FPHY041](https:\u002F\u002Fclawhub.ai\u002FPHY041)\n","# Telegram Bot Payments — Paywall Implementation\n\nAdd paid credits to any OpenClaw Telegram bot. Supports three payment methods with a hybrid approach to maximize developer margin.\n\n## When to Use\n\n- Adding a paywall to an OpenClaw Telegram bot\n- Implementing per-image or per-use quota with paid top-ups\n- Choosing the right payment method for your user base\n- Setting up Stripe, Telegram Stars, or TON payments\n\n---\n\n## Payment Method Decision\n\n| Method | User pays $10 → You receive | When to use |\n|--------|------------------------------|-------------|\n| **Stripe (external link)** | **~$9.41 (94%)** | Android, Desktop, Web users — best margin |\n| **TON Wallet Pay** | **~$9.90 (99%)** | Crypto-savvy users — best margin, zero fees |\n| **Telegram Stars** | **~$6.50 (65%)** | iOS users ONLY — legally required for in-app digital goods on iOS |\n\n### Why NOT Stars-only\n\nStars = two fees back-to-back:\n```\nUser pays $10\n  → Apple\u002FGoogle takes ~30% (mandatory IAP)\n  → Telegram takes ~5%\n  → You receive ~$6.50\n```\n\nFor image generation at $0.03–$0.08\u002Fimage, Stars makes most packages unprofitable.\n\n### The Hybrid Rule\n\n```\nUser on iOS?   → Stars (no choice — Apple policy)\nUser on Android\u002FDesktop\u002FWeb? → Stripe external link (9x better margin)\n```\n\nTelegram does NOT currently ban external payment links. Risk is low-medium.\nIf enforced in future, fall back to Stars or TON.\n\n---\n\n## Architecture\n\n```\nQuota exhausted\n    ↓\nAgent detects (check_quota.py returns allowed=false)\n    ↓\nAgent sends payment options message + buttons\n    ↓\n    ├─ [Pay with Card ⭐] → Stripe Payment Link (external browser)\n    ├─ [Pay with Stars ⭐] → Telegram Stars invoice (iOS compliance)\n    └─ [Pay with TON 💎] → TON Wallet Pay link (optional)\n    ↓\nPayment completed → Stripe\u002FStars webhook fires\n    ↓\npayment_server.py updates \u002Fworkspaces\u002F{USER_ID}\u002Fusage.json credits\n    ↓\nUser continues generating\n```\n\n---\n\n## Implementation: Stripe External Link (Primary Method)\n\n### Step 1: Create Stripe Payment Links\n\nIn Stripe Dashboard → Payment Links → Create:\n\n```\nProduct: \"20 Image Credits\"   Price: $2.00  → copy link e.g. https:\u002F\u002Fbuy.stripe.com\u002Fxxx\nProduct: \"50 Image Credits\"   Price: $4.00  → copy link e.g. https:\u002F\u002Fbuy.stripe.com\u002Fyyy\nProduct: \"100 Image Credits\"  Price: $7.00  → copy link e.g. https:\u002F\u002Fbuy.stripe.com\u002Fzzz\n```\n\n**Critical:** Add a metadata field `telegram_user_id` — but Payment Links don't support dynamic metadata natively. Two options:\n\n**Option A (Simple) — URL with client_reference_id:**\nStripe Payment Links support `?client_reference_id=USER_ID` as a query param. Append the user's Telegram ID:\n```\nhttps:\u002F\u002Fbuy.stripe.com\u002Fxxx?client_reference_id=697391377\n```\nThe `client_reference_id` appears in the webhook payload.\n\n**Option B (Proper) — Stripe Checkout Session:**\nCreate a dynamic session per user via API (see `create_checkout.py` below). More control, supports pre-filling email, adding metadata.\n\n---\n\n### Step 2: `payment_server.py` (FastAPI, runs on port 8001)\n\n```python\n\"\"\"\nUnified payment webhook server.\nHandles: Stripe webhooks + Telegram Stars pre_checkout_query + successful_payment\nRun: uvicorn payment_server:app --host 0.0.0.0 --port 8001\n\"\"\"\nimport json\nimport os\nimport pathlib\nimport httpx\nfrom fastapi import FastAPI, Request, HTTPException\nimport stripe\n\napp = FastAPI()\nWORKSPACES = pathlib.Path(os.environ.get(\"WORKSPACES_DIR\", \"\u002Fworkspaces\"))\nBOT_TOKEN = os.environ[\"TELEGRAM_BOT_TOKEN\"]\nSTRIPE_WEBHOOK_SECRET = os.environ.get(\"STRIPE_WEBHOOK_SECRET\", \"\")\nstripe.api_key = os.environ.get(\"STRIPE_SECRET_KEY\", \"\")\n\nCREDIT_PACKAGES = {\n    \"price_20\":  {\"credits\": 20,  \"price_id\": \"price_xxx\"},  # replace with real Stripe price IDs\n    \"price_50\":  {\"credits\": 50,  \"price_id\": \"price_yyy\"},\n    \"price_100\": {\"credits\": 100, \"price_id\": \"price_zzz\"},\n}\n\n\ndef add_credits(user_id: str, credits: int):\n    \"\"\"Add credits to user's usage.json.\"\"\"\n    usage_file = WORKSPACES \u002F user_id \u002F \"usage.json\"\n    if usage_file.exists():\n        usage = json.loads(usage_file.read_text())\n    else:\n        usage = {\"daily_count\": 0, \"credits\": 0, \"tier\": \"free\"}\n    usage[\"credits\"] = usage.get(\"credits\", 0) + credits\n    usage_file.write_text(json.dumps(usage, indent=2))\n    return usage[\"credits\"]\n\n\ndef notify_user(user_id: str, credits_added: int, total_credits: int):\n    \"\"\"Send Telegram message to user after successful payment.\"\"\"\n    httpx.post(\n        f\"https:\u002F\u002Fapi.telegram.org\u002Fbot{BOT_TOKEN}\u002FsendMessage\",\n        json={\n            \"chat_id\": user_id,\n            \"text\": f\"✅ 充值成功！\\n\\n+{credits_added} 张图片额度\\n剩余总额度：{total_credits} 张\\n\\n直接告诉我你想要什么吧 👇\",\n        },\n        timeout=10,\n    )\n\n\n# ── Stripe Webhook ──────────────────────────────────────────────────────────\n\n@app.post(\"\u002Fwebhook\u002Fstripe\")\nasync def stripe_webhook(request: Request):\n    payload = await request.body()\n    sig = request.headers.get(\"stripe-signature\", \"\")\n\n    try:\n        event = stripe.Webhook.construct_event(payload, sig, STRIPE_WEBHOOK_SECRET)\n    except stripe.error.SignatureVerificationError:\n        raise HTTPException(status_code=400, detail=\"Invalid signature\")\n\n    if event[\"type\"] == \"checkout.session.completed\":\n        session = event[\"data\"][\"object\"]\n        user_id = session.get(\"client_reference_id\") or session.get(\"metadata\", {}).get(\"telegram_user_id\")\n        credits = int(session.get(\"metadata\", {}).get(\"credits\", 0))\n\n        if user_id and credits:\n            total = add_credits(user_id, credits)\n            notify_user(user_id, credits, total)\n\n    return {\"ok\": True}\n\n\n# ── Telegram Stars Webhook ───────────────────────────────────────────────────\n\n@app.post(\"\u002Fwebhook\u002Ftelegram\")\nasync def telegram_webhook(request: Request):\n    data = await request.json()\n\n    # Must answer pre_checkout_query within 10 seconds\n    pq = data.get(\"pre_checkout_query\")\n    if pq:\n        httpx.post(\n            f\"https:\u002F\u002Fapi.telegram.org\u002Fbot{BOT_TOKEN}\u002FanswerPreCheckoutQuery\",\n            json={\"pre_checkout_query_id\": pq[\"id\"], \"ok\": True},\n            timeout=8,\n        )\n        return {\"ok\": True}\n\n    msg = data.get(\"message\", {})\n    payment = msg.get(\"successful_payment\")\n    if payment:\n        # payload format: \"credits_20_697391377\"\n        parts = payment.get(\"invoice_payload\", \"\").split(\"_\")\n        if len(parts) == 3 and parts[0] == \"credits\":\n            credits = int(parts[1])\n            user_id = parts[2]\n            total = add_credits(user_id, credits)\n            notify_user(user_id, credits, total)\n\n    return {\"ok\": True}\n```\n\n---\n\n### Step 3: `buy_credits.py` (agent calls this to send payment options)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nSend payment options to user when quota is exhausted.\nUsage: python3 buy_credits.py \u003Cuser_id> [stars|stripe|both]\n\"\"\"\nimport sys\nimport os\nimport httpx\n\nBOT_TOKEN = os.environ[\"TELEGRAM_BOT_TOKEN\"]\nUSER_ID = sys.argv[1]\nMODE = sys.argv[2] if len(sys.argv) > 2 else \"both\"\n\n# Replace these with your actual Stripe Payment Links\nSTRIPE_LINKS = {\n    \"20\":  \"https:\u002F\u002Fbuy.stripe.com\u002Fxxx?client_reference_id=\" + USER_ID,\n    \"50\":  \"https:\u002F\u002Fbuy.stripe.com\u002Fyyy?client_reference_id=\" + USER_ID,\n    \"100\": \"https:\u002F\u002Fbuy.stripe.com\u002Fzzz?client_reference_id=\" + USER_ID,\n}\n\n# Stars packages (currency XTR, 1 star ≈ $0.013 received by developer)\nSTARS_PACKAGES = {\n    \"20\":  {\"stars\": 200, \"credits\": 20},   # ~$2.60 retail → ~$1.69 to you\n    \"50\":  {\"stars\": 450, \"credits\": 50},   # ~$5.85 retail → ~$3.80 to you\n    \"100\": {\"stars\": 800, \"credits\": 100},  # ~$10.40 retail → ~$6.76 to you\n}\n\nif MODE in (\"stripe\", \"both\"):\n    # Send external link buttons\n    httpx.post(\n        f\"https:\u002F\u002Fapi.telegram.org\u002Fbot{BOT_TOKEN}\u002FsendMessage\",\n        json={\n            \"chat_id\": USER_ID,\n            \"text\": \"今天的免费额度用完了！\\n\\n💳 用银行卡充值（推荐）：\",\n            \"reply_markup\": {\n                \"inline_keyboard\": [\n                    [{\"text\": \"20张 $2.00\", \"url\": STRIPE_LINKS[\"20\"]},\n                     {\"text\": \"50张 $4.00\", \"url\": STRIPE_LINKS[\"50\"]}],\n                    [{\"text\": \"100张 $7.00 🔥\", \"url\": STRIPE_LINKS[\"100\"]}],\n                ]\n            },\n        },\n        timeout=10,\n    )\n\nif MODE in (\"stars\", \"both\"):\n    # Send Stars invoice for the most popular package\n    httpx.post(\n        f\"https:\u002F\u002Fapi.telegram.org\u002Fbot{BOT_TOKEN}\u002FsendInvoice\",\n        json={\n            \"chat_id\": USER_ID,\n            \"title\": \"50张图片额度\",\n            \"description\": \"购买50张图片生成额度，不过期\",\n            \"payload\": f\"credits_50_{USER_ID}\",\n            \"currency\": \"XTR\",\n            \"prices\": [{\"label\": \"50张图片\", \"amount\": STARS_PACKAGES[\"50\"][\"stars\"]}],\n        },\n        timeout=10,\n    )\n\nprint(\"PAYMENT_OPTIONS_SENT\")\n```\n\n---\n\n### Step 4: `entrypoint.sh` additions\n\n```bash\n# Install dependencies\npip3 install fastapi uvicorn stripe httpx\n\n# Start payment server in background\nuvicorn payment_server:app --host 0.0.0.0 --port 8001 &\n\n# Register Telegram webhook for Stars payments\npython3 - \u003C\u003C 'EOF'\nimport httpx, os\ntoken = os.environ[\"TELEGRAM_BOT_TOKEN\"]\n# Replace with your server's public IP\u002Fdomain\nserver = os.environ.get(\"SERVER_PUBLIC_URL\", \"https:\u002F\u002Fyour-server.com\")\nhttpx.post(\n    f\"https:\u002F\u002Fapi.telegram.org\u002Fbot{token}\u002FsetWebhook\",\n    json={\"url\": f\"{server}\u002Fwebhook\u002Ftelegram\"}\n)\nprint(\"Telegram webhook set\")\nEOF\n```\n\n### Step 5: `AGENTS.md` payment behavior\n\n```markdown\n## 付费引导（额度用完时）\n\n当 check_quota.py 输出 `allowed=false` 时：\n1. 如果本次请求已生成图片，先发出图片\n2. 运行：exec python3 \u002Fworkspaces-shared\u002Fskills\u002Fpayments\u002Fbuy_credits.py {PEER_ID} both\n3. 不要多说，让按钮说话\n\n严格禁止：\n- 不要解释定价逻辑\n- 不要提到 Stripe、Stars 是什么\n- 不要说「我无法生成了」——说「今天的免费额度用完了」\n\n文字聊天、问题回答即使额度=0也继续正常进行。只有生成图片时才触发付费引导。\n```\n\n---\n\n## Stripe Setup Checklist\n\n```\n□ Stripe 账号创建并验证身份（需要护照\u002FID）\n□ 创建三个 Payment Links（20\u002F50\u002F100张）\n□ 每个 Product 的 metadata 里加 credits 字段（如 credits=20）\n□ Webhook endpoint 添加：https:\u002F\u002Fyour-server\u002Fwebhook\u002Fstripe\n□ 选择监听事件：checkout.session.completed\n□ 复制 Webhook Signing Secret → 填入 STRIPE_WEBHOOK_SECRET env var\n□ 测试：用 Stripe test card 4242 4242 4242 4242 付款，确认 credits 更新\n```\n\n---\n\n## Pricing Strategy\n\nGoal: cover API cost + profit. Using Seedream ($0.03\u002Fimage):\n\n| Package | Price | Stripe到手 | 成本(Seedream) | 利润 | 利润率 |\n|---------|-------|------------|----------------|------|--------|\n| 20张    | $2.00 | $1.41      | $0.60          | $0.81 | 57% |\n| 50张    | $4.00 | $3.41      | $1.50          | $1.91 | 56% |\n| 100张   | $7.00 | $6.41      | $3.00          | $3.41 | 53% |\n\nUsing NB2 ($0.08\u002Fimage) — not recommended for paid packages, only free tier:\n\n| Package | Price | Stripe到手 | 成本(NB2) | 利润 | 利润率 |\n|---------|-------|------------|-----------|------|--------|\n| 20张    | $2.00 | $1.41      | $1.60     | **-$0.19** | **亏损** |\n| 50张    | $4.00 | $3.41      | $4.00     | **-$0.59** | **亏损** |\n\n**结论：付费包只用 Seedream。NB2 限制在免费试用。**\n\n---\n\n## Soft Paywall UX Rules\n\nFrom `bot-ux-checklist.md`:\n\n```\n✅ 先出图，再提示额度用完（软 paywall）\n✅ 渐进式提示：「还剩2张」→「最后1张」→「用完了，充值继续」\n✅ 即使额度=0，文字对话继续正常进行\n✅ 付款成功后立即发确认消息（payment_server 里已实现）\n❌ 不要在生成前弹付款提示\n❌ 不要重复推送付款按钮\n```\n\n---\n\n## Known Issues \u002F Gotchas\n\n1. **Stripe Payment Links 无法动态注入 metadata** — 用 `client_reference_id` 传 user ID。如果需要 credits 数量，在 Stripe Dashboard 的 Product metadata 里提前设好，webhook 里从 `line_items` 读取。\n\n2. **Telegram webhook 和 OpenClaw 不能共用同一个 port** — OpenClaw 用 8815，payment server 用 8001，分开。\n\n3. **setWebhook 会覆盖 OpenClaw 的 Telegram 轮询** — 如果 OpenClaw 用 long-polling（默认），设了 webhook 后 OpenClaw 会收不到消息。解决：OpenClaw 配置 webhook 模式，或者 payment server 用独立 bot token（推荐创建一个独立的 @YourBotPaymentBot 专门处理支付回调）。\n\n4. **中国用户** — Stripe 支持中国发行的 Visa\u002FMastercard，但不支持支付宝\u002F微信支付（需要 Stripe China 账号）。如果主要是中国用户：考虑用 TON 或接入 Creem（支持更多支付方式）。\n\n5. **Stars 21天 hold** — 提现要等21天，且只能提 TON。Stars 做为 iOS 合规保底，不作为主要收入。\n\n---\n\n## Author\n\n**[Canlah AI](https:\u002F\u002Fcanlah.ai)** — Run performance marketing without breaking your brand.\n\n- GitHub: [github.com\u002FPHY041](https:\u002F\u002Fgithub.com\u002FPHY041)\n- All Skills: [clawhub.ai\u002FPHY041](https:\u002F\u002Fclawhub.ai\u002FPHY041)\n",{"name":5,"license":15,"homepage":24,"metadata":25,"description":7,"allowed-tools":35,"user-invocable":36},"https:\u002F\u002Fcanlah.ai",{"tags":26,"author":33,"version":34},[27,28,29,30,31,32],"telegram","payments","stripe","stars","openclaw","monetization","Canlah AI","1.0.2","Bash Read Edit Write Grep Glob Agent",true,"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fp\u002Fphy-telegram-bot-payments",0,"https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":47,"prompt":57,"zipAvailable":36},[48,51,54],{"tool":49,"command":50},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill telegram-bot-payments",{"tool":52,"command":53},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill telegram-bot-payments",{"tool":55,"command":56},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill telegram-bot-payments","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fp\u002Fphy-telegram-bot-payments\u002FSKILL.md",[],[60,67,74,81,88,95],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":19},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]