Skip to content

A lightweight Cloudflare Worker that forwards Adapty subscription events to Telegram in real-time

Notifications You must be signed in to change notification settings

egebese/Adapty-Notifications-for-Telegram

Repository files navigation

🔔 Adapty Telegram Webhook

A lightweight Cloudflare Worker that forwards Adapty subscription events to Telegram in real-time

License: MIT Cloudflare Workers Telegram Bot API Deploy to Cloudflare Workers

FeaturesQuick StartConfigurationDocumentationSupport


✨ Features

🚀 Performance

  • Real-time notifications - Instant webhook delivery
  • Global edge network - Low latency worldwide
  • Free hosting - 100K requests/day on Cloudflare
  • Zero maintenance - Serverless architecture

🔒 Security & Reliability

  • Bearer token auth - Secure webhook validation
  • Production-only mode - Auto-filters sandbox events
  • Encrypted secrets - Cloudflare Workers KV
  • 100% uptime - Cloudflare infrastructure

📊 Rich Data

  • Detailed metrics - Revenue, pricing, conversions
  • Multi-currency support - Local + USD pricing
  • Paywall tracking - A/B testing insights
  • HTML formatting - Beautiful Telegram messages

⚙️ Customization

  • Event filtering - Choose which events to track
  • Custom domains - Use your own domain
  • Message templates - Fully customizable format
  • Easy deployment - One command setup

📋 Supported Events

Emoji Event Type Description Use Case
🎉 subscription_started New subscription started Track new customers
🔄 subscription_renewed Subscription renewed Monitor retention
⚠️ subscription_renewal_cancelled Auto-renewal cancelled Identify churn risk
subscription_renewal_reactivated Auto-renewal reactivated Track win-backs
💰 non_subscription_purchase One-time purchase (credits, IAPs) Monitor transactions

📸 Screenshots

See what you'll receive in Telegram:

New Subscription Started
🎉 New Subscription
Subscription Renewed
🔄 Subscription Renewed
Auto-renewal Cancelled
⚠️ Auto-renewal Cancelled

Rich, detailed notifications with pricing, revenue, location, and more!

📦 Prerequisites

Required

Knowledge

  • Basic command line usage
  • How to create Telegram bots
  • Understanding of webhooks
  • Familiarity with environment variables

🚀 Quick Start

1. Clone and Install

git clone https://github.com/egebese/Adapty-Notifications-for-Telegram.git
cd Adapty-Notifications-for-Telegram
npm install

2. Create a Telegram Bot

  1. Open Telegram and search for @BotFather
  2. Send /newbot command
  3. Follow the instructions to create your bot
  4. Save the Bot Token (looks like 123456789:ABCdefGHIjklMNOpqrsTUVwxyz)

3. Get Your Telegram Chat ID

Option A: Personal notifications

  1. Search for @userinfobot on Telegram
  2. Start a chat with it
  3. It will reply with your Chat ID (looks like 123456789)

Option B: Group notifications

  1. Create a group and add your bot to it
  2. Send a message in the group
  3. Visit https://api.telegram.org/bot<BOT_TOKEN>/getUpdates
  4. Find the chat.id in the response (negative number for groups)

4. Generate an Auth Token

# macOS/Linux
openssl rand -base64 32

# Windows (PowerShell)
[Convert]::ToBase64String((1..32 | ForEach-Object { Get-Random -Maximum 256 }))

Save this token - you'll need it for both the worker and Adapty.

5. Configure Secrets

Set your secrets in Cloudflare Workers (they'll be prompted):

npx wrangler secret put TELEGRAM_BOT_TOKEN
# Paste your bot token from BotFather

npx wrangler secret put TELEGRAM_CHAT_ID
# Paste your chat ID

npx wrangler secret put WEBHOOK_AUTH_TOKEN
# Paste the auth token you generated

6. Deploy to Cloudflare Workers

npm run deploy

After deployment, you'll get a URL like:

https://adapty-telegram-webhook.your-subdomain.workers.dev

Save this URL! You'll need it for Adapty configuration.

7. Configure Adapty Webhook

Now connect your Cloudflare Worker to Adapty.

Step-by-step:

  1. Open Adapty Dashboard

  2. Toggle Webhook On

    • Enable the webhook integration
  3. Configure Production Endpoint

    • Production endpoint URL: https://your-worker.workers.dev/webhook
      • Replace with your actual worker URL from step 6
    • Authorization header value: Bearer YOUR_AUTH_TOKEN
      • Use the same token you set with wrangler secret put
  4. Configure Sandbox Endpoint (Optional but recommended)

    • Sandbox endpoint URL: https://your-worker.workers.dev/webhook (same URL)
    • Authorization header value: Bearer YOUR_AUTH_TOKEN (same token)
    • Note: Sandbox events will be filtered by the worker (no Telegram notifications)
  5. Select Event Types

    • Under Events names section, enable the events you want to track:
      • subscription_started - New subscriptions
      • subscription_renewed - Renewals
      • subscription_renewal_cancelled - Cancellations
      • subscription_renewal_reactivated - Reactivations
      • non_subscription_purchase - One-time purchases (if applicable)
  6. Additional Options (Optional)

    • Exclude historical events - Recommended to avoid sending old events
    • You can leave other options unchecked unless you need them
  7. Save Configuration

    • Click Save at the bottom
📝 Example Configuration
Production endpoint URL:
https://adapty-telegram-webhook.your-subdomain.workers.dev/webhook

Authorization header value for production endpoint:
Bearer ABC123YourSecretTokenHere

Sandbox endpoint URL:
https://adapty-telegram-webhook.your-subdomain.workers.dev/webhook

Authorization header value for sandbox endpoint:
Bearer ABC123YourSecretTokenHere

Events enabled:
✓ subscription_started
✓ subscription_renewed
✓ subscription_renewal_cancelled
✓ subscription_renewal_reactivated
✓ non_subscription_purchase

⚠️ Important: Make sure the Bearer token in Adapty exactly matches the WEBHOOK_AUTH_TOKEN you set in Cloudflare Workers!

8. Test the Integration

Set your worker URL and auth token:

export WEBHOOK_URL=https://your-worker.workers.dev/webhook
export WEBHOOK_AUTH_TOKEN=your-auth-token-here

Then run the test:

# Quick test (single event)
./test-webhook-simple.sh

# Full test suite (all events + security tests)
./test-webhook.sh

You should receive notifications in your Telegram chat! 🎉

⚙️ Configuration

Custom Domain (Optional)

To use a custom domain instead of *.workers.dev:

  1. Add your domain to Cloudflare
  2. Edit wrangler.toml:
[[routes]]
pattern = "webhook.yourdomain.com/*"
zone_name = "yourdomain.com"
  1. Deploy: npm run deploy
  2. Update Adapty webhook URL to your custom domain

Environment Filtering

By default, sandbox events are automatically filtered and won't send Telegram notifications. This prevents test transactions from cluttering your notifications.

To receive sandbox notifications, edit src/index.js around line 103:

if (environment === 'Sandbox') {
  // Comment out this entire block to receive sandbox notifications
}

Event Filtering

To track different events, edit the TRACKED_EVENTS array in src/index.js:

const TRACKED_EVENTS = [
  'subscription_started',
  'subscription_renewed',
  'subscription_renewal_cancelled',
  'subscription_renewal_reactivated',
  'non_subscription_purchase'
];

See Adapty Event Types for all available events.

Message Customization

Edit the formatTelegramMessage() function in src/index.js to customize notification formatting.

🛠️ Development

Command Description
npm run dev 🔥 Run locally with hot reload
npm run tail 📊 View live production logs
npm run deploy 🚀 Deploy to Cloudflare Workers
./test-webhook-simple.sh ✅ Quick single event test
./test-webhook.sh 🧪 Full test suite (8 tests)

💬 Message Format

Each notification includes comprehensive data from Adapty webhooks, beautifully formatted in HTML:

Example Telegram Notification

📝 Fields Included

📊 Subscription Details

  • Product ID & base plan
  • Access level granted
  • Store type (App Store, Play Store, Stripe)
  • User's country

💰 Financial Data

  • Price in local currency
  • USD conversion (if different)
  • Net revenue (after platform cuts)
  • Consecutive payment count

⏰ Timing Information

  • Event timestamp
  • Subscription expiry date
  • Renewal information

🎯 Analytics

  • Paywall name (A/B testing)
  • Environment (Production/Sandbox)
  • Profile & Customer IDs

Note: Not all fields may be present in every webhook - only available data is shown.

🔌 API Endpoints

Endpoint Method Auth Required Description
/health GET ❌ No Health check with configuration status
/webhook POST ✅ Yes (Bearer) Main webhook endpoint for Adapty events
/* OPTIONS ❌ No CORS preflight handling

🔍 Troubleshooting

Not receiving notifications?

  1. Check Adapty Event Feed: Dashboard → Event Feed to see if events are being sent
  2. View worker logs: npm run tail
  3. Test health endpoint: curl https://your-worker.workers.dev/health
  4. Verify secrets: Health endpoint shows boolean flags for each secret
  5. Check bot permissions: Make sure you've sent /start to your bot

Authorization errors?

  1. Token mismatch: Ensure Adapty's Bearer token matches your WEBHOOK_AUTH_TOKEN
  2. Check logs: npm run tail shows received vs. expected token (first 10 chars)
  3. Verify format: Header must be Authorization: Bearer YOUR_TOKEN

Bot not sending messages?

  1. Start conversation: Send /start to your bot first
  2. Verify token: Check TELEGRAM_BOT_TOKEN is correct
  3. Check chat ID: Ensure TELEGRAM_CHAT_ID is correct (use @userinfobot)
  4. Group permissions: If using a group, ensure bot has send message permissions

Testing with real Adapty events

Make a test purchase in your app to trigger real events. Remember:

  • Sandbox purchases won't send notifications (by design)
  • Production purchases will send notifications
  • Check worker logs with npm run tail to see what's happening

💰 Cost

Service Free Tier Paid Tier Typical Usage
Cloudflare Workers 100,000 requests/day $5/month for 10M requests ~1,000-5,000/day
Telegram Bot API Unlimited messages Always free Unlimited
Total $0/month for most apps 🎉

🔐 Security

✅ Implemented

  • Bearer token authorization
  • Encrypted secrets (Cloudflare KV)
  • CORS headers configured
  • Rate limiting (Cloudflare)
  • Input validation
  • Error handling (no data leaks)

⚠️ Best Practices

  • Rotate auth tokens regularly
  • Use strong random tokens (32+ bytes)
  • Never commit .env file
  • Monitor logs for suspicious activity
  • Use custom domains with HTTPS
  • Review Adapty webhook IPs

📚 Resources

📖 Documentation

🔗 Related Projects

🤝 Contributing

Contributions are welcome! Here's how you can help:

🐛 Report Bugs Found a bug? Open an issue with:

  • Steps to reproduce
  • Expected behavior
  • Actual behavior
  • Logs from npm run tail

💡 Suggest Features Have an idea? Create a feature request with:

  • Use case description
  • Proposed implementation
  • Example mockups/code

🔧 Submit PRs Want to contribute code?

  1. Fork the repo
  2. Create feature branch
  3. Make your changes
  4. Test thoroughly
  5. Submit PR

📄 License

MIT License - see LICENSE file for details

💬 Support

Type Channel
🐛 Bug Reports GitHub Issues
💡 Feature Requests GitHub Issues
📖 Adapty Support Adapty Help Center
☁️ Cloudflare Support Cloudflare Community

⭐ Star History

Star History Chart


👨‍💻 Created by Ege Bese

Twitter Website GitHub

Made with ❤️ for mobile app developers

If this project helped you, consider ⭐ starring it on GitHub

About

A lightweight Cloudflare Worker that forwards Adapty subscription events to Telegram in real-time

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •