You can now create more than one wallet per customer.
Each wallet has its own settings: define its priority, limit its scope to specific billable metrics, and configure dedicated recurring top-up rules to better control how credits are applied.
[Learn more](/guide/wallet-and-prepaid-credits/overview#create-wallets)
## Invoice issuing date preferences
**Take full control of when your subscription invoices are dated.**
Many businesses need invoices dated on the last day of the billing period, not the first day of the next. This is mainly useful for revenue recognition, compliance, or cleaner accounting.
You can now configure this at the Billing Entity level (with per-customer overrides) using two new settings: **Issuing Date Anchor** and **Issuing Date Adjustment**.
For example, an October subscription invoice can now show October 31st instead of November 1st.
[Learn more](/guide/invoicing/invoicing-settings/issuing_date)
## Metadata for credit notes
You can now enrich your credit notes with custom metadata.
This allows teams to store key operational details — such as the reason for issuing the credit note, internal notes, or synchronization references for external tools.
[Learn more](/guide/invoicing/credit-notes/credit-note-metadata)
## Agentic AI for Billing Operations
Introducing our 1st Lago AI Agent, called the **Billing Assistant**, a conversational assistant to help you manage billing operations using natural language.
This conversational assistant helps you **manage billing operations using natural language**, reducing the time spent on manual and repetitive tasks.
Ask questions, retrieve data, and perform actions across your billing entities, all through a simple chat interface.
Conversations are saved for context-aware follow-ups, and built-in safeguards require confirmation before executing any destructive actions.
[Learn more](/guide/ai-agents/billing-assistant)
Lago now generates invoices in the correct formats required for **E-invoicing integrations**. The first fully supported jurisdiction is France 🇫🇷, and **adding new jurisdictions is straightforward through template updates or open source contributions**.
For invoices, credit notes, and payments, Lago now produces two documents:
* A hybrid PDF/A 3 with embedded XML using UN/CEFACT Cross Industry Invoice, suitable for human reading; and
* A pure XML file using UBL EN 16931, suitable for machine processing.
While Lago **does not handle automatic transmission to local authorities**, you can download all XML files and upload them to your jurisdiction portal.
Feel free to contact the team or submit an open source contribution, especially for jurisdictions that share similar formats with minor adjustments.
[Learn more](/guide/invoicing/einvoicing)
## New integration mapping per Lago Billing Entity
We enhanced how accounting and tax integrations are configured with Lago.
You can now **map product items and tax items at the Lago Entity level** across all your integrations.
This gives you precise control over how each Lago entity connects to external accounting or tax systems and ensures accurate data syncs for your team.
Forecasting revenue is notoriously challenging, especially for usage-based companies. Usage fluctuates over time, definitions of revenue vary from a company to another, and reliable prediction models are often missing.
At Lago, we set out to make this process easier!
We have introduced our first **ML model** to **forecast your usage-based revenue up to 12 months ahead**. The model provides **three scenarios**: **Realistic**, **Pessimistic**, and **Optimistic**, and regularly refines its predictions based on your invoiced usage data.
Quickly find the right customers by filtering your list (via API or UI) using metadata, active subscriptions, Tax ID, and more — making large datasets easier to navigate and act on.
[Learn more](/api-reference/customers/get-all?playground=open)
## Wallet transaction limits
You can now define minimum and maximum amounts for each paid wallet transaction. Any top-up must stay within these boundaries; transactions below the minimum or above the maximum will be rejected. This ensures better control over wallet usage and prevents unexpected amounts being processed.
For added flexibility, you can bypass wallet transaction limits when needed. Overrides can be applied either by adding the `ignore_paid_top_up_limits` flag in the API payload or by enabling the Skip top-up limits for this transaction option in the UI. This applies to both one-off and recurring (automatic) top-ups.
[Learn more](/guide/wallet-and-prepaid-credits/overview#wallet-transaction-limits)
Add context to your invoices by naming wallet transactions — whether they come from a manual top-up or a recurring rule.
The transaction name now appears on prepaid credit purchase invoices.
[Learn more](/api-reference/wallets/top-up#body-wallet-transaction-name)
In addition to weekly, monthly, quarterly, and yearly billing intervals, subscriptions can now also be billed on a **semiannual** basis.
This new option also applies to recurring wallet top-ups, which can now be scheduled every 6 months.
[Learn more](/guide/plans/plan-model#plan-interval)
## Entitlements are now supported in Lago 🎉
Until now, Lago supported subscriptions, discounts, prepaid credits, and usage-based charges. But one key piece was missing: **Entitlements**.
Entitlements are the features included in a plan or subscription that aren't usage-based, but still define what a customer can access. For example:
* On **Plan A**, a customer gets **Okta SSO** and can invite **up to 3 members**.
* On **Plan B**, another customer can invite **up to 10 members** and gets a **7-day log retention**.
Traditionally, billing and entitlements were managed separately. But they shouldn't be. They are two siblings. Two faces of the same coin. That's why, starting today, you can:
1. **Define features** directly in Lago.
2. Attach (**entitle**) them to plans.
3. **Override** them for individual subscriptions.
4. Create **feature-level privileges** that vary across plans.
With this release, entitlements become first-class citizens in Lago, right alongside subscriptions, metering and usage-based billing.
[Learn more](/guide/entitlements)
## Revenue streams dashboard improvements
We've made some improvements to the Revenue Streams dashboard to make it more intuitive, espeicially for the gross vs net revenue calculation. We now display the contra revenue, including coupons, discounts, and credits.
[Learn more](/guide/analytics/revenue-streams)
## Set service periods on one-off line items
You can now define a service period for one-off line items. Instead of recognizing them on a single date, they can cover a period — in the past, starting today, or in the future.
This gives you full flexibility to set the billing boundaries you need, for each line item individually.
[Learn more](/guide/one-off-invoices/create-one-off-invoices)
## Terminate subscriptions without unwanted credit notes
By default, Lago issues a credit note when you terminate a **pay-in-advance** subscription. Now, you decide what happens: skip the credit note, credit the unused amount, or refund it.
No more cleaning up credit notes that were never meant to be sent — just pick the right option in the termination dialog.
[Learn more](/guide/subscriptions/terminate-subscription#generate-a-closing-credit-note-at-subscription-termination)
## Do not generate invoice at subscription termination
Created a subscription by mistake? You can now terminate it **without generating a closing invoice**, so you don’t have to deal with invoices that were never meant to exist.
Just pick the option in the termination dialog — and we’ll skip creating it.
[Learn more](/guide/subscriptions/terminate-subscription#generate-a-closing-invoice-at-subscription-termination)
Give your customers visibility into their upcoming bills, before the invoice drops.
With the new Projected Usage endpoint, you can help users estimate their final usage and costs for the current billing period, based on real-time consumption trends.
Perfect for:
1. Displaying projected costs inside your app
2. Give customers visibility into their upcoming bills
3. Helping customers stay in control of their spend
Built on the same engine as the [current usage endpoint](../../api-reference/customer-usage/get-current), it ensures consistent and trustworthy projections.
[Learn more](/guide/events/retrieve-usage#retrieve-projected-usage)
## Regenerate voided invoices
We've just made it easier to **fix and reissue invoices** — no more starting from scratch. With our new **"Regenerate Voided Invoice"** feature, you can now recreate a voided invoice directly from the UI in just a few clicks.
The original line items and fees are pre-filled for convenience, and you can still make changes such as adjusting quantities or updating amounts before sending it out. The regenerated invoice remains linked to the original one, ensuring full traceability for your accounting records.
And the cherry on top 🍒: you now have **multiple refund options when voiding an invoice**, giving you greater flexibility based on the payment method and accounting preferences.
[Learn more](/guide/invoicing/void#regenerate-a-voided-invoice)
## Limit prepaid credits to specific billable metrics
If you're offering prepaid credits, great, you're riding the AI wave! But not all usage should be tied to credits. Some metrics are better off billed the old-fashioned way: with traditional payment methods.
What's new? You can now choose which metrics are deducted from prepaid credits, and which ones are billed separately using other payment methods.
This gives you more control over your pricing strategy and helps align billing with your product's value delivery.
[Learn more](/guide/wallet-and-prepaid-credits/overview#application-scope)
## Get payment links for pending invoices
You're not a technical user, but your customer is asking for a way to pay an invoice generated through Lago. No worries, it's easy! Just click the “Get payment link” button to generate a secure checkout link you can share.
## Custom pricing units for more flexible billing!
You can now express charges in **pricing units** like `credits` or `tokens` — not just fiat currency.
This gives you more flexibility to align your pricing with how your product delivers value. You can now:
* **Create pricing units** (e.g., tks, cdt) from your settings.
* **Define charges** in pricing units within a plan, with a **conversion rate** back to fiat for accurate invoicing.
* **Track usage** in both fiat and pricing units.
* **Generate invoices** that show both values, while ensuring billing in fiat stays consistent.
* **Use pricing units independently or alongside wallets** — they don’t interfere with each other.
[Learn more](/guide/plans/custom-pricing-units)
## Enforce login methods per organization
You can now customize which login methods are allowed for each organization — including requiring SSO (e.g. Okta) while disabling others like email/password or Google.
This ensures better security and compliance for teams with strict authentication requirements.
➡️ Head to Settings → Authentication to configure allowed methods.
[Learn more](/guide/security/sso#login-method-enforcement)
## New navigation bar
July is here, and the sun is knocking on our door!
We’ve redesigned the navigation bar to make it more intuitive and easier to use.
This new navigation will give you access to even more features — but shhh… they’re not ready to launch just yet 🤫
❓'Which endpoints have been used?'
❓❓'Which requests are failing?'
❓❓❓'Which API client triggered this request?'
API logs offer a comprehensive record of all API requests and calls made within your organization. They serve as an essential tool for monitoring activity, troubleshooting issues, and auditing system usage.
[Learn more](/guide/security/audit-logs#api-logs)
## Pricing group keys
**Launch Week IV, Day 5: Pricing Group Keys**
AI and infrastructure platforms often tailor pricing based on variables such as geography, hosting provider, or service tier. Lago's Pricing Group Keys offer a streamlined way to support this kind of dynamic pricing without duplicating product definitions.
With pricing group keys, you can group usage events to a single product based on configurable dimensions—like cloud provider, model type, deployment region, or instance class. This allows you to reflect real-world cost variations while keeping your product catalog clean and manageable.
When setting up a charge, you define the relevant keys. You don't need to predefine every possible value. Instead, Lago intelligently routes each usage event to the correct pricing group based on the attributes provided at runtime.
[Learn more](/guide/plans/charges/grouping#pricing-group-keys)
## Prepaid credits limited to specific charges
**Launch Week IV, Day 4: Restrict Prepaid Credits to Specific Charges**
You can now configure prepaid credits to apply only to designated charges within an invoice. This allows greater control over credit usage—for instance, preventing customers from using their prepaid credits to cover the entire invoice and instead limiting them to specific eligible items or charge types.
[Learn more](/guide/wallet-and-prepaid-credits/overview#application-scope)
## Avalara Tax Integration
**Launch Week IV, Day 3: End Tax Guesswork — Lago x Avalara Integration**
You can now connect Lago to Avalara to make tax management easier. This native integration allows you to automatically update your invoices with tax amounts sourced directly from Avalara.
1️⃣ Lago sends the customer's address, tax identifier (if applicable), and the relevant tax code to calculate the appropriate tax for each line item.
2️⃣ Avalara calculates the tax for the invoice and returns the data to Lago, which is used to update the invoice with accurate tax information.
3️⃣ Lago synchronizes updates for voided and disputed invoices, as well as any credit notes created, ensuring that your records remain up to date.
This integration is accessible with a premium add-on.
[Learn more](/integrations/taxes/avalara)
## Activity Logs
**Launch Week IV, Day 2: Billing Activity Logs**
❓'Who changed that price point?'
❓❓'Who created that plan?'
❓❓❓'What happened to this invoice?'
We got you! That's why we are launching one of the most underrated but essential billing features: Activity Logs.
Lago is used by engineering, finance, sales, and growth teams. Engineers build the billing engine, sales customize deals, finance reviews data—it can get messy. Activity logs bring clarity!
Every change is now logged. You’ll know who did what, when, and how—whether it came from the UI or API. We track the user or API key, the action, timestamps, resource IDs, and more. It is like git, but for your billing stack.
[Learn more](/guide/security/audit-logs)
## Budget & Usage Alerts
**Launch Week IV, Day 1: Budget & Usage Alerts!**
We've all heard the horror stories of unsupervised AWS instances that lead to million-dollar invoices. Even when we're not talking about millions, you probably know the feeling of usage-based bills far more expensive than you thought.
Lago now helps you prevent those scenarios. With budget & usage alerts, you can put hard edges around consumption and billing.
The feature is basically a multi-layered warning system. You can track:
1. **Lifetime spend** for the entire subscription—ideal for free trials that should never exceed, say, a total of \$100.
2. **Current-period spend** so finance knows when a customer hits 80 percent of this month's credits and engineering can act before overages accrue.
3. **Metric-based spend** in amount or usage units, meaning you can send an alert when a user has used up 1 million API calls or \$100 of API calls.
[Learn more](/guide/alerts)
You can now manage multiple billing entities within a single Lago account.
Whether you operate with different subsidiaries or invoice on behalf of third parties, this feature lets you issue invoices from multiple senders, different subsidiaries—without duplicating your setup.
Your existing configuration (billable metrics, plans, settings, etc.) stays intact, making it easy to scale across entities while invoice settings (timezone, locale, grace period, etc.) can be configured differently.
[Learn more](/guide/billing-entities)
## Know everything about prepaid credits consumption
Our new prepaid credits dashboard is now live in beta! You can now track the flow of your prepaid credits, including the amount of credits offered, paid, consumed, and voided.
[Learn more](../guide/analytics/prepaid-credits)
We made the payment URL generation idempotent to safely share with your end customers.
Each URL remains valid and unchanged for 24 hours, no matter how many times the endpoint is called — helping you prevent duplicate payments and simplify the checkout flow.
After 24 hours, a new URL will be generated on the next call, valid for the next 24-hour period.
[Learn more](/guide/payments/payment-retries#generate-a-payment-url)
## Lago Data Pipeline is now in beta
You need to **sync your Lago data to your data warehouse or cloud storage?** We've got you covered with a new native integration called `Lago Data Pipeline`!
Lago Data Pipeline is now in beta and available for a selected group of customers. Reach out to your account manager to get access.
More than 20 data destinations are supported, including Snowflake, BigQuery, Redshift, Databricks, Athena, ClickHouse, MotherDuck, Postgres, Aurora Postgres, MySQL, Aurora MySQL, SQL Server, SingleStore, S3, S3-Compatible, GCS, ABS, and Google Sheets.
[Learn more](../integrations/data/lago-data-pipeline)
## Failed payment nightmares are over: Lago payment pre-authorization
Sick of launching a subscription, watching customers dive in all month, only to have payment fail at billing time—and then radio silence when you reach out? Failed charges not only leave revenue on the table but also create churn, frustrate customers, and bog your team down in manual follow-ups.
With Lago's Payment Pre-Authorization, **you can now verify a card's validity and available funds when starting a subscription.** Catch bad payment methods upfront, automate notifications for declined pre-auths, and keep your service—and your revenue—flowing seamlessly. Enable it in your Lago dashboard today and turn payment nightmares into smooth, uninterrupted growth.
[Learn more](../guide/payments/payment-authorization)
## Pay your Lago invoices with Moneyhash
You can now pay your Lago invoices using [Moneyhash](https://moneyhash.io)!
Moneyhash is the leading payment infrastructure software in Africa and the Middle East.
They help businesses across Emerging Markets to optimize payment performance, scale operations, cut costs, and grow revenue through an all-in-one orchestration platform.
If you issue invoices for customers in Africa or MENA, this integration is for you!
[Learn more](../integrations/payments/moneyhash-integration)
We've just launched Analytics v2 in beta for some premium customers! This upgraded experience brings deeper insights and more powerful tools to understand your revenue performance:
1. Revenue per Stream: Get a detailed breakdown of how each stream contributes to your bottom line.
2. Enhanced MRR Dashboard: Track your Monthly Recurring Revenue breakout with detailed views
This marks a major step forward in Lago's new Analytics view, designed to help you make smarter, data-driven decisions. If you're part of the beta, we'd love to hear your feedback!
[Learn more](../guide/analytics/revenue-streams)
Payment intent failed? No worries — we've added a new endpoint that generates a payment URL for pending and failed wallet transactions. This feature allows your customers to complete their wallet top-ups through a secure checkout page, similar to how invoice payments work.
A smoother recovery, a better experience. Dive into the docs for all the details!
[Learn more](../api-reference/wallets/wallet-transaction-payment-url)
## Track every cent: Payment Receipts are now available!
If you don’t rely on our PDFs, you can now configure Lago—via an environment variable—to skip PDF generation for invoices, credit notes, and receipts.
Lago won’t process any jobs related to these documents, keeping your queues less crowded.
[Learn more](../guide/lago-self-hosted/docker#environment-variables)
## Invoice previews for upgrades and downgrades
You can now preview invoices not just for new customers or dry runs on existing subscriptions, but also for upgrades, downgrades, and even plan terminations.
This means you have all the tools you need to estimate and preview invoices for every billing scenario. Get ready to take control of your billing like a pro!
[Learn more](../guide/invoicing/previews#preview-an-invoice-for-upgrades-and-downgrades)
## Enhanced wallet transaction details
You can now view detailed information about a wallet transaction by simply clicking on it.
We’ve added comprehensive data to improve your understanding, including all relevant transaction details, linked payments, and associated invoices.
This update makes it easier to track and analyze your wallet transactions at a glance.
## Failed wallet transaction
We’ve introduced the `failed` wallet transaction! Now, when a wallet transaction is linked to a failed payment, its status will automatically update from `pending` to `failed`.
This enhancement provides a clearer view of the transaction lifecycle and simplifies debugging when needed.
## Expiration date for wallet recurring transaction rule
As part of our initiative to enhance the wallet experience, we’ve introduced two new settings for wallet recurring transaction rules.
* You can now set an expiration date for a rule, and Lago will automatically terminate it once reached, preventing any further top-ups.
* Additionally, you can define metadata for recurring top-ups directly through the Dashboard.
[Learn more](../guide/wallet-and-prepaid-credits/wallet-top-up-and-void#expiration-date)
We’ve introduced new webhook messages to help you better understand activity on your wallets. You can now listen to `wallet.created`, `wallet.updated`, and `wallet.terminated` events.
[Learn more](../api-reference/webhooks/messages#wallets-and-prepaid-credits)
## Pay Lago invoices via Bank Transfers
Lago now supports Stripe’s bank transfers (customer\_balance) for invoice payments. Supported methods:
* JPY: Japan
* GBP: United Kingdom
* EUR: Specific SEPA countries (see Stripe documentation)
* MXN: Mexico
* USD: United States, United Kingdom, and select SEPA countries
[Learn more](../guide/payments/stripe-integration#bank-transfers-customer-balance)
## Custom SMTP Management
By default, Lago automatically handles your SMTP configuration—no extra setup required.
However, if you prefer to use your own SMTP server, Enterprise customers can now send emails through a custom SMTP configuration.
## Effortless Docker deployment in a single command
We heard you—the old Docker commands were a bit of a hassle, so we've made things easier. Now, you can get the app up and running with just one simple command in your shell. Enjoy!
[Learn more](../guide/lago-self-hosted/docker#run-the-app-with-a-one-click-docker-command)
## To the moon: Crypto payments are now available
Lago now supports crypto payments! Don't worry though, your customers won't be paying you in a dog meme coin anytime soon. For now, we support USDC/USDP payments if you're using Lago with Stripe payments.
If you don't know, USDC is a stablecoin that's pegged to the US Dollar and always worth exactly \$1, so it's not some speculative memecoin you're getting into.
Of course, you can turn this on and off as you like.
[Learn more](../guide/payments/stripe-integration#crypto-stablecoins)
## Record payments and partial payments
We’ve increased the limit on the number of webhook endpoints available in your Lago app!
You can now add up to 10 webhook endpoints in the developer section.
[Learn more](../guide/webhooks#adding-a-webhook-url)
## Add fees to your draft invoices
As communicated, we no longer generate fees at 0 units, but you can still add them to Draft invoices if no event has been received.
Don’t hestiate to navigate into a Draft invoice and add fees linked to charges with no Event.
[Learn more](../guide/invoicing/draft-invoices#add-fees-to-draft-invoice)
## Retrieve a wallet transaction endpoint
We’ve added a new endpoint to the wallet experience!
No need to query the full wallet transaction list to view the details of a specific transaction—you can now retrieve a single wallet transaction directly with the new `GET /wallet_transactions/{lago_id}` endpoint.
[View endpoint](../api-reference/wallets/get-specific-transaction)
## Let Lago sync your customers directly with Salesforce!
We’ve streamlined the Salesforce integration experience.
Like all our other integrations, you can now set up the creation of a customer in Lago to sync with Salesforce.
If you need to test the Salesforce package, feel free to [reach out](mailto:hello@getlago.com)!
[Learn more](../integrations/crm/salesforce-crm#sync-customers-to-salesforce-v2-7)
## No need to leave Salesforce to apply coupons to accounts!
We understand that sales teams prefer to stay within Salesforce as much as possible, so we’ve enhanced the Salesforce integration.
You can now select specific coupons and apply or remove them directly to or from your accounts in Salesforce—no need to switch to Lago.
[Learn more](../integrations/crm/salesforce-crm#applying-coupons-to-accounts)
## Display custom invoice sections
Tailor invoices to each customer by adding personalized bank details!
With the custom invoice section, you can easily personalize templates and include essential details like legal information, all conveniently displayed in the footer.
Head to **Settings > Invoices > Invoice Custom Section** to try out this new feature.
[Learn more](../guide/invoicing/download-invoices#add-custom-invoice-section)
Users can now filter the list of credit notes (e.g. by currency, customer, issuing date, amount, reason, etc.) and the filtered list can then be exported from the user interface.
Two export options are available:
* Standard, including the list of credit notes and credit note amounts (i.e. one row per credit note); and
* Advanced, including the list of credit note line items (i.e. one row per line item, so multiple rows per credit note if it includes multiple items).
The list is automatically emailed to the requester in a CSV file.
[Learn more](../guide/invoicing/export#filter-and-export-credit-notes)
## Granular API key permissions
You can now customize permissions for API keys in Lago! 🔒
When creating or editing an API key, you can define **read**, **write**, or **read and write** access for every object in the Lago API. This gives you full control over which endpoints can be accessed and how.
If an API key doesn’t have the required permissions, the API will block the request, ensuring enhanced security and precise access control.
[Learn more](../guide/security/api-keys#set-api-key-permissions)
You can now instantly update dunning campaign thresholds, delays, and attempts to fit your needs—changes may trigger new attempts for linked customers. No longer need a campaign? Delete it! Customers will either switch to the default campaign or be excluded if none exists.
[Learn more](../guide/dunning/automatic-dunning#edit-a-dunning-campaign)
## Create new API keys
Oops! Think your API key might be exposed, or just want to rotate it to stay safe? No worries—you don’t need to reach out to us. You can now quickly roll your key anytime in the Developer section.
[Learn more](../guide/security/api-keys)
## Automatic dunning: Payment reminders on autopilot
For businesses billing on usage, keeping payments timely is essential. That's why we're introducing **Automatic Dunning**—a hands-off way to manage overdue invoices and keep cash flow steady.
With Automatic Dunning, you can **set up tailored reminder campaigns** for different customer groups. Once activated, **these campaigns run on autopilot**, sending scheduled email reminders for any unpaid invoices. Reminders will keep going until the payment is made or you adjust the settings.
Automatic Dunning keeps your payment reminders on autopilot, so you can focus on what matters while your billing engine handles collections in the background.
[Learn more](../guide/dunning/automatic-dunning)
## Customizable rounding for usage metrics
Previously, usage rounding in Lago was limited to a default precision. Now, with **Customizable Rounding Rules**, you have full control over how usage-based metrics are rounded.
Choose from these rounding options:
* **Ceil**: Always round up to the nearest integer.
* **Floor**: Always round down to the nearest integer.
* **Round**: Round to the nearest integer using standard rounding rules.
Additionally, you can specify a **precision level**—positive or negative—allowing you to round usage to a set number of decimals.
[Learn more](../guide/billable-metrics/rounding)
## Build any usage-based metric with SQL expressions
Previously, usage-based metrics in Lago were powered by a single field—ideal for simplicity but limited in flexibility. Now, we are giving you complete control with SQL Expressions.
**With SQL Expressions, you can build metrics tailored to your needs**. Use advanced math operations, concatenations, rounding, and more to create precise, custom metrics that reflect your unique usage patterns.
**Custom expressions allow you to define more advanced computation logic** by dynamically using any event field within your expression. Here are a few examples:
* **Concatenation:** `CONCAT(value1, '_', value2)`
* **Math operations:** `((value1 * value2) / value3)`
* **Rounding:** `ROUND(value1 / value2)`
```SQL SQL Expression example theme={"dark"}
CEIL((event.properties.ended_at - event.timestamp) / 3600)
```
[Learn more](../guide/billable-metrics/sql-expressions)
## Cascade plan editions to overridden subscriptions
You have now the flexibility to decide whether changes made to the parent plan should automatically cascade to all overridden subscriptions.
For instance, if you add a new charge to the parent plan, it will immediately reflect in the overridden subscriptions, ensuring that all pricing updates are seamlessly applied across your entire customer base while maintaining the flexibility of custom pricing.
[Learn more](../guide/plans/overview#editing-plans)
## Sync billing data to HubSpot
With Lago’s new integration, you can now seamlessly sync billing data in real time to HubSpot. By connecting your Lago account to HubSpot, you’ll enable the following:
1. **Customer Creation**: Automatically create Contacts or Companies in HubSpot based on your Lago customer data.
2. **Invoice Syncing**: Real-time invoice sync to a HubSpot custom object named `LagoInvoices`.
3. **Subscription Syncing**: Real-time subscription sync to a HubSpot custom object named `LagoSubscriptions`.
[Learn more](../integrations/crm/hubspot)
## Quote in Salesforce CPQ, bill in Lago!
Our enhanced Salesforce package now enables you to use Salesforce CPQ for quoting leads and customers.
**Once a quote is approved and signed, it automatically triggers a real-time subscription in Lago**.
No need for separate processes—your sales team can directly create subscriptions from validated quotes within Salesforce.
[Learn more](../integrations/crm/salesforce-cpq)
## Dynamic pricing
Do your prices change dynamically based on a provider or complex in-house calculations?
Here are some real-life use cases:
* 🤖 AI companies: prices fluctuating based on real-time models cost
* 🏦 Fintech: matching prices to live market data
* 📱 Telco/CPaaS: adjusting costs to fluctuating carrier rates
We've heard you, and we're excited to introduce Dynamic Pricing for this!
You can now set a charge model as Dynamic and send the event amount directly through each event. No more headaches trying to manage interchange fees or fluctuating custom prices.
[Learn more](../guide/plans/charges/charge-models/dynamic)
We’ve **completely reworked the Customer Portal**. You can now embed the portal URL to display in real-time **plans and usage information**, **wallet data**, **customer info**, and **invoice lists**.
Additionally, your end customers can take actions directly within the portal, such as **adding prepaid credits** and **updating their customer info**—all automatically synced with your Lago back office.
**Cherry on top?** We’re offering the new Customer Portal **for free** to all users, including those on our open-source plan.
## Usage ingestion sources
Premium ingestion sources for metering and usage consumption are now **generally available**.
Instead of using the basic API, you can leverage dedicated connectors to ingest data directly from sources like **AWS S3**, **AWS Kinesis**, **Kafka**, **MongoDB**, and **Azure**.
Most connectors support ingestion rates of **over 15,000 events per second** (compared to 1,000 via the basic REST API).
For custom ingestion connectors, please contact the Lago team.
[Learn more](/guide/events/metering-source)
## Customer type

Users can specify whether the customer is a company or an individual by setting the customer type.
By default, if no customer type is specified, customers are created without a defined type and you will need to assign one manually.
[Learn more](/guide/customers/customer-management#companies-vs-individuals)
## Send tax invoices

Lago invoices are now fully compliant with local legislation in Australia, Indonesia, New Zealand and the United Arab Emirates.
In those countries, it is mandatory to emit "Tax Invoices" accord to specific rules. This can now be handled with Lago.
## Retrieve all events using the API
Users can now retrieve and filters all events using the API. The endpoint also allows for filtering by:
* `code`
* `external_subscription_id`
* `timestamp_from`
* `timestamp_to`
[Learn more](/api-reference/events/list-events)
## Billing assistant capabilities
1. **Automate repetitive tasks:** Bulk updates, batch operations, and routine billing actions;
2. **Query billing data instantly:** Get quick answers without clicking through multiple screens;
3. **Streamline manual operations:** Create invoices, apply coupons, manage subscriptions and more, all through conversation;
4. **Receive actionable responses:** Formatted results with clickable links to relevant records; and
5. **Work faster with context:** The assistant remembers your past conversations for seamless follow-ups.
## Getting started
### Requirements
To use the AI Agent, you need access to your Lago organization and have the AI chat permission enabled for your account.
## Tips for best results
* **Be specific:** "Show invoices over \$1,000 from last month" works better than "Show me some invoices";
* **Use follow-ups:** After getting a list, ask follow-up questions like "Tell me more about the first one" or "Retry all of these";
* **Specify timeframes:** Include date ranges when relevant ("in the last 30 days", "from Q3");
* **Name entities clearly:** Use customer `external_id`, invoice `id`, or useful identfiers when you have them; and
* **Chain tasks together:** Complete related operations in one conversation to save time.
## Technical details
### System Overview
```mermaid theme={"dark"}
flowchart LR
Frontend["Frontend
## How forecasting works
### Data-driven predictions
The ML pipeline uses historical usage data, grouped by billable metric, subscription, charge, and charge filter to identify patterns and trends and train ML models.
The target variable to forecast is future paid usage, as opposed to just invoiced usage which may or may not be eventually paid.
The model generates forecasts for 12 months ahead at monthly granularity.
As a rule of thumb, the forecasts are updated in the first 2 weeks of the month.
### Forecasting methods
The system supports two main forecasting approaches:
#### 1. Trained ML Models
Advanced machine learning models that learn from historical patterns, including:
* **LightGBM**: Gradient boosting model with quantile loss for probabilistic forecasting
* **N-BEATS**: Deep learning neural network specialized for time series
* **Ensemble**: Combines multiple models for improved accuracy
These models generate three forecast scenarios (conservative, realistic, and optimistic) based on different probability quantiles.
#### 2. Historical Mean
A simpler baseline method that uses historical average usage as the forecast. It is used whenever there is insufficient data to train ML models.
### Probabilistic forecasting
All trained model forecasts include three scenarios:
* **Conservative**: Lower-bound estimate for cautious planning
* **Realistic**: Median forecast representing the most likely outcome
* **Optimistic**: Upper-bound estimate for best-case scenarios
This probabilistic approach helps you understand the range of possible outcomes and plan accordingly.
### Subscription growth
We explicitly model the growth in the number of subscriptions using the historical data of your organization.
### Limitations
The models forecast the future usage amounts for a subset of all potential future revenue sources. For example, it doesn't explicitly account for new business products and features.
Recently created and unused/deleted billable metrics and charges can be excluded from the forecasts.
## Filtering options
Filter forecasted usage data by:
* Currency
* Customer country
* Customer external ID
* Customer type
* Customer has TaxID
* Plan code
* Subscription external ID
* Billable metric
### Time-based MRR analysis
You can analyze your Monthly Recurring Revenue (MRR) data using different time groupings:
* **Daily**: View day-by-day MRR breakdown
* **Weekly**: Aggregate MRR data by week
* **Monthly**: See monthly MRR trends and patterns
### MRR breakout
The graph details the MRR flows for a selected time period. It includes the following elements:
* **New MRR:** The MRR generated from new subscriptions during the selected period.
* **Expansion MRR:** The MRR generated from existing subscriptions that have been upgraded during the selected period.
* **Contraction MRR:** The MRR lost from existing subscriptions that have been downgraded during the selected period.
* **Churn MRR:** The MRR lost from existing subscriptions that have been canceled during the selected period.
### Starting MRR vs Ending MRR
The graph also includes the Starting MRR and Ending MRR for the selected time period. The sum of the MRR breakout described above should equal the difference between the Starting MRR and Ending MRR.
### Growth metrics
For the selected time period, you can track:
* **Total MRR**: Absolute MRR total
* **Growth Percentage**: Period-over-period MRR growth rate
### Filtering options
* Date range selection
* Currency
* Customer country
* Customer external ID
* Customer type
* Plan code
* Subscription external ID
# Overview
Source: https://getlago.com/docs/guide/analytics/overview
Lago is your go-to solution for in-depth billing analytics data, enabling you to accurately calculate revenue with ease.
Our commitment to delivering valuable insights drives us to regularly expand our suite of revenue dashboards.
These dashboards are not just a feature; they're the very first thing you encounter when you log in to your Lago account,
ensuring you have immediate access to critical financial information. Additionally, users can access this data via our API for seamless integration.
## Currency filter
Keep in mind that our revenue analytics dashboards are segmented by currency.
If you have invoices in multiple currencies, please note that no conversion rate is applied.
## Time grouping
In the user interface, you can easily group metrics by various timeframes to gain better insights into your data. The available options are:
* `1D`: Group revenue metrics by day for daily insights
* `1W`: Group revenue metrics by week for weekly trends
* `1M`: Group revenue metrics by month for monthly overviews
## API-Driven revenue insights
At Lago, our analytics dashboards are accessible through both the user interface and dedicated API endpoints.
When interacting with our APIs, you have the flexibility to fine-tune your data retrieval by incorporating currency-based
filters. This means you can seamlessly obtain the insights that matter most to you, all while harnessing the power of
Lago's analytics capabilities.
## Data refresh strategy
Lago optimizes data retrieval for revenue analytics in both UI and API endpoints through strategic caching.
This ensures faster performance. However, it's important to note that **this data is refreshed every day around 12:00 AM UTC**.
Consequently, there may be a slight delay in reflecting the most current revenue data at the time of access.
# Prepaid credits
Source: https://getlago.com/docs/guide/analytics/prepaid-credits
This dashboard provides an overview of your prepaid credits flows within a specific time period.
## Prepaid credits flows
This graph displays the prepaid credits flows for a selected time period. It includes the following elements:
1. **Offered credits**: The total amount of credits granted for free to your customers;
2. **Paid credits**: The total amount of credits paid and invoiced to your customers;
3. **Consumed credits**: The total amount of credits consumed by your customers; and
4. **Voided credits**: The total amount of credits expired or voided.
### Time-based prepaid credits analysis
You can analyze your Prepaid Credits data using different time groupings:
* **Daily**: View day-by-day prepaid credit flow breakdown
* **Weekly**: Aggregate prepaid credit flow data by week
* **Monthly**: See monthly prepaid credit flow trends and patterns
### Filtering options
* Date range selection
* Currency
* Customer country
* Customer external ID
* Customer type
* Subscription external ID
### Time-based revenue streams analysis
You can analyze your revenue data using different time groupings:
* **Daily**: View day-by-day revenue breakdown
* **Weekly**: Aggregate revenue data by week
* **Monthly**: See monthly revenue trends and patterns
### Revenue types
Revenue is categorized into four main streams:
* **Subscriptions**: Recurring revenue from subscription plans
* **Usage-based**: Revenue generated from consumption-based billing
* **Commitments**: Revenue from committed spending agreements
* **One-off Invoices**: Revenue from single, non-recurring charges
### Gross vs net revenue
The dashboard displays both gross and net revenue figures:
* **Gross Revenue**: Total revenue before any deductions
* **Contra revenue**: Details of all contra revenue, including coupons, discounts, and credits
* **Net Revenue**: Final revenue after applying contra revenue
### Growth metrics
For the selected time period, you can track:
* **Total Revenue**: Absolute revenue figures for each stream
* **Growth Percentage**: Period-over-period growth rates
### Filtering options
* Date range selection
* Currency
* Customer country
* Customer external ID
* Customer type
* Plan code
* Subscription external ID
# Aggregation examples
Source: https://getlago.com/docs/guide/billable-metrics/aggregation-types/aggregation-examples
Imagine you are a Tracking API company (such as
[Segment.com](https://www.segment.com/)). For the same events received, the
result provided by the aggregation types proposed by Lago is completely
different. This result is used to charge your customers.
## Example of events received[](#example-of-events-received "Direct link to heading")
You decided to charge the `Tracked Pages`. **This is your Billable metric.**
Here are the 2 events sent by your backend to Lago, based on the consumption of
a customer:
```json Event received n°1 theme={"dark"}
{
"transaction_id": "1111-1111-1111-1111",
"external_customer_id": "1",
"timestamp": "2022-03-16T00:00:00Z",
"code": "tracked_pages",
"properties": {
"tracked_user_id": "1234-5678-9098-7654",
"pageviews": 10
}
}
```
```json Event received n°2 theme={"dark"}
{
"transaction_id": "2222-2222-2222-2222",
"external_customer_id": "1",
"timestamp": "2022-03-17T00:00:00Z",
"code": "tracked_pages",
"properties": {
"tracked_user_id": "1234-5678-9098-7654",
"pageviews": 20
}
}
```
Let's see below the differences between the aggregation types.
## Differences between the aggregation types[](#differences-between-the-aggregation-types "Direct link to heading")
| Aggregation | Code | Units to be charged |
| ---------------- | -------------------------------------------------------- | ------------------- |
| **COUNT** | `COUNT(tracked_pages)` | 2 |
| **SUM** | `SUM(tracked_pages.properties.pageviews)` | 30 |
| **MAX** | `MAX(tracked_pages.properties.pageviews)` | 20 |
| **COUNT UNIQUE** | `UNIQUE_COUNT(tracked_pages.properties.tracked_user_id)` | 1 |
Based on the aggregation type you defined for your Billable metric
`Tracked Pages`, the result that is going to be charged to your customer is
completely different. Make sure to choose the right aggregation type for all
your Billable metrics. If you need help, don't hesitate to reach out the Lago
Team!
# COUNT
Source: https://getlago.com/docs/guide/billable-metrics/aggregation-types/count
The count aggregation type is straightforward. It tallies the exact number of events received during a period.
## COUNT billable metric
## UNIQUE COUNT billable metric
## LATEST billable metric
## MAX billable metric
## SUM billable metric
## WEIGHTED SUM billable metric
# Billing entities
Source: https://getlago.com/docs/guide/billing-entities
Billing entities allow an organization to manage different billing configurations.
## Embedding the dashboard
You can also use the API to generate an embeddable Customer Portal that can be displayed in your application by using an iframe. To do so, use the endpoint `/customers/:external_customer_id/portal_url` to generate an embeddable URL that can be displayed in your user interface.
### 2. Customer information
In addition to viewing their invoice list, customers can retrieve essential billing information, including legal name, tax identification number, billing email, and billing/shipping addresses.
Customers can also update this information directly through the portal, ensuring that their billing details remain synchronized with the latest data.
### 3. Plans and usage information
In addition to viewing their invoices and customer details, customers can access their subscriptions and usage directly through the portal.
For subscription details, they can view key information such as the plan name, recurring fee, and subscription renewal date.
Customers also have real-time access to comprehensive usage details, including:
* Total lifetime usage and the next threshold for subscriptions using progressive billing;
* A detailed usage report, showing the number of units consumed and associated costs; and
* A full breakdown of usage by billing filters and groups.
### 4. Prepaid credits information
The customer portal provides your customers with real-time access to their prepaid credit balance, showing the remaining credits based on their current usage.
Additionally, customers can top up their paid credits, ensuring their wallet is always sufficiently funded.
# Invoice a customer
Source: https://getlago.com/docs/guide/customers/invoice-customer
If a customer has an active subscription, Lago will automatically generate an [invoice](/guide/invoicing/overview) for them at the end of the billing period.
## Bill following your customer's timezone
By clicking on it, a panel opens so you can:
* Review the invoices included in the overdue balance,
* Review the email which will be sent in case the payment fails, or if no payment provider is linked
* Confirm you want to request the payment.
As mentioned above, some information in the email template can be customized based on the settings of your account, including:
1. The logo of your organization;
2. The name of your organization; and
3. The email address of your organization.
# Entitlements
Source: https://getlago.com/docs/guide/entitlements
Unify entitlements and billing in one streamlined platform with Lago.
In a billing system, entitlements define what a customer can access and how much they can use, based on their subscription or contract.
This includes feature gates, which control whether a feature is enabled or disabled for a given customer; feature privileges, which determine the level of access within a feature, such as basic or advanced functionality; allowances, which represent the included usage in a plan, like 100 API calls per month; and quotas, which are the maximum usage limits that may trigger overage charges or access restrictions. Together, these components help enforce product limits, manage access, and support accurate usage-based billing.
In addition to the usage-based engine for allowances and quotas, Lago lets you define Features and Entitlements.
## Set up your features
To assign features to a plan:
1. Create a new plan or edit an existing one;
2. Navigate to the **Advanced Settings** section;
3. Select the features you want to entitle for that plan; and
4. Configure the values for each feature's privileges according to the plan's rules.
## Accessing a specific event[](#accessing-a-specific-event "Direct link to heading")
In the events list view, by clicking on a specific event, you will have access to 2 main
blocks:
1. **A list of useful properties returned**
* **Time:** timestamp of the received events;
* **Customer ID:** the ID of your customer;
* **Billable metric code:** code of the billable metric linked to the event;
* **Billable metric name:** name of the billable metric linked to the event;
* **Transaction ID:** unique `transaction_id` of the event used as
idempotency key;
* **IP Address:** IP address of the event sender; and
* **Client API:** Lago Client API used to send the event.
2. **A JSON with event's arguments sent in the payload**
## Possible warnings[](#possible-warnings "Direct link to heading")
Some events can be ingested but triggering a bad or unexpected behavior. This is
why Lago displays in the UI two possible warnings:
1. The event `code` is **not related to an existing billable metric**; and
2. The billable metric's **property used for the aggregation is not sent**
through this event.
# Ingesting usage
Source: https://getlago.com/docs/guide/events/ingesting-usage
This guide explains how Lago ingests usage-based events coming from your application.
## Define a billable metric[](#define-a-billable-metric "Direct link to heading")
**Usage events are designed to target very specific
[billable metrics](/guide/billable-metrics/create-billable-metrics) created from the UI**. If you don't understand the
concept of billable metrics, we recommend you to read it first.
First things first, you need to define a billable metric from the UI to send
usage measurement events:
1. In the Lago app, go to the **"Billable metrics"** section;
2. Click **"Add a billable metric"**;
3. Add metric information, including:
* `name`
* `code` (used to send events via API)
* `description` (optional)
4. Define whether or not this metric is `recurring`; and
5. Choose an aggregation type to define how usage should be calculated.
Billable metrics represent the features of your product. Events should automatically be sent to Lago by your application
based on your customers' actions.
## Send usage measurements to Lago[](#send-usage-measurements-to-lago "Direct link to heading")
To send usage events to Lago, you need to use the **Lago API**. A measurement
event is JSON with the following fields:
```json theme={"dark"}
{
"transaction_id": "__TRANSACTION_ID__", // (Required) Unique identifier of the event
"external_subscription_id": "__SUBSCRIPTION_ID__", // (Required) Unique identifier of your customer's subscription
"code": "__EVENT_CODE__", // (Required) The billable metric's code
"timestamp": 1650893379, // (Optional) UNIX timestamp of the event
"precise_total_amount_cents": "140", // (Optional) Precise amount cents of the event used for dynamic charge model
"properties": {
"custom_field": 12, // (Optional) Custom variables defined as properties
"operation_type": "add" or "remove" // (Optional) Required only for recurring metric based on the unique count aggregation
}
}
```
## TL;DR: Billing is just 100x harder than you will ever think[](#tldr-billing-is-just-100x-harder-than-you-will-ever-think "Direct link to heading")
"Let's bill yearly as well, should be pretty straightforward" claims the Revenue
team. Great! Everyone is excited to start working on it. Everyone, except the
Tech team. When you start building your internal billing system, it's hard to
think of all the complexity that will pop up down the road, unless you've
experienced it before.
It's common to start a business with a simple pricing. You define one or two
price plans and limit this pricing to a defined number of features. However,
when the company is growing, your pricing gets more and more complex, just like
your entire codebase.
At Qonto, our first users could only onboard on a €9 plan. We quickly decided to
add plans, and 'pay-as-you-go' features (e.g. ATM withdrawals, foreign currency
payments, capital deposit, etc.) to grow revenue.
Also, as Qonto is a neobank, we wanted to charge our customers' wallets
directly, through a ledger connected to our internal billing system. The team
started from a duo of full-time engineers building a billing system (which is
already a considerable investment) to a dedicated cross-functional Pricing team.
This is not specific to Qonto of course. Pleo, another fintech unicorn from
Denmark faced similar issues:
> *"I've learned to appreciate that billing systems are hard to build, hard to
> design, and hard to get working for you if you deviate from 'the standard'
> even by a tiny bit."*
>
> Arnon Shimoni, Product Billing Infrastructure Lead at Pleo
This is not even specific to fintechs. The Algolia team ended up creating a
whole pricing department, now led by Djay, a pricing and monetization veteran
from Twilio, VMWare, Service Now. They switched to a 'pay-as-you-go' pricing
model based on the number of monthly API searches.
> *"It looks easy on paper — however, it's a challenge to bring automation and
> transparency to a customer, so they can easily understand. There is a lot of
> behind-the-scenes work that goes into this, and it takes a lot of engineering
> and investment to do it the right way."*
>
> Bernardette Nixon, CEO at Venture Beat
## Dates[](#dates "Direct link to heading")
When implementing a billing system, dealing with dates is often the number 1
complexity. Somehow, all your subscriptions and charges are based on a number of
days. Whether you make your customers pay weekly, monthly or yearly, you need to
define the billing period.
Here is a non-exhaustive list of difficulties for engineers:
1. How to deal with leap years?
2. Do your subscriptions start at the beginning of the month or at the creation
date of the customer?
3. How many days/months of trial do you offer?
4. Who decided February only holds 28 days?
5. Wait, point 1 is also important for February...
6. How to calculate usage-based charges (price per second, hour, day)?
7. Do I resume the consumption or do I stack it month over month? Year over
year?
8. Do I apply a pro-rata based on the number of days consumed by my customer?
Although every decision is reversible, billing cycle questions are often the
most important source of customer support tickets, and iterating on them is
quite complex. For instance, Qonto switched from 'anniversary' dates to calendar
dates for its billing periods (see
[here](https://medium.com/qonto-way/biller-migration-how-we-changed-our-billing-cycle-cf3c4cdd7cf4)).
This change was not trivial.
## Upgrades & Downgrades[](#upgrades--downgrades "Direct link to heading")
You need to allow your customers to upgrade or downgrade their subscriptions.
Moving from plan A to plan B seems pretty easy, but it's not. Let's zoom on
potential edge cases.
What should we do when the user:
1. Upgrades or downgrades in the middle of a period;
2. Has paid for the original plan in advance;
3. Needs to pay for the original plan in arrears;
4. Downgrades from a yearly plan to a monthly plan;
5. Upgrades from a monthly plan to a yearly plan;
6. Upgrades or downgrades from a plan paid in advance to a plan paid in arrears
(and vice-versa); or
7. Has a discount and upgrades/downgrades?
We did not have a free trial period at the time at Qonto, but Arnon from Pleo
describes this situation
[here](https://arnon.dk/5-things-i-learned-developing-billing-system/).
## Usage-based computations[](#usage-based-computations "Direct link to heading")
Subscription-based billing is the first step when implementing a billing system.
Each customer needs to be affiliated to a plan in order to start charging the
right amount at the right time.
But for a growing number of companies, like Qonto, other charges come alongside
this subscription. These charges are based on what customers really consume.
This is what we call 'usage-based billing'. Most companies end up having a
hybrid pricing model: a monthly subscription fee and 'add-ons' or
'pay-as-you-go' charges on top of it.
These consumption-based charges are tough to track at scale, because they often
come with calculation rules performed on a high volume of events.
Here are some examples:
Segment's pricing is based on the number of monthly tracked users. This means
that they need to count the distinct number of users each month and reset this
value to zero for the next billing period. In order to retrieve the number of
unique visitors, they need to apply a 'distinct' function to deduplicate them.
Algolia tracks the number of API searches per month. This means they need to sum
the number of monthly searches for each customer and reset this value to zero
for the next billing period.
It becomes even more complex when you start calculating charges based on a
timeframe. For instance, Snowflake charges for the compute usage of a data
warehouse per second. This means that they sum the number of gigabytes or
terabytes consumed, multiplied by the number of seconds of compute time.
Consider the example of a utility company that charges \$10 per kilowatt of
electricity per hour. The illustration below shows what needs to be modeled and
automated by the billing system.
* **Hour 1**: 10 KW used for 0.5 hour = 5 KW (10 x 0.5)
* **Hour 2**: 20 KW used for 1 hour = 20 KW (20 x 1)
* **Hour 3**: 0 KW used for 1 hour = 0 KW (0 x 1)
* **Hour 4**: 30 KW used for 0.5 hour = 15 KW (30 x 0.5)
* **TOTAL** = 40 KW used x $10 ⇒ $40
## Idempotency done right[](#idempotency-done-right "Direct link to heading")
Billing errors sometimes occur. Charging a user twice for the same product is
obviously bad for the customer experience, but failing to charge when needed
hurts revenue. That's partly why Finance and BI teams spend so much time on
revenue recognition.
For 'pay-as-you-go' companies, the billing system will process a high volume of
events. When an event needs to be replayed, it needs to happen without billing
the user again. Engineers call it 'idempotency', which means the **ability to
apply the same operation multiple times without changing the result beyond the
first try**.
It's a simple design principle, however, maintaining it at all times is hard.
## The case for a Cash Collection Officer[](#the-case-for-a-cash-collection-officer "Direct link to heading")
Cash collection is the process of collecting the money that customers owe you.
The pet peeve of cash collection is dunning: when payments fail, the merchant
needs to persist and make repeated payment requests to their customers, while
trying not to damage the relationship.
At Qonto, we called these 'waiting funds'. A client's status was 'waiting funds'
when they successfully went through the sign-up, KYC and KYB process but their
account balance was still 0.
For a neobank, the impact is twofold: you can't charge your service fees (e.g.
monthly subscription) and your customer does not generate interchange revenues
(e.g. when you make a payment of $100 with your card, the card issuer earns
$0.5-\$1 of interchange revenue through the merchant's fees).
Therefore, your two main revenue streams are 'null' but you did pay to acquire,
onboard, KYC the user and then to produce and send them a card. We often
half-joked about the need to hire a 'chief waiting funds officer': the financial
impact of this is just as high as the problem is underestimated.
All companies face dunning challenges. For engineers, on top of the billing
architecture, this means that they need to design and build:
1. A **'retry logic'** to ask for a new payment intent;
2. An **invoice reconciliation system** (e.g. if several months of charges are
recovered);
3. An **app logic to disable access** to the service; and
4. An **emailing workflow** to urge a user to proceed to the payment.
Some SaaS are even on a mission to fight dunnings and have built full-fledged
companies around cash collection, such as Upflow, which is used by successful
B2B scale-ups, including Front and Lattice.
> *"Sending quality and personalized reminders took us a lot of time and, as
> Lattice was growing fast, it was essential for us to scale our cash collection
> processes. We use Upflow to personalize how we ask our customers for money,
> repeatedly, while keeping a good relationship. We now collect 99% of our
> invoices, effortlessly."*
>
> Jason Lopez, Controller at Lattice
## The labyrinth of taxes and VAT[](#the-labyrinth-of-taxes-and-vat "Direct link to heading")
Taxes are challenging and depend on multiple dimensions. Taxes depend on what
you are selling, your home country and your customer's home country. In the
simplest situations, your tax decision tree should look like this:
Now, imagine that you sell different types of goods/services to different types
of customers in 100+ countries. If you think the logic on paper looks complex,
the engineering challenge is tenfold. Engineers need to think of an entire tax
logic within the application. This pyramidal logic is based on customers and
products, including:
1. **Taxes at company level**: your company will have a general tax rate that
applies to all customers by default;
2. **Taxes at customer level**: the default tax rate can be overridden for each
customer, depending on the dimensions mentioned above (see illustration); and
3. **Taxes at feature level**: this is mostly the case for the banking industry.
At Qonto for instance, banking fees are not subject to taxes but a 20% VAT
rate applies to non-banking features.
With billing, the devil's in the detail, which is why I always cringe when I see
engineering teams build a home-made system, just because they think "it's not
that complex".
If you've already tackled the topics listed above and think it's a good
investment of your engineering time, go ahead and build it in-house, but make
sure to budget for the maintenance work that is always needed. Another option is
to rely on existing billing platforms, built by specialized teams.
To solve this problem at scale, we've adopted a radical approach: we're building
an open-source billing API for product-led SaaS. Our API and architecture are
open, so that you can embed, fork and customize them as much as your pricing and
internal processes require.
If you're interested, you can [get started](https://www.getlago.com/get-started)
here or [book a demo](https://getlago.com/book-a-demo).
# Credit note metadata
Source: https://getlago.com/docs/guide/invoicing/credit-notes/credit-note-metadata
Metadata on a credit\_note object allows you to store additional structured information and context. This is especially useful when integrating Lago with external systems.
For example, after creating a credit note, you can save your government-issued credit note ID, the synchronization status with your ERP, or any internal reference needed for your workflows.
## Formats and contributions
The output type is typically either an **embedded XML file** (PDF/A-3 with XML) or a **standalone XML**, depending on the requirements of each jurisdiction.
Lago supports two standard e-invoicing formats: **UBL (Universal Business Language)** and **CII (Cross Industry Invoice)**.
Using Lago's core templates for these formats, you can extend or customize them to meet the specific requirements of additional jurisdictions.
If your jurisdiction is not yet supported and you'd like to contribute to a new format, please **[contact us](mailto:hello@getlago.com)**.
Here is an example of an Cross Industry Invoice (CII) XML file for Factur-X in France:
```xml theme={"dark"}
Here is the list of filter options you will encounter in Lago:
* **Amount:** Filter invoices by amount;
* **Currency:** Filter invoices based on the currency in which they are issued;
* **Customer:** Filter by the customer associated with the invoices;
* **Disputed:** Filter invoices to show only those that are disputed or undisputed;
* **Issuing Dates:** Filter invoices by their issuing dates;
* **Overdue:** Filter to display only overdue invoices;
* **Payment Status:** Filter invoices by their payment status;
* **Status:** Filter invoices by their status;
* **Type:** Filter invoices by their type;
* **Billing entity:** Filter invoice by their billing entity; and
* **Metadata:** Filter invoices by their metadata (API option only).
## Basic invoices export
The first option is a basic invoice export. This process generates a CSV file containing one row per invoice, based on the filters you have previously applied.
The exported CSV includes relevant invoice details and is sent to the email address of the user who requested the export.
The download link for the CSV file remains valid for 7 days.
## Detailed invoice fees export
The second option is an advanced invoice export. This process generates a CSV file containing one row per fee (line item of your invoices),
based on the filters you have previously applied. The exported CSV includes detailed information on each fee and line item of your invoices, and is
sent to the email address of the user who requested the export. The download link for the CSV file is valid for 7 days.
## Filter and export Credit notes[](#filter-and-export-credit-notes "Direct link to heading")
Please note that the `Credit Notes` list can be filtered and exported. The behavior aligns with the functionality defined above based on the credit note fields.
# Fees
Source: https://getlago.com/docs/guide/invoicing/fees
A fee is a line item in an invoice.
There are few types of fees:
* **Subscription fees** that correspond to the base amount of the plan;
* **Charge fees** that correspond to usage-based charges (i.e. the costs
associated with each billable metric), this fee can be linked to a true-up fee;
* **Add-on fees** that correspond to a line item appearing in a one off invoice; and
* **Credits** that correspond to the consumed prepaid credits.
Information about fees includes (but is not limited to):
* Type;
* Amount;
* Currency; and
* Taxes.
The fee object is embedded within an invoice or credit note object, making it retrievable on its own.
This is illustrated below.:
```json theme={"dark"}
{
"fee": {
"lago_id": "e7e0ee24-7ef3-4b19-8bbf-fb0e75f5c79b",
"lago_group_id": null,
"lago_invoice_id": "ffbafe19-2b8d-4376-9510-314566b90724",
"lago_true_up_fee_id": null,
"lago_true_up_parent_fee_id": null,
"item": {
"type": "add_on",
"code": "test",
"name": "Test ",
"lago_item_id": "1e8d90cb-e305-438b-86b5-a566e97209d0",
"item_type": "AddOn"
},
"pay_in_advance": false,
"invoiceable": true,
"amount_cents": 10000,
"amount_currency": "USD",
"taxes_amount_cents": 3000,
"taxes_rate": 30.0,
"total_amount_cents": 13000,
"total_amount_currency": "USD",
"units": "1.0",
"description": "",
"unit_amount_cents": 10000,
"events_count": null,
"payment_status": "pending",
"created_at": "2023-07-06T21:01:41Z",
"succeeded_at": null,
"failed_at": null,
"refunded_at": null,
"vat_amount_cents": 3000,
"vat_amount_currency": "USD",
"applied_taxes": [
{
"lago_id": "3bdac336-af27-4be4-a4a5-58433f401708",
"lago_fee_id": "e7e0ee24-7ef3-4b19-8bbf-fb0e75f5c79b",
"lago_tax_id": "38325421-2145-4b79-bff1-d38a702afe3a",
"tax_name": "TVA",
"tax_code": "french_standard_vat",
"tax_rate": 20.0,
"tax_description": "French standard VAT",
"amount_cents": 2000,
"amount_currency": "USD",
"created_at": "2023-07-06T21:01:41Z"
}
]
}
}
```
## Update fee payment status
## Define a grace period at billing entity level[](#define-a-grace-period-at-organization-level "Direct link to heading")
The grace period set at the billing entity level applies to all customers linked to this entity by default.
## Application scope[](#application-scope "Direct link to heading")
The net payment term period applies to all types of invoices, and is used to compute the payment due date.
When the `payment_due_date` has passed, the invoice is flagged as overdue (`payment_overdue` = `true`), and Lago emits an `invoice.payment_overdue`
[webhook message](/api-reference/webhooks/messages).
The invoice stays flagged as overdue until the payment is `succeeded`, or `payment_dispute_lost_at` is applied, or the invoice is voided.
## Define a net payment term at entity level[](#define-a-net-payment-term-at-entity-level "Direct link to heading")
The entity's net payment term applies to all customers link to this object by default.
# Lago Cloud
Source: https://getlago.com/docs/guide/lago-cloud
Lago Cloud is the fully hosted version of our open-source billing API.
With a cloud account:
1. You don't have to maintain the solution;
2. You can start building your billing system immediately; and
3. You benefit from automatic updates.
[Request access to Lago Cloud](https://getlago.com/book-a-demo) to get started.
# Lago OpenAPI
Source: https://getlago.com/docs/guide/lago-open-api
Using our Open API is a great way to explore and interact with Lago's API documentation.
## Prerequisites[](#prerequisites "Direct link to heading")
Before you start using our Open API, here are some important prerequisites and useful links:
1. Create a free [Postman](https://postman.com) account;
2. Use the [Swagger](https://swagger.getlago.com/) for Lago's API documentation;
3. Open a Lago account to get your API key; and
4. Check out our public [GitHub repository](https://github.com/getlago/lago-openapi).
## Using Lago Open API with Postman[](#using-lago-open-api-with-postman "Direct link to heading")
The Swagger used to document Lago's API can be imported directly into Postman. To do so:
1. **Copy the following link:** [https://swagger.getlago.com/openapi.yaml](https://swagger.getlago.com/openapi.yaml) (this link can also be found on the Swagger's page);
2. In Postman, under **Import > Link**, paste the URL above;
3. Click **Continue**;
4. Click the **Import** button; and
5. In the menu, under **API**, find the newly created **Lago API documentation**.
It only takes a few seconds to complete the import. You can then use this API to generate a new collection.
Please don't forget to enter the API key associated with your organization's Lago account to authenticate your API requests.
# Useful commands
Source: https://getlago.com/docs/guide/lago-self-hosted/commands
Useful commands for self-hosted users.
Below is a compilation of essential commands tailored for open-source enthusiasts, primarily designed for managing invoicing tasks,
whether for immediate processing or scheduling.
These commands are designed to execute a Rails console (rails c) within a Docker container named api, which is managed by Docker Compose.
```
docker-compose exec api rails c
```
## Dry-run invoice in the future
Use this to simulate a dry run invoice for a future date. Ensure to specify the correct subscription `external_id` and the targeted invoice issuance date.
```ruby theme={"dark"}
# In the rails Console
subscription = Subscription.find_by(external_id: 'YOUR_SUB_EXTERNAL_ID')
date = DateTime.parse('2024-10-01').to_i
BillSubscriptionJob.perform_later([subscription], date)
```
## Issue invoice immediately
Use this to issue an invoice immmediately. Ensure to specify the correct subscription `external_id` and the current date.
```ruby theme={"dark"}
# In the rails Console
subscription = Subscription.find_by(external_id: 'YOUR_SUB_EXTERNAL_ID')
timestamp = DateTime.parse('2024-04-01').to_i
BillSubscriptionJob.perform_now([subscription], timestamp, invoicing_reason: :subscription_periodic)
```
## Remove cache for a subscription
Use this to remove the cache on a specific subscription.
```ruby theme={"dark"}
# In the rails Console
Subscriptions::ChargeCacheService.expire_for_subscription(Subscription.find('YOUR_SUB_EXTERNAL_ID'))
```
To remove the cache for all subscriptions, you can alternatively use this command:
```ruby theme={"dark"}
# In the rails Console
Subscription.find_each {|s| Subscriptions::ChargeCacheService.expire_for_subscription(s) }
```
## Audit logs of a subscription
Use this to view all changes applied to a subscription and identify which membership made those changes.
```ruby theme={"dark"}
# In the rails Console
subscription = Subscription.find_by(external_id: 'YOUR_SUB_EXTERNAL_ID')
subscription.versions
```
# Database maintenance
Source: https://getlago.com/docs/guide/lago-self-hosted/database-maintenance
Keeping your Postgres at its best
Lago relies a lot on Postgres. If you're hosting your own instance, you must ensure Postgres is correctly configured.
First, we recommend installing PgHero and keeping an eye on slow queries: [https://github.com/ankane/pghero]().
## `ANALYZE` and `VACCUM`
Postgres needs to [analyze and vacuum](https://www.postgresql.org/docs/current/routine-vacuuming.html#ROUTINE-VACUUMING) regularly for optimal performance.
Postgres can do it automatically for you. Make sure the `autovacuum_analyze_scale_factor`
and `autovacuum_vacuum_scale_factor` are set to a sensible value. We recommend `0.1` by default,
but it depends on the size of your tables.
```sql theme={"dark"}
SELECT
current_setting('autovacuum_analyze_scale_factor') AS analyze_scale_factor,
current_setting('autovacuum_vacuum_scale_factor') AS vacuum_scale_factor;
```
```sql theme={"dark"}
ALTER SYSTEM
SET autovacuum_vacuum_scale_factor = 0.1;
ALTER SYSTEM
SET autovacuum_analyze_scale_factor = 0.1;
SELECT pg_reload_conf();
```
Some tables need extra attention and usually much lower values: `events`, `invoices`, `charges` and `fees`.
Configure custom override values for these tables.
For example, the `events` table should use a value lower than `0.01`.
Because this factor is a ratio, it's expected to lower it from time to time as your table size grows.
```
ALTER TABLE events
SET (
autovacuum_vacuum_scale_factor = 0.01,
autovacuum_analyze_scale_factor = 0.01
);
```
## Why update your Lago self-hosted instance?
### Bug fixes and security enhancements
Updating your Lago open source instance serves a key purpose: resolving bugs and enhancing security protocols.
Just like any software, glitches may emerge, impacting operations and even jeopardizing security.
This is particularly vital in intricate tasks like metering, billing calculations, tax application, and managing financial statements.
By keeping up with updates, you guarantee your instance remains unaffected by recognized problems and vulnerabilities.
This proactive approach maintains a resilient and secure operational landscape for your company.
### Access to new features
Lago consistently evolves to meet the needs of its users. Each update introduces a host of new features aimed at enhancing the user
experience and expanding the capabilities of the platform. Some notable new features that updates might bring include core billing
enhancements, tax-related features, and additional settings options. By updating regularly, you can take advantage of these features and
streamline your workflows.
## Determining update frequency
The frequency of updates varies based on the development cycle of Lago. Generally, updates are released approximately once a week.
Keeping an eye on the [release notes](https://github.com/getlago/lago/releases) provided by the Lago team will give you insight into when updates are available and what changes they
entail. Regularly monitoring these release notes will allow you to stay informed and plan your updates accordingly. Billing updates occur
frequently, precisely every 1 or 2 weeks. Over the course of a year, we've completed over 70 releases, culminating in approximately
30 comprehensive [product updates](https://www.getlago.com/changelog).
## A seamless update process
Updating your Lago open source instance doesn't have to be a daunting task. With a clear procedure in place, you can ensure
a smooth transition to the latest version. Here's a step-by-step guide to help you navigate the update process:
### 1. Access your instance repository
Navigate to the repository where your Lago open source instance is stored. This is typically where you initially cloned or
downloaded the instance.
### 2. Check you current version
In the repository directory, execute the following command to check the current Lago version:
```bash theme={"dark"}
git describe --tags --abbrev=0
```
### 3. Check for the bridge releases
In the **"Outstanding"** and **"Overdue"** tabs of the **"Invoices"** section, you can also click **"Resend for collection"** in the upper right corner to re-trigger the payment process for all invoices in the respective lists.
# Graduated percentage
Source: https://getlago.com/docs/guide/plans/charges/charge-models/graduated-percentage
Select the graduated percentage model if you want to define several percentage tiers. You can also
apply a **flat fee** per tier in addition to the rate.
Note that the **rate** is the only mandatory value. It's particularly useful for fintech charging graduated rates for a feature.
Consider the following example, where each unit represents an API call:
| Tier | First unit | Last unit | Rate | Flat fee |
| ------ | ---------- | --------- | ---- | -------- |
| Tier 1 | 0 | 1,000 | 1% | \$200 |
| Tier 2 | 1,001 | 10,000 | 2% | \$300 |
| Tier 3 | 10,001 | ∞ | 3% | \$400 |
A first transaction at \$500 would cost (500 units x 1%) + \$200 flat fee = \$205.00;
A second transaction at \$550 would cost \[(500 units x 1%) + (50 units x 2%)] + \$300 flat fee = \$306.00;
A third transaction at \$4,000 would cost (4,000 x 2%) = \$80.00.
# Percentage
Source: https://getlago.com/docs/guide/plans/charges/charge-models/percentage
Select the percentage charge model if you want to apply a **percentage and a
fixed fee on transactions** (e.g. bank transfers, ATM withdrawals, etc.).
This charge model is generally used with billable metrics that allow users to
calculate the total amount of transactions (e.g. `sum` aggregation type and
`amount` defined as the event property -
[learn more](/guide/billable-metrics/aggregation-types)).
You can define several parameters for the percentage charge model, including:
* **Percentage rate**: charge rate that applies to the total amount (e.g. 1.2%
on transactions);
* **Fixed fee (optional)**: fee that applies to each event ingested during the
billing period (e.g. \$0.10 per transaction);
* **Free units (per event - optional)**: number of events that are not subject to
the fixed fee;
* **Free units (total amount - optional)**: amount that is not subject to the
charge rate;
* **Per-transaction spending minimum (per event - optional)**: sets the minimum amount of spending required for each individual transaction; and
* **Per-transaction spending maximum (per event - optional)**: sets the maximum amount of spending required for each individual transaction.
When free units are defined for both the total amount and number of events, Lago
performs checks each time a new event is ingested to determine whether the free
units still apply. In the illustration below for instance, the first 3 events or
\$500 are free.
Consider the following list of events:
| Event | Amount | Total number of events | Total amount | Result |
| ------------- | ------ | ------------------------------ | ------------------ | ---------- |
| Transaction 1 | \$200 | 1 free event (out of 3) | \$200 (\$500 free) | No charges |
| Transaction 2 | \$100 | 2 free events (out of 3) | \$300 (\$500 free) | No charges |
| Transaction 3 | \$100 | 3 free events (out of 3) | \$400 (\$500 free) | No charges |
| Transaction 4 | \$50 | 4 events (free units exceeded) | \$450 (\$500 free) | Charge |
Therefore, for the fourth transaction, the charge will be \$0.10 x 1 event + 1.2%
of \$50 = \$0.70.
# Standard
Source: https://getlago.com/docs/guide/plans/charges/charge-models/standard
Select the standard charge model if you want to charge the **same price for each
unit** consumed.
Imagine that your API company charges \$0.05 per API call (i.e. your billable
metric). By selecting the standard charge model, you will define a fixed unit
price. If a customer makes 1,000 API calls during the billing period, the total
invoice amount will be \$0.05 x 1,000 API calls = \$50.
By sending usage events with a `regions` property, you can include any number of region values. Lago will automatically group and aggregate usage based on the values provided in your events.
```json theme={"dark"}
{
"event": {
"transaction_id": "{{$randomUUID}}",
"external_subscription_id": "8546dce0-d9e6-4544-ac8a-fbc77340cd9f",
"code": "storage",
"properties": {
"gb": 20,
"regions": "us-east-1"
}
}
}
```
# Invoiceable vs Uninvoiceable
Source: https://getlago.com/docs/guide/plans/charges/invoiceable-vs-noninvoiceable
In-advance charges can be either invoiceable or not.
## Update invoice display names[](#invoice-display-names "Direct link to heading")
When creating or updating a charge within our system, you have the flexibility to customize the way it
appears by overriding its default name. This can be achieved by defining an `invoice display name` for the charge.
By doing so, the newly specified name will take precedence and be reflected across all relevant contexts,
including prominently on the invoice template.
# Prorated vs Full
Source: https://getlago.com/docs/guide/plans/charges/prorated-vs-full
Usage-based charges can be either billed fully or prorated based on the number of days used.
You can **determine whether a charge is prorated or fully-billed**. Understanding the distinction between these two types of charges is crucial for effectively managing your billing processes. In this documentation, we will delve into the differences between prorated and fully-billed charges and their implications within the Lago system.
## Prorated charges
For the progressive billing feature, you can configure two types of thresholds: Step-Based Thresholds and Recurring Thresholds.
### Step-based thresholds
### Invoicing during job execution
It's important to note that **threshold billing occurs when our progressive billing job runs** (every 5 minutes by default, though this interval can be adjusted on a case-by-case basis).
This means that Lago does not trigger the invoice immediately when the threshold is crossed but rather at a predefined interval.
As a result, Lago will invoice the total usage at the time the job runs, **which may slightly exceed the threshold**.
For instance, if your billing threshold is \$10 but the job runs when the customer's current usage is \$12, Lago will invoice for the full \$12.
### Charges included in the calculation
**Only charges billed in arrears (recurring or metered) are included in the lifetime usage calculation for progressive billing invoices**.
This means any charges paid in advance are excluded from this progressive billing feature.
### Excluding already billed usage
When a customer crosses a threshold for a specific subscription, Lago will invoice the total usage for the current period,
ensuring that any 'previously billed usage' is excluded.
This approach provides customers with a clear view of their current consumption while preventing them from being charged again
for usage already invoiced under previous thresholds.
It's important to note that the invoice template (as shown below) includes the following details:
* The total usage for the current period;
* An adjustment that excludes previously billed usage; and
* A footer that provides context, explaining the reason for the invoice, including lifetime usage and the threshold that was crossed.
### Grace period edge cases
It's important to note that **progressive billing invoices are not subject to a grace period** and, therefore, cannot be in a `draft` status.
The reason for this is that draft invoices are not `finalized`, and progressive billing calculations are based solely on `finalized` invoices. Including draft invoices in these calculations would significantly alter the accuracy of the progressive billing process.
### Applying discounts
Progressive billing invoices will automatically apply any available discounts, including coupons, prepaid credits, or credit notes.
### Overriding subscription thresholds
To provide maximum flexibility with the progressive billing feature, you can **override the default plan's thresholds for a specific subscription**.
This allows a particular subscription to have its own customized thresholds. You can add or remove thresholds as needed, or even disable the progressive billing feature entirely for a specific subscription.
### Modifying thresholds
You can edit, add, or remove progressive billing thresholds—or even disable this feature—at any time for a plan or subscription.
This flexibility allows you to adjust thresholds to meet your customer's needs without needing to rebuild everything from scratch.
### Being notified
Since progressive billing invoices can be triggered at any time during a billing period, it's crucial to stay informed when a customer crosses a threshold.
Lago sends a [webhook notification](/api-reference/webhooks/messages#subscription-usage-threshold-reached), `subscription.usage_threshold_reached`, providing details about the subscription and the specific threshold that was exceeded.
# Revenue share
Source: https://getlago.com/docs/guide/revenue-share
Model your revenue-sharing structure within Lago.
## Create an API key
## Delete an API key
To delete an API key, navigate to the **Developers > API keys** section and click the delete button. The API key will be permanently deleted and immediately rendered unusable.
Please note that you can only delete an API key if your organization has more than one API key defined.
## API key "Last used" field
For security purposes, a Last used field displays the last time this API key was accessed. This serves as a helpful indicator to determine if the key is still actively in use.
**Example 2:** Start date in the past and subscription fee to be paid in arrears
**Example 4:** Start date in the future and subscription fee to be paid in arrears
Free credits are added to the customer's wallet instantly, while purchased
credits are added to the wallet when payment is confirmed (see below).
Each customer can only have one active wallet.
## Real time wallet balance[](#real-time-wallet-balance "Direct link to heading")
## Expiration date and termination[](#expiration-date-and-termination "Direct link to heading")
By default, if you don't set an expiration date, prepaid credits are carried
over to the next billing period until the wallet balance is zero.
If you define an expiration date, when the date is reached, all remaining
credits are **automatically voided**.
To modify the expiration date of the prepaid credits through the user interface:
1. Open the **"Wallets"** tab and click **"Edit wallet"** on the right;
2. Select **"Edit information"**;
3. Modify the expiration date; and
4. Click **"Edit information"** to confirm.
The expiration date displayed in the app is based on the organization's timezone.
You also have the ability to terminate a wallet manually, before its expiration
date:
1. Open the **"Wallets"** tab and click **"Edit wallet"** on the right;
2. Select **"Terminate wallet"**; and
3. Click again to confirm.
## Accessing the webhook logs
Once a webhook is registered in the app, you can access the webhook logs:
1. Go to the **Developers** section via the sidebar;
2. Open the **Webhooks** tab;
3. Click on the webhook endpoint to see the list of events; and
4. Click the reload icon to see new events (optional).
## Accessing a specific event
You can see the details of a specific event by clicking on it. Depending on the event status, you will have access to two or three main blocks:
1. **A list of properties, including:**
1. **Timestamp:** the timestamp of the event;
2. **Webhook URL:** the URL used to listen to events;
3. **Unique key:** idempotency key associated with the event;
4. **Webhook type:** the webhook type used to understand the action triggered;
5. **Response:** the response code (i.e. acknowledgement of receipt);
6. **Number of retries:** if the event failed, the number of retries attempted;
2. **A JSON snippet with the arguments sent by Lago; and**
3. **If the event failed, an error response will be included.**
## Errors and retries
Your webhook server should response with a 2xx (`200`, `201`, `202`, `204`) status code to acknowledge the receipt of the event. If the response is not supported as a success, Lago will consider it as failed.
Some events generated by Lago may not be received on the user side, which is why Lago displays an error status in the user interface.
# NetSuite
Source: https://getlago.com/docs/integrations/accounting/netsuite
Lago seamlessly integrates with NetSuite, enabling real-time synchronization of billing data with your preferred accounting tool.
### Deploy Lago Scripts
1. Navigate to **Customization > Scripting > Scripts > Create a New Script**;
2. Deploy the Lago script for **All roles** and **All employees** (you can create custom roles if needed); and
3. Make sure to change the script status to `released`.
By deploying this script, you'll generate a **custom endpoint url** that is crucial for the authentication process and enables seamless data synchronization between Lago and NetSuite.
## Mandatory NetSuite settings
To ensure the sync doesn't fail, verify that the following settings are correctly configured. This will enable Lago to sync data to NetSuite properly.
### Remove Locations on invoices and credit memos
Lago doesn't recognize the location field on invoices, which is mandatory by default. To resolve this, remove the location requirement from your invoice form:
1. Navigate to **Customization > Forms > Transaction Forms**;
2. Locate the form related to your invoices;
3. Go to the **Screen Fields** tab; and
4. Find the Location field and **uncheck both the Show and Mandatory checkboxes**.
## Connecting Lago to NetSuite
To fully integrate Lago with NetSuite, start by connecting your Lago instance to a new NetSuite connection.
You can have an unlimited number of NetSuite connections. First, link your NetSuite account to Lago.
Once connected, activate the specific syncs and actions required for your use case.
This ensures that your Lago instance is properly configured to communicate with NetSuite, enabling seamless data synchronization and management.
### Create a new integration in NetSuite
After logging into your NetSuite account, navigate to **Setup > Integration > Manage Integrations > New**.
Enter the required integration details and follow these steps:
* Make sure the [oAuth feature is enabled](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_157771482304.html#To-enable-OAuth-2.0-feature%3A) for your NetSuite instance;
* Make sure the *SOAP WEB SERVICES* and *REST WEB SERVICES* features are enabled in **NetSuite > Company > Enable Features > SuiteCloud**;
* Under Authentication, select **TOKEN-BASED AUTHENTICATION**;
* Disable *TBA: AUTHORIZATION FLOW* and *AUTHORIZATION CODE GRANT*; and
* Save your new integration.
The Client Credentials will be displayed. **Copy the `Consumer Key/Client ID` and `Consumer Secret/Client Secret`** and save them in a secure document for future reference, as this information will not be accessible once you leave the screen.
### Create a new access token in NetSuite
* Log into your NetSuite account and navigate to the homepage by **clicking the home icon**;
* In the **Settings** section at the bottom left corner, locate and click the **Manage Access Tokens** button;
* Select the **Application Name** created for this integration;
* Enter a **token Name**; and
* Save your new access token.
The Token Credentials will be displayed. **Copy the `Token ID` and `Token Secret`** and save them in a secure document for future reference, as this information will not be accessible once you leave the screen.
### Authentication flow
The authentication process connects Lago and NetSuite through OAuth2.
To establish this connection, you need to provide the following mandatory fields:
* **Connection Name:** an internal name for the connection within Lago;
* **Unique Connection Code:** an internal code for the connection within Lago;
* **NetSuite Account ID:** your NetSuite [account identifier](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_1498754928.html#:~:text=You%20can%20find%20your%20NetSuite,an%20underscore%2C%20for%20example%20123456_RP.);
* **NetSuite Client ID:** the [client ID](/integrations/accounting/netsuite#create-a-new-integration-in-netsuite) from your NetSuite account;
* **NetSuite Client Secret:** the [client secret](/integrations/accounting/netsuite#create-a-new-integration-in-netsuite) from your NetSuite account;
* **NetSuite Token Id:** the [token ID](/integrations/accounting/netsuite#create-a-new-access-token-in-netsuite) from your NetSuite account;
* **NetSuite Token Secret:** the [token secret](/integrations/accounting/netsuite#create-a-new-access-token-in-netsuite) from your NetSuite account;
* **Custom RESTlet Endpoint:** The endpoint created from the [custom RESTlet script](/integrations/accounting/netsuite#restlet-script-configuration).
### Enable actions and syncs
Here is a list of syncs and actions that Lago uses with NetSuite. Some are mandatory, while others are optional:
* `Customers`: Syncs or fetch customer data from NetSuite Customers *(mandatory)*;
* `Invoices`: Syncs invoice data to NetSuite Invoices *(optional)*;
* `Credit Notes`: Syncs credit note data to NetSuite Credit Memos *(optional)*; and
* `Payments`: Syncs payment data to NetSuite Customer Payments *(optional)*.
## Mapping items between Lago and NetSuite
**Mapping between Lago and NetSuite is done by Lago Entity → NetSuite Subsidiary**. You can define a
default mapping that applies across all subsidiaries, but a single item (including tax items)
can be mapped differently for each subsidiary. When a mapping is defined for a specific Lago
entity, that entity-specific mapping overrides the default mapping for the corresponding
NetSuite subsidiary. If all your entities share the same mapping, you only need to configure
the default mapping.
Follow these steps to map items or tax items between Lago and NetSuite:
1. Navigate to the **NetSuite Integration** page in Lago;
2. Select the **Item Mapping** tab;
3. Click on the item you want to map;
4. Fill all the required fields; and
5. Save your mapping.
### Mapping a tax item
To override the tax amount for an invoice, sales order, or credit note, you need to map a single tax item from NetSuite.
This mapped item will be used to assign the correct tax amount.
**To ensure taxes are sent from Lago to NetSuite, complete the tax mapping** for the following [tax fields you created here](#create-lago-tax-nexus-type-and-code):
1. Tax Nexus;
2. Tax Type; and
3. Tax Code.
Use the `id` for each item, found either in the UI or in the URL of the specific item. You can define a specific tax mapping for each Lago entity or NetSuite Subsidiary.
### Mapping default objects
Coupons, credit notes, subscription fees, minimum commitments, and prepaid credits require a one-to-many mapping.
Each of these objects must be mapped to a single default item from your NetSuite instance. Lago will use this mapped item
whenever any of these objects appear on the final invoice sent to NetSuite. You can override the default mapping for each Lago entity or NetSuite Subsidiary if needed.
### Mapping custom objects
Billable metrics and add-ons require a one-to-one mapping. Each billable metric, used for usage-based billing, must represent a specific SKU in your NetSuite instance.
You need to map each of these individually. Lago will use the mapped items whenever any of these metrics or add-ons appear on the final invoice sent to NetSuite.
You can override the default mapping for each Lago entity or NetSuite Subsidiary if needed.
## Mapping currencies between Lago and NetSuite
As NetSuite supports multiple currencies for a single customer, it's essential to map the currencies used in Lago to those in NetSuite.
This ensures that all financial data is accurately represented and synchronized between the two systems. To map currencies, follow these steps:
1. Navigate to the **NetSuite Integration** page in Lago;
2. Select the **Currency Mapping** tab;
3. Click the **Add Currency mapping** button; and
4. Map the Lago currency code with the currency ID used in NetSuite.
## Customers synchronization
When creating or updating a Lago customer, you can choose to link it to a NetSuite customer.
The first option is to **automatically create a new customer from Lago to NetSuite**. Follow these steps:
1. Create or update a new Lago customer;
2. Select the targeted NetSuite connection;
3. Check the box labeled 'Create this customer automatically in NetSuite';
4. Choose a NetSuite subsidiary from the list (Lago will fetch the list of subsidiaries from your NetSuite instance); and
5. Save and create this new customer.
If the customer is successfully created in NetSuite, a new field will be displayed in the Lago customer view, providing a direct link to the corresponding NetSuite customer.
The second option is to **import an existing NetSuite customer to a Lago customer**. Follow these steps:
1. Create or update a Lago customer;
2. Select the targeted NetSuite connection;
3. Ensure the box labeled 'Create this customer automatically in NetSuite' is unchecked;
4. Paste the NetSuite customer ID in the appropriate field; and
5. Save and create this new customer.
## Invoices synchronization
If a Lago customer is linked to a NetSuite customer, Lago syncs invoices to NetSuite Invoices in real-time.
It's important to note the following:
* Each fee issued by Lago is synced as a line item on a NetSuite invoice;
* The Lago fee `units` are synced to NetSuite as `quantity`;
* The Lago fee `precise_unit_amount` is synced to NetSuite as `rate`;
* Lago overrides the total tax amount of a NetSuite invoice using the tax item, as NetSuite does not support tax details at the line item level; and
* Any discounts on an invoice (coupon, credit note, or prepaid credits) are synced as negative line items on the NetSuite invoice.
If the invoice is successfully created in NetSuite, a new field will be displayed in the Lago invoice view, providing a direct link to the corresponding NetSuite invoice.
## Credit Notes synchronization
If a Lago customer is linked to a NetSuite customer, Lago syncs credit notes to NetSuite Credit Memos in real-time.
It's important to note the following:
* Each fee refunded by Lago is synced as a line item on a NetSuite Credit Memo;
* Lago overrides the total tax amount of a NetSuite credit memo using the tax item, as NetSuite does not support tax details at the line item level; and
* Any discounts on an credit note (like coupon, for instance) are synced as line items on the NetSuite Credit Memo.
If the credit note is successfully created in NetSuite, a new field will be displayed in the Lago credit note view, providing a direct link to the corresponding NetSuite Credit Memo.
## Enable actions and syncs
Here is a list of syncs and actions that Lago uses with Xero. Some are mandatory, while others are optional:
* `Accounts`: Fetch account data from Xero *(mandatory)*;
* `Customers`: Syncs or fetch customer data from Xero *(mandatory)*;
* `Items`: Fetch item data from Xero *(mandatory)*;
* `Invoices`: Syncs invoice data to Xero *(mandatory)*;
* `Credit Notes`: Syncs credit note data to Xero *(optional)*; and
* `Payments`: Syncs payment data to Xero *(optional)*.
## Mapping items between Lago and Xero
To sync invoices, credit notes and payments to Xero, Lago maps each Lago object to a corresponding Xero object (one-to-one). You can define mappings per Lago entity when different entities require distinct Xero items. If the same mapping applies across entities, configure a default mapping. It will be used for any entity that doesn't have a specific override.
Follow these steps to map an item:
* **Access a Xero Connection in Lago:** navigate to your connected Xero integration within the Lago platform;
* **Select the Item to map:** click on the specific item in Lago that you wish to map to a corresponding Xero item;
* **Fetch Items from Xero:** Lago will automatically retrieve the relevant items from your Xero instance;
* **Map the Item:** choose the appropriate Xero item from the list provided by Lago; and
* **Click 'Save'** to finalize the mapping.
### Mapping a fallback item (mandatory)
The fallback item is a dummy item used as a backup in case the mapping of other objects fails.
To ensure continuous data synchronization between Lago and Xero, this fallback item will be used whenever there is a mapping issue.
### Mapping a payment account (mandatory)
To synchronize invoice payments between Lago and Xero, ensure that at least one payment account is mapped.
To set up a payment account in Xero, follow these steps:
1. Log in to your Xero instance;
2. Navigate to **Accounting > Chart of Accounts**;
3. Select an existing revenue account or create a new one; and
4. When editing or creating the account, ensure the **'Enable payments to this account'** checkbox is selected.
In Lago, you can now map it in the dedicated section '**Account linked to payments**'.
### Mapping custom objects
Billable metrics and add-ons require a one-to-one mapping. Each billable metric, used for usage-based billing, must represent a specific SKU in your Xero instance.
You need to map each of these individually. Lago will use the mapped items whenever any of these metrics or add-ons appear on the final invoice sent to Xero.
## Customers synchronization
When creating or updating a Lago customer, you can choose to link it to a Xero customer.
The first option is to **automatically create a new customer from Lago to Xero**. Follow these steps:
1. Create or update a new Lago customer;
2. Select the targeted Xero connection;
3. Check the box labeled 'Create this customer automatically in Xero'; and
4. Save and create this new customer.
If the customer is successfully created in Xero, a new field will be displayed in the Lago customer view, providing a direct link to the corresponding Xero customer.
The second option is to **import an existing Xero customer to a Lago customer**. Follow these steps:
1. Create or update a Lago customer;
2. Select the targeted Xero connection;
3. Ensure the box labeled 'Create this customer automatically in Xero' is unchecked;
4. Paste the Xero customer ID in the appropriate field; and
5. Save and create this new customer.
**Here is the list of fields that is currently synced to Xero:**
| Lago | Xero |
| ------------------------------------ | ------------ |
| customer | type |
| customer.name | Name |
| customer.email | EmailAddress |
| customer.phone | Phones |
| customer.tax\_identification\_number | TaxNumber |
| customer.address\_line\_1 | AddressLine1 |
| customer.address\_line\_2 | AddressLine2 |
| customer.city | City |
| customer.zip | PostalCode |
| customer.country | Country |
| customer.state | Region |
## Invoices synchronization
If a Lago customer is linked to a Xero customer, Lago syncs invoices to Xero Invoices in real-time.
It's important to note the following:
* Each fee issued by Lago is synced as a line item on a Xero invoice;
* The Lago fee `units` are synced to Xero as `Quantity`;
* The Lago fee `precise_unit_amount` is synced to Xero as `UnitAmount`;
* Lago can send the total tax amount for a specific line item; and
* Lago can apply discount to a specific line item.
If the invoice is successfully created in Xero, a new field will be displayed in the Lago invoice view, providing a direct link to the corresponding Xero invoice.
**Here is the list of fields that is currently synced to Xero:**
| Lago | Xero |
| ------------------------------------------- | -------------- |
| invoice | type |
| invoice.number | InvoiceNumber |
| invoice.status | Status |
| invoice.currency | CurrencyCode |
| invoice.issuing\_date | Date |
| invoice.payment\_due\_date | DueDate |
| invoice.fee.units | Quantity |
| invoice.fee.precise\_unit\_amount | UnitAmount |
| invoice.fee.amount\_cents | LineAmount |
| invoice.fee.taxes\_amount\_cents | TaxAmount |
| invoice.fee.precise\_coupons\_amount\_cents | DiscountAmount |
## Credit Notes synchronization
If a Lago customer is linked to a Xero customer, Lago syncs credit notes to Xero Credit Notes in real-time.
It's important to note the following:
* Each fee refunded by Lago is synced as a line item on a Xero Credit Note; and
* Any discounts on an credit note (like coupon, for instance) are synced as line items on the Xero Credit Note.
If the credit note is successfully created in Xero, a new field will be displayed in the Lago credit note view, providing a direct link to the corresponding Xero Credit Note.
In this example, we are going to build an alert anytime a usage threshold is overcome. Here is a summary of this workflow:
1. Use a **Cron** expression to call the Lago API every X minutes/hours/days
2. Call the [**Current usage**](/api-reference/customer-usage/get-current) endpoint available in Lago to fetch your customers' current usage;
3. Create a **IF statement** to condition the trigger (in our case, messages are triggered above a specific overconsumption); and
4. **Send a message** whenever this threshold is reached. You could use an emailing tool, Slack or a CRM. In our case, we are using Slack.
## 1st Node - CRON expression to repeat tasks at a defined interval
The first node is repeatedly and automatically triggering the automation at a defined interval.
1. Add a new **Node**;
2. Select **CRON** as a new application node;
3. The **Mode** is set to `Every X`; and
4. The **Value** is defined to `10` and the the **Units** to `minutes`.
This will trigger the flow automatically every 10 minutes. You can obviously change the value and the units to your preferred interval.
## 2nd Node - Catch customers' current usage with a HTTP Request
This node is used to fetch current usage from Lago API, using a HTTP request.
1. Add a new **Node**;
2. Select **HTTP Request** as a new application node;
3. Fetch [customers' current usage](/api-reference/customer-usage/get-current) from Lago API;
4. Make sure to set the `API_KEY` and the `Content-Type` as headers of your request; and
5. Execute the node to fetch the payload from Lago's API.
## 3rd Node - IF conditional statement to trigger messages under conditions
This node is used to trigger the alert only when your customers overcome a threshold of usage. Those limits depend on your product and your paying features.
In our present use case, we want to trigger an alert **when the total consumption of usage-based features overcomes \$200**. You could also use the `number of units` consumed or another useful value from the payload.
1. Add a new **Node**;
2. Select **IF** as a new application node;
3. Create a condition for the **TRUE** branch (when conditions are met);
4. The **Value** is the parameter of your condition (in our case the `amount_cents` of the current usage);
5. The **Operation** is the math operation you want to apply (in our case, condition is met when the total `amount_cents` is larger or equal to \$200);
It is important to mention that:
* You can add as many conditions as you need;
* You could add an action when the condition is `FALSE`.
## 4th Node - Send an alert message to Slack
This last node is used to trigger the message. In the example, we use a Slack channel, but you could even decide to send an email directly to your customers when they pass the limits of usage.
1. Add a new **Node**;
2. Select **Slack** as a new application node;
3. Select the targeted **Slack Account** & **Slack Channel**;
4. Choose the option to **POST** a **Message**; and
5. **Define a message** and use the variables of your payload to give context to your customers about their current usage.
# Zapier
Source: https://getlago.com/docs/integrations/alerting/zapier
Here is a typical use case of using Lago with Zapier to create powerful alerting automation.
## Invoice Alerting Example (with Zapier)
In this example, we are going to **build an alert anytime a new invoice is emitted**. To create this workflow, we are using:
1. Lago's webhook when a new invoice is emitted;
2. Zapier as an automation tool, to catch, tranform and send the data; and
3. Slack as the "receiver" to alert your team anytime a new invoice is created.
## 1. Catch a webhook when a new invoice is emitted
Lago automatically creates an invoice when a billable period is over. The invoice's payload gives you a detailed view of what has been invoiced. The first action we need to perform is to catch this invoice with a webhook:
1. In Zapier, create a new Zap;
2. Use the **Webhooks by Zapier** as the trigger of this Zap;
3. Select the **Catch Raw Hook** event trigger;
4. Copy the Zapier Webhook URL and paste it in Lago (**Developers** > **Webhooks** > **Add a webhook**); and
5. Catch your first webhook when an invoice is emitted (whenever you assign an add-on or a subscription).
## 2. Run a script to transform the webhook
In Zapier, create a second action by clicking the `+` icon. This new event action is used to format the webhook with a breakdown of fields that can be used in a message.
1. Select **Code by Zapier** as a new *Event Action*;
2. Click on **Javascript** as the event code language to run;
3. Create a field called `payload`. The value of this field is the full **Raw body** of your invoice object received);
4. Run the script (code snippet below) in the **Code** section;
5. Test the action. If valid, it returns a breakdown of fields.
```javascript theme={"dark"}
var obj = JSON.parse(inputData.payload);
if(obj.object_type == "invoice"){
return obj
}
```
## 3. Send a message to a Slack Channel
Once you catch the breakdown of fields returned by the invoice payload, you can easily use them to create a Slack text message.
In Zapier, create a third action by clicking the `+` icon. This new event action is used to send a message to Slack by using the fields of the invoice payload.
1. Select **Slack** as a new app action;
2. Select the **Send Channel Message** action;
3. Choose the targeted **Slack Account**;
4. Choose the targeted **Slack Channel**; and
5. Create a message by using the fields returned by the payload.
By testing and validating the entire Zap, a Slack message is sent anytime a new invoice is emitted by Lago. You can use the same message example as detailed below:
# HubSpot
Source: https://getlago.com/docs/integrations/crm/hubspot
Lago syncs billing data to HubSpot in real-time.
## Integration configuration
### oAuth connection
To fully integrate Lago with HubSpot, start by connecting your Lago instance to a new HubSpot connection. You can have an unlimited number of HubSpot connections. First, link your HubSpot account to Lago. Once connected, activate the specific syncs and actions required for your use case. This ensures that your Lago instance is properly configured to communicate with HubSpot, enabling seamless data synchronization and management.
1. In Lago, navigate to **Integrations** > **HubSpot**;
2. Create a **new HubSpot connection**;
3. Assign a unique **name** and **code** to the connection;
4. Select the **default targeted object** for Lago customers between HubSpot Contacts or Companies; and
5. Use OAuth2 to grant access to the desired HubSpot account.
There you go, Lago is fully connected to HubSpot!
### List of scopes
Here's a list of scopes you grant to Lago when connecting your HubSpot instance: `oauth`, `crm.objects.companies.read`, `crm.objects.companies.write`,
`crm.objects.custom.read`, `crm.objects.custom.write`, `crm.schemas.companies.read`, `crm.schemas.companies.write`, `crm.schemas.custom.read`,
`crm.objects.contacts.read`, `crm.objects.contacts.write`, `crm.schemas.contacts.read`, `crm.schemas.contacts.write` and `crm.schemas.custom.write`.
### Custom properties deployment
By connecting HubSpot to Lago, **custom properties are automatically added to both your HubSpot Companies and Contacts** (native objects).
These fields are used to sync customer data between HubSpot and Lago.
* `lago_customer_id`: internal id of a Lago customer (unique);
* `lago_customer_external_id`: your customer's external id in Lago;
* `lago_billing_email`: your customer's billing email in Lago;
* `lago_tax_identification_number`: your customer's tax identification number in Lago; and
* `lago_customer_link`: the URL path to the related Lago customer.
You can instruct Lago to automatically create a new Company or Contact in your HubSpot account, or link an existing one by pasting a HubSpot ID into the corresponding Lago customer record.
### Sync subscriptions to HubSpot
Whenever a Lago customer is linked to a HubSpot Contact or Company, **Lago Subscriptions are automatically synced in real-time with the `LagoSubscriptions` object in HubSpot**.
The subscription record is then automatically associated with the corresponding Contact or Company in HubSpot.
### Sync invoices to HubSpot
Whenever a Lago customer is linked to a HubSpot Contact or Company, **Lago Invoices are automatically synced in real-time with the `LagoInvoices` object in HubSpot**.
The invoice record is then automatically associated with the corresponding Contact or Company in HubSpot.
# Salesforce CPQ
Source: https://getlago.com/docs/integrations/crm/salesforce-cpq
Lago syncs billing data to Salesforce in real-time.
## Pre-requisite:
* Salesforce CPQ (> Summer '19)
* Install Lago For Salesforce CRM Package [Lago Base Package](/integrations/crm/salesforce-crm)
## I. Integration configuration
### Install Salesforce CRM Package and complete Integration configuration step
* [Integration configuration ](/integrations/crm/salesforce-crm#install-salesforce-crm-package)
* [Establish and finalize connection](/integrations/crm/salesforce-crm#establish-and-finalize-connection)
### Install Salesforce CPQ Package
To gain premium access to our Salesforce Package application, please don't hesitate to contact us.
You can initiate the installation process **by clicking on the provided link**, which will direct you to the installation
page where you can follow step-by-step instructions for a seamless integration. If you have any questions or need assistance
during the installation, our dedicated support team is here to help you every step of the way.
To ensure a successful installation, please follow these steps:
1. We recommend selecting the **"Install for all users"** option;
2. Click on the **"Install" button**;
3. Make sure to **check the box to grant access to these third-party websites**; and
4. Once completed, you'll have **successfully installed** the Lago Salesforce App.
## I. Integration configuration
### Create integration for Salesforce on Lago Side
To gain premium access to our Salesforce Package application, please don't hesitate to contact us. Login to Lago as admin user, navigate to Settings > Integrations > *Salesforce* (allowed only if team has enabled it for your account), and click "Create new". Enter the following details:
* Name
* Code
* Salesforce Instance (URL of your Salesforce instance)
Make note of the integration code as shown in the connection details - you'll need this later:
### Install Salesforce CRM Package
You can initiate the installation process **by clicking on the provided link**, which will direct you to the installation
page where you can follow step-by-step instructions for a seamless integration. If you have any questions or need assistance
during the installation, our dedicated support team is here to help you every step of the way.
To ensure a successful installation, please follow these steps:
1. We recommend selecting the **"Install for all users"** option;
2. Click on the **"Install" button**;
3. Make sure to **check the box to grant access to these third-party websites**; and
4. Once completed, you'll have **successfully installed** the Lago Salesforce App.
Now, go to your Lago app and past this webhook into the webhook’s settings:
1. Within Lago, navigate to **Developers**;
2. Visit the **Webhooks** tab;
3. Choose `HMAC` as the **mandatory signature type**;
4. Paste your Salesforce webhook URL; and
5. Save this webhook endpoint.
Congratulations! You're ready to sync real-time data from Lago to Salesforce! 🎉
**Option 1: Configure a standard API Base URL**
To establish a connection between your Lago instance and the Salesforce Package, follow these steps:
1. Access Salesforce and locate the **App Launcher**;
2. Find and open the Lago app you recently installed;
3. Within the Lago Base Configuration tab:
* Provide your **Lago API Key** (located in Lago's Developer Section)
* Enter your Lago **API base URL**. Do not insert the `api/v1` at the end of the URL. By default, the valid URL is `https://api.getlago.com/`.
If you want to change the API base URL to another one (e.g., `https://api.eu.getlago.com/` or a custom self-hosted one), please follow option 2.
* Enter lago app URL (**Front End Base URL**). By default, the valid URL is `https://app.getlago.com/` (it will be different for self-hosted).
* Enter Lago Integration code from Step 1 [`Salesforce integration on Lago`](/integrations/crm/salesforce-crm#create-integration-for-salesforce-on-lago-side)
4. **"Save and validate"** your connection; and
* If the **Lago API Key** is valid then only **Start Data Sync** button will be enabled.
5. Click the **"Start Data Sync"** to finalize the connection between Lago and Salesforce.
### Sync subscriptions to Salesforce
Whenever a subscription is created for a Lago Customer, the subscription details will be automatically
synced in real-time with Salesforce using the `Lago Subscriptions` custom object.
Here is a list of Subscription fields that are automatically synced.
Note that this subcription is automatically linked to a Salesforce Account:
* Subscription Id;
* Subscription Name;
* Subscription Start Date;
* Subscription Status;
* Subscription Termination Date (synced when the subscription is terminated);
* Subscription Billing Time (either `calendar` or `anniversary`); and
* Plan Code.
### Sync invoices to Salesforce
Whenever an invoice is issued for a Lago Customer, the invoice details will be automatically
synced in real-time with Salesforce using the `Lago Invoices` custom object.
Here is a list of Subscription fields that are automatically synced:
* Invoices Number;
* Invoice Payment Status;
* Invoice Type (`subscription` or `one-off`);
* Invoice Issuing Date;
* Invoice Amount;
* Invoice File Url; and
* Invoice Currency.
### Sync credit notes to Salesforce
Whenever a credit note is issued for a Lago Invoice, the credit note details will be automatically
synced in real-time with Salesforce using the `Lago CreditNotes` custom object.
### Sync Plans, Add-Ons, Coupons to Salesforce
Plans and Add-ons are synced to Salesforce when we initially click on **Start Data Sync** from Lago Base Configuration page.
* Plans are synced to `Lago Plans` object and `Product2` standard object. We also create a *price book entry* for all the products in `Standard Price Book` price book
* Add-Ons are synced to `Lago Add-Ons` object and `Product2` standard object. We also create a *price book entry* for all the products in `Standard Price Book` price book.
### Sync coupons and applied coupons to Salesforce
Coupons and Applied coupons are synced to Salesforce when we click on **Start Data Sync** from Lago Base Configuration page.
* Coupons are synced to `Lago Coupons` custom object. All the existing coupons will be available in Salesforce. Please note: we cannot create coupons from Salesforce to Lago, we must create coupons in Lago.
* Applied coupons are synced to `Lago Applied Coupon` custom object.
### Schedule Sync from Lago To Salesforce
We also provide option to schedule the data sync from Lago to Salesforce.
* `LagoSyncScheduleable` -- a schedulable class which helps us schedule either all the data or any one of them.
* To schedule the sync of any *ONE* of the object:
* Create a new instance of class by passing any one of the following string: `CUSTOMER`, `SUBSCRIPTION`, `PLAN`, `ADDON`, `INVOICE`, `CREDITNOTE`
* Ex: To sync Plans from lago to Salesforce everyday at 1PM, execute below anonymous code in Anonymous window in Developer Console. ([click here to learn more about CRON expression](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm))
```
//Create a new instance. Pass 'PLAN' in brackets.
lago.LagoSyncScheduleable syncPlan = new lago.LagoSyncScheduleable('PLAN');
//CRON expression to schedule a job everyday at 1 PM
String schedule_cron = '0 0 13 * * ?';
//schedule(name, cron_expression, class_instance)
System.schedule('Sync Lago Plan', schedule_cron, syncPlan);
```
* To schedule the sync of *ALL* the objects:
* create a new instance of class by passing `true`
* Ex: To sync **all** objects from lago to Salesforce everyday at 1PM, execute below anonymous code in Anonymous window in Developer Console. ([click here to learn more about CRON expression](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm))
```
//Create a new instance. Pass true in brackets.
lago.LagoSyncScheduleable syncAll = new lago.LagoSyncScheduleable(true);
//CRON expression to schedule a job everyday at 1 PM
String schedule_cron = '0 0 13 * * ?';
//schedule(name, cron_expression, class_instance)
System.schedule('Sync Lago all', schedule_cron, syncAll);
```
## III. Actions from Salesforce to Lago
Beyond just syncing data from Lago to Salesforce, you can also initiate actions in Lago directly from Salesforce.
You can leverage Salesforce `Flows` to execute actions in Lago. Lago provides several customizable templates for creating customers from Salesforce Accounts, directly assigning subscriptions to customers from Salesforce, creating one-off invoice from salesforce.
### Create customers
#### Flow: `Lago Template - Create Customer in Lago on Account Create`
To create a customer in Lago upon the creation of a Salesforce Account, utilize the Flow template provided by Lago.
1. Log into your Salesforce instance;
2. Access the Setup section via the settings wheel icon in Salesforce;
3. Find and select `Flows` under Process Automation in the sidebar;
4. Locate and open the `Lago Template - Create Customer in Lago on Account Create`;
5. Click 'Save As' to create and save your own version of the template; and
6. Do not forget to click the `Activate` button to activate your flow.
You have the **flexibility to modify various aspects of this flow, including the trigger conditions and field mappings**.
By default, the action is initiated when a Lago ID is absent. Additionally, you can customize how fields are mapped from your Salesforce instance to Lago. You can also configure `customer type` to 'Individual' or 'Company' which creating customer from Salesforce to Lago.
### Create subscriptions (automation)
Assigning a plan to a customer, adjusting negotiated prices, and initiating the subscription upon winning an opportunity represents a key action from Salesforce to Lago.
This enables sales teams to remain within Salesforce, their primary tool, and activate billing processes directly, without the need to switch platforms.
To assign a subscription and set prices in Lago directly from Salesforce, use the provided two flows via following Lago Flow templates.
#### Flow 1: `Lago Template - Create Lago SObject Records`
This Flow is used to create intermediate records in Lago Objects - `Lago Subscription`
1. Log into your Salesforce instance;
2. Access the Setup section via the settings gear icon in Salesforce;
3. Find and select `Flows` under Process Automation in the sidebar;
4. Locate and open the `Lago Template - Create Lago SObject Records`;
5. Click 'Save As' to create and save your own version of the template; and
6. Do not forget to click the `Activate` button to activate your flow.
### Managing Coupons in Salesforce
The Salesforce integration allows you to manage customer coupons directly from your Salesforce interface. This section explains how to apply new coupons to customer accounts and manage existing coupons effectively.
#### Applying Coupons to Accounts
Before you begin applying coupons, you'll need to ensure your Salesforce environment is properly configured. The "Apply Coupon" action button must be available in your account page layout or lightning record page. If you don't see this button, work with your Salesforce administrator to add it through the page layout editor or lightning app builder.
Once your environment is configured, follow these steps to apply a coupon to a customer account:
1. Navigate to the Account Details> Access the account details page for the customer who will receive the coupon.
2. Initiate Coupon Application > Click the "Apply Coupon" action button. This will open a popup dialog for coupon configuration.
3. Select and Configure the Coupon. The configuration options will vary depending on the type of coupon you're applying:
* For Fixed Amount Coupons: Enter the discount amount, select the appropriate currency, Choose the frequency for applied coupon
#### Terminating Active Coupons
There may be times when you need to end a coupon's application before its natural expiration. Here's how to terminate an active coupon:
1. Access the Coupon Record. Navigate to the Applied Coupon details page for the coupon you wish to terminate.
2. Initiate Termination, locate the "Terminate Coupon" checkbox in the record.
3. Confirm Termination: Check the box to initiate the termination process. Upon saving:
* The coupon status will update from "Active" to "Terminated"
* The change will synchronize with Lago
* The customer will no longer receive the discount
## 2. Select a destination
You can select any of the data destinations available in Airbyte. It could be a warehouse (BigQuery, Redshift, Snowflake...) or a file storage tool (S3, for instance). Please find here the entire list of [data destinations available in Airbyte](https://docs.airbyte.com/integrations/destinations/).
## 3. Sync billing data
In the following example, we connected Lago billing data to Snowflake data warehouse. Obviously, you can select another destination if needed.
1. Create a **data sync** between Lago source and your destination;
2. Define a **sync frequency**; and
3. Activate the sync in Airbyte between Lago source and your destination.
This action will populate Lago billing data into a warehouse (Snowflake in our example).
## 4. Query Lago billing data
Once the data has been populated in your destination, a warehouse in our example, you can easily query your billing data. Here is a query calculating your monthly revenue with Lago:
# Lago Data Pipeline
Source: https://getlago.com/docs/integrations/data/lago-data-pipeline
Sync your Lago data with your data warehouse or cloud storage
Lago Data Pipeline lets you automate the flow of your billing, subscription, and usage data into your analytics and storage systems.
Whether you're running complex queries on warehouses, or simply building data visualization dashboards for your finance team, you can keep all your data in sync with just a few clicks.
## Prerequisites
* **Data sync frequency:** 1 day by default, but we can go down to 15 minutes;
* **Data transfers:** Incremental or Backfill; and
* **Data security:** high-level of security and encryption.
## Data destinations
You can sync your Lago data to any of the following destinations:
| Vendor | Type | Status |
| ----------------- | -------------- | --------- |
| `Snowflake` | OLAP | Supported |
| `BigQuery` | OLAP | Supported |
| `Redshift` | OLAP | Supported |
| `Databricks` | OLAP | Supported |
| `Athena` | OLAP | Supported |
| `ClickHouse` | OLAP | Supported |
| `MotherDuck` | OLAP | Supported |
| `Postgres` | OLTP | Supported |
| `Aurora Postgres` | OLTP | Supported |
| `MySQL` | OLTP | Supported |
| `Aurora MySQL` | OLTP | Supported |
| `SQL Server` | OLTP | Supported |
| `SingleStore` | OLTP | Supported |
| `S3` | Object Storage | Supported |
| `S3-Compatible` | Object Storage | Supported |
| `GCS` | Object Storage | Supported |
| `ABS` | Object Storage | Supported |
| `Google Sheets` | Spreadsheet | Supported |
## Data sources
Here is the list of tables synced from Lago to your data destination:
| Name | Type |
| --------------------- | ----- |
| `applied_coupons` | Table |
| `billable_metrics` | Table |
| `charges` | Table |
| `coupons` | Table |
| `credit_notes_taxes` | Table |
| `credit_notes` | Table |
| `customers` | Table |
| `fees_taxes` | Table |
| `fees` | Table |
| `invoices_taxes` | Table |
| `invoices` | Table |
| `plans` | Table |
| `subscriptions` | Table |
| `taxes` | Table |
| `wallet_transactions` | Table |
| `wallets` | Table |
# Oso
Source: https://getlago.com/docs/integrations/entitlements/osohq
[Oso](https://www.osohq.com/) is an authorization-as-a-service provider partnering with Lago to offer entitlements. You can use either the open-source version (available on [Github](https://github.com/osohq/oso)) or the cloud-hosted version. To create entitlements with Lago, you must open an account on Oso.
Oso offers a suitable solution for Entitlements. For more information, please refer to [Oso's documentation](https://www.osohq.com/docs/guides/model/entitlements).
## Define available features and plan's quota
First, define the available features for each plan. For instance, the Basic plan has a limited set of features, while the Premium plan offers the full range.
In addition to this, you can use Lago to bill metering and overage. This information can then be passed directly to Oso's `plan_quota` and `quota_used` to limit usage for a specific feature.
## Example
[Oso's documentation](https://www.osohq.com/docs/guides/model/entitlements) explains the following example of entitlements properly.
```ruby theme={"dark"}
actor User { }
resource Organization {
roles = ["admin", "member"];
permissions = ["create_repository"];
"member" if "admin";
}
resource Plan {
roles = ["subscriber"];
relations = { subscribed_organization: Organization };
"subscriber" if role on "subscribed_organization";
}
resource Feature {
relations = { plan: Plan };
}
declare plan_quota(Plan, Feature, Integer);
declare quota_used(Organization, Feature, Integer);
plan_quota(Plan{"pro"}, Feature{"repository"}, 10);
plan_quota(Plan{"basic"}, Feature{"repository"}, 0);
has_quota_remaining(org: Organization, feature: Feature) if
has_quota(org, feature, quota) and
quota_used(org, feature, used) and
used < quota;
has_quota(org: Organization, feature: Feature, quota: Integer) if
plan matches Plan and
has_relation(plan, "subscribed", org) and
plan_quota(plan, feature, quota);
has_permission(user: User, "create_repository", org: Organization) if
has_role(user, "member", org) and
has_quota_remaining(org, Feature{"repository"});
test "members can create repositorys if they have quota" {
setup {
quota_used(Organization{"apple"}, Feature{"repository"}, 5);
quota_used(Organization{"netflix"}, Feature{"repository"}, 10);
quota_used(Organization{"amazon"}, Feature{"repository"}, 0);
has_relation(Plan{"pro"}, "subscribed", Organization{"apple"});
has_relation(Plan{"pro"}, "subscribed", Organization{"netflix"});
has_relation(Plan{"basic"}, "subscribed", Organization{"amazon"});
has_role(User{"alice"}, "member", Organization{"apple"});
has_role(User{"bob"}, "member", Organization{"netflix"});
has_role(User{"charlie"}, "member", Organization{"amazon"});
}
assert has_quota_remaining(Organization{"apple"}, Feature{"repository"});
# Apple has quota remaining, so all good
assert allow(User{"alice"}, "create_repository", Organization{"apple"});
# Netflix has used all quota
assert_not allow(User{"bob"}, "create_repository", Organization{"netflix"});
# Amazon doesn't have any quota left
assert_not allow(User{"charlie"}, "create_repository", Organization{"amazon"});
}
```
# Introduction
Source: https://getlago.com/docs/integrations/introduction
Find all Lago integrations with third-party tools—whether for payment providers, alerting systems, or data integrations. Note that some integrations are native and actively maintained by Lago, while others are community-developed and come with limited support.
## Payments integrations
## Setting up Adyen Webhook for listening to important events
**This step is crucial and mandatory** for Lago to receive and process messages from Adyen, enabling functionalities such as customer creation/update, payment processing, and refunds. To configure Adyen webhook and establish communication with Lago, follow the steps below:
1. Access your Adyen application and navigate to the **Developers** section;
2. Select **Webhooks** and create a new webhook of type **Standard**;
3. In the **Server configuration** section, locate the **General** settings; and
4. Copy and paste the following URL: **`https://api.getlago.com/webhooks/adyen/{{your_organization_id}}?code={{connection_code}}`**.
Once the customer is added in Lago, they will be automatically synchronized with Adyen. Adyen will generate a unique Shopper ID, which will be stored in Lago. Typically, Adyen utilizes the Lago customer's **`external_id`** as the Shopper ID for seamless integration between the two platforms.
Upon successful customer creation, you will receive two **[webhook messages](/api-reference/webhooks/messages)** to keep you informed:
1. **`customer.checkout_url_generated`**: This message includes the checkout URL that provides access to the default payment method. It allows you to perform a pre-authorization payment and store the payment method securely; and
2. **`customer.payment_provider_created`**: This message confirms the successful creation of the customer in Adyen, indicating that the customer's details have been added to the Adyen database.
## Redirect url after checkout[](#checkout-redirect-url "Direct link to heading")
After establishing the connection with Adyen, set a success URL where your end customer will be directed after completing the checkout.
Please note that if it's not defined, your end customer will be redirected to Adyen's website.
Please note that you can edit or delete the redirect URL, and this will only affect new checkout URLs created.
## Regenerate checkout link on demand
In cases where your end customer has not had the opportunity to complete the checkout process to inform their payment method
or wishes to modify the saved payment information, you can generate a new checkout link using the designated [endpoint](/api-reference/customers/psp-checkout-url).
```json theme={"dark"}
POST /api/v1/customers/:customer_external_id/checkout_url
```
Upon successful generation, the new checkout link will be available in the endpoint response, and it will not be delivered through a webhook message.
It is important to note that the new link will inherit the same expiration setting as the original one.
It is crucial to be aware that if a customer is not associated with any payment provider, the response will contain an error message.
## Creating payments from Lago Invoices
When a customer has Adyen defined as their payment provider, Lago seamlessly automates the process of triggering payments in Adyen whenever a new invoice is generated.
This integration ensures that payments are initiated in Adyen without any manual intervention. Lago's automatic payment creation saves time and effort, providing a streamlined experience for both you and your customers.
## Creating refunds from Lago Credit Notes
In cases where a customer has Adyen defined as their payment provider, Lago simplifies the refund process by automatically triggering refunds in Adyen whenever a new refund is initiated through credit notes.
This integration eliminates the need for manual refund processing and ensures that refunds are efficiently handled in Adyen. Lago's automated refund functionality helps you maintain accurate and timely refund transactions, enhancing customer satisfaction and operational efficiency.
## Payment disputes
In the event of a **lost** chargeback (dispute) within Adyen, Lago initiates an automatic response by marking the relevant invoice as disputed lost. This action involves populating the `dispute_lost_at` field with the timestamp when the dispute was lost. Following this update:
* The invoice becomes non-voidable;
* Generating a credit note is possible; however, refunding the payment back to the original payment method is not permitted; and
* The invoice cannot be resent for collection.
## Watch the demo video
# Cashfree Payments
Source: https://getlago.com/docs/integrations/payments/cashfree-integration
Make your users pay Lago invoices with Cashfree Payments, India's leading payments and API banking company.
## Create a webhook endpoint
## Collect payments via Cashfree
### Connect a Lago Customer to Cashfree
To begin collecting payments for your Lago invoices via Cashfree, you need to link a Lago customer to a Cashfree connection.
When creating or editing a customer in Lago, simply select the relevant Cashfree connection under **external apps** to enable invoice payments.
### Generate a checkout link
Note that payments through Cashfree does not automatically proceed when Lago generates an invoice. You need to programmatically generate a checkout link by calling the [following endpoint](/api-reference/invoices/payment-url):
```bash Request theme={"dark"}
curl --request POST \
--url https://api.getlago.com/api/v1/invoices/{lago_id}/payment_url \
--header 'Authorization: Bearer
### Create webhook endpoints[](#create-webhook-endpoints "Direct link to heading")
In addition to this, you must create a webhook endpoint in Lago to retrieve the
checkout URL associated with each customer account
([learn more](#direct-debit)). To do so:
1. Go to the **"Developers"** section of the Lago application;
2. In the **"Webhooks"** tab, click **"Add a webhook"** on the right;
3. Enter your webhook URL; and
4. Click **"Add webhook"** to confirm.
For more information about our webhooks, please refer to the
[API documentation](/api-reference/webhooks/format---signature).
## Redirect url after checkout[](#checkout-redirect-url "Direct link to heading")
After establishing the connection with GoCardless, set a success URL where your end customer will be directed after completing the checkout.
Please note that if it's not defined, your end customer will be redirected to GoCardless’s website.
Please note that you can edit or delete the redirect URL, and this will only affect new checkout URLs created.
When the customer is successfully created, you will receive two
[webhook messages](/api-reference/webhooks/messages):
* `customer.payment_provider_created` that confirms the creation of the customer
in GoCardless; and
* `customer.checkout_url_generated` that includes the checkout URL to set up the
direct debit ([learn more](#direct-debit)).
### Existing customer[](#existing-customer "Direct link to heading")
If the customer and direct debit mandate already exist in GoCardless, then you
should create the customer record in Lago, either via the user interface or
[the API](/api-reference/customers/create). When adding customer information, you
must:
1. Provide the customer's email address;
2. Define GoCardless as the **default payment provider**;
3. Select the GoCardless connected account;
4. Provide the **GoCardless customer ID**; and
5. **Disable** the option to automatically create the customer in GoCardless.
## Direct debit[](#direct-debit "Direct link to heading")
To collect payments via direct debit, a mandate must be created. To do so:
1. Retrieve the checkout URL included in the `customer.checkout_url_generated`
webhook; and
2. Redirect your customer to the checkout page, so that they can complete the
online form and approve the mandate.
The mandate must be validated by GoCardless before the first payment can be
processed. It can take up to six business days to validate a new mandate. For
more information about payment timings, please consult the
[GoCardless FAQ](https://gocardless.com/faq/merchants/direct-debit/).
Each time a new invoice with an **amount greater than zero** is generated by
Lago, a payment will automatically be created. GoCardless will record the
invoice ID and process the payment. Payments via direct debit are usually
processed within five business days. If the payment is successful, the status of
the payment will switch from `pending` to `succeeded`.
If the payment fails, the status of the payment will switch from `pending` to
`failed` and Lago will generate an `invoice.payment_failure`
[webhook](/api-reference/webhooks/messages).
## Create a webhook endpoint
### Existing customer[](#existing-customer "Direct link to heading")
If the customer already exists in Stripe but not in Lago, you should create the
customer record, either via the user interface or
[the API](/api-reference/customers/create). When adding customer
information, you must:
1. Define Stripe as the **default payment provider**;
2. Provide the **Stripe customer ID**;
3. **Disable** the option to automatically create the customer in Stripe; and
4. Define payment method options for this customer. Possible values are `card`, `link`, `sepa_debit`, `us_bank_account`, `bacs_debit`, `boleto`, `crypto` or `customer_balance`.
## Supported payment methods
Lago's Stripe integration accommodates a variety of payment methods, both generic and region-specific.
The checkout URL provided by Lago is designed to handle multiple payment options seamlessly.
### General payment methods
### Mapping items between Lago and Anrok (mandatory)
To synchronize invoices and retrieve tax data, Lago needs to establish a one-to-one relationship between its objects and Anrok products.
**You can define tax mappings per Lago entity when different entities require distinct Anrok Product IDs**. If the same mapping applies across entities, configure a default mapping. It will be used for any entity that doesn't have a specific override.
Follow these steps to map an item:
1. In Anrok, navigate to the **Products IDs** section.
2. Click on a product and **copy its Product ID.**
3. In Lago, navigate to **Integration** > **Anrok** > **Mapping**.
4. Choose the item you want to associate with the Product ID selected in step 2.
5. **Paste the Product ID to map the item** — repeat this action for all items in Lago that require mapping.
## Customer configuration for tax calculation
### Customer synchronization
When creating or updating a Lago customer, you can choose to link it to an existing Anrok customer.
The first option is to **automatically create a new customer from Lago to Anrok**. Follow these steps:
1. Create or update a new Lago customer;
2. Select the targeted Anrok connection;
3. Check the box labeled ‘Create this customer automatically in Anrok’; and
4. Save and create this new customer.
If the customer is successfully created in Anrok, a new field will be displayed in the Lago customer view, providing a direct link to the corresponding Anrok customer.
The second option is to **import an existing Anrok customer to a Lago customer**. Follow these steps:
1. Create or update a Lago customer;
2. Select the targeted Anrok connection;
3. Ensure the box labeled ‘Create this customer automatically in Anrok’ is unchecked;
4. Paste the Anrok customer ID in the appropriate field; and
5. Save and create this new customer.
If the customer is successfully synced in Anrok, a new field will be displayed in the Lago customer view, providing a direct link to the corresponding Anrok customer.
### Tax identifier
If a customer has a `tax_identification_number` configured in Lago, this ID will be sent to Anrok for tax calculation and reporting. This ID is essential for determining whether the transaction is subject to a reverse charge in eligible VAT countries.
### Tax exempt customers
For customers who qualify for tax exemptions, you need to create a Certificate in your Anrok dashboard. Ensure that the customer profile in Lago uses the same customer ID as in Anrok in the Anrok customer ID. This consistency allows Lago to correctly identify the customer and apply the exemption certificates when calculating taxes.
## Current usage
Lago queries Anrok for the current usage and wallet ongoing balance. To ensure the best experience, Lago caches the results of current usage taxes for 24 hours.
## Error management
### Refresh draft invoice with tax errors
When an invoice is in `draft` and encounters a tax synchronization error, you have the option to refresh the invoice to recalculate the tax. The invoice remains editable during this process, and the error will not prevent the invoice from being `finalized`. However, if the error persists after attempting to finalize the invoice, the invoice will be marked as `failed`.
### Retry synchronization for failed invoice
When an invoice fails due to a tax synchronization error, you have the option to manually re-sync each invoice individually from the invoice details page or via this [endpoint](/api-reference/invoices/retry_finalization). Alternatively, you can go to the integration settings and trigger a bulk invoice synchronization.
### Retry synchronization for voided / disputed invoices
When an invoice is voided or disputed, Lago will sync this updated record with Anrok to ensure your reports are accurate. If the sync fails, you will be notified via webhook. In that case, please manually resync the voided or disputed invoice through the dashboard.
### Retry synchronization for credit notes
When a credit note is created, Lago will sync this record with Anrok to ensure your reports are accurate. If the sync fails, you will be notified via webhook. In that case, please manually resync the credit note through the dashboard.
### Pay in advance non invoiceable charge
Lago will notify you via webhook if a tax error occurs when a non-invoiceable fee paid in advance is generated. The fee will not be created. Please note that you will need to fix the issue and resend the event to generate the fee. For any assistance, please contact the Lago team.
### Tax error scenario
If Lago is unable to generate an invoice or sync it to Anrok, you will be alerted via the dashboard and webhook.
Tax synchronization and invoice generation can fail due to the following reasons:
1. Incorrect connection settings (API key).
2. Items used in objects or fallback items not mapped.
3. Missing customer shipping or billing address.
4. Timeout or internal service error.
Tax synchronization can fail during the following processes:
1. Calculating taxes in one-off-invoice form
2. Refreshing a draft invoice
3. Finalizing an invoice
4. Generating a fee paid in advance non-invoiceable
5. Fetching current usage
6. Voiding an invoice
7. Disputing an invoice
8. Creating a credit note
If an issue arises, please check the mapping, verify the customer address and launch a synchronization; or contact the Lago team for assistance.
# Avalara
Source: https://getlago.com/docs/integrations/taxes/avalara
Lago's native integration with Avalara allows you to automatically update your invoices with tax amounts sourced directly from Avalara. This integration ensures compliance with international tax regulations by calculating taxes for US & non-US obligations, like VAT.
## Customer configuration for tax calculation
### Customer synchronization
When creating or updating a Lago customer, you can establish a connection to an existing Avalara customer or automatically create a new one.
**Automatically creating a new Avalara customer**
To create a new customer in Avalara directly from Lago:
1. Create or update a Lago customer;
2. Ensure the customer has a valid address;
3. Verify the customer's state uses valid two or three-character ISO 3166 region codes;
4. Select your target Avalara connection;
5. Check the box labeled "Create this customer automatically in Avalara"; and
6. Save the customer to complete the process.
**Results:**
* **Success**: A new field appears in the Lago customer information tab with a direct link to the corresponding Avalara customer
* **Failure**: The `customer.tax_provider_error` webhook is triggered to notify you of any issues
**Importing an existing Avalara customer**
To link a Lago customer to an existing Avalara customer:
1. Create or update a Lago customer
2. Select your target Avalara connection
3. Ensure the box labeled "Create this customer automatically in Avalara" is unchecked
4. Enter the existing Avalara customer ID in the designated field
5. Save the customer to complete the import
**Results**:
* **Success**: A new field appears in the Lago customer information tab with with a direct link to the corresponding Avalara customer
* **Failure**: The `customer.tax_provider_error` webhook is triggered if the sync encounters issues
### Address requirements
Avalara requires that each customer in Lago has a valid shipping address with a valid state following the two or three character **ISO 3166 region codes**.
If a shipping address is not available, Lago will default to using the billing address for tax calculation purposes.
If both addresses are invalid or missing, Lago will be unable to generate the invoice, and the invoice status will be marked as failed.
In such cases, you will be notified of the failure in the dashboard and via webhook.
### Customer exemptions
If you need to apply exemptions to a customer, you can upload valid exemption certificates for your customers in Avalara.
Ensure that when you create a customer profile in Lago, you use the same customer ID as in Avalara.
This consistency allows Lago to correctly identify the customer and apply the exemption certificates when calculating taxes.
### Tax identifier
If a customer has a `tax_identification_number` configured in Lago, this ID will be sent to Avalara for tax calculation and reporting. This ID is essential for determining whether the transaction is subject to a reverse charge in eligible VAT countries.
### Tax exempt customers
For customers who qualify for tax exemptions, you need to create a Certificate in your Avalara dashboard. Ensure that the customer profile in Lago uses the same customer ID as in Avalara in the Avalara customer ID. This consistency allows Lago to correctly identify the customer and apply the exemption certificates when calculating taxes.
## Current usage
Lago queries Avalara for the current usage and wallet ongoing balance. To ensure the best experience, Lago caches the results of current usage taxes for 24 hours.
## Error management
### Refresh draft invoice with tax errors
When an invoice is in `draft` and encounters a tax synchronization error, you have the option to refresh the invoice to recalculate the tax. The invoice remains editable during this process, and the error will not prevent the invoice from being `finalized`. However, if the error persists after attempting to finalize the invoice, the invoice will be marked as `failed`.
### Retry synchronization for failed invoice
When an invoice fails due to a tax synchronization error, you have the option to manually re-sync each invoice individually from the invoice details page or via this [endpoint](/api-reference/invoices/retry_finalization). Alternatively, you can go to the integration settings and trigger a bulk invoice synchronization.
### Retry synchronization for voided / disputed invoices
When an invoice is voided or disputed, Lago will sync this updated record with Avalara to ensure your reports are accurate. If the sync fails, you will be notified via webhook. In that case, please manually resync the voided or disputed invoice through the dashboard.
### Retry synchronization for credit notes
When a credit note is created, Lago will sync this record with Avalara to ensure your reports are accurate. If the sync fails, you will be notified via webhook. In that case, please manually resync the credit note through the dashboard.
### Pay in advance non invoiceable charge
Lago will notify you via webhook if a tax error occurs when a non-invoiceable fee paid in advance is generated. The fee will not be created. Please note that you will need to fix the issue and resend the event to generate the fee. For any assistance, please contact the Lago team.
### Tax error scenario
If Lago is unable to generate an invoice or sync it to Avalara, you will be alerted via the dashboard and webhook.
Tax synchronization and invoice generation can fail due to the following reasons:
1. Incorrect connection settings (API key).
2. Items used in objects or fallback items not mapped.
3. Missing customer shipping or billing address.
4. Timeout or internal service error.
Tax synchronization can fail during the following processes:
1. Calculating taxes in one-off-invoice form
2. Refreshing a draft invoice
3. Finalizing an invoice
4. Generating a fee paid in advance non-invoiceable
5. Fetching current usage
6. Voiding an invoice
7. Disputing an invoice
8. Creating a credit note
If an issue arises, please check the mapping, verify the customer address and launch a synchronization; or contact the Lago team for assistance.
# Lago EU Taxes
Source: https://getlago.com/docs/integrations/taxes/lago-eu-taxes
Lago now features an automatic European tax detection integration for your customers.
## Enable Lago's EU Tax integration
Activate Lago's automatic EU tax detection in just a few steps:
1. Navigate to your Lago instance **Settings**;
2. Select the **'Lago EU Tax Management'** integration;
3. Enter or confirm your organization's country; and
4. Hit **'Connect'** to activate this integration.
## Automated EU tax rates detection
When you connect the Lago EU Tax Management integration, it automatically generates a list of standard European tax rates.
These rates, labeled as `automated` in Lago, are synchronized with the latest standard tax rates for European countries,
ensuring your tax calculations are always up-to-date and compliant.
Each tax rate begins with the `lago_` prefix, ensuring a uniform and easily identifiable format across your tax rate list.
This systematic approach simplifies the management and recognition of these automated tax entries within your system.
## Auto-application of taxes: decision tree
Lago's initial step in the automated tax application involves verifying if a customer has a `tax_identification_number`.
This check occurs whenever a customer's profile is created or updated, ensuring that the most current tax-related information
is used in subsequent processes.
### B2B tax decision process
When a `tax_identification_number` is identified on a customer profile, Lago conducts a real-time verification
using the [EU's VAT Information Exchange System (VIES)](https://ec.europa.eu/taxation_customs/vies/#/vat-validation) to
confirm the existence of the company.
**In case the VIES check matches a valid company:**
1. If the customer's company is registered in the same country as your organization, Lago applies the customer
country's tax rate;
2. If the customer's company is registered in the same country as your organization, but there is a tax exception for a particular zipcode, Lago applies the tax exception of this specific zipcode; or
3. If the customer's company is registered in a different country than your organization, Lago implements a
**reverse charge** mechanism, applying a 0% tax rate.
### B2C tax decision process
If the VIES check does not confirm an active company or if no `tax_identification_number` is provided,
Lago then assesses the `country` associated with your customer. Based on this:
1. If your customer's `country` is unspecified, Lago defaults to applying your organization's country tax rate; or
2. If your customer's `country` is within the European Union, Lago applies the tax rate corresponding your customer's EU country; or
3. If your customer's `country` is outside the European Union, Lago applies a **tax exempt** rate at 0%.
## Guidelines for VIES checks by Lago
Lago performs VIES verifications under these circumstances:
* The Lago EU Tax Management integration is activated;
* A customer profile is either created or updated. Changes in customer details could influence their applicable tax rates;
* Zipcodes are important to define tax exceptions. Make sure to define them for all your customers; and
* When a new tax rate is identified for a customer, Lago automatically updates the customer's profile by replacing the old tax rate with the new one.
## Logging VIES verifications
Lago ensures transparency and compliance by logging each VIES check. This occurs whenever you create or update a customer.
For each check, Lago dispatches a webhook message. This allows you to record these validations for compliance purposes.
You can access and review any of these automated checks as needed.
# Hightouch
Source: https://getlago.com/docs/integrations/usage/hightouch
Hightouch is a Data Activation platform that syncs data from sources (database, warehouses, spreadsheet and much more) to business applications and developer tools. This data can be sent to Lago, our usage-based billing platform, to automate your billing process and ensure accurate invoicing for your customers.
Here's a step-by-step guide to help you get started:
## Prerequisites
**In Lago:**
1. Create a Lago organization to manage your billing and invoicing;
2. Create a Billable metric to track the usage of your customers;
3. Create a Plan and price the above billable metric to determine the billing rates for your customers; and
4. Create a Customer and assign the Plan.
**In Hightouch:**
1. Create a Hightouch account;
2. Create a data source (ideally, product usage of your customer);
3. Create a **HTTP Request** destination.
## Send usage from Hightouch to Lago
### Create a data source
To accomplish this, you'll need first to create a source in Hightouch. This can be done by following these simple steps:
1. Navigate to the **Sources** tab;
2. Add a **new source**; and
3. Choose and set up a data source that is available in Hightouch (it could be a database, a warehouse or a spreadsheet, for instance).
### Use the HTTP Request destination
Lago uses Hightouch's HTTP Request to ingest usage. Here is how to set it up:
1. Go to the **Destinations** tab;
2. Select the **HTTP Request** destination;
3. Define your **Headers**. Lago requires `Authorization` (secret, used for the API Key) and `Content-Type: application/json` headers; and
4. Save this newly created destination.
### Create a Sync
In order to send usage from Hightouch to Lago, you will have to create a new **Sync**. To do so, go in the **Syncs** tab and create a new sync from a source to this HTTP Request destination.
1. Configure when you want to trigger the event (row added, row deleted, row updated);
2. Define `POST` as the targeted HTTP Method;
3. Define the targeted url (for usage events, use `https://api.getlago.com/api/v1/events`);
4. Send data as `JSON` and use the JSON editor;
5. Define rate limits, if applicable
### Example of JSON payload
You can define manually the JSON payload that will be sent to Lago. Note that Hightouch supports Liquid template language to insert variables from your source to your JSON payload. These variables are created following this syntax: `"{{ row.variable }}"`, *"variable"* being the column name of your source.
Here is a JSON payload example to send usage events to Lago:
```json theme={"dark"}
{
"event": {
"transaction_id": "{{ row.transactionId }}",
"external_customer_id": "{{ row.customerId }}",
"code": "invoice_created",
"properties": {
"invoice_id": "{{ row.invoiceId }}"
}
}
}
```
## Hightouch to Lago - demo video
If easier, please find a demo video explaining the full setup to send events from Hightouch to Lago.
# Segment
Source: https://getlago.com/docs/integrations/usage/segment
Segment is a powerful tool that allows you to track the usage of your customers, providing valuable insights that can help you make data-driven decisions. This data can be sent to Lago, our usage-based billing platform, to automate your billing process and ensure accurate invoicing for your customers.
Here's a step-by-step guide to help you get started:
## Prerequisites
**In Lago:**
1. Create a Lago organization to manage your billing and invoicing;
2. Create a Billable metric to track the usage of your customers;
3. Create a Plan and price the above billable metric to determine the billing rates for your customers; and
4. Create a Customer and assign the Plan.
**In Segment:**
1. Create a Segment account;
2. Create a data source (ideally, product usage of your customer);
## Send usage from Segment to Lago
### Create a function
To accomplish this, you'll need to create a custom **Function** in Segment. This can be done by following these simple steps:
1. Navigate to the **Catalog** in Segment;
2. Click the **Functions** tab to access the custom Functions feature;
3. Choose to create your first function and follow the prompts to set it up.
### Use the Destination function
Make sure to select the **Destination function**, as you want to send data from Segment to Lago.
### Post Request to Lago events
To successfully integrate Lago with Segment, you'll need to replace the pre-written functions in the code editor with the following code. This example function, written by the Lago team, will catch a **Track** event from Segment, define the targeted endpoint (events) in Lago, build the body of the request, and finally post the event.
```javascript theme={"dark"}
// Running everytime a Track call is made on Segment
async function onTrack(event, settings) {
// events endpoint to reach
const endpoint = 'https://api.getlago.com/api/v1/events';
// body of the event following Lago documentation
const body = {
event: {
transactionId: event.messageId,
externalCustomerId: event.userId,
code: event.event,
properties: {
invoiceId: event.properties.invoice_id
}
}
};
// Post event
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Authorization': `Bearer ${settings.api}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
});
return response.json();
}
```
### Hide sensitive data
Let's take back the example from the code written above. We decided to hide the **API Key** and mark it as sensitive information. By setting this as a variable, you make sure not to hard code your private key in the function.
To create **Settings** variables:
1. Go to the **Settings** tab;
2. **Add** a new Setting;
3. Define a **Name** and a **Label** for this Settings;
4. Define it as **Required** or **Optional**; and
5. Mark is as **Sensitive** or not.
### Send usage events to Lago
By running the function in Segment, this will send a test usage to Lago events. You can retrieve this event in the events list. By finalizing the setup in Segment, the function will be automatically triggered based on your defined behavior
## Segment to Lago - demo video
If easier, please find a demo video explaining the full setup of custom functions to send event from Segment.com to Lago.
# Clone Segment pricing
Source: https://getlago.com/docs/templates/hybrid/segment
Replicate Segment's hybrid pricing model with Lago.
Build a hybrid pricing and billing system like [Segment](https://segment.com/), the Customer Data Platform leader, based on subscription plans, with a usage-based component that makes your revenue grow with your users.
## Pricing structure
Segment offers three pricing plans, called 'Free', 'Team' and 'Business'. As the latter has a custom pricing, we will focus on the first two plans.
| Plan | Free plan | Team plan |
| --------------------------- | ---------- | ----------------- |
| Subscription Fee | \$0/month | \$120/month |
| Base Consumption (included) | 1,000 MTUs | 10,000 MTUs |
| Consumption (10k-25k MTUs) | n/a | \$0.012/month/MTU |
| Consumption (25k-100k MTUs) | n/a | \$0.011/month/MTU |
| Consumption (100k+ MTUs) | n/a | \$0.010/month/MTU |
| Trial Period | n/a | 14 days |
The usage-based component in Segment's pricing is related to **monthly tracked users (MTUs)**, namely the number of unique users whose data is stored on the platform each month.
## Get started
Learn everything about Lago billing engine. Build your first plans in minutes.
Automate your billing actions with our API references and SDKs.
Ask questions, share your feedback and get help from the community.
Clone and replicate billing templates from top-tier companies.
See the latest product updates and improvements.
Read the latest news, billing tips and articles from the Lago team.