Financial analysis report chatbot agent with Gemini 2.5 Flash and Discord
This n8n template turns chat questions into structured financial reports using Gemini and posts them to a Discord channel via webhook. Ask about tickers, sectors, or theses (e.g., “NVDA long‑term outlook?” or “Gold ETF short‑term drivers?”) and receive a concise, shareable report.
Good to know
- Not financial advice: Use for insights only; verify independently.
- Model availability can vary by region. If you see “model not found,” it may be geo‑restricted.
- Costs depend on model and tokens. Check current Gemini pricing for updates.
- Discord messages are limited to ~2000 characters per post; long reports may need splitting.
- Rate limits: Discord webhooks are rate‑limited; add short waits for bursts.
How it works
- Chat Trigger collects the user’s question (public chat supported when the workflow is activated).
- Conversation Memory keeps a short window of recent messages to maintain context.
- Connect Gemini provides the LLM (e.g., gemini‑2.5‑flash‑lite) and parameters (temperature, tokens).
- Agent (agent1) applies a financial analysis System Message to produce structured insights.
- Structured Output Parser enforces a simple JSON schema: idea (one‑line thesis) + analysis (Markdown sections).
- Code formats a Discord‑ready Markdown report (title, question, executive summary, sections, disclaimer).
- Edit Fields maps the formatted report to a clean content field.
- Discord Webhook posts the final report to your channel.
How to use
- Start with the built‑in Chat Trigger: click Open chat, ask a question, and verify the Discord post.
- Replace or augment with a Cron or Webhook trigger for scheduled or programmatic runs.
- For richer context, add HTTP Request nodes (prices, news, filings) and pass summaries to the agent.
Requirements
- n8n instance with internet access
- Google AI (Gemini) API key
- Discord server with a webhook URL
Customising this workflow
- System Message: Adjust tone, depth, risk profile, and required sections (Summary, Drivers, Risks, Metrics, Next Steps, Takeaway).
- Model settings: Switch models or tune temperature/tokens in Connect Gemini.
- Schema: Extend the parser and formatter with fields like drivers[], risks[], or metrics{}.
- Formatting: Edit the Code node to change headings, emojis, disclaimers, or add timestamps.
- Operations: Add retries, message splitting for long outputs, and rate‑limit handling for Discord.
n8n Financial Analysis Report Chatbot Agent with Gemini 1.5 Flash and Discord
This n8n workflow creates an AI-powered chatbot agent that responds to chat messages, leveraging Google Gemini 1.5 Flash for conversational AI and Discord for communication. It's designed to process incoming chat messages, maintain conversation history, and generate structured responses.
What it does
This workflow automates the following steps:
- Listens for Chat Messages: Triggers when a new chat message is received from a configured chat service (e.g., Discord).
- Initializes Memory: Sets up a simple buffer window memory to maintain the context of the conversation.
- Processes with AI Agent: Uses an AI Agent (Langchain) to interpret the incoming message, considering the conversation history.
- Generates Response with Google Gemini: Employs the Google Gemini 1.5 Flash chat model to formulate a relevant and intelligent response.
- Parses Structured Output: Processes the AI's output into a structured format, if specified by the AI agent's configuration.
- Prepares Discord Message: Formats the AI's response for posting to Discord.
- Posts to Discord: Sends the AI-generated response back to the Discord channel where the message originated.
Prerequisites/Requirements
To use this workflow, you will need:
- n8n Instance: A running n8n instance.
- Discord Account & Bot: A Discord account and a Discord bot configured with the necessary permissions to send and receive messages in your desired channel(s). You will need the bot token for n8n credentials.
- Google Cloud Project & Gemini API Key: Access to Google Cloud with the Gemini API enabled and an API key for the Google Gemini Chat Model.
- n8n Langchain Nodes: Ensure the
@n8n/n8n-nodes-langchainpackage is installed in your n8n instance.
Setup/Usage
-
Import the Workflow:
- Download the provided JSON file.
- In your n8n instance, go to "Workflows" and click "New".
- Click the three dots menu (⋮) in the top right and select "Import from JSON".
- Paste the workflow JSON or upload the file.
-
Configure Credentials:
- Discord Node (ID: 60):
- Click on the "Discord" node.
- Create or select an existing Discord API credential. You'll need your Discord Bot Token.
- Google Gemini Chat Model Node (ID: 1262):
- Click on the "Google Gemini Chat Model" node.
- Create or select an existing Google Gemini API credential. You'll need your Google Gemini API Key.
- Discord Node (ID: 60):
-
Configure Chat Trigger (ID: 1247):
- Click on the "When chat message received" node.
- Select the Discord credential you configured in the previous step.
- Specify the Discord channel(s) or user(s) the bot should listen to.
-
Customize AI Agent (ID: 1119):
- Click on the "AI Agent" node.
- Review and adjust the agent's instructions, tools, and other parameters as needed for your specific financial analysis tasks.
-
Activate the Workflow:
- Once all credentials and configurations are set, click the "Activate" toggle in the top right corner of the workflow editor to enable it.
Your chatbot agent is now ready to respond to messages in the configured Discord channel!
Related Templates
Generate customer statements with credit risk analysis, PDF export & Gmail delivery
Automated Customer Statement Generator with Risk Analysis & Credit Monitoring Transform account statement management from hours to minutes - automatically compile transaction histories, calculate aging analysis, monitor credit limits, assess payment risk, and deliver professional PDF statements while syncing with accounting systems and alerting your team about high-risk accounts. What This Workflow Does Revolutionizes customer account management with intelligent statement generation, credit monitoring, and risk assessment: Webhook-Triggered Generation - Automatically creates statements from accounting systems, CRM updates, or scheduled monthly triggers Smart Data Validation - Verifies transaction data, validates account information, and ensures statement accuracy before generation Running Balance Calculation - Automatically computes running balances through all transactions with opening and closing balance tracking Comprehensive Aging Analysis - Calculates outstanding balances by age buckets (Current, 31-60 days, 61-90 days, 90+ days) Overdue Detection & Highlighting - Automatically identifies overdue amounts with visual color-coded alerts on statements Professional HTML Design - Creates beautifully branded statements with modern layouts, aging breakdowns, and payment information PDF Conversion - Transforms HTML into print-ready, professional-quality PDF statements with preserved formatting Automated Email Delivery - Sends branded emails to customers with PDF attachments and account summary details Google Drive Archival - Automatically saves statements to organized folders with searchable filenames by account Credit Limit Monitoring - Tracks credit utilization, detects over-limit accounts, and generates alerts at 75%, 90%, and 100%+ thresholds Risk Scoring System - Calculates 0-100 risk scores based on payment behavior, aging, credit utilization, and overdue patterns Payment Behavior Analysis - Tracks days since last payment, average payment time, and payment reliability trends Automated Recommendations - Generates prioritized action items like "escalate to collections" or "suspend new credit" Accounting System Integration - Syncs statement delivery, balance updates, and risk assessments to QuickBooks, Xero, or FreshBooks Conditional Team Notifications - Different Slack alerts for overdue accounts (urgent) vs current accounts (standard) with risk metrics Transaction History Table - Detailed itemization of all charges, payments, and running balances throughout statement period Multiple Payment Options - Includes bank details, online payment links, and account manager contact information Key Features Automatic Statement Numbering: Generates unique sequential statement numbers with format STMT-YYYYMM-AccountNumber for easy tracking and reference Aging Bucket Analysis: Breaks down outstanding balances into current (0-30 days), 31-60 days, 61-90 days, and 90+ days overdue categories Credit Health Dashboard: Visual indicators show credit utilization percentage, available credit, and over-limit warnings in statement Risk Assessment Engine: Analyzes multiple factors including overdue amounts, credit utilization, payment frequency to calculate comprehensive risk score Payment Behavior Tracking: Monitors days since last payment, identifies patterns like "Excellent - Pays on Time" or "Poor - Chronic Late Payment" Intelligent Recommendations: Automatically generates prioritized action items based on account status, risk level, and payment history Transaction Running Balance: Shows balance after each transaction so customers can verify accuracy and reconcile their records Over-Limit Detection: Immediate alerts when accounts exceed credit limits with escalation recommendations to suspend new charges Good Standing Indicators: Visual green checkmarks and positive messaging for accounts with no overdue balances Account Manager Details: Includes dedicated contact person for questions, disputes, and payment arrangements Dispute Process Documentation: Clear instructions on how customers can dispute transactions within required timeframe Multi-Currency Support: Handles USD, EUR, GBP, INR with proper currency symbols and formatting throughout statement Accounting System Sync: Logs statement delivery, balance updates, and risk assessments in QuickBooks, Xero, FreshBooks, or Wave Conditional Workflow Routing: Different automation paths for high-risk overdue accounts vs healthy current accounts Activity Notes Generation: Creates detailed CRM notes with account summary, recommendations, and delivery confirmation Print-Optimized PDFs: A4 format with proper margins and color preservation for professional printing and digital distribution Perfect For B2B Companies with Trade Credit - Manufacturing, wholesale, distribution businesses offering net-30 or net-60 payment terms Professional Services Firms - Consulting, legal, accounting firms with monthly retainer clients and time-based billing Subscription Services (B2B) - SaaS platforms, software companies, membership organizations with recurring monthly charges Equipment Rental Companies - Construction equipment, party rentals, medical equipment with ongoing rental agreements Import/Export Businesses - International traders managing accounts receivable across multiple customers and currencies Healthcare Billing Departments - Medical practices, clinics, hospitals tracking patient account balances and payment plans Educational Institutions - Private schools, universities, training centers with tuition payment plans and installments Telecommunications Providers - Phone, internet, cable companies sending monthly account statements to business customers Utilities & Energy Companies - Electric, gas, water utilities managing commercial account statements and collections Property Management Companies - Real estate firms tracking tenant charges, rent payments, and maintenance fees Credit Card Companies & Lenders - Financial institutions providing detailed account activity and payment due notifications Wholesale Suppliers - Distributors supplying restaurants, retailers, contractors on credit terms with monthly settlements Commercial Insurance Agencies - Agencies tracking premium payments, policy charges, and outstanding balances Construction Contractors - General contractors billing for progress payments, change orders, and retention releases What You Will Need Required Integrations HTML to PDF API - PDF conversion service (API key required) - supports HTML/CSS to PDF API, PDFShift, or similar providers (approximately 1-5 cents per statement) Gmail or SMTP - Email delivery service for sending statements to customers (OAuth2 or SMTP credentials) Google Drive - Cloud storage for statement archival and compliance record-keeping (OAuth2 credentials required) Optional Integrations Slack Webhook - Team notifications for overdue and high-risk accounts (free incoming webhook) Accounting Software Integration - QuickBooks, Xero, FreshBooks, Zoho Books API for automatic statement logging and balance sync CRM Integration - HubSpot, Salesforce, Pipedrive for customer activity tracking and collections workflow triggers Payment Gateway - Stripe, PayPal, Square payment links for one-click online payment from statements Collections Software - Integrate with collections management platforms for automatic escalation of high-risk accounts SMS Notifications - Twilio integration for payment due reminders and overdue alerts via text message Quick Start Import Template - Copy JSON workflow and import into your n8n instance Configure PDF Service - Add HTML to PDF API credentials in the "HTML to PDF" node Setup Gmail - Connect Gmail OAuth2 credentials in "Send Email to Customer" node and update sender email Connect Google Drive - Add Google Drive OAuth2 credentials and set folder ID for statement archival Customize Company Info - Edit "Enrich with Company Data" node to add company name, address, contact details, bank information Configure Credit Limits - Set default credit limits and payment terms for your customer base Adjust Risk Thresholds - Modify risk scoring logic in "Credit Limit & Risk Analysis" node based on your policies Update Email Template - Customize email message in Gmail node with your branding and messaging Configure Slack - Add Slack webhook URLs in both notification nodes (overdue and current accounts) Connect Accounting System - Replace code in "Update Accounting System" node with actual API call to QuickBooks/Xero/FreshBooks Test Workflow - Submit sample transaction data via webhook to verify PDF generation, email delivery, and notifications Schedule Monthly Run - Set up scheduled trigger for automatic end-of-month statement generation for all customers Customization Options Custom Aging Buckets - Modify aging periods to match your business (e.g., 0-15, 16-30, 31-45, 46-60, 60+ days) Industry-Specific Templates - Create different statement designs for different customer segments or business units Multi-Language Support - Translate statement templates for international customers (Spanish, French, German, Mandarin) Dynamic Credit Terms - Configure different payment terms by customer type (VIP net-45, standard net-30, new customers due on receipt) Late Fee Calculation - Add automatic late fee calculation and inclusion for overdue balances Payment Plan Tracking - Track installment payment plans with remaining balance and next payment due Interest Charges - Calculate and add interest charges on overdue balances based on configurable rates Partial Payment Allocation - Show how partial payments were applied across multiple invoices Customer Portal Integration - Generate secure links for customers to view statements and make payments online Batch Processing - Process statements for hundreds of customers simultaneously with bulk email delivery White-Label Branding - Create different branded templates for multiple companies or subsidiaries Custom Risk Models - Adjust risk scoring weights based on your industry and historical payment patterns Collections Workflow Integration - Automatically create tasks in collections software for high-risk accounts Early Payment Incentives - Highlight early payment discounts or prompt payment benefits on statements Dispute Management - Track disputed transactions and adjust balances accordingly with audit trail Expected Results 90% time savings - Reduce statement creation from 2-3 hours to 5 minutes per customer 100% accuracy - Eliminate calculation errors and missing transactions through automated processing 50% faster payment collection - Professional statements with clear aging drive faster customer payments Zero filing time - Automatic Google Drive organization with searchable filenames by account 30% reduction in overdue accounts - Proactive credit monitoring and risk alerts prevent bad debt Real-time risk visibility - Instant identification of high-risk accounts before they become uncollectible Automated compliance - Complete audit trail with timestamped statement delivery and accounting sync Better customer communication - Professional statements improve customer satisfaction and reduce disputes Reduced bad debt write-offs - Early warning system catches payment issues before they escalate Improved cash flow - Faster statement delivery and payment reminders accelerate cash collection Pro Tips Schedule Monthly Batch Generation - Run workflow automatically on last day of month to generate statements for all customers simultaneously Customize Aging Thresholds - Adjust credit alert levels (75%, 90%, 100%) based on your risk tolerance and industry norms Segment Customer Communications - Use different email templates for VIP customers vs standard customers vs delinquent accounts Track Payment Patterns - Monitor days-to-pay metrics by customer to identify chronic late payers proactively Integrate with Collections - Connect workflow to collections software to automatically escalate 90+ day accounts Include Payment Portal Links - Add unique payment links to each statement for one-click online payment Automate Follow-Up Reminders - Build workflow extension to send payment reminders 7 days before due date Create Executive Dashboards - Export risk scores and aging data to business intelligence tools for trend analysis Document Dispute Resolutions - Log all disputed transactions in accounting system with resolution notes Test with Sample Data First - Validate aging calculations with known test data before processing real customer accounts Archive Statements for Compliance - Maintain 7-year archive in Google Drive organized by year and customer Monitor Credit Utilization Trends - Track credit utilization changes month-over-month to predict cash flow needs Benchmark Against Industry - Compare your DSO and bad debt ratios to industry averages to identify improvement areas Personalize Account Manager Info - Assign dedicated contacts to customers and include their direct phone and email Use Descriptive Transaction Details - Ensure transaction descriptions clearly explain charges to reduce disputes Business Impact Metrics Track these key metrics to measure workflow success: Statement Generation Time - Measure average minutes from trigger to delivered statement (target: under 5 minutes) Statement Volume Capacity - Count monthly statements generated through automation (expect 10-20x increase in capacity) Aging Calculation Accuracy - Track statements with aging errors (target: 0% error rate) Days Sales Outstanding (DSO) - Monitor average days to collect payment (expect 15-30% reduction) Bad Debt Write-Offs - Track uncollectible accounts as percentage of revenue (expect 30-50% reduction) Collection Rate - Monitor percentage of invoices collected within terms (expect 10-20% improvement) Customer Disputes - Count statement disputes and billing inquiries (expect 50-70% reduction) Over-Limit Accounts - Track number of accounts exceeding credit limits (early detection prevents losses) High-Risk Account Identification - Measure days between risk detection and collection action (target: within 48 hours) Cash Flow Improvement - Calculate working capital improvement from faster collections (typical: 20-35% improvement) Template Compatibility Compatible with n8n version 1.0 and above Works with n8n Cloud and Self-Hosted instances Requires HTML to PDF API service subscription (1-5 cents per statement) No coding required for basic setup Fully customizable for industry-specific requirements Integrates with major accounting platforms via API Multi-currency and multi-language ready Supports batch processing for large customer bases Compliant with financial record-keeping regulations --- Ready to transform your account receivables management? Import this template and start generating professional statements with credit monitoring, risk assessment, and automated collections alerts - improving your cash flow, reducing bad debt, and freeing your accounting team to focus on strategic financial management!
Track expenses from receipt photos with AI, Google Sheets & Slack reports
Who’s it for This template is for individuals or households who want to: Easily digitize and track their spending from physical receipts. Automate budget management and financial reporting. Get quick insights into their spending habits on a daily and monthly basis. Stay informed about their remaining budget through Slack notifications. What it does This workflow automates your household budget tracking in several steps: Receipt Photo Upload: You upload a photo of your receipt to a webhook. Parse Receipt: An AI agent extracts the date, store name, purchased items, and total amount from the receipt text. Add to Budget Sheet: The extracted data is then appended to your designated Google Sheet. Daily Budget Report: After each receipt entry, the workflow calculates your current month's spending, remaining budget, and sends a summary to Slack. Monthly Budget Report: Once a day (triggered by a cron job), it reads all budget data for the current month from Google Sheets, performs an analysis (total spending, daily average, top stores, items, and spending days), and sends a comprehensive report to Slack. How to set up Requirements n8n Account: Self-hosted or Cloud. Google Sheets: A Google Sheet set up with columns for "Date", "Store", "Items", and "Amount". Slack Workspace: A Slack channel where you want to receive budget updates. OpenRouter Account: An API key for OpenRouter to use their chat models. Steps Google Sheets Setup: Create a new Google Sheet (or use an existing one) and name it "Household Budget". In the first sheet (e.g., "Sheet1"), set up the following headers in the first row: "Date", "Store", "Items", "Amount". Share the Google Sheet with the service account email associated with your n8n Google Sheets credentials, granting "Editor" access. In the 'Add to Budget Sheet' and 'Get Budget Sheet (Daily)' nodes, select your Google Sheet and the appropriate sheet name. OpenRouter Credentials: Sign up or log in to OpenRouter (https://openrouter.ai/). Generate an API key. In n8n, create a new "OpenRouter" credential using your API key. Apply this credential to the 'OpenRouter Chat Model1', 'OpenRouter Chat Model2', and 'OpenRouter Chat Model' nodes. Slack Credentials: In n8n, create a new "Slack" credential. Follow the instructions to connect your Slack workspace. In the 'Send a message' and 'Send monthly report' nodes, select the Slack channel where you want to receive messages. Make sure the Slack app has permission to post to the selected channels. Webhook URLs: After activating the workflow, the 'Receipt Photo Upload' node will generate a webhook URL. Copy this URL. You will use this URL to send receipt text (e.g., from a mobile app that scans text). Monthly Budget Adjustment: In the 'Code in JavaScript2' node, locate the line const budget = 30000; and change 30000 to your desired monthly budget in JPY. How to customize the workflow Daily Report Trigger The 'Daily Report Trigger' node is set to run once a day. You can modify its schedule to trigger more or less frequently by adjusting its cron settings. AI Model You can change the AI models used in the 'OpenRouter Chat Model' nodes to any other large language model supported by n8n, such as OpenAI, Anthropic, or custom hosted models, by updating the credentials and model names. Output Formatting The Slack messages generated by the 'Report Budget' and 'Monthly Report' nodes can be customized by editing the systemMessage and text parameters in those nodes to change the tone, content, or language of the reports. Additional Integrations You can extend this workflow by adding more nodes: Integrate with other accounting software. Send notifications to different platforms (e.g., email, Discord, Telegram). Add sentiment analysis to your spending habits. Categorize expenses automatically based on items or stores using another AI node.
Create autonomous payment agents using AgentGatePay and multi-chain tokens
AgentGatePay N8N Quick Start Guide Get your AI agents paying for resources autonomously in under 10 minutes. > ⚠️ BETA VERSION: These templates are currently in beta. We're actively adding features and improvements based on user feedback. Expect updates for enhanced functionality, additional blockchain networks, and new payment options. --- What You'll Build Buyer Agent: Automatically pays for API resources using USDC, USDT, or DAI on Ethereum, Base, Polygon, or Arbitrum blockchains Seller API: Accepts multi-token payments and delivers resources Monitoring: Track spending and revenue in real-time across all chains and tokens Supported Tokens: USDC (6 decimals) - Recommended USDT (6 decimals) DAI (18 decimals) Supported Blockchains: Ethereum (mainnet) Base (recommended for low gas fees ~$0.001) Polygon Arbitrum --- Prerequisites (5 minutes) Create AgentGatePay Accounts Buyer Account (agent that pays): bash curl -X POST https://api.agentgatepay.com/v1/users/signup \ -H "Content-Type: application/json" \ -d '{ "email": "buyer@example.com", "password": "SecurePass123!", "user_type": "agent" }' Seller Account (receives payments): bash curl -X POST https://api.agentgatepay.com/v1/users/signup \ -H "Content-Type: application/json" \ -d '{ "email": "seller@example.com", "password": "SecurePass123!", "user_type": "merchant" }' Save both API keys - shown only once! Deploy Transaction Signing Service (2 minutes) One-Click Render Deploy: Click: [](https://render.com/deploy?repo=https://github.com/AgentGatePay/TX) Enter: AGENTGATEPAYAPIKEY: Your buyer API key WALLETPRIVATEKEY: Your wallet private key (0x...) Deploy → Copy service URL: https://your-app.onrender.com Fund Wallet Send USDC, USDT, or DAI to your buyer wallet Default: Base network (lowest gas fees) Need ~$1 in tokens for testing + ~$0.01 ETH for gas (on Ethereum) or ~$0.001 on Base --- Installation (3 minutes) Step 1: Import Templates In N8N: Go to Workflows → Add Workflow Click ⋮ (three dots) → Import from File Import all 4 workflows: 🤖 Create a Cryptocurrency-Powered API for Selling Digital Resources with AgentGatePay 💲Create a Cryptocurrency-Powered API for Selling Digital Resources with AgentGatePay 📊 Buyer Agent [Monitoring] - AgentGatePay Autonomous Payment Workflow 💲 Seller Agent [Monitoring] - AgentGatePay Autonomous Payment Workflow Step 2: Create Data Table In N8N Settings: Go to Settings → Data → Data Tables Create table: AgentPay_Mandates Add column: mandate_token (type: String) Save --- Configuration (2 minutes) Configure Seller API First Open: 💲Seller Resource API - CLIENT TEMPLATE Edit Node 1 (Parse Request): javascript const SELLER_CONFIG = { merchant: { wallet_address: "0xYourSellerWallet...", // ← Your seller wallet apikey: "pklive_xyz789..." // ← Your seller API key }, catalog: { "demo-resource": { id: "demo-resource", price_usd: 0.01, // $0.01 per resource description: "Demo API Resource" } } }; Activate workflow → Copy webhook URL Configure Buyer Agent Open: 🤖 Buyer Agent - CLIENT TEMPLATE Edit Node 1 (Load Config): javascript const CONFIG = { buyer: { email: "buyer@example.com", // ← Your buyer email apikey: "pklive_abc123...", // ← Your buyer API key budget_usd: 100, // $100 mandate budget mandatettldays: 7 // 7-day validity }, seller: { api_url: "https://YOUR-N8N.app.n8n.cloud/webhook/YOUR-WEBHOOK-ID" // ← Seller webhook base URL ONLY (see README.md for extraction instructions) }, render: { service_url: "https://your-app.onrender.com" // ← Your Render URL } }; --- Run Your First Payment (1 minute) Execute Buyer Agent Open Buyer Agent workflow Click Execute Workflow Watch the magic happen: Mandate created ($100 budget) Resource requested (402 Payment Required) Payment signed (2 transactions: merchant + commission) Payment verified on blockchain Resource delivered Total time: ~5-8 seconds Verify on Blockchain Check transactions on BaseScan: https://basescan.org/address/YOURBUYERWALLET You'll see: TX 1: Commission to AgentGatePay (0.5% = $0.00005) TX 2: Payment to seller (99.5% = $0.00995) --- Monitor Activity Buyer Monitoring Open: 📊 Buyer Monitoring - AUDIT LOGS Edit Node 1: Set your buyer wallet address and API key Execute → See: Mandate budget remaining Payment history Total spent Average transaction size Seller Monitoring Open: 💲 Seller Monitoring - AUDIT LOGS Edit Node 1: Set your seller wallet address and API key Execute → See: Total revenue Commission breakdown Top payers Payment count --- How It Works Payment Flow Buyer Agent requests resource ↓ Seller returns 402 Payment Required (includes: wallet address, price, token, chain) ↓ Buyer signs TWO blockchain transactions via Render: Merchant payment (99.5%) Gateway commission (0.5%) ↓ Buyer resubmits request with transaction hashes ↓ Seller verifies payment with AgentGatePay API ↓ Seller delivers resource Key Concepts AP2 Mandate: Pre-authorized spending authority Budget limit ($100 in example) Time limit (7 days in example) Stored in N8N Data Table for reuse x402 Protocol: HTTP 402 "Payment Required" status code Seller specifies payment details Buyer pays and retries with proof Two-Transaction Model: Transaction 1: Merchant receives 99.5% Transaction 2: Gateway receives 0.5% Both verified on blockchain --- Customization Change Resource Price Edit seller Node 1: javascript catalog: { "expensive-api": { id: "expensive-api", price_usd: 1.00, // ← Change price description: "Premium API access" } } Add More Resources javascript catalog: { "basic": { id: "basic", price_usd: 0.01, description: "Basic API" }, "pro": { id: "pro", price_usd: 0.10, description: "Pro API" }, "enterprise": { id: "enterprise", price_usd: 1.00, description: "Enterprise API" } } Buyer requests by ID: ?resource_id=pro Change Blockchain and Token By default, templates use Base + USDC. To change: Edit buyer Node 1 (Load Config): javascript const CONFIG = { buyer: { / ... / }, seller: { / ... / }, render: { / ... / }, payment: { chain: "polygon", // Options: ethereum, base, polygon, arbitrum token: "DAI" // Options: USDC, USDT, DAI } }; Important: Ensure your wallet has the selected token on the selected chain Update Render service to support the chain (add RPC URL) Gas fees vary by chain. Token Decimals: USDC/USDT: 6 decimals (automatic conversion) DAI: 18 decimals (automatic conversion) Schedule Monitoring Replace "Execute Workflow" trigger with Schedule Trigger: Buyer monitoring: Every 1 hour Seller monitoring: Every 6 hours Add Slack/Email node to send alerts. --- Troubleshooting "Mandate expired" Fix: Delete mandate from Data Table → Re-execute workflow "Transaction not found" Fix: Wait 10-15 seconds for blockchain confirmation → Retry "Render service unavailable" Fix: Render free tier spins down after 15 min → First request takes ~5 sec (cold start) "Insufficient funds" Fix: Send more tokens (USDC/USDT/DAI) to buyer wallet Check balance on blockchain explorer (BaseScan for Base, Etherscan for Ethereum, etc.) "Webhook not responding" Fix: Ensure seller workflow is Active (toggle in top-right) --- Production Checklist Before going live: [ ] Use separate wallet for agent (not your main wallet) [ ] Set conservative mandate budgets ($10-100) [ ] Monitor spending daily (use monitoring workflows) [ ] Upgrade Render to paid tier ($7/mo) for no cold starts [ ] Set up Slack/email alerts for low balance [ ] Test with small amounts first ($0.01-0.10) [ ] Keep API keys secure (use N8N credentials manager) [ ] Review transactions on blockchain explorer weekly --- Summary You just built: Autonomous payment agent (buys resources automatically) Monetized API (sells resources for USDC, USDT, or DAI) Multi-chain support (Ethereum, Base, Polygon, Arbitrum) Real blockchain transactions (verified on-chain) Budget management (AP2 mandates) Monitoring dashboard (track spending/revenue) Total setup time: ~10 minutes Total cost: $0 (Render free tier + AgentGatePay free) --- Ready to scale? Connect multiple agents, add more resources, integrate with your existing systems! Questions? Check README.md or contact support@agentgatepay.com Website: https://www.agentgatepay.com