Skip to content

sachithrrra/rcat-tg

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Telegram Bot with RevenueCat Webhook Integration

A serverless Telegram bot built on Cloudflare Workers that receives RevenueCat webhook notifications and sends formatted messages to your Telegram chat.

Features

  • 🔄 Real-time purchase notifications from RevenueCat
  • 📱 Formatted Telegram messages with purchase details
  • 🔐 Secure webhook signature verification
  • ⚡ Serverless deployment on Cloudflare Workers
  • 📊 Optional event tracking with Cloudflare KV
  • 🛡️ Error handling and logging

Prerequisites

Before you begin, make sure you have:

  • Node.js (v16 or higher)
  • npm or yarn
  • A Cloudflare account
  • A Telegram account

Complete Setup Tutorial

1. Clone and Install Dependencies

# Clone the repository
git clone <your-repo-url>
cd rcat-tg

# Install dependencies
npm install

2. Set Up Telegram Bot

Step 1: Create a Telegram Bot

  1. Open Telegram and search for @BotFather
  2. Send /newbot command
  3. Follow the prompts to create your bot:
    • Choose a name for your bot (e.g., "RevenueCat Notifications")
    • Choose a username (must end with 'bot', e.g., "revenuecat_notifications_bot")
  4. BotFather will provide you with a bot token (save this for later)

Step 2: Get Your Chat ID

  1. Search for @userinfobot in Telegram
  2. Send any message to this bot
  3. It will reply with your chat ID (save this for later)

Step 3: Test Your Bot

  1. Start a conversation with your bot by searching for its username
  2. Send /start to initialize the bot
  3. The bot should respond (this ensures it can send you messages)

3. Set Up Cloudflare Workers

Step 1: Install Wrangler CLI

npm install -g wrangler

Step 2: Login to Cloudflare

wrangler login

This will open your browser to authenticate with Cloudflare.

Step 3: Configure Your Project

The wrangler.toml file is already configured, but you can modify it if needed:

name = "rcat-tg"
main = "src/index.js"
compatibility_date = "2024-01-01"

[[kv_namespaces]]
binding = "KV_BINDING"
id = "your-kv-namespace-id"

[observability.logs]
enabled = true

4. Set Up Cloudflare KV (Key-Value Storage)

Step 1: Create KV Namespace

# Create a new KV namespace
wrangler kv:namespace create "RCAT_TG_KV"

Step 2: Update wrangler.toml

Replace the KV namespace ID in your wrangler.toml with the one from the previous step:

[[kv_namespaces]]
binding = "KV_BINDING"
id = "your-actual-kv-namespace-id"

5. Set Environment Variables as Secrets

Step 1: Set Telegram Bot Token

wrangler secret put TELEGRAM_BOT_TOKEN

When prompted, enter your bot token from Step 2.

Step 2: Set Telegram Chat ID

wrangler secret put TELEGRAM_CHAT_ID

When prompted, enter your chat ID from Step 2.

Step 3: Set RevenueCat Webhook Secret

wrangler secret put REVENUECAT_WEBHOOK_SECRET

When prompted, enter your RevenueCat webhook secret (you'll get this in the next step).

6. Configure RevenueCat Webhook

Step 1: Deploy Your Worker First

# Deploy to get your worker URL
wrangler deploy

Step 2: Configure RevenueCat

  1. Log in to your RevenueCat Dashboard
  2. Navigate to your project
  3. Go to Project SettingsWebhooks
  4. Click Add Webhook
  5. Configure the webhook:
    • URL: https://rcat-tg.your-subdomain.workers.dev/webhook/revenuecat
    • Events: Select the events you want to receive (recommended: all events)
    • Secret: Generate a new secret or use an existing one
  6. Copy the webhook secret and set it as a wrangler secret:
    wrangler secret put REVENUECAT_WEBHOOK_SECRET

7. Deploy and Test

Step 1: Deploy to Production

wrangler deploy

Step 2: Test Your Setup

  1. Test Environment Variables:

    curl https://rcat-tg.your-subdomain.workers.dev/test/env
  2. Test Telegram Message:

    curl -X POST https://rcat-tg.your-subdomain.workers.dev/test/telegram \
      -H "Content-Type: application/json" \
      -d '{"message": "Test message from RevenueCat bot!"}'
  3. Test Health Check:

    curl https://rcat-tg.your-subdomain.workers.dev/health

8. Verify RevenueCat Integration

Step 1: Test Webhook (Optional)

You can test the webhook with a sample payload:

curl -X POST https://rcat-tg.your-subdomain.workers.dev/test/webhook \
  -H "Content-Type: application/json" \
  -d '{
    "event": {
      "type": "INITIAL_PURCHASE",
      "id": "test_event_123",
      "app_user_id": "user123",
      "product_id": "premium_monthly",
      "price": 9.99,
      "currency": "USD",
      "store": "app_store",
      "environment": "production",
      "purchased_at_ms": 1640995200000
    }
  }'

Step 2: Monitor Logs

View your worker logs in the Cloudflare dashboard or via wrangler:

wrangler tail

API Endpoints

Health Check

GET /health

Returns the health status of the worker.

RevenueCat Webhook

POST /webhook/revenuecat

Receives RevenueCat webhook events and sends notifications to Telegram.

Test Telegram Message

POST /test/telegram
Body: { "message": "Test message" }

Sends a test message to your configured Telegram chat.

Environment Check

GET /test/env

Returns the status of your environment variables (without exposing sensitive data).

Test Webhook (Bypasses Signature Validation)

POST /test/webhook
Body: { "event": { ... } }

For testing webhook processing without signature validation.

Supported RevenueCat Events

  • INITIAL_PURCHASE - New subscription or purchase
  • RENEWAL - Subscription renewal
  • PRODUCT_CHANGE - Subscription plan change
  • CANCELLATION - Subscription cancellation
  • UNCANCELLATION - Subscription reactivation
  • BILLING_ISSUE - Payment failed
  • SUBSCRIBER_ALIAS - User account merge
  • NON_RENEWING_PURCHASE - One-time purchase
  • SUBSCRIPTION_PAUSED - Subscription paused
  • EXPIRATION - Subscription expired
  • TRANSFER - Subscription transferred
  • REFUND - Purchase refunded
  • REFUND_REVERSED - Refund reversed
  • SUBSCRIPTION_EXTENDED - Subscription extended
  • TRIAL_STARTED - Trial period started
  • TRIAL_CANCELLED - Trial cancelled
  • TRIAL_CONVERTED - Trial converted to paid
  • INVOICE_ISSUANCE - Invoice generated
  • TEMPORARY_ENTITLEMENT_GRANT - Temporary access granted
  • VIRTUAL_CURRENCY_TRANSACTION - Virtual currency transaction
  • TEST - Test event

Development

Local Development

# Start local development server
npm run dev

The worker will be available at http://localhost:8787

Message Format

Purchase notifications include:

  • Event type with emoji
  • User ID
  • Product information
  • Price and currency
  • Transaction details
  • Store and environment
  • Renewal information
  • Expiration and purchase dates
  • Country and pricing details
  • Family sharing status
  • Offering information
  • Subscriber attributes
  • Entitlements and expiration dates
  • Timestamp

Security

  • Webhook signatures are verified using HMAC-SHA256
  • All sensitive data are stored as Cloudflare Worker secrets
  • CORS headers are configured for cross-origin requests
  • Idempotency is implemented to prevent duplicate processing

Troubleshooting

Common Issues

  1. Webhook not receiving events:

    • Check that your RevenueCat webhook URL is correct and accessible
    • Verify the webhook is enabled in RevenueCat dashboard
    • Check worker logs: wrangler tail
  2. Telegram messages not sending:

    • Verify your bot token and chat ID are correct
    • Ensure you've started a conversation with your bot
    • Check if the bot has permission to send messages
  3. Signature validation failing:

    • Ensure your webhook secret matches the one in RevenueCat
    • Check that the secret is properly set: wrangler secret list
  4. KV storage not working:

    • Verify KV namespace is properly configured in wrangler.toml
    • Check that the KV binding is available in your worker
  5. Environment variables not available:

    • Verify secrets are set: wrangler secret list
    • Check the /test/env endpoint for debugging

Debugging Commands

# View worker logs
wrangler tail

# List secrets
wrangler secret list

# Test environment
curl https://your-worker.workers.dev/test/env

# Check KV namespace
wrangler kv:namespace list

Monitoring and Analytics

Cloudflare Analytics

  • View analytics in the Cloudflare dashboard
  • Monitor request volume and response times
  • Set up alerts for errors

Custom Monitoring

  • Use the /health endpoint for uptime monitoring
  • Monitor webhook delivery in RevenueCat dashboard
  • Check Telegram message delivery manually

Cost Optimization

  • Cloudflare Workers: Free tier includes 100,000 requests/day
  • KV storage: Free tier includes 100,000 read/write operations/day
  • Monitor usage in Cloudflare dashboard

License

MIT License

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Test thoroughly
  5. Submit a pull request

Support

For issues and questions:

  1. Check the troubleshooting section above
  2. Review Cloudflare Workers documentation
  3. Check RevenueCat webhook documentation
  4. Open an issue in the repository

About

Get RevenueCat notifications on Telegram

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published