# Introduction Vatly is the European merchant of record for AI, software and digital products. It becomes the legal seller on every sale and handles payments, tax and compliance, so you just ship. Sell subscriptions and one-off products through a single API. To understand what adopting Vatly involves, start with [Build your own integration](https://docs.vatly.com/guides/build-your-own-integration). Using a specific platform? Find [Lovable payments with Vatly](https://docs.vatly.com/integrations/lovable) and [Bolt payments with Vatly](https://docs.vatly.com/integrations/bolt) under **Integrations**, with platform-specific setup and agent prompts. ::card-group :::card --- icon: i-heroicons:shopping-cart title: Hosted Checkouts to: https://docs.vatly.com/api-reference/checkouts --- Create hosted checkout sessions with one API call. Support for one-off products and subscription plans with automatic tax calculation. ::: :::card --- icon: i-heroicons:arrow-path title: Subscriptions to: https://docs.vatly.com/api-reference/subscriptions --- Full subscription lifecycle management. Handle upgrades, downgrades, proration, trials, and cancellations. ::: :::card --- icon: i-heroicons:document-text title: Orders & Invoices to: https://docs.vatly.com/api-reference/orders --- Every payment generates an order with automatic tax calculation and invoicing. Vatly handles EU VAT, US sales tax, and reporting as your Merchant of Record. ::: :::card --- icon: i-heroicons:bell-alert title: Webhooks to: https://docs.vatly.com/guides/webhooks --- Real-time event notifications for checkouts, orders, subscriptions, refunds, and chargebacks. ::: :: ## Get started in minutes 1. Create a new account at [vatly.com](https://my.vatly.com){rel=""nofollow""}. 2. Grab your API keys from **Developers » API keys**. 3. Connect your Mollie account. 4. Set up your products. 5. Integrate Vatly using one of our [packages](https://docs.vatly.com/packages). ## Going live Test mode works from the start, so you can build and test your integration right away. Your live keys work once Vatly has approved you and Mollie has verified your business. - **Product review.** Vatly is the seller on every sale, so it reviews every product before it goes on sale. A review typically takes one to two business days, and you get an email whether or not the product is approved. - **Mollie verification.** Mollie verifies your business on your own connected Mollie account. Connect the account you already have, or open one in the same flow. - **Payouts.** Your earnings go to your own Mollie account after a 7-day hold that covers refunds and disputes. See [Payouts & Settlement](https://docs.vatly.com/guides/payouts). ## Next steps - [Build your own integration](https://docs.vatly.com/guides/build-your-own-integration): plan what your app needs and brief your developer or agent - [Quickstart guide](https://docs.vatly.com/guides/quickstart): make your first API call - [Authentication](https://docs.vatly.com/guides/authentication): learn how API keys work - [API Reference](https://docs.vatly.com/api-reference/customers): explore all endpoints - [PHP SDK](https://docs.vatly.com/packages/php/readme): get the official PHP package - [Download OpenAPI spec](https://docs.vatly.com/openapi.yaml){rel=""nofollow""} for code generation and tooling # Quickstart ::note Before you can make requests to the Vatly API, you will need to grab your API key from your dashboard. You find it under [Developers » API keys](https://my.vatly.com){rel=""nofollow""} . :: This Quickstart covers your first authenticated API request. To understand the full integration before implementing it, start with [Build your own integration](https://docs.vatly.com/guides/build-your-own-integration). For platform-specific setup, see [Integrations](https://docs.vatly.com/integrations), including Lovable and Bolt. ## Choose your client Before making your first API request, choose a client. Vatly offers packages for JavaScript / TypeScript, Python, and PHP, with framework integrations for Django and Laravel. See [available packages](https://docs.vatly.com/packages) for installation and language-specific examples. This page demonstrates a first request with cURL or the PHP SDK. ::code-group{sync="client"} ```bash [cURL] # cURL is most likely already installed on your machine curl --version ``` ```bash [PHP] # Install the latest alpha of the Vatly PHP SDK composer config minimum-stability alpha composer config prefer-stable true composer require vatly/vatly-api-php ``` :: [Check out our list of first-party SDKs](https://docs.vatly.com/guides/sdks) ## Making your first API request After picking your preferred client, you are ready to make your first call to the Vatly API. Below, you can see how to send a GET request to the Checkouts endpoint to get a list of all your checkouts. In the cURL example, results are limited to ten checkouts, the default page length for each client. ::code-group{sync="client"} ```bash [cURL] curl -G https://api.vatly.com/v1/checkouts \ -H "Authorization: Bearer test_your_api_key_here" \ -d limit=10 ``` ```php [PHP] $vatly = new Vatly\Api\VatlyApiClient; $vatly->setApiKey($key); $vatly->checkouts->page(); ``` :: [Read the docs for the Checkouts endpoint](https://docs.vatly.com/api-reference/checkouts) ## What's next? Great, you're now set up with an API client and have made your first request to the API. Here are a few links that might be handy as you venture further into the Vatly API: - [Grab your API key from the Vatly dashboard](https://my.vatly.com){rel=""nofollow""} - [Follow the typical selling flow in Vatly](https://docs.vatly.com/guides/selling-workflow) - [Check out the Checkouts endpoint](https://docs.vatly.com/api-reference/checkouts) - [Learn about the different error messages in Vatly](https://docs.vatly.com/guides/errors) # Payouts & Settlement ## How you get paid Vatly settles each payment to your connected Mollie account after a 7-day hold by default. Your share is the sale price excluding the customer's tax, minus Vatly's fee. Where VAT applies to your supply to Vatly, it is settled along with it. In your Mollie account, you can configure payouts to your own bank account or another one. Mollie's payout schedule and payout fees apply from there. ::note You need a connected Mollie account to receive live payments. Connect it during onboarding in the Vatly dashboard. :: ## The hold period The hold starts when a payment is paid. Each payment is settled on its own, so a payment made today is settled about a week from now, regardless of when your other payments were made. The hold gives room to handle refunds, chargebacks and risk checks before money moves to your account. Vatly can apply a longer hold where risk checks require it. ## Follow your settlements in the dashboard Open **Settlements** in the Vatly dashboard. Payments are grouped into monthly settlement periods. Each period shows its **Payout release status**: | Line | Meaning | | --------------------------- | -------------------------------------------------------------------------------------------------------- | | Released to your account | Already settled to your Mollie account. | | Scheduled for release | Still in its hold period. The next release date is shown alongside. | | Held for settlement | Could not be released with the payment itself, so it is handled through the period's settlement instead. | | Charged back before release | Charged back before its hold ended, so it was not released. | ## Test mode Test-mode payments are settled after a much shorter hold, so you can follow the full flow while you build. No real money moves in test mode. # Customer Emails ## Vatly sends the billing emails As Merchant of Record, Vatly is the seller on your customer's invoice. That makes Vatly responsible for the billing communication with your customers, so you don't need to build receipts, payment reminders or refund confirmations yourself. Vatly sends these emails automatically. Use [webhooks](https://docs.vatly.com/guides/webhooks) to keep your own application in sync, for example to grant or revoke access. Anything about your product itself, such as onboarding or usage emails, stays with you. ## What your customers see Every customer email: - Shows your storefront name and logo in the header - Is sent by Vatly, and states that the sale is made by Vatly - Points billing and payment questions to [Vatly support](https://vatly.com/support){rel=""nofollow""} - Is written in English Set your storefront name and logo in the Vatly dashboard under **Settings » Branding**. Until you set a name, customers see a placeholder name in their emails. ## Purchases and invoices | Email | When it is sent | | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Receipt | After every successful payment: a one-off purchase, the first payment of a subscription, and every renewal. It lists the items, any discount and the VAT, and links to the invoice. | | Invoice link | When a customer opens an expired invoice link and requests a new one. | Each order gets one receipt. The receipt links to the invoice in the customer portal instead of attaching a PDF. ## Subscriptions | Email | When it is sent | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Upcoming renewal | Ahead of the renewal of a subscription billed less often than monthly, or of its first charge after a free trial. It shows the amount, the date and how to cancel. | | Payment initiated | When Vatly starts a recurring payment, such as a renewal. It shows the amount, the payment method and the expected charge date. | | Cancellation confirmation | When the customer cancels their subscription in the customer portal. It confirms until when they keep access. | | Cancellation notice | When you cancel a subscription through the API, or Vatly cancels it on your behalf. It tells the customer when their access ends. | The upcoming renewal email goes out 7 days ahead for plans billed up to every 3 months, 14 days ahead for plans up to every 6 months, and 30 days ahead for longer plans. Monthly and shorter plans don't get one. If the renewal changes after the email went out, for example because you scheduled a plan change, the customer gets an updated email. If the renewal date changes or the subscription is canceled or paused before the email goes out, Vatly doesn't send it. A changed date gets its own email. If you end a trial early with an immediate plan change, Vatly charges the first paid cycle on the day of the change, so the customer gets the payment emails that day. A subscription that was canceled during its trial keeps its trial end date. ## Payment methods | Email | When it is sent | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Card expiring | When the card used for a subscription is about to expire. It asks the customer to update their payment method. | | Recurring payment setup failed | When a recurring payment could not be set up because the customer's first payment never completed. It asks the customer to set up their payment method again. | | Payment method update link | When a customer opens an expired payment method update link and requests a new one. | ## Failed payments When a recurring payment fails, Vatly starts a payment recovery process for the subscription. The customer receives: 1. A **Payment failed** email straight away. 2. A series of reminders while Vatly retries the payment. The reminders become more urgent as the process continues, ending with a final notice. 3. If the payment still fails, a **Service canceled** email. Vatly cancels the subscriptions that use the failed payment method. Payment recovery also starts if a customer updates their payment method while a renewal payment is still processing and that payment then fails. Vatly retries using the updated payment method. When the payment method can't be charged at all, for example because the card is no longer valid, Vatly does not retry. Instead, the customer receives reminders to update their payment method. As soon as a retry succeeds or the customer adds a working payment method, the reminders stop and the customer receives the usual receipt. Follow the process on your side with the `order.payment_failed` and `order.paid` webhooks. See [Handling failed subscription payments](https://docs.vatly.com/guides/webhooks#handling-failed-subscription-payments). ## Refunds | Email | When it is sent | | ---------------- | ------------------------------------------------------------------------------------------------------------------------------- | | Refund processed | When a refund is completed, whether you created it through the API or the dashboard. It lists the refunded items and the total. | ## Customer portal | Email | When it is sent | | ------------ | -------------------------------------------------------------------------- | | Sign-in link | When a customer requests a sign-in link on the customer portal login page. | [Customer portal sessions](https://docs.vatly.com/api-reference/customers#create-a-customer-portal-session) created through the API return a URL and do not send an email. ## Test mode Emails for test mode orders are never delivered to a real inbox. Vatly still renders and saves them, so you can review what your customer would receive. Open an order in the dashboard and find its emails under **Emails**. ## Customization You can't turn off these emails. Most of them are required for Vatly to bill your customers correctly, such as the receipt and the invoice. Additional email branding is on the [roadmap](https://roadmap.vatly.com/projects/2-merchant-ui/items/26-email-co-branding){rel=""nofollow""}. Vote for it to let us know it matters to you. # Build your own integration You do not need to build a payment form or your own tax and invoicing workflow to sell with Vatly. Vatly is the European merchant of record for AI, software and digital products: it acts as the legal seller and provides hosted checkout. Your app delivers the product and controls access. This guide helps you decide what to connect before writing code or asking an agent to implement it. Whether a developer or an AI agent does the work, the responsibilities are the same. ## Choose your starting point - **Using Lovable or Bolt?** Follow the [Lovable](https://docs.vatly.com/integrations/lovable) or [Bolt](https://docs.vatly.com/integrations/bolt) guide for the setup in your platform and a ready-to-use agent prompt. Find platform-specific instructions under [Integrations](https://docs.vatly.com/integrations). - **Connecting your own app?** Continue below to plan the integration and choose the right implementation documentation. - **Ready to make an API request?** The [Quickstart](https://docs.vatly.com/guides/quickstart) covers your first authenticated call. It is a technical first step, not a complete payment integration. ## What Vatly handles, and what stays in your app | Vatly handles | Your app handles | | ---------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | | Being the legal seller, including tax and customer invoicing for Vatly sales | Your software or digital product, customer accounts, and support for your product | | The hosted checkout and payment flow | Your pricing UI and the decision about which products a customer can buy | | Billing events, including payments and subscription changes | Delivering downloads, activating licenses, or granting and updating access | | A hosted customer portal for eligible customers | Authenticating the customer and opening their portal session securely | Portal access requires an issued invoice. See the [customer portal documentation](https://docs.vatly.com/packages/fluent-js/customerportal). Your existing login and database can remain in place; adding Vatly does not require replacing them. ## What a purchase looks like 1. A customer chooses a product or plan in your app. 2. Your backend checks what that customer can buy and asks Vatly to create a checkout. The API key stays on your server. 3. Your app sends the customer to Vatly's hosted checkout to pay, then shows a return page in your app. 4. Vatly sends a signed notification, called a webhook, to your backend. Your app verifies it before recording the purchase and delivering access. 5. For subscriptions, your app keeps access in step with renewals, cancellations, and other billing changes. Refunds and disputes also need an access policy. The return page is not proof of payment. A customer may close the checkout tab or visit the return URL directly; delivery must depend on the verified billing result, not that browser visit. The [Selling Workflow](https://docs.vatly.com/guides/selling-workflow) walks through the sale lifecycle in more detail. ## Prepare a test integration [Create a Vatly account](https://my.vatly.com){rel=""nofollow""}, get a `test_` key under **Developers » API keys**, and create a test product under **Manage Products**. Choose a one-off product for a single purchase or a subscription plan for recurring access. Keep the key, products, and customers in the same storefront and mode. Your app needs a deployed backend that can call Vatly privately, receive HTTPS webhooks, and store billing state. A frontend-only site needs a backend or server functions for these tasks. Store API keys and webhook signing secrets in that backend's secret manager—not browser code, frontend environment variables, or agent chat. Test mode is available before going live. Your first milestone is one complete test purchase that grants the right customer access, not a finished billing dashboard. ## Choose your tools For app-level billing, start with a fluent package rather than assembling every flow from low-level API calls: - **JavaScript / TypeScript:** [`@getvatly/fluent`](https://docs.vatly.com/packages/fluent-js/readme) builds on `@getvatly/sdk` with checkout and subscription builders, customer bindings, and webhook processing. Follow [configuration](https://docs.vatly.com/packages/fluent-js/configuration) for compatible versions and runtime requirements. - **PHP:** [PHP Fluent](https://docs.vatly.com/packages/fluent-php/webhook-flow) provides higher-level billing flows. The [Laravel package](https://docs.vatly.com/packages/laravel/readme) wires fluent for Laravel. - **Python:** [Python Fluent](https://docs.vatly.com/packages/fluent-python/readme) provides async-first billing flows and storage contracts. The [Django package](https://docs.vatly.com/packages/django/readme) integrates fluent with Django's ORM and webhook handling. Both are available on PyPI. - **Direct API access:** Use the matching [SDK](https://docs.vatly.com/packages) when you only need the API client, or the [HTTP API](https://docs.vatly.com/api-reference) from another server-side language. The [Python SDK](https://docs.vatly.com/packages/python/readme) is available on PyPI as `vatly-api-python` (import `vatly`). The JavaScript, Python, Django and PHP fluent packages are **alpha**. Every alpha release may include breaking changes. Lock the version you install and review the release notes before upgrading. Follow each package's installation guidance and review upgrades. Fluent packages provide building blocks, not your app's access policy or a database integration that configures itself: your developer or agent must wire the required storage drivers and authorization checks. ## Hand off a clear brief Give your developer or agent the decisions that belong to your business: - Which products or plans you will sell, and what each purchase unlocks. - Which existing login, database, and deployed backend to use. - Where customers should return after completing or canceling checkout. - How access should change after a renewal, cancellation, refund, or dispute. Ask them to follow the chosen package's checkout and webhook documentation, and to show you the deployed checkout flow and webhook URL. Secrets should be entered through the host's secure secret form, never included in the brief. Agents can use the [documentation index](https://docs.vatly.com/llms.txt){rel=""nofollow""}, [API reference](https://docs.vatly.com/api-reference), and [OpenAPI specification](https://docs.vatly.com/openapi.yaml){rel=""nofollow""} to check implementation details. ## Know when you are ready to sell Before switching to live credentials, review the integration as a customer: - A completed test purchase grants the right access; a canceled checkout or a visit to the return URL alone does not. - Customers cannot buy on another user's account or grant themselves access through the browser. - Repeated webhook deliveries do not fulfill a purchase twice, invalid signatures are rejected, and failed processing can retry. - Subscription and post-payment changes follow the access policy you chose. Your implementer can use the [webhook guide](https://docs.vatly.com/guides/webhooks), [test-mode guide](https://docs.vatly.com/guides/testing), and package-specific tests for these checks. Live selling also requires [Vatly approval, product review, and Mollie verification](https://docs.vatly.com/introduction#going-live). A working test integration is not a guarantee of a go-live date. # Selling Workflow Planning your integration? Start with [Build your own integration](https://docs.vatly.com/guides/build-your-own-integration) for responsibilities, implementation choices, and a brief for your developer or agent. This page follows the sale itself, from setup through delivery and post-payment events. ## The typical Vatly flow For most use cases, the Vatly integration follows the same happy path: 1. Create your Vatly account and collect your API key. 2. Configure the products you want to sell in the Vatly dashboard. 3. Register a webhook endpoint that Vatly can reach. 4. Create a checkout with the product IDs you want to sell. 5. Redirect the customer to the hosted checkout URL. 6. Listen for the payment webhook and fulfill the order in your app. 7. Stay prepared to handle refunds and chargebacks after the sale. This guide ties those steps together so you can see the full flow before diving into each API endpoint. ## 1. Finish the initial setup Start with the basics: - Create your Vatly account. - Grab your API keys from the dashboard under **Developers » API keys**. - For live payments, connect your Mollie account and complete onboarding with both Mollie and Vatly. Most merchants and developers should begin in test mode. In test mode, the customers, products, and checkouts you create stay in your test environment so you can validate the full flow safely before you start accepting real payments. The online Vatly dashboard has a testmode toggle. For API calls, use your dedicated test API key (starting with `test_`). When you are ready to sell for real, switch to live mode. Each product you want to sell must be verified by Vatly before it can be used in a live selling flow. Do not wait until the last minute to create your products in the dashboard. Product verification can take some time because Vatly needs to review them for compliance before they can be used in a live selling flow. If you have not made your first authenticated request yet, start with the [Quickstart guide](https://docs.vatly.com/guides/quickstart). ## 2. Set up the products you want to sell Before you can create a checkout, you need at least one product in Vatly. You can sell two kinds of products: - [One-off products](https://docs.vatly.com/api-reference/one-off-products) for a single purchase such as a digital download, license, or one-time service. - [Subscription plans](https://docs.vatly.com/api-reference/subscription-plans) for recurring access such as a SaaS plan. Products are configured in the Vatly dashboard. After creating them, keep track of their product IDs because you will need those IDs when you create a checkout through the API. ## 3. Register your webhook before going live Set up your webhook endpoint before you send customers to checkout. That endpoint is how Vatly tells your application that something important happened, such as a checkout being paid, a subscription changing, or a refund being created. Configure the webhook in the dashboard and make sure the endpoint is: - Reachable from the public internet - Served over HTTPS - Able to verify the `Vatly-Signature` header This is a critical part of the integration. Use webhooks to confirm what happened instead of relying only on the customer's browser returning to your site. [Read the webhook guide](https://docs.vatly.com/guides/webhooks) ## 4. Create a checkout for the right products When a customer is ready to buy, your app creates a checkout with the product IDs you configured earlier. A checkout can contain: - A single one-off product - A single subscription plan - A list of products, depending on what your flow allows The API request is made from your backend using your secret API key. ::code-group ```bash [cURL] curl https://api.vatly.com/v1/checkouts \ -H "Authorization: Bearer live_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "products": [ { "id": "one_off_product_Vr8kQdFhSrG4Y3DnfsdqH", "quantity": 1 } ], "redirectUrlSuccess": "https://example.com/success", "redirectUrlCanceled": "https://example.com/canceled" }' ``` ```php [PHP] use Vatly\Api\VatlyApiClient; $vatly = new VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $checkout = $vatly->checkouts->create([ 'products' => [ [ 'id' => 'one_off_product_Vr8kQdFhSrG4Y3DnfsdqH', 'quantity' => 1, ], ], 'redirectUrlSuccess' => 'https://example.com/success', 'redirectUrlCanceled' => 'https://example.com/canceled', ]); $checkoutUrl = $checkout->links->checkoutUrl->href; return redirect()->away($checkoutUrl); ``` :: The response includes a hosted checkout URL in `links.checkoutUrl.href`. That is the URL your customer should visit to complete payment. ```json [Response] { "id": "checkout_QGQ0qDrQ2B4O1yXVTr6Wc", "status": "created", "redirectUrlSuccess": "https://example.com/success", "redirectUrlCanceled": "https://example.com/canceled", "links": { "checkoutUrl": { "href": "https://checkout.vatly.com/chk_test_123456789" } } } ``` [Read the Checkouts API reference](https://docs.vatly.com/api-reference/checkouts) ## 5. Redirect the customer to the checkout URL After creating the checkout, redirect the customer to the URL returned by Vatly. At that point, Vatly handles the hosted payment flow. The customer completes payment on the Vatly checkout page and is then redirected back to your success or cancellation URL. The browser redirect is helpful for user experience, but your backend should still wait for the relevant webhook event before treating the order as paid. ## 6. Fulfill the order after payment Once the checkout is paid, Vatly notifies your webhook endpoint. That is the point where your application should decide what to deliver. Typical fulfillment actions include: - Granting access to your SaaS - Sending an email with access instructions - Providing a download link for a digital product - Activating a subscription in your own application The exact webhook event you handle depends on your setup, but `checkout.paid` and the related order or subscription events are the key signals that the sale completed. ## 7. Prepare for post-payment events The happy path ends with a successful sale and fulfillment, but a production integration also needs to handle post-payment scenarios. At minimum, merchants and developers should be prepared for: - [Refunds](https://docs.vatly.com/api-reference/refunds), whether partial or full - [Chargebacks](https://docs.vatly.com/api-reference/chargebacks), which are created when a payment dispute is initiated These events should also flow through your webhook handling so your application can revoke access, update account state, notify staff, or trigger follow-up support processes when needed. Vatly actively prevents and disputes chargebacks. If extra evidence is needed, Vatly will check in with you for details such as proof of delivery or proof that the customer received access to the product. ## Where to go next - [Quickstart](https://docs.vatly.com/guides/quickstart) - [Webhooks](https://docs.vatly.com/guides/webhooks) - [Checkouts API](https://docs.vatly.com/api-reference/checkouts) - [One-off Products API](https://docs.vatly.com/api-reference/one-off-products) - [Subscription Plans API](https://docs.vatly.com/api-reference/subscription-plans) - [Refunds API](https://docs.vatly.com/api-reference/refunds) - [Chargebacks API](https://docs.vatly.com/api-reference/chargebacks) # Vatly SDKs Vatly is the European merchant of record for AI, software and digital products. Use a fluent package for app-level billing, or an SDK for direct API calls. ## PHP SDK The official PHP SDK is the primary way to interact with the Vatly API from your PHP application. For installation, usage examples, and the full list of available resources, see the [PHP SDK docs](https://docs.vatly.com/packages/php/readme). ## PHP Fluent [`vatly/vatly-fluent-php`](https://packagist.org/packages/vatly/vatly-fluent-php){rel=""nofollow""} adds higher-level billing flows to the PHP SDK. ```bash composer config minimum-stability alpha composer config prefer-stable true composer require vatly/vatly-fluent-php ``` Follow its [README](https://github.com/vatly/vatly-fluent-php#readme){rel=""nofollow""} for setup. The synced docs currently cover [webhook flow](https://docs.vatly.com/packages/fluent-php/webhook-flow) and [adapting to your framework](https://docs.vatly.com/packages/fluent-php/host-owns-its-tables). ## Laravel The Vatly Laravel package was inspired by Laravel Cashier and provides a fluent way of integrating Vatly into your application. For installation and usage examples, see the [Laravel Vatly docs](https://docs.vatly.com/packages/laravel/readme). ## JavaScript SDK The official JavaScript / TypeScript SDK, [`@getvatly/sdk`](https://www.npmjs.com/package/@getvatly/sdk){rel=""nofollow""}, provides a typed client for the Vatly API on Node.js and edge runtimes. ```bash npm install --save-exact @getvatly/sdk ``` For installation, usage examples, and the full list of available resources, see the [JavaScript / TypeScript SDK docs](https://docs.vatly.com/packages/javascript/readme). The source is available on [GitHub](https://github.com/vatly/vatly-api-js){rel=""nofollow""}. ## JavaScript Fluent The framework-agnostic fluent package, [`@getvatly/fluent`](https://www.npmjs.com/package/@getvatly/fluent){rel=""nofollow""}, builds on `@getvatly/sdk` with checkout builders, customer and subscription handles, and webhook processing. ```bash npm install --save-exact @getvatly/sdk @getvatly/fluent ``` For installation and usage examples, see the [fluent JavaScript / TypeScript docs](https://docs.vatly.com/packages/fluent-js/readme). The source is available on [GitHub](https://github.com/vatly/vatly-fluent-js){rel=""nofollow""}. ## Python SDK [`vatly-api-python`](https://pypi.org/project/vatly-api-python/){rel=""nofollow""} provides typed synchronous and asynchronous API clients for Python 3.10+. Import it as `vatly`. ```bash pip install --pre vatly-api-python ``` See the [Python SDK docs](https://docs.vatly.com/packages/python/readme) for initialization and API resources, or the source on [GitHub](https://github.com/vatly/vatly-api-python){rel=""nofollow""}. ## Python Fluent [`vatly-fluent-python`](https://pypi.org/project/vatly-fluent-python/){rel=""nofollow""} builds on the Python SDK with async-first billing flows, checkout builders, subscriptions and transactional webhooks. Import it as `vatly_fluent`. ```bash pip install --pre vatly-fluent-python ``` See the [Python Fluent docs](https://docs.vatly.com/packages/fluent-python/readme) for storage contracts and configuration, or the source on [GitHub](https://github.com/vatly/vatly-fluent-python){rel=""nofollow""}. ## Django [`vatly-django`](https://pypi.org/project/vatly-django/){rel=""nofollow""} integrates Python Fluent with Django, including ORM storage, billable operations and webhook handling. Import it as `vatly_django`. ```bash pip install --pre vatly-django ``` See the [Django docs](https://docs.vatly.com/packages/django/readme) for installation and settings, or the source on [GitHub](https://github.com/vatly/vatly-django){rel=""nofollow""}. Like Laravel for PHP, Django is the framework integration; its reference lives under Packages. These packages are in alpha. Every alpha release may include breaking changes. Lock the version you install and review the release notes before upgrading. The commands above install the latest alpha: Composer needs `minimum-stability` set to `alpha` (with `prefer-stable` keeping your other dependencies stable), and pip needs `--pre`. --- ## SDK availability | SDK | Status | | -------------------------------------------------------------------------------- | ----------------- | | [PHP SDK](https://docs.vatly.com/packages/php/readme) | Available (alpha) | | [PHP Fluent](https://docs.vatly.com/packages/fluent-php/webhook-flow) | Available (alpha) | | [Laravel](https://docs.vatly.com/packages/laravel/readme) | Available (alpha) | | [JavaScript SDK](https://docs.vatly.com/packages/javascript/readme) | Available (alpha) | | [JavaScript Fluent](https://docs.vatly.com/packages/fluent-js/readme) | Available (alpha) | | [Python SDK](https://docs.vatly.com/packages/python/readme) | Available (alpha) | | [Python Fluent](https://docs.vatly.com/packages/fluent-python/readme) | Available (alpha) | | [Django](https://docs.vatly.com/packages/django/readme) | Available (alpha) | | [FluentCart (WordPress)](https://docs.vatly.com/packages/fluentcart/readme) | Available (alpha) | | [Paid Memberships Pro (WordPress)](https://docs.vatly.com/packages/pmpro/readme) | Available (alpha) | | Ruby | Planned | In the meantime, you can use the [REST API directly](https://docs.vatly.com/guides/authentication) with any HTTP client in any language. --- ## OpenAPI specification The whole Vatly API is described by an OpenAPI 3.1 specification. Download it here: {rel=""nofollow""} Use it to generate a typed client in your language, import the API into Postman, Insomnia, or another tool, or feed it to your own codegen and tests. It stays in sync with the live API, so a client generated from it matches this reference. ## Point your AI agent at the docs These docs are built to be read by AI coding agents, not only by people. Point an assistant such as Claude or ChatGPT at `docs.vatly.com` and it can build your integration against the real API surface. - **`llms.txt`**: a machine-readable index of the site at [docs.vatly.com/llms.txt](https://docs.vatly.com/llms.txt){rel=""nofollow""}, with the full documentation as one file at [docs.vatly.com/llms-full.txt](https://docs.vatly.com/llms-full.txt){rel=""nofollow""}. Give your agent either one and it has the whole reference in a single fetch. - **Markdown for every page**: put `/raw` in front of any docs path and add `.md`. For this page that is [docs.vatly.com/raw/guides/sdks.md](https://docs.vatly.com/raw/guides/sdks.md){rel=""nofollow""}. - **Open in ChatGPT or Claude**: every page has buttons in its header to copy it as Markdown or open it straight in ChatGPT or Claude. - **OpenAPI spec**: the [specification above](https://docs.vatly.com/#openapi-specification) gives an agent the exact endpoints, parameters, and schemas. # Authentication ## API keys To authenticate with the Vatly API, you need to include your API key in the `Authorization` header of each request. You can obtain your API key from the [Vatly dashboard](https://my.vatly.com){rel=""nofollow""} under **Developers » API keys**. Vatly provides separate API keys for live and test environments: - **Live keys** are prefixed with `live_` and are used for production requests. - **Test keys** are prefixed with `test_` and are used for testing and development. ::note Use your test API key during development to avoid affecting live data. Switch to your live API key when you're ready to go to production. :: Here's how to authenticate your requests using cURL: ```bash [Example request with API key] curl https://api.vatly.com/v1/checkouts \ -H "Authorization: Bearer live_your_api_key_here" ``` Always keep your API key safe and never expose it in client-side code or commit it to version control. If you suspect your API key has been compromised, you can regenerate it from the Vatly dashboard. ## Using an SDK If you use one of our official SDKs, authentication is straightforward. Simply provide your API key when initializing the client, and the SDK will handle the rest. ```php [PHP SDK example] $vatly = new Vatly\Api\VatlyApiClient; $vatly->setApiKey('live_your_api_key_here'); ``` [Check out our list of first-party SDKs](https://docs.vatly.com/guides/sdks) # Pagination When an API response returns a list of objects, no matter the amount, pagination is supported. In paginated responses, objects are nested in a `data` attribute and have `links` with `next` and `prev` URLs for navigation. When `links.next` is `null`, you have reached the end of the results. You can use the `startingAfter` and `endingBefore` query parameters to browse pages. ## Example using cursors In this example, we request the page that starts after the checkout with id `checkout_QdEpFhdSrG4Y3DnfsdqsH`. As a result, we get a list of three checkouts and can tell by `links.next` being `null` that we have reached the end of the resultset. | Name | Type | Description | | --------------- | --------- | -------------------------------------------------------------------------------------- | | `startingAfter` | `string` | The last ID on the page you're currently on when you want to fetch the next page. | | `endingBefore` | `string` | The first ID on the page you're currently on when you want to fetch the previous page. | | `limit` | `integer` | Limit the number of items returned. | ```bash [Manual pagination using cURL] curl -G https://api.vatly.com/v1/checkouts \ -H "Authorization: Bearer live_your_api_key_here" \ -d startingAfter="checkout_QdEpFhdSrG4Y3DnfsdqsH" \ -d limit=10 ``` ```json [Paginated response] { "data": [ { "id": "checkout_Bm7xNvPwKr3YjTgHcZaE" }, { "id": "checkout_Wt5mNvBxKw7YcZaEjLhR" }, { "id": "checkout_Fp2kQrSvWm8NjLhYbUcP" } ], "count": 3, "links": { "self": { "href": "https://api.vatly.com/v1/checkouts?startingAfter=checkout_QdEpFhdSrG4Y3DnfsdqsH&limit=10", "type": "application/json" }, "next": null, "prev": { "href": "https://api.vatly.com/v1/checkouts?endingBefore=checkout_Bm7xNvPwKr3YjTgHcZaE&limit=10", "type": "application/json" } } } ``` # Errors You can tell if your request was successful by checking the status code in the API response. If a response is unsuccessful, use the HTTP status code and error message to understand what went wrong. --- ## Status codes Here is a list of the different categories of status codes returned by the Vatly API. Use these to understand if a request was successful. | Status | Description | | ------ | ------------------------------------------------------------------------------------------------------------------------------------ | | `2xx` | A 2xx status code indicates a successful response. | | `4xx` | A 4xx status code indicates a client error. This means there's an issue with the request. | | `5xx` | A 5xx status code indicates a server error. This means the issue is on Vatly's end and we are automatically notified of the problem. | ### Common status codes | Code | Meaning | | ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | `200` | OK - Request succeeded. | | `201` | Created - Resource was successfully created. | | `204` | No Content - Request succeeded with no response body (e.g., deletes). | | `400` | Bad Request - The request was malformed. | | `401` | Unauthorized - Invalid or missing API key. | | `403` | Forbidden - The API key doesn't have permission for this action. | | `404` | Not Found - The requested resource doesn't exist. | | `409` | Conflict - Idempotency mismatch, request still in progress, outcome unknown, a concurrent write, or a refund of the same order already being created. | | `422` | Unprocessable Entity - Validation failed. Check the `errors` field for details. | | `429` | Too Many Requests - Rate limit exceeded. Slow down your requests. | | `500` | Internal Server Error - Something went wrong on Vatly's end. | --- ## Error responses Whenever a request is unsuccessful, the Vatly API will return an error response with a human-readable message. Combine it with the HTTP status code to understand what has gone wrong and how to fix it. Most of the error messages are pretty helpful and actionable. ```json [Error response] { "message": "Resource not found." } ``` Some errors also include an optional `details` object with structured context about the failure. Treat unknown keys as forward-compatible additions and branch on the HTTP status code rather than the shape of `details`. ```json [Error response with details] { "message": "The requested resource was not found.", "details": { "resource_type": "checkout", "resource_id": "checkout_abc123" } } ``` ### Validation errors When a `422` status code is returned, the response includes field-specific error details: ```json [Validation error response] { "message": "The given data was invalid.", "errors": { "email": [ "The email field is required." ], "products.0.id": [ "The selected products.0.id is invalid." ] } } ``` The `errors` object uses dot notation for nested fields. Each key maps to an array of error messages for that field. # Webhooks ## Registering webhooks To register a new webhook, you need to have a URL in your app that Vatly can call. You can configure a new webhook from the Vatly dashboard under [Developers » Webhooks](https://my.vatly.com){rel=""nofollow""}. Give your webhook a name, pick the [events](https://docs.vatly.com/#event-types) you want to listen for, and add your URL. You can also manage endpoints programmatically with the [Webhook Endpoints API](https://docs.vatly.com/api-reference/webhook-endpoints), handy for provisioning from CI / infrastructure-as-code or pointing an ephemeral preview environment at its own public URL. A storefront can register up to five endpoints per mode (test and live), each subscribing to its own set of events via `enabledEvents`, and you supply the signing secret when you register one. Now, whenever something of interest happens in your app, a webhook is fired off by Vatly. In the next section, we'll look at how to consume webhooks. ::note For security reasons, your webhook URL needs to be HTTPS with a valid certificate and reachable from Vatly. :: ## Consuming webhooks Each delivery is an HTTP `POST` whose body is a `webhook_event` object, the same shape returned by the [Get webhook event](https://docs.vatly.com/api-reference/webhook-events) endpoint. Check `eventName` to see what happened, and use `entityType` / `entityId` (or the embedded `object` snapshot) to act on the affected resource. The envelope also carries a `reason` field: always present, but `null` for every event except `subscription.updated`, where it says what triggered the change (see [Event types](https://docs.vatly.com/#event-types)). ```json [Example delivery body] { "id": "webhook_event_Qk8pRtSvWm2NjLhYcZaE", "resource": "webhook_event", "eventName": "order.paid", "reason": null, "entityType": "order", "entityId": "order_Hn5xWqVfKm8RjTgYbUcP", "testmode": false, "createdAt": "2024-01-15T10:30:00Z", "object": { "id": "order_Hn5xWqVfKm8RjTgYbUcP", "resource": "order", "testmode": false, "status": "paid", "total": { "value": "29.99", "currency": "EUR" }, "subtotal": { "value": "24.79", "currency": "EUR" } }, "links": { "self": { "href": "https://api.vatly.com/v1/webhook-events/webhook_event_Qk8pRtSvWm2NjLhYcZaE", "type": "application/json" } } } ``` ::note The body is the `webhook_event` object shown above (its fields are top-level; there is **no `data` wrapper** ). For the full `WebhookDelivery` schema, see the [OpenAPI spec](https://docs.vatly.com/openapi.yaml){rel=""nofollow""} . :: Every request also carries two headers you should use: | Header | Purpose | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------ | | `Vatly-Signature` | Lets you verify the delivery really came from Vatly. See [Verifying signatures](https://docs.vatly.com/#verifying-signatures). | | `Vatly-Event-Id` | The event's ID (also in the body as `id`). It is **stable across retries**, so use it as the key to deduplicate deliveries. | ::note Respond with a `2xx` status as soon as you've stored the event, and do any heavy work asynchronously. The same event may arrive more than once, so deduplicate on `Vatly-Event-Id` . See [Delivery and retries](https://docs.vatly.com/#delivery-and-retries) for how failed deliveries are handled. :: ## Delivery and retries A delivery counts as **successful** only when your endpoint returns a `2xx` status. **Anything else is a failed delivery:** a non-`2xx` status, a connection Vatly can't establish, or a response that doesn't arrive before Vatly's delivery timeout. Vatly retries a failed delivery with backoff, so a transient problem on your side (a deploy, a brief outage, a slow dependency) recovers on its own once your endpoint is healthy again. Every retry carries the **same `Vatly-Event-Id`** and a **fresh `Vatly-Signature`**. So deduplicate on the event ID (a retried delivery is the same event, not a new one) and verify the signature on every attempt independently. The exact timeout and retry cadence, how long Vatly waits for a response, how many attempts it makes, and over what total window, are operational details Vatly tunes over time, so they aren't pinned here. Integrate against the behavior rather than specific numbers: trust the retries, deduplicate on `Vatly-Event-Id`, and your integration keeps working if those values change. ::tip **Don't race the timeout by doing your work before you answer.** If you run heavy processing before returning `2xx` , a slow run can blow past the timeout, Vatly counts the delivery as failed, and you get a retry for work you already did. Acknowledge first: store the event (or enqueue its `Vatly-Event-Id` ), return `2xx` right away (aim for within a second or two), then do the real work asynchronously. A fast acknowledgement stays comfortably inside any timeout no matter how heavy the downstream work is, and because retries deduplicate on `Vatly-Event-Id` , a crash between acknowledging and processing is safe to recover from. :: ## Event types The `eventName` field identifies what happened. The available events are: | Event | Description | | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `checkout.paid` | A checkout was paid successfully. | | `checkout.failed` | A checkout payment failed. | | `checkout.canceled` | A checkout was canceled. | | `checkout.expired` | A checkout session expired. | | `order.paid` | An order payment was successful. | | `order.canceled` | An order was canceled. When payment recovery for an unpaid order is exhausted, that order is canceled and carries `cancellationReason: payment_failure`. | | `order.chargeback_received` | A chargeback was received for an order. | | `order.chargeback_reversed` | A chargeback was reversed. | | `order.payment_failed` | A payment for this order failed and Vatly's automated payment recovery (dunning) now covers it. Delivered once per failed order, when the order enters recovery, not on each retry. Recovery runs per payment method: if another order on the same payment method fails while recovery is already running (an immediate upgrade charge during a renewal's recovery, say), it joins that recovery and you receive its own `order.payment_failed`. If recovery succeeds you receive `order.paid` for each recovered order; if it is exhausted the related subscriptions are canceled. See [Handling failed subscription payments](https://docs.vatly.com/#handling-failed-subscription-payments). | | `refund.completed` | A refund was processed successfully. | | `refund.failed` | A refund failed to process. | | `refund.canceled` | A refund was canceled. | | `subscription.started` | A subscription was started. | | `subscription.canceled_immediately` | A subscription was canceled with immediate effect at the merchant's request. `object` is the subscription and carries `cancellationReason: merchant_request`. | | `subscription.canceled_for_nonpayment` | Payment recovery for a failed renewal was exhausted, so the subscription was canceled with immediate effect. `object` is the subscription and carries `cancellationReason: payment_failure`. | | `subscription.canceled_with_grace_period` | A subscription was canceled; the customer keeps access until the period ends. | | `subscription.cancellation_grace_period_completed` | The grace period after a cancellation ended. | | `subscription.resumed` | A canceled subscription was resumed during its grace period. | | `subscription.billing_updated` | A subscription's billing details changed, in practice the mandate (payment method on file), e.g. a refreshed masked payment-method identifier. | | `subscription.updated` | A subscription changed. Fires on an immediate change, when a scheduled change takes effect at renewal, and when a renewal payment is confirmed. `object` is the subscription after the change; the envelope's `reason` says which case it is: `updated_immediately` (a plan, price, interval, or quantity change took effect now), `updated_on_renewal` (a scheduled change took effect at renewal, before the renewal is paid), or `renewed` (a renewal payment was confirmed, so `renewedAt` / `renewedUntil` moved). See the [payload details](https://docs.vatly.com/#payload-details-for-specific-events) below. | | `subscription.update_scheduled` | A plan, price, or quantity change was scheduled to take effect at the next billing cycle. `object` is the subscription as it is *today*; the target values are carried in `object.scheduledUpdate`. | | `one_off_product.update_submitted` | An update to a one-off product was submitted and is awaiting review. `object` is the one-off product, with the requested changes in `object.pendingUpdates` and `object.updateStatus: pending`. | | `one_off_product.update_approved` | A submitted one-off product update was approved and is now live. `object` is the one-off product with the new values applied and `object.pendingUpdates: null`. | | `one_off_product.update_rejected` | A submitted one-off product update was rejected. `object` is the unchanged one-off product with `object.pendingUpdates: null`. | | `one_off_product.archived` | A one-off product was archived and can no longer be sold. `object` is the one-off product with a non-null `object.archivedAt`. | | `one_off_product.unarchived` | An archived one-off product was put back on sale. `object` is the one-off product with `object.archivedAt: null`. | | `subscription_plan.update_submitted` | An update to a subscription plan was submitted and is awaiting review. `object` is the subscription plan, with the requested changes in `object.pendingUpdates` and `object.updateStatus: pending`. | | `subscription_plan.update_approved` | A submitted subscription plan update was approved and is now live. `object` is the subscription plan with the new values applied and `object.pendingUpdates: null`. | | `subscription_plan.update_rejected` | A submitted subscription plan update was rejected. `object` is the unchanged subscription plan with `object.pendingUpdates: null`. | | `subscription_plan.archived` | A subscription plan was archived and closed to new business. `object` is the subscription plan with a non-null `object.archivedAt`. | | `subscription_plan.unarchived` | An archived subscription plan was re-opened to new business. `object` is the subscription plan with `object.archivedAt: null`. | | `webhook.setup` | A verification call Vatly sends when you register a webhook endpoint or change its URL. See the [payload details](https://docs.vatly.com/#payload-details-for-specific-events) below. | ### Payload details for specific events A few events put extra structure in the payload worth calling out. **`object` is the affected resource,** keyed by its own `resource` field (`order`, `chargeback`, `refund`, `subscription`, `checkout`, `one_off_product`, `subscription_plan`, or `webhook`). For chargeback events this differs from `entityType`: `order.chargeback_received` and `order.chargeback_reversed` carry `entityType: order` (the order the chargeback belongs to), but the `object` itself is a Chargeback. **`subscription.update_scheduled`** carries the subscription's *current* state in `object`, plus the future target values in `object.scheduledUpdate` (`subscriptionPlanId`, `name`, `description`, `basePrice`, `quantity`, `interval`, `intervalCount`, `effectiveAt`). The same `scheduledUpdate` object is also returned on the subscription resource by the REST API, so you can reconcile a pending change at any time without relying on this once-delivered event. When that scheduled change takes effect at renewal, Vatly sends `subscription.updated` with `reason: updated_on_renewal`; an immediate change instead arrives as `subscription.updated` with `reason: updated_immediately`. In both cases the delivered `object` already reflects the new values and has no pending `scheduledUpdate`. **`subscription.updated` and the `reason` field.** This event fires for three distinct causes, told apart by the envelope's `reason`: `updated_immediately`, `updated_on_renewal`, or `renewed`. A renewal that also applies a scheduled change therefore emits *two* events (`subscription.updated` with `reason: updated_on_renewal` when the change takes effect, then `subscription.updated` with `reason: renewed` once the renewal is paid), each with its own stable `Vatly-Event-Id`. Test-mode renewals, including fast-forwarded ones, emit these too. New `reason` values may be added; treat an unknown one as a generic change and re-read the subscription from `object`. **`webhook.setup`** is delivered when you register an endpoint (or change its URL) to confirm it's reachable. It arrives as a normal, signed delivery (`entityType: webhook`, `object` is the secret-free endpoint config), so there's nothing special to parse: just acknowledge it with a `2xx`. Unlike event deliveries, this call is a one-shot verification check and is **not** retried (see [Delivery and retries](https://docs.vatly.com/#delivery-and-retries)), so a non-`2xx` response fails endpoint registration. It is also the one event that is never persisted, so it does not appear on the [Get webhook event](https://docs.vatly.com/api-reference/webhook-events) endpoint. ### Example: `subscription.started` ```json [subscription.started] { "id": "webhook_event_b167W0AChY7Z0Amr", "resource": "webhook_event", "eventName": "subscription.started", "reason": null, "entityType": "subscription", "entityId": "subscription_QdEpFhdSrG4Y3DnfsdqsH", "testmode": false, "createdAt": "2024-01-15T10:30:00Z", "object": { "id": "subscription_QdEpFhdSrG4Y3DnfsdqsH", "resource": "subscription", "customerId": "customer_Bm7xNvPwKr3YjTgHcZaE", "subscriptionPlanId": "subscription_plan_Rk5pQrSvWm8NjLhYbUcP", "testmode": false, "name": "Premium Plan", "status": "active", "basePrice": { "value": "99.99", "currency": "EUR" }, "quantity": 1, "interval": "month", "intervalCount": 1, "startedAt": "2024-01-15T10:30:00Z", "nextRenewalAt": "2024-02-15T10:30:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/subscriptions/subscription_QdEpFhdSrG4Y3DnfsdqsH", "type": "application/json" }, "customer": { "href": "https://api.vatly.com/v1/customers/customer_Bm7xNvPwKr3YjTgHcZaE", "type": "application/json" } } }, "links": { "self": { "href": "https://api.vatly.com/v1/webhook-events/webhook_event_b167W0AChY7Z0Amr", "type": "application/json" } } } ``` ## Handling failed subscription payments When a subscription renewal payment fails, Vatly runs an automated **payment recovery** process (dunning) on your behalf. You never have to schedule your own retries, but you do decide when to restrict access. Here is what happens, and what you receive: 1. The renewal payment fails and recovery begins. You receive a single `order.payment_failed` webhook for the renewal order (sent once, when recovery starts, not on each retry). Recovery runs per payment method: if another order on the same payment method fails while it is running (an immediate upgrade charge, say), that order joins the recovery and you receive its own `order.payment_failed`. The subscription's `status` stays `active` throughout recovery: it does **not** move to a "past due" state, and `on_grace_period` is never used for payment failure. That status means a *voluntary* cancellation that keeps access until the period ends. 2. Vatly attempts to recover the payment, and how it does so depends on why the charge failed: - **Soft decline** (e.g. insufficient funds, a temporary decline): the payment method is still valid, so Vatly automatically re-attempts the charge over a multi-week window, emailing the customer along the way. - **Hard decline** (e.g. an expired, canceled, or invalid payment method): retrying cannot succeed, so Vatly instead prompts the customer to supply a new payment method, on a shorter window. 3. **If recovery succeeds**, the original renewal order is paid and you receive `order.paid` for that same order. Because the subscription was never interrupted, access simply continues. Nothing else is needed. 4. **If recovery is exhausted** (the customer never resolves it), Vatly cancels the subscription: you receive `subscription.canceled_for_nonpayment` and the subscription `status` becomes `canceled` with `cancellationReason: payment_failure`. Each order that is still unpaid is canceled too: you receive `order.canceled` for it, and the order `status` becomes `canceled` with `cancellationReason: payment_failure`. ### Recommended integration Gate access on the events, not on a timer you keep in sync with ours: - On `order.payment_failed`: keep access on, and start your own grace period if your product has one. - On `order.paid` for the same order: recovery succeeded, so clear that grace period. - If your grace period elapses with no matching `order.paid`: restrict access on your side if you wish. Vatly's recovery keeps running underneath, so a later `order.paid` lets you restore access automatically. - On the subscription's cancellation: remove access permanently. ::note The number of retry attempts and the exact retry cadence are operational details that Vatly tunes over time. Integrate against these webhook events rather than against specific durations or attempt counts. :: ## Inspecting webhooks To make integrating Vatly as smooth as possible, you can inspect a detailed webhook history in your Vatly dashboard. If you store the event ID from a webhook delivery, you can also retrieve the full stored event later via the API: - [Get webhook event](https://docs.vatly.com/api-reference/webhook-events) That endpoint returns the event metadata plus the exact resource snapshot that was delivered at the time. ## Testing webhook flows For recurring billing flows, Vatly also exposes a test helper so you can trigger webhook-producing scenarios in test mode: - [Fast-forward subscription renewal](https://docs.vatly.com/api-reference/test-helpers) This is useful when you want to verify renewals and the events they produce without waiting for real billing dates. --- ## Verifying signatures To know for sure that a webhook was sent by Vatly and not a malicious actor, verify the signature on every delivery. Vatly signs each request with the `Vatly-Signature` header, which has the structured form: ```text Vatly-Signature: t=,v1= ``` - `t` is the Unix timestamp (in seconds) when the signature was generated. - `v1` is `HMAC-SHA256("{t}.{rawBody}", yourWebhookSecret)`, hex-encoded (the timestamp and a literal `.` prepended to the **exact raw request body**). To verify a delivery: 1. Parse `t` and `v1` out of the header. 2. Reject the request if `t` is more than **300 seconds** (5 minutes) from your server's current time. This guards against replay. 3. Recompute the HMAC over `"{t}.{rawBody}"` using your webhook secret and the **raw request body bytes** (not a re-serialized copy; re-encoding JSON changes the bytes and breaks the signature). 4. Compare your value against `v1` using a constant-time comparison. ::note Future signature schemes will ship alongside `v1` (e.g. `t=…,v1=…,v2=…` ). Match on the `v1=` key specifically rather than assuming the order or the only scheme present, so your code keeps working when new versions are added. :: ::tip If you use a Vatly SDK, signature verification is built in, for example PHP's `Vatly\API\Webhooks\Webhook::parse($rawBody, $signatureHeader, $secret)` or the Node SDK's `constructEvent()` . They parse the header, enforce the tolerance window, and verify the HMAC for you, throwing on failure. :: To verify it yourself: ::code-group ```js [JavaScript] import crypto from 'node:crypto' // `rawBody` must be the exact bytes Vatly sent (e.g. express.raw()), not a parsed object. function verifyVatlySignature(rawBody, header, secret, toleranceSeconds = 300) { const parts = Object.fromEntries(header.split(',').map((kv) => kv.split('='))) const timestamp = Number(parts.t) const signature = parts.v1 if (!timestamp || !signature) throw new Error('Malformed Vatly-Signature header') // Replay protection if (Math.abs(Math.floor(Date.now() / 1000) - timestamp) > toleranceSeconds) { throw new Error('Signature timestamp outside tolerance window') } const expected = crypto .createHmac('sha256', secret) .update(`${timestamp}.${rawBody}`) .digest('hex') if (!crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature))) { throw new Error('Invalid Vatly signature') } } ``` ```python [Python] import hashlib import hmac import time def verify_vatly_signature(raw_body: str, header: str, secret: str, tolerance_seconds: int = 300) -> None: parts = dict(part.split("=", 1) for part in header.split(",")) timestamp, signature = parts.get("t"), parts.get("v1") if not timestamp or not signature: raise ValueError("Malformed Vatly-Signature header") # Replay protection if abs(int(time.time()) - int(timestamp)) > tolerance_seconds: raise ValueError("Signature timestamp outside tolerance window") message = f"{timestamp}.{raw_body}".encode() expected = hmac.new(secret.encode(), message, hashlib.sha256).hexdigest() if not hmac.compare_digest(expected, signature): raise ValueError("Invalid Vatly signature") ``` ```php [PHP] $payload = file_get_contents('php://input'); $header = $_SERVER['HTTP_VATLY_SIGNATURE'] ?? ''; $toleranceSeconds = 300; $parts = []; foreach (explode(',', $header) as $part) { [$key, $value] = array_pad(explode('=', $part, 2), 2, null); $parts[trim((string) $key)] = trim((string) $value); } $timestamp = $parts['t'] ?? null; $signature = $parts['v1'] ?? null; if (! $timestamp || ! $signature || abs(time() - (int) $timestamp) > $toleranceSeconds) { http_response_code(400); exit('Invalid signature'); } $expected = hash_hmac('sha256', $timestamp . '.' . $payload, $secret); if (hash_equals($expected, $signature)) { // Request is verified } else { http_response_code(400); exit('Invalid signature'); } ``` :: Keep your webhook secret safe and never commit it to source control. If it leaks, you can no longer trust that a given webhook was sent by Vatly. # Idempotency ## What is idempotency? Idempotency is a property of an API endpoint that ensures multiple identical requests will have the same effect as a single request. This is particularly important when dealing with network issues, timeouts, or when you need to retry failed requests. For example, if you're creating a checkout and the request fails due to a network error, you can safely retry the request without worrying about creating duplicate checkouts. ## Using idempotency keys To make an idempotent request, include a unique `Idempotency-Key` header with your request: ::code-group{sync="client"} ```bash [cURL] curl -X POST https://api.vatly.com/v1/checkouts \ -H "Authorization: Bearer live_your_api_key_here" \ -H "Idempotency-Key: 123e4567-e89b-12d3-a456-426614174000" \ -H "Content-Type: application/json" \ -d '{ "products": [{"id": "subscription_plan_Bm7xNvPwKr3YjTgHcZaE"}], "redirectUrlSuccess": "https://example.com/success", "redirectUrlCanceled": "https://example.com/canceled" }' ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $checkout = $vatly->checkouts->create([ 'products' => [ ['id' => 'subscription_plan_Bm7xNvPwKr3YjTgHcZaE'], ], 'redirectUrlSuccess' => 'https://example.com/success', 'redirectUrlCanceled' => 'https://example.com/canceled', ], [ 'idempotencyKey' => '123e4567-e89b-12d3-a456-426614174000', ]); ``` :: ::note The idempotency key must be a unique string up to 255 characters. We recommend using a UUID v4 to ensure uniqueness. :: ## How it works 1. When you make a request with an idempotency key, our API records the **first** response keyed by that request and returns it verbatim on any later request with the same key. 2. A replayed response carries an `Idempotent-Replayed: true` header so you can tell it apart from a freshly processed request. 3. **The first HTTP response is final for that key.** This includes a rendered `4xx` or `5xx` response, once request processing has started. Retry the exact request with the same key to retrieve that stored response. Only use a fresh key for corrected parameters after you have reconciled whether the original mutation took effect. 4. After 24 hours, idempotency keys expire and become reusable as a fresh idempotency boundary. ## What binds an idempotency key A key is bound to the exact shape of the first request. The following are **contract-significant**. Replaying the same key with a different value returns `409 Conflict` **without executing the operation again**: - The HTTP method - The public endpoint and its concrete path - The query string - The request body - The normalized `Content-Type` media type - The normalized, ordered `Content-Encoding` When you hit a mismatch `409`, either retry with the original parameters or generate a new key. **Scope is per public route URI template.** The same key value used against a different endpoint is treated as a new key. Internal route-name or controller refactors on our side do not change replay identity; only the public route matters. ## Best practices Here are some tips for using idempotency effectively: 1. **Generate unique keys**: Use UUIDs or another method to generate unique keys for each request. 2. **Store keys**: Keep track of idempotency keys alongside your request data. 3. **Set retry policies**: Configure your HTTP client to automatically retry failed requests with the same idempotency key. 4. **Handle errors**: Check error responses to determine if you should retry with the same key. ## Example retry implementation Here's an example of how to implement automatic retries with idempotency: ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); function createCheckoutWithRetry($vatly, $data) { $idempotencyKey = \Ramsey\Uuid\Uuid::uuid4()->toString(); $maxRetries = 3; $attempt = 0; while ($attempt < $maxRetries) { try { return $vatly->checkouts->create($data, [ 'idempotencyKey' => $idempotencyKey, ]); } catch (\Vatly\Exception\ApiException $e) { $attempt++; // Only retry on network errors or server errors (5xx) if ($e->getCode() < 500 || $attempt >= $maxRetries) { throw $e; } // Wait before retrying (with exponential backoff) sleep(pow(2, $attempt)); } } } ``` ## Supported endpoints All mutating requests accept an optional `Idempotency-Key` header: - All `POST` requests - All `PATCH` requests - All `PUT` requests - All `DELETE` requests ::note An `Idempotency-Key` sent on a `GET` or `HEAD` request is ignored, since those methods don't mutate state. :: ## Error handling If you receive an error response, check the status code to determine if you should retry the request: - `4xx` errors: Client errors (like validation errors) should not be retried with the same data. - `5xx` errors: Server errors can be safely retried with the same idempotency key. ### Understanding `409 Conflict` A `409` shares one HTTP status across several distinct cases. The `message` distinguishes them, and idempotency cases also set `details.idempotency_outcome`: - **Replay mismatch**: the `Idempotency-Key` was reused with different request parameters (see [What binds an idempotency key](https://docs.vatly.com/#what-binds-an-idempotency-key)). Retry with the original parameters or generate a new key. - **`details.idempotency_outcome = in_progress`**: **retryable.** Another caller is still processing this exact request. Wait the number of seconds in the `Retry-After` header, then resend the exact same request and key. - **`details.idempotency_outcome = unknown`**: **not retryable.** The mutation may have completed, but its response could not be recorded and cannot be replayed safely. Read and reconcile the affected resource state before taking any further mutating action. Never automatically retry, with either the same key or a fresh one. - **Concurrent write**: two writers modified the same resource at the same version. Reload the latest state and retry; the conflict resolves itself unless contention is sustained. - **Refund already being created**: another refund of the same order is still being created, flagged by `details.retry_with_new_idempotency_key = true`. This response is stored against the `Idempotency-Key` you sent, so retry with a **new** key. ::note `Retry-After` is present only for the `in_progress` case. It tells you how many seconds to wait before resending the exact request and key. :: ## Rate limits **Exact replays still consume rate-limit budget.** API and per-merchant write throttles run *before* the idempotency lookup, so an otherwise valid replay can return `429 Too Many Requests` instead of the stored response. When this happens, wait for the interval in the `Retry-After` header, then resend the exact same request and key. # Testing ## Overview Vatly provides test helper endpoints that let you simulate billing events without waiting for real billing cycles. These endpoints are only available in **test mode** and require a `test_` prefixed API token. ## Taxes in test mode ::warning In test mode, Vatly does **not** run real tax determination. Checkouts and orders created with a `test_` token use a **fixed, predefined set of tax rates** so results are predictable while you build your integration. **These rates are simulated for testing only. They are not guaranteed to match real, current statutory rates, and must never be relied upon for pricing decisions, accounting, invoicing, or tax compliance.** Switch to a `live_` token to get Vatly's real, jurisdiction-accurate tax determination. :: ### How test-mode rates are applied The buyer's country determines a single fixed **standard** VAT rate from a built-in lookup. Any country without a specific entry is taxed at a flat **20%**. As an example of multi-rate handling, a Canada (`CA`) buyer also gets an additional 9.975% `QST` line. Only the standard rate is ever applied: there are no reduced or product-specific rates, and the lookup is not kept in sync with statutory changes. ### Tax IDs and reverse charge in test mode Tax IDs are **not** checked against VIES or any real registry in test mode. A test tax ID is treated as **valid only when it starts with the buyer's uppercase country code**. For example, `DE123456789` is valid for a German buyer, while `de123456789` or `FR123…` for a German buyer is not. When a **valid** test tax ID is supplied and the buyer's country **differs** from the seller's, a **0% reverse charge** is applied (B2B cross-border). Otherwise the buyer's country standard rate applies. ## Fast-forward subscription renewal Simulates a subscription renewal cycle, allowing you to test renewal billing flows, lifecycle events, and webhooks without waiting for the actual billing interval. The subscription must be active and have a scheduled next renewal. Like a live renewal, this runs **asynchronously**: the request is accepted immediately, the renewal runs from a queue a moment later, and the outcome arrives on your `order.paid` / `order.payment_failed` webhooks. The response therefore returns the subscription **before** the renewal: `renewedAt`, `renewedUntil`, and `nextRenewalAt` have not moved yet. ### Request `POST /v1/test-helpers/subscriptions/{subscriptionId}/fast-forward-renewal` | Parameter | Type | Description | | ---------------- | ------ | ------------------------------------------------------------- | | `subscriptionId` | string | ID of the subscription to renew (starts with `subscription_`) | The request body is **optional**. Omit it to advance the billing cycle and leave the renewal payment pending, the endpoint's original behaviour. Provide it to force a specific renewal payment outcome so you can exercise your payment-recovery handling. | Field | Type | Description | | --------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `paymentStatus` | string | Optional. Outcome to force on the renewal payment: `paid` or `failed`. Omit to leave the payment pending. `failed` declines the payment and starts a payment recovery (delivering `order.payment_failed` to your webhook); `paid` settles it. | | `failureReason` | string | Optional. Which decline to simulate, valid only with `paymentStatus: failed`. Soft declines (`insufficient_funds`, `temporary_decline`, `general_failure`) retry over multiple weeks; every other value is a hard decline that asks the customer for a new payment method. Defaults to `general_failure`. Allowed values: `insufficient_funds`, `temporary_decline`, `general_failure`, `invalid_mandate`, `mandate_canceled`, `account_closed`, `card_expired`, `card_lost_or_stolen`, `invalid_card_details`, `authentication_failed`, `fraud_suspected`. | ### Example Advance the cycle and leave the renewal payment pending: ::code-group{sync="client"} ```bash [cURL] curl -X POST https://api.vatly.com/v1/test-helpers/subscriptions/subscription_Lp3mNvBxKw7RjTgYcZaE/fast-forward-renewal \ -H "Authorization: Bearer test_your_api_key_here" ``` ```php [PHP] $vatly->testHelpers->fastForwardRenewal('subscription_Lp3mNvBxKw7RjTgYcZaE'); ``` :: Force the renewal payment to fail with a hard decline to test payment recovery: ::code-group{sync="client"} ```bash [cURL] curl -X POST https://api.vatly.com/v1/test-helpers/subscriptions/subscription_Lp3mNvBxKw7RjTgYcZaE/fast-forward-renewal \ -H "Authorization: Bearer test_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "paymentStatus": "failed", "failureReason": "card_expired" }' ``` ```php [PHP] $vatly->testHelpers->fastForwardRenewal('subscription_Lp3mNvBxKw7RjTgYcZaE', [ 'paymentStatus' => 'failed', 'failureReason' => 'card_expired', ]); ``` :: ### Response Returns the subscription **as it was before the renewal**: `renewedAt`, `renewedUntil`, and `nextRenewalAt` still hold their pre-renewal values because the renewal runs from the queue shortly after. Watch your webhooks for the actual outcome. ```json { "id": "subscription_Lp3mNvBxKw7RjTgYcZaE", "resource": "subscription", "customerId": "customer_Lp3mNvBxKw7RjTgYcZaE", "subscriptionPlanId": "subscription_plan_Rk5pQrSvWm8NjLhYbUcP", "testmode": true, "name": "Pro Monthly", "description": "Full access to all Pro features", "billingAddress": { "fullName": "John Doe", "companyName": "Acme Corp", "streetAndNumber": "123 Main Street", "city": "Berlin", "postalCode": "10115", "country": "DE" }, "basePrice": { "value": "29.00", "currency": "EUR" }, "quantity": 1, "interval": "month", "intervalCount": 1, "status": "active", "cancellationReason": null, "mandate": { "method": "card", "maskedIdentifier": "4242" }, "startedAt": "2024-01-15T10:30:00Z", "endedAt": null, "canceledAt": null, "renewedAt": null, "renewedUntil": null, "nextRenewalAt": "2024-02-15T10:30:00Z", "trialUntil": null, "scheduledUpdate": null, "links": { "self": { "href": "https://api.vatly.com/v1/subscriptions/subscription_Lp3mNvBxKw7RjTgYcZaE", "type": "application/json" }, "customer": { "href": "https://api.vatly.com/v1/customers/customer_Lp3mNvBxKw7RjTgYcZaE", "type": "application/json" } } } ``` ## Simulate an order payment When a fast-forward (or its payment recovery) leaves a renewal payment pending, settle or decline it with the order payment simulation helper. It resolves a payment that is already awaiting an outcome **without** advancing the billing cycle, useful for driving an `order.paid` on a renewal, or exercising payment recovery with `paymentStatus: failed`. `POST /v1/test-helpers/orders/{orderId}/simulate-payment` ```bash [cURL] curl -X POST https://api.vatly.com/v1/test-helpers/orders/order_Hn5xWqVfKm8RjTgYbUcP/simulate-payment \ -H "Authorization: Bearer test_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{"paymentStatus": "paid"}' ``` Like fast-forward renewal, this is asynchronous: the response returns the order still awaiting payment, and the outcome arrives on your webhooks. See [Simulate an order payment](https://docs.vatly.com/api-reference/test-helpers#simulate-an-order-payment) in the API reference for the request body and full response. # Customers ## The Customer API Resource Below you'll find all properties for the Vatly Customer API resource. ### Properties | Name | Type | Description | | ----------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier for the customer (starts with `customer_`). | | `resource` | `string` | The resource type. Always `customer`. | | `testmode` | `boolean` | Whether this resource is in test mode. | | `email` | `string` | The customer's email address. Internationalized domains are stored and returned in their Punycode (ASCII) form per UTS #46, e.g. `user@xn--mller-kva.de`. Convert back to Unicode for display in your own UI. | | `name` | `string | null` | The customer's display / account-holder name. An identity field used for communication (dunning emails, dashboard), distinct from, and with no effect on, the billing name on invoices. | | `createdAt` | `string` | When this customer was created (ISO 8601 format). | | `metadata` | `object | null` | Arbitrary key-value metadata for your application. Up to 50 keys, with key names up to 40 characters and values up to 500 characters. | | `links` | `object` | HATEOAS links to related resources. Contains `self` link. | --- ## List all customers `GET /v1/customers` This endpoint allows you to retrieve a paginated list of all your customers. By default, a maximum of ten customers are shown per page. Pass `email` to filter the list down to the customers holding an address, the way back to a customer id you no longer have. ### Optional attributes | Name | Type | Description | | --------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `email` | `string` | Return customers with this email address, within the storefront and mode the API token is scoped to. Canonicalized before matching, exactly as on write. Beyond that the comparison is exact, so `büyer@example.com` does not match `buyer@example.com`. An address can be held by more than one customer, in which case all of them are returned. A value that is not a valid email address returns `422`. | | `limit` | `integer` | The number of customers to return (default: 10, max: 100). | | `startingAfter` | `string` | A cursor for use in pagination. Returns results after this customer ID. | | `endingBefore` | `string` | A cursor for use in pagination. Returns results before this customer ID. | ::code-group{sync="api"} ```bash [cURL] curl -G https://api.vatly.com/v1/customers \ -H "Authorization: Bearer live_your_api_key_here" \ -d email=john.doe@example.com ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $customers = $vatly->customers->page(['email' => 'john.doe@example.com']); ``` ```json [Response] { "data": [ { "id": "customer_7kBmRtPvXw2NjLhYcZaE", "resource": "customer", "testmode": false, "email": "john.doe@example.com", "name": "John Doe", "createdAt": "2024-01-15T10:30:00Z", "metadata": { "userId": "user_Qp8kNvBxKw7RjTgYcZaE" }, "links": { "self": { "href": "https://api.vatly.com/v1/customers/customer_7kBmRtPvXw2NjLhYcZaE", "type": "application/json" } } }, { "id": "customer_Lp3mNvBxKw7RjTgYcZaE", "resource": "customer", "testmode": false, "email": "jane.smith@acme.com", "name": "Jane Smith", "createdAt": "2024-01-10T08:15:00Z", "metadata": {}, "links": { "self": { "href": "https://api.vatly.com/v1/customers/customer_Lp3mNvBxKw7RjTgYcZaE", "type": "application/json" } } } ], "count": 2, "links": { "self": { "href": "https://api.vatly.com/v1/customers", "type": "application/json" }, "next": null, "prev": null } } ``` :: --- ## Create a customer `POST /v1/customers` Creates a customer, or returns the one that already holds the address. Customers are uniquely identified by email within a storefront and testmode, and this endpoint is get-or-create on that key: posting an address that already exists returns the existing customer rather than a validation error, so an integration that lost its Vatly customer id can always get back to it. The status code says which happened: | Status | Meaning | | ------ | --------------------------------------------------------------------- | | `201` | The customer was created by this request. | | `200` | A customer with this email already existed and is returned unchanged. | A `200` response never modifies the customer: `name` and `metadata` in the request body are ignored for an existing customer. Use [`PATCH /v1/customers/:id`](https://docs.vatly.com/#update-a-customer) to change one. A `201` can also complete a create that was interrupted before it finished, in which case the customer keeps the `id` and `createdAt` of that earlier attempt, so `createdAt` may predate the request. Treat it as when the customer came into being, not as when this call happened. Addresses are canonicalized before they are compared, so `User@MÜLLER.de` and `user@xn--mller-kva.de` are the same customer. Beyond that the comparison is exact: `büyer@example.com` is a different mailbox and gets its own customer. ### Required attributes | Name | Type | Description | | ------- | -------- | ------------------------------------------------------------------------------------------------ | | `email` | `string` | The email address for the customer. Must be unique within the storefront for the given testmode. | ### Optional attributes | Name | Type | Description | | ---------- | --------------- | ------------------------------------------------------------------ | | `name` | `string | null` | The customer's display / account-holder name (max 255 characters). | | `metadata` | `object` | Arbitrary key-value metadata for your application. | ::code-group{sync="api"} ```bash [cURL] curl https://api.vatly.com/v1/customers \ -H "Authorization: Bearer live_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{"email": "customer@example.com", "metadata": {"userId": "user_Qp8kNvBxKw7RjTgYcZaE"}}' ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $vatly->customers->create([ 'email' => 'customer@example.com', 'metadata' => [ 'userId' => 'user_Qp8kNvBxKw7RjTgYcZaE', ], ]); ``` ```json [Response] { "id": "customer_7kBmRtPvXw2NjLhYcZaE", "resource": "customer", "testmode": false, "email": "customer@example.com", "name": "John Doe", "createdAt": "2024-01-15T10:30:00Z", "metadata": { "userId": "user_Qp8kNvBxKw7RjTgYcZaE" }, "links": { "self": { "href": "https://api.vatly.com/v1/customers/customer_7kBmRtPvXw2NjLhYcZaE", "type": "application/json" } } } ``` :: --- ## Retrieve a customer `GET /v1/customers/:id` This endpoint allows you to retrieve a customer by providing their Vatly id. Refer to [the list](https://docs.vatly.com/#the-customer-api-resource) at the top of this page to see which properties are included with customer objects. ::code-group{sync="api"} ```bash [cURL] curl https://api.vatly.com/v1/customers/customer_7kBmRtPvXw2NjLhYcZaE \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $vatly->customers->get('customer_7kBmRtPvXw2NjLhYcZaE'); ``` ```json [Response] { "id": "customer_7kBmRtPvXw2NjLhYcZaE", "resource": "customer", "testmode": false, "email": "john.doe@example.com", "name": "John Doe", "createdAt": "2024-01-15T10:30:00Z", "metadata": { "userId": "user_Qp8kNvBxKw7RjTgYcZaE" }, "links": { "self": { "href": "https://api.vatly.com/v1/customers/customer_7kBmRtPvXw2NjLhYcZaE", "type": "application/json" } } } ``` :: --- ## Update a customer `PATCH /v1/customers/:id` Updates a customer's identity fields. Only `name` and `email` may be changed here, and both are optional: send whichever you want to update. Billing-address details (company name, tax ID, street, city, country, etc.) are **not** supported by this endpoint and are ignored. Amend those through the [hosted billing-update flow](https://docs.vatly.com/api-reference/subscriptions#create-billing-update-link), which validates tax-relevant data centrally so invoices stay accurate. ### Optional attributes | Name | Type | Description | | ------- | --------------- | ------------------------------------------------------------------------------------------ | | `name` | `string | null` | The customer's display / account-holder name (max 255 characters). | | `email` | `string` | The customer's email address. Must be unique within the storefront for the given testmode. | ::code-group{sync="api"} ```bash [cURL] curl -X PATCH https://api.vatly.com/v1/customers/customer_7kBmRtPvXw2NjLhYcZaE \ -H "Authorization: Bearer live_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{"name": "John Doe", "email": "new.email@example.com"}' ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $customer = $vatly->customers->update('customer_7kBmRtPvXw2NjLhYcZaE', [ 'name' => 'John Doe', 'email' => 'new.email@example.com', ]); ``` ```json [Response] { "id": "customer_7kBmRtPvXw2NjLhYcZaE", "resource": "customer", "testmode": false, "email": "new.email@example.com", "name": "John Doe", "createdAt": "2024-01-15T10:30:00Z", "metadata": { "userId": "user_Qp8kNvBxKw7RjTgYcZaE" }, "links": { "self": { "href": "https://api.vatly.com/v1/customers/customer_7kBmRtPvXw2NjLhYcZaE", "type": "application/json" } } } ``` :: --- ## Create a customer portal session `POST /v1/customers/:customerId/portal-sessions` Creates a short-lived, single-use link that sends an authenticated customer straight to this API token's storefront in Vatly's hosted portal. The portal lets the customer view invoices and manage subscriptions for the storefront: opening invoice history, updating eligible payment methods, and canceling an active subscription. Customers with one-off purchases and no subscription can still use the portal for their invoice history. The session is locked to the customer, storefront, merchant, and live/test mode represented by the token; it never exposes a storefront picker or other stores associated with the same email address. For a merchant with multiple storefronts, each API token issues portal links for its own storefront. Redirect the customer's browser to `url`. The link expires after roughly 15 minutes by default and can be consumed once. If an idempotency key replays a response after its URL has already been used, request a replacement with a fresh key. The response is credential-bearing, so it is returned with `Cache-Control: no-store, private`. Do not log or store the `url`. ::note Portal sessions are available only for customers that are active, not archived, have a usable email address, belong to the authenticated API token's storefront and mode, and have at least one issued invoice in that storefront and mode. Invoices remain eligible after a refund or chargeback; a subscription without an issued invoice does not grant access. Vatly returns `404` when those conditions are not met. :: ### Optional attributes | Name | Type | Description | | ----------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `returnUrl` | `string | null` | Absolute HTTPS URL without embedded credentials, rendered as a return link in the hosted portal (max 2048 bytes). Vatly never fetches or automatically redirects to this URL. | ### Response | Name | Type | Description | | ----------- | --------------- | ------------------------------------------------------------------------------------------ | | `url` | `string` | Single-use HTTPS URL to redirect the customer to. | | `expiresAt` | `string` | Expiry of the one-time entry link, not of the resulting browser session (ISO 8601 format). | | `returnUrl` | `string | null` | The validated absolute HTTPS return URL supplied in the request, or `null`. | ::code-group{sync="api"} ```bash [cURL] curl https://api.vatly.com/v1/customers/customer_7kBmRtPvXw2NjLhYcZaE/portal-sessions \ -H "Authorization: Bearer live_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{"returnUrl": "https://merchant.example/account/billing"}' ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $vatly->customers->createPortalSession('customer_7kBmRtPvXw2NjLhYcZaE', [ 'returnUrl' => 'https://merchant.example/account/billing', ]); ``` ```json [Response] { "url": "https://billing.vatly.com/authenticate?credential=...", "expiresAt": "2026-09-01T12:15:00Z", "returnUrl": "https://merchant.example/account/billing" } ``` :: # Webhook Endpoints ## The Webhook Endpoint API Resource A webhook endpoint is the URL Vatly `POST`s event deliveries to. Each delivery is signed with the secret you set (see the `Vatly-Signature` header in the [Webhooks guide](https://docs.vatly.com/guides/webhooks#verifying-signatures)). A storefront can have **up to five endpoints per mode** (test and live are separate; the mode is determined by the API token you use). Each endpoint carries its own `enabledEvents` subscription list, so you can fan different events out to different URLs. Managing endpoints from the API is useful for provisioning from CI / infrastructure-as-code, or pointing an ephemeral preview environment at its own public URL. ::note The signing **secret is write-only** : you supply it on creation (and may rotate it via update), but it is never returned in any response. Store the value you send. The API will not give it back. :: ### Properties | Name | Type | Description | | --------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier for the webhook endpoint (starts with `webhook_`). | | `resource` | `string` | The resource type. Always `webhook_endpoint`. | | `testmode` | `boolean` | Whether this endpoint receives test-mode events. | | `url` | `string` | The HTTPS URL deliveries are POSTed to. | | `enabledEvents` | `array` | The event names this endpoint is subscribed to. Only these are delivered. An empty list means the endpoint is dormant (no domain events), though the `webhook.setup` verification event is always sent regardless. New event names are **not** added automatically; update the endpoint to opt in. See the [event types](https://docs.vatly.com/guides/webhooks#event-types) for the subscribable names. | | `createdAt` | `string` | When this endpoint was created (ISO 8601 format). | | `links` | `object` | HATEOAS links to related resources. Contains `self`. | --- ## List webhook endpoints `GET /v1/webhook-endpoints` Returns the webhook endpoints for the authenticated storefront, filtered by the testmode determined from the API token (up to five per mode). Each endpoint includes its `enabledEvents` subscriptions; the signing secret is never included. ### Optional attributes | Name | Type | Description | | --------------- | --------- | ------------------------------------------------------------------------ | | `limit` | `integer` | The number of endpoints to return (default: 10, max: 100). | | `startingAfter` | `string` | A cursor for use in pagination. Returns results after this endpoint ID. | | `endingBefore` | `string` | A cursor for use in pagination. Returns results before this endpoint ID. | ::code-group{sync="api"} ```bash [cURL] curl -G https://api.vatly.com/v1/webhook-endpoints \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $endpoints = $vatly->webhookEndpoints->page(); ``` ```json [Response] { "data": [ { "id": "webhook_QdEpFhdSrG4Y3DnfsdqsH", "resource": "webhook_endpoint", "testmode": false, "url": "https://merchant.example/webhooks/vatly", "enabledEvents": [ "order.paid", "refund.completed" ], "createdAt": "2024-01-15T10:30:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/webhook-endpoints/webhook_QdEpFhdSrG4Y3DnfsdqsH", "type": "application/json" } } }, { "id": "webhook_Vm6zTjNsKp9LcRwXyBaF", "resource": "webhook_endpoint", "testmode": false, "url": "https://analytics.example/webhooks/vatly", "enabledEvents": [ "checkout.paid" ], "createdAt": "2024-02-10T08:15:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/webhook-endpoints/webhook_Vm6zTjNsKp9LcRwXyBaF", "type": "application/json" } } } ], "count": 2, "links": { "self": { "href": "https://api.vatly.com/v1/webhook-endpoints", "type": "application/json" }, "next": null, "prev": null } } ``` :: --- ## Register a webhook endpoint `POST /v1/webhook-endpoints` Registers a webhook endpoint for the mode determined by the API token. You supply the signing `secret`; it is write-only and never returned, so keep the value you send: you use it to verify the `Vatly-Signature` HMAC on deliveries. Vatly sends a `webhook.setup` verification ping to the URL and validates its SSL certificate; if either fails the request is rejected with `422`. A storefront may register **up to five endpoints per mode**, and each URL must be unique within that storefront and mode; a duplicate URL or a sixth endpoint returns `422`. `enabledEvents` is an explicit snapshot. If omitted, Vatly stores every event name available at registration time; events introduced later are **not** enabled automatically. Send `[]` for a dormant endpoint. The `webhook.setup` verification event is unconditional and cannot be selected. ### Required attributes | Name | Type | Description | | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `url` | `string` | The HTTPS URL deliveries are POSTed to. Must be publicly reachable and present a valid SSL certificate. `localhost` and loopback addresses are not allowed. Must be unique within the storefront and mode. | | `secret` | `string` | Signing secret for this endpoint (at least 10 characters), used to compute the `Vatly-Signature` HMAC on every delivery. You choose it (e.g. pinned from an environment variable). Write-only: the API never returns it. | ### Optional attributes | Name | Type | Description | | --------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `enabledEvents` | `array` | The event names to deliver to this endpoint, drawn from the subscribable set (see [event types](https://docs.vatly.com/guides/webhooks#event-types)). Omit to subscribe to every event available at registration time; send `[]` for a dormant endpoint. `webhook.setup` is always sent and cannot be listed here. | ::code-group{sync="api"} ```bash [cURL] curl https://api.vatly.com/v1/webhook-endpoints \ -H "Authorization: Bearer live_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "url": "https://merchant.example/webhooks/vatly", "secret": "whsec_3f9a1c7e2d4f7b9c5a2c1d5b7e9f3a8d", "enabledEvents": ["order.paid", "refund.completed"] }' ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $endpoint = $vatly->webhookEndpoints->create([ 'url' => 'https://merchant.example/webhooks/vatly', 'secret' => 'whsec_3f9a1c7e2d4f7b9c5a2c1d5b7e9f3a8d', 'enabledEvents' => ['order.paid', 'refund.completed'], ]); ``` ```json [Response] { "id": "webhook_QdEpFhdSrG4Y3DnfsdqsH", "resource": "webhook_endpoint", "testmode": false, "url": "https://merchant.example/webhooks/vatly", "enabledEvents": [ "order.paid", "refund.completed" ], "createdAt": "2024-01-15T10:30:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/webhook-endpoints/webhook_QdEpFhdSrG4Y3DnfsdqsH", "type": "application/json" } } } ``` :: --- ## Get a webhook endpoint `GET /v1/webhook-endpoints/:id` Retrieves a webhook endpoint by ID. The signing secret is never included. ### Parameters | Name | Type | Description | | ------------------- | -------- | ---------------------------------------------- | | `webhookEndpointId` | `string` | The unique identifier of the webhook endpoint. | ::code-group{sync="api"} ```bash [cURL] curl https://api.vatly.com/v1/webhook-endpoints/webhook_QdEpFhdSrG4Y3DnfsdqsH \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $endpoint = $vatly->webhookEndpoints->get('webhook_QdEpFhdSrG4Y3DnfsdqsH'); ``` ```json [Response] { "id": "webhook_QdEpFhdSrG4Y3DnfsdqsH", "resource": "webhook_endpoint", "testmode": false, "url": "https://merchant.example/webhooks/vatly", "enabledEvents": [ "order.paid", "refund.completed" ], "createdAt": "2024-01-15T10:30:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/webhook-endpoints/webhook_QdEpFhdSrG4Y3DnfsdqsH", "type": "application/json" } } } ``` :: --- ## Update a webhook endpoint `PATCH /v1/webhook-endpoints/:id` Updates a webhook endpoint's `url`, its signing `secret`, and/or its complete `enabledEvents` subscription set. A new URL is revalidated for reachability and a valid SSL certificate just like on creation. The secret is write-only and is never returned. Omitting `enabledEvents` preserves the current subscriptions; sending `[]` makes the endpoint dormant; sending a list **replaces** the whole set. Sending an empty body is a no-op that returns the current endpoint. ### Optional attributes | Name | Type | Description | | --------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `url` | `string` | New HTTPS delivery URL. Revalidated for reachability and SSL the same way as on creation; must stay unique within the storefront and mode. | | `secret` | `string` | New signing secret (at least 10 characters). Write-only: keep the value, as the API never returns it. | | `enabledEvents` | `array` | Replaces the endpoint's complete event subscription set (see [event types](https://docs.vatly.com/guides/webhooks#event-types)). Omit to preserve the current set; send `[]` to make the endpoint dormant. New event names are never added automatically; `webhook.setup` is not subscribable. | ::code-group{sync="api"} ```bash [cURL] curl -X PATCH https://api.vatly.com/v1/webhook-endpoints/webhook_QdEpFhdSrG4Y3DnfsdqsH \ -H "Authorization: Bearer live_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "url": "https://merchant.example/webhooks/vatly-v2", "enabledEvents": ["checkout.paid", "order.paid"] }' ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $endpoint = $vatly->webhookEndpoints->update('webhook_QdEpFhdSrG4Y3DnfsdqsH', [ 'url' => 'https://merchant.example/webhooks/vatly-v2', 'enabledEvents' => ['checkout.paid', 'order.paid'], ]); ``` ```json [Response] { "id": "webhook_QdEpFhdSrG4Y3DnfsdqsH", "resource": "webhook_endpoint", "testmode": false, "url": "https://merchant.example/webhooks/vatly-v2", "enabledEvents": [ "checkout.paid", "order.paid" ], "createdAt": "2024-01-15T10:30:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/webhook-endpoints/webhook_QdEpFhdSrG4Y3DnfsdqsH", "type": "application/json" } } } ``` :: --- ## Delete a webhook endpoint `DELETE /v1/webhook-endpoints/:id` Deletes a webhook endpoint. Vatly stops sending deliveries to it immediately. To receive events again, register a new endpoint. ### Parameters | Name | Type | Description | | ------------------- | -------- | ---------------------------------------------- | | `webhookEndpointId` | `string` | The unique identifier of the webhook endpoint. | ::code-group{sync="api"} ```bash [cURL] curl -X DELETE https://api.vatly.com/v1/webhook-endpoints/webhook_QdEpFhdSrG4Y3DnfsdqsH \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $vatly->webhookEndpoints->delete('webhook_QdEpFhdSrG4Y3DnfsdqsH'); ``` :: Returns `204 No Content` on success. # Test helpers ## Test helper endpoints Vatly provides a small set of test helper endpoints for recurring billing scenarios. These endpoints are only available in test mode. ::warning Use a `test_` API token for every endpoint on this page. Test helper endpoints are not available with live credentials. :: --- ## Fast-forward subscription renewal `POST /v1/test-helpers/subscriptions/{subscriptionId}/fast-forward-renewal` Simulate a renewal cycle for an existing subscription. The subscription must be active and have a scheduled next renewal. This helper is **asynchronous, just like a live renewal**. The request is validated straight away, but the renewal itself runs from a queue a few seconds later, so the response returns the subscription **as it was before the renewal**: `renewedAt`, `renewedUntil`, and `nextRenewalAt` have not moved yet. Follow the `order.paid` and `order.payment_failed` webhooks for the outcome, exactly as your live integration should. Useful for: - testing renewal billing flows without waiting for the real billing interval - verifying subscription lifecycle events and webhook delivery - validating dunning or invoice follow-up automation in your sandbox flow - forcing the renewal payment to fail so you can exercise your payment-recovery handling ### Request body The request body is optional. Omit it to advance the billing cycle and leave the renewal payment pending (this endpoint's original behaviour). | Attribute | Type | Description | | --------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `paymentStatus` | string | Optional. Outcome to force on the renewal payment. One of `paid` or `failed`. Omit to leave the renewal payment pending. `failed` declines the payment and starts a payment recovery for the renewal order (delivering `order.payment_failed` to your webhook endpoint); `paid` settles it. | | `failureReason` | string | Optional. Which decline to simulate. Only valid alongside `paymentStatus: failed` (sending it with `paid` is rejected). Soft declines (`insufficient_funds`, `temporary_decline`, `general_failure`) keep the payment method and retry on a multi-week timeline; every other value is a hard decline that drives the customer to supply a new payment method on a short timeline. Defaults to `general_failure`. Allowed values: `insufficient_funds`, `temporary_decline`, `general_failure`, `invalid_mandate`, `mandate_canceled`, `account_closed`, `card_expired`, `card_lost_or_stolen`, `invalid_card_details`, `authentication_failed`, `fraud_suspected`. | ::note The renewal payment is simulated **locally** . Vatly never submits a charge to the provider sandbox. When `paymentStatus` is provided it is the deterministic outcome; when it is omitted the payment stays pending, and you can settle or decline it later with [Simulate an order payment](https://docs.vatly.com/#simulate-an-order-payment) . A requested `failed` outcome can start payment recovery even before a payment exists, but `paid` cannot be applied until there is a chargeable payment. If the payment mandate is not active yet, the cycle still advances. Only one unresolved fast-forward per subscription may be in flight at a time; a second request returns `409` while the first is still queued, running, or awaiting recovery. :: ::note Because the simulated payment lives only inside Vatly, it cannot receive a provider-originated chargeback or dispute. Use a normal provider-backed test payment when you need to test chargeback webhooks. :: ::code-group ```bash [cURL] curl -X POST https://api.vatly.com/v1/test-helpers/subscriptions/subscription_Lp3mNvBxKw7RjTgYcZaE/fast-forward-renewal \ -H "Authorization: Bearer test_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "paymentStatus": "failed", "failureReason": "card_expired" }' ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('test_your_api_key_here'); $subscription = $vatly->testHelpers->fastForwardRenewal('subscription_Lp3mNvBxKw7RjTgYcZaE', [ 'paymentStatus' => 'failed', 'failureReason' => 'card_expired', ]); ``` ```json [Response] { "id": "subscription_Lp3mNvBxKw7RjTgYcZaE", "resource": "subscription", "customerId": "customer_Lp3mNvBxKw7RjTgYcZaE", "subscriptionPlanId": "subscription_plan_Rk5pQrSvWm8NjLhYbUcP", "testmode": true, "name": "Pro Monthly", "description": "Full access to all Pro features", "billingAddress": { "fullName": "John Doe", "companyName": "Acme Corp", "streetAndNumber": "123 Main Street", "city": "Berlin", "postalCode": "10115", "country": "DE" }, "basePrice": { "value": "29.00", "currency": "EUR" }, "quantity": 1, "interval": "month", "intervalCount": 1, "status": "active", "cancellationReason": null, "mandate": { "method": "card", "maskedIdentifier": "4242" }, "startedAt": "2024-01-15T10:30:00Z", "endedAt": null, "canceledAt": null, "renewedAt": null, "renewedUntil": null, "nextRenewalAt": "2024-02-15T10:30:00Z", "trialUntil": null, "scheduledUpdate": null, "links": { "self": { "href": "https://api.vatly.com/v1/subscriptions/subscription_Lp3mNvBxKw7RjTgYcZaE", "type": "application/json" }, "customer": { "href": "https://api.vatly.com/v1/customers/customer_Lp3mNvBxKw7RjTgYcZaE", "type": "application/json" } } } ``` :: ### Errors | Status | Meaning | | ------ | ----------------------------------------------------------------------------------- | | `401` | Missing or invalid API key | | `403` | Endpoint not available for this token or resource | | `404` | Subscription not found | | `409` | A fast-forward for this subscription is still queued, running, or awaiting recovery | | `422` | Invalid request body (for example, `failureReason` sent with `paymentStatus: paid`) | --- ## Simulate an order payment `POST /v1/test-helpers/orders/{orderId}/simulate-payment` Settle or decline the pending payment of a test order that was charged to the customer's saved payment method, for example a subscription renewal, or a subscription update made with `invoiceImmediately: true`. Use this when a test-mode payment on a saved payment method is still pending. Test **card** payments settle as paid right away. Test **SEPA Direct Debit** payments settle as paid automatically 10 to 15 minutes after they are created, unless you simulate an outcome first: simulate `failed` within the first 10 minutes to test your payment-recovery handling. Payments created locally by the fast-forward and payment-recovery helpers are **never** settled automatically; they stay pending until you simulate an outcome here. Unlike [fast-forward renewal](https://docs.vatly.com/#fast-forward-subscription-renewal), this does **not** advance the billing cycle; it only resolves a payment that is already awaiting an outcome. This helper is **asynchronous, just like a live payment**. The request is validated straight away, but the outcome is applied from a queue a few seconds later, so the returned order is still awaiting payment. Follow the `order.paid` / `order.payment_failed` webhooks for the result. ### Request body | Attribute | Type | Description | | --------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `paymentStatus` | string | Required. Outcome to force on the order's pending payment. One of `paid` or `failed`. `paid` settles it (delivering `order.paid`); `failed` declines it and starts a payment recovery (delivering `order.payment_failed`). | | `failureReason` | string | Optional. Which decline to simulate. Only valid alongside `paymentStatus: failed` (sending it with `paid` is rejected). Soft declines (`insufficient_funds`, `temporary_decline`, `general_failure`) keep the payment method and retry on a multi-week timeline; every other value is a hard decline that drives the customer to supply a new payment method on a short timeline. Defaults to `general_failure`. Allowed values: `insufficient_funds`, `temporary_decline`, `general_failure`, `invalid_mandate`, `mandate_canceled`, `account_closed`, `card_expired`, `card_lost_or_stolen`, `invalid_card_details`, `authentication_failed`, `fraud_suspected`. | ::note A payment that already completed or failed cannot be simulated again. If the payment mandate is not active yet, no payment exists: `failed` still starts a payment recovery, but `paid` is rejected. Only one simulation per order can be queued at a time; a second request while one is queued returns `409` . :: ::code-group ```bash [cURL] curl -X POST https://api.vatly.com/v1/test-helpers/orders/order_Hn5xWqVfKm8RjTgYbUcP/simulate-payment \ -H "Authorization: Bearer test_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "paymentStatus": "paid" }' ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('test_your_api_key_here'); $order = $vatly->testHelpers->simulateOrderPayment('order_Hn5xWqVfKm8RjTgYbUcP', [ 'paymentStatus' => 'paid', ]); ``` ```json [Response] { "id": "order_Hn5xWqVfKm8RjTgYbUcP", "resource": "order", "customerId": "customer_Xk9pQrSvWm4NjLhYbUcP", "testmode": true, "metadata": {}, "paymentMethod": null, "createdAt": "2024-01-15T10:30:00Z", "status": "pending", "cancellationReason": null, "invoiceNumber": null, "total": { "value": "35.09", "currency": "EUR" }, "subtotal": { "value": "29.00", "currency": "EUR" }, "reversedSubtotal": { "value": "0.00", "currency": "EUR" }, "refundableSubtotal": { "value": "29.00", "currency": "EUR" }, "taxSummary": [ { "taxRate": { "name": "VAT", "percentage": 21, "taxablePercentage": 100 }, "amount": { "value": "6.09", "currency": "EUR" } } ], "lines": [ { "id": "order_item_Jk4pQrSvWm8NjLhYbUcP", "resource": "orderline", "description": "Pro Monthly Subscription", "quantity": 1, "basePrice": { "value": "29.00", "currency": "EUR" }, "total": { "value": "35.09", "currency": "EUR" }, "subtotal": { "value": "29.00", "currency": "EUR" }, "taxes": [ { "taxRate": { "name": "VAT", "percentage": 21, "taxablePercentage": 100 }, "amount": { "value": "6.09", "currency": "EUR" } } ], "productType": "subscription", "productId": "subscription_Hn5xWqVfKm8RjTgYbUcP" } ], "customerDetails": { "fullName": "John Doe", "companyName": "Acme Corp", "streetAndNumber": "123 Main Street", "city": "Berlin", "postalCode": "10115", "country": "DE", "email": "john@acme.com" }, "links": { "self": { "href": "https://api.vatly.com/v1/orders/order_Hn5xWqVfKm8RjTgYbUcP", "type": "application/json" }, "customer": { "href": "https://api.vatly.com/v1/customers/customer_Xk9pQrSvWm4NjLhYbUcP", "type": "application/json" }, "customerInvoice": { "href": "https://vatly.com/invoices/order_Hn5xWqVfKm8RjTgYbUcP", "type": "text/html" } } } ``` :: ### Errors | Status | Meaning | | ------ | ------------------------------------------------------------------------------------------------------------------------------------------- | | `401` | Missing or invalid API key | | `403` | Endpoint not available for this token or resource | | `404` | Order not found | | `409` | A simulation for this order is already queued | | `422` | Invalid request body (for example, `failureReason` sent with `paymentStatus: paid`, or `paid` requested before a chargeable payment exists) | # Checkouts ## The Checkout API Resource Below you'll find all properties for the Vatly Checkout API resource. ### Properties | Name | Type | Description | | --------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `id` | `string` | Unique identifier for the checkout (starts with `checkout_`). | | `resource` | `string` | The resource type. Always `checkout`. | | `orderId` | `string | null` | Unique identifier for the order created from this checkout. Only available when the checkout has been paid successfully. | | `customerId` | `string | null` | The customer associated with this checkout. Always present; `null` until a customer is associated. For an anonymous checkout this happens when the buyer completes payment. | | `testmode` | `boolean` | Whether this checkout is in test mode. | | `redirectUrlSuccess` | `string` | The URL to which the checkout should redirect the user after the checkout has been paid successfully. May contain the literal `{CHECKOUT_ID}` placeholder, which Vatly substitutes with this checkout's ID at creation time (e.g. `https://example.com/return?checkout_id={CHECKOUT_ID}`). | | `redirectUrlCanceled` | `string` | The URL to which the user should get redirected when the user cancels the checkout. Supports the same `{CHECKOUT_ID}` placeholder as `redirectUrlSuccess`. | | `metadata` | `object | null` | Arbitrary key-value metadata for your application. Up to 50 keys, with key names up to 40 characters and values up to 500 characters. | | `locale` | `string | null` | The language the hosted checkout was asked to present in, as sent on creation. `null` means none was specified and the checkout picks a language from the shopper's browser. One of `en`, `de`, `fr`, `nl`, `es`, `it`, `pt`, `pl`, or `null`. | | `status` | `string` | The status of the checkout. Can be `created`, `paid`, `canceled`, `failed`, or `expired`. | | `expiresAt` | `string | null` | When this checkout will expire (ISO 8601 format). | | `createdAt` | `string` | The moment the checkout was created, in ISO 8601 format. | | `links` | `object` | HATEOAS links to related resources. Contains `checkoutUrl` (the hosted checkout page URL), `self`, and `order`. `order` is always present and is `null` until the checkout completes. | --- ## List all checkouts `GET /v1/checkouts` This endpoint allows you to retrieve a paginated list of all your checkouts. By default, a maximum of ten checkouts are shown per page. ### Optional attributes | Name | Type | Description | | --------------- | --------- | ------------------------------------------------------------------------ | | `limit` | `integer` | The number of checkouts to return (default: 10, max: 100). | | `startingAfter` | `string` | A cursor for use in pagination. Returns results after this checkout ID. | | `endingBefore` | `string` | A cursor for use in pagination. Returns results before this checkout ID. | ::code-group{sync="api"} ```bash [cURL] curl -G https://api.vatly.com/v1/checkouts \ -H "Authorization: Bearer live_your_api_key_here" \ -d limit=10 ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $checkouts = $vatly->checkouts->page(); ``` ```json [Response] { "data": [ { "id": "checkout_QdEpFhdSrG4Y3DnfsdqsH", "resource": "checkout", "customerId": null, "orderId": null, "testmode": false, "redirectUrlSuccess": "https://example.com/success", "redirectUrlCanceled": "https://example.com/canceled", "metadata": {}, "locale": null, "status": "created", "expiresAt": "2024-01-16T10:30:00Z", "createdAt": "2024-01-15T10:30:00Z", "links": { "checkoutUrl": { "href": "https://checkout.vatly.com/checkout_QdEpFhdSrG4Y3DnfsdqsH", "type": "text/html" }, "self": { "href": "https://api.vatly.com/v1/checkouts/checkout_QdEpFhdSrG4Y3DnfsdqsH", "type": "application/json" }, "order": null } } ], "count": 1, "links": { "self": { "href": "https://api.vatly.com/v1/checkouts", "type": "application/json" }, "next": null, "prev": null } } ``` :: --- ## Create a checkout `POST /v1/checkouts` This endpoint allows you to start a new hosted Vatly Checkout. Make sure you have at least one subscription plan or one-off product configured in your Vatly account. Once paid, any subscription plan product assigned to the checkout will kick off a new subscription for that plan. ### Required attributes | Name | Type | Description | | --------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `products` | `array` | An array of product objects to include in this checkout. Each product can have: `id` (required, starts with `one_off_product_` or `subscription_plan_`), `quantity` (optional, default: 1), `price` (optional, EUR-only price override; see [Custom pricing](https://docs.vatly.com/#custom-pricing)), `trialDays` (optional, for subscription plans), `metadata` (optional). | | `redirectUrlSuccess` | `string` | The URL to which the checkout should redirect the user after the checkout has been paid successfully. You may include the literal `{CHECKOUT_ID}` placeholder anywhere in the URL, and Vatly substitutes it with this checkout's ID, so your return page can read the checkout ID without a server-side token store. | | `redirectUrlCanceled` | `string` | The URL to which the user should get redirected when the user cancels the checkout. Supports the same `{CHECKOUT_ID}` placeholder. | ### Optional attributes | Name | Type | Description | | ---------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `metadata` | `object` | Arbitrary key-value metadata for your application. | | `customerId` | `string` | The ID for an existing customer to associate with this checkout. If provided, the customer's email will be pre-filled. Must match the testmode of the API token. | | `billingAddress` | `object` | Optional editable prefill for the billing address fields on the hosted checkout. Accepts the standard address fields (`fullName`, `companyName`, `taxId`, `streetAndNumber`, `streetAdditional`, `city`, `region`, `postalCode`, `country`). When `country` is supplied it takes precedence over the shopper's IP address for determining their country. A supplied `taxId` is only a prefill; it is not registered until the buyer submits the checkout. | | `locale` | `string | null` | Language to present the hosted checkout in, including its validation and error messages. Send a bare language code (`de`), a BCP 47 tag (`de-AT`), or a POSIX / ISO 15897 locale (`de_DE`); all three fold to the language, so there are no region-specific variants. The language also carries through to the payment provider's own hosted page. Supported languages: `en`, `de`, `fr`, `nl`, `es`, `it`, `pt`, `pl`; anything else is a `422` naming the supported set. Omit it (or send `null`) to detect the language from the shopper's `Accept-Language` header, falling back to English. The response echoes back the folded language, not the string you sent. | ::code-group{sync="api"} ```bash [cURL] curl https://api.vatly.com/v1/checkouts \ -H "Authorization: Bearer live_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "products": [ {"id": "one_off_product_Vr8kQdFhSrG4Y3DnfsdqH", "quantity": 1}, {"id": "subscription_plan_Rk5pQrSvWm8NjLhYbUcP", "trialDays": 14} ], "redirectUrlSuccess": "https://example.com/return?checkout_id={CHECKOUT_ID}", "redirectUrlCanceled": "https://example.com/canceled", "locale": "de" }' ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $checkout = $vatly->checkouts->create([ 'products' => [ ['id' => 'one_off_product_Vr8kQdFhSrG4Y3DnfsdqH', 'quantity' => 1], ['id' => 'subscription_plan_Rk5pQrSvWm8NjLhYbUcP', 'trialDays' => 14], ], 'redirectUrlSuccess' => 'https://example.com/return?checkout_id={CHECKOUT_ID}', 'redirectUrlCanceled' => 'https://example.com/canceled', 'locale' => 'de', ]); // Redirect the user to the checkout URL header('Location: ' . $checkout->links->checkoutUrl->href, true, 303); ``` ```json [Response] { "id": "checkout_Bm7xNvPwKr3YjTgHcZaE", "resource": "checkout", "customerId": null, "orderId": null, "testmode": false, "redirectUrlSuccess": "https://example.com/return?checkout_id=checkout_Bm7xNvPwKr3YjTgHcZaE", "redirectUrlCanceled": "https://example.com/canceled", "metadata": {}, "locale": "de", "status": "created", "expiresAt": "2024-01-16T10:30:00Z", "createdAt": "2024-01-15T10:30:00Z", "links": { "checkoutUrl": { "href": "https://checkout.vatly.com/checkout_Bm7xNvPwKr3YjTgHcZaE", "type": "text/html" }, "self": { "href": "https://api.vatly.com/v1/checkouts/checkout_Bm7xNvPwKr3YjTgHcZaE", "type": "application/json" }, "order": null } } ``` :: ### Custom pricing Charge an amount that differs from the product's dashboard price by setting `price` on the item, a `Money` object whose `value` is a decimal string with exactly two decimals. **Currently only `EUR` is accepted**; any other currency returns a `422`. When the customer pays in another currency, the amount is converted from this EUR price at checkout, and for a subscription the converted amount and currency are then fixed, so renewals charge the same. The `id` still references a product you created in the dashboard; products cannot be created on the fly via the API. Omit `price` to use the product's configured price. For a **subscription plan**, a custom `price` is not a first-cycle discount; it becomes the subscription's recurring price and carries over to every renewal. This is how you give a cohort a permanent price (for example, a lower price for an early group of customers). If you'd prefer to track that cohort separately, create a dedicated subscription plan at the target price and check out against that instead; the recurring price is the same, but reporting stays cleaner. ::code-group{sync="api"} ```bash [cURL] curl https://api.vatly.com/v1/checkouts \ -H "Authorization: Bearer live_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "products": [ { "id": "one_off_product_Vr8kQdFhSrG4Y3DnfsdqH", "quantity": 2, "price": {"value": "49.99", "currency": "EUR"} } ], "redirectUrlSuccess": "https://example.com/success", "redirectUrlCanceled": "https://example.com/canceled" }' ``` ```php [PHP] $checkout = $vatly->checkouts->create([ 'products' => [ [ 'id' => 'one_off_product_Vr8kQdFhSrG4Y3DnfsdqH', 'quantity' => 2, 'price' => ['value' => '49.99', 'currency' => 'EUR'], ], ], 'redirectUrlSuccess' => 'https://example.com/success', 'redirectUrlCanceled' => 'https://example.com/canceled', ]); ``` :: ### VAT and reverse charge As Merchant of Record, Vatly determines the applicable tax when the checkout is paid, based on the buyer's country and tax status. You don't calculate or configure rates yourself. For EU B2B, the buyer's VAT ID is validated against the EU's VIES registry as part of that determination: when a valid VAT ID is supplied and the buyer is in a different country from the supplier, the **reverse charge** applies (0% VAT) and the resulting order reflects it. Otherwise the buyer's country standard rate applies. ::note This describes **live mode** . In test mode VIES is not called and validity is simulated; see [Tax IDs and reverse charge in test mode](https://docs.vatly.com/guides/testing#tax-ids-and-reverse-charge-in-test-mode) . :: ::tip The full request and response schema (every accepted field and its validation rules) is published in the [OpenAPI spec](https://docs.vatly.com/openapi.yaml){rel=""nofollow""} . Point your code generator or AI assistant at it when an example leaves a field ambiguous. :: ### Payment methods in test mode A few payment methods work in live mode but cannot be completed in test mode, because the payment provider cannot settle them there. A test-mode checkout still lists them, greyed out and labelled as unavailable, so you can see they exist without being able to select one: | Method | Test mode | Reason | | -------------- | -------------- | ------------------------------------------------------- | | `banktransfer` | Not selectable | The provider cannot settle bank transfers in test mode. | | `paybybank` | Not selectable | The provider cannot settle Pay by Bank in test mode. | Every other method behaves identically in both modes. Test a checkout with any selectable method (`creditcard` and `ideal` cover the one-off and mandate flows), and the resulting orders, invoices and webhooks are the same ones live mode produces. --- ## Retrieve a checkout `GET /v1/checkouts/:id` This endpoint allows you to retrieve a checkout by providing the checkout id. Refer to [the list](https://docs.vatly.com/#the-checkout-api-resource) at the top of this page to see which properties are included with checkout objects. ::code-group{sync="api"} ```bash [cURL] curl https://api.vatly.com/v1/checkouts/checkout_QdEpFhdSrG4Y3DnfsdqsH \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $checkout = $vatly->checkouts->get('checkout_QdEpFhdSrG4Y3DnfsdqsH'); ``` ```json [Response] { "id": "checkout_QdEpFhdSrG4Y3DnfsdqsH", "resource": "checkout", "customerId": "customer_Hn6pQrSvWm8NjLhYbUcP", "orderId": "order_Jk4pQrSvWm8NjLhYbUcP", "testmode": false, "redirectUrlSuccess": "https://example.com/success", "redirectUrlCanceled": "https://example.com/canceled", "metadata": { "campaign": "summer-sale" }, "locale": null, "status": "paid", "expiresAt": "2024-01-16T10:30:00Z", "createdAt": "2024-01-15T10:30:00Z", "links": { "checkoutUrl": { "href": "https://checkout.vatly.com/checkout_QdEpFhdSrG4Y3DnfsdqsH", "type": "text/html" }, "self": { "href": "https://api.vatly.com/v1/checkouts/checkout_QdEpFhdSrG4Y3DnfsdqsH", "type": "application/json" }, "order": { "href": "https://api.vatly.com/v1/orders/order_Jk4pQrSvWm8NjLhYbUcP", "type": "application/json" } } } ``` :: # One-off Products A one-off product is a digital product that can be bought once. Products can be created via the API or in the Vatly dashboard, and added to checkouts. Looking for subscription plans? See the [Subscription Plans API](https://docs.vatly.com/api-reference/subscription-plans) instead. ## The one-off product model Below you'll find all properties for the Vatly One-off Product API resource. ### Properties | Name | Type | Description | | ---------------- | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier for the product (starts with `one_off_product_`). | | `resource` | `string` | The resource type. Always `one_off_product`. | | `testmode` | `boolean` | Whether this product is in test mode. | | `name` | `string` | Display name of the product. | | `description` | `string` | Detailed description of the product. | | `basePrice` | `Money` | Default price of the product (can be overridden in checkout). A Money object with `value` (decimal string) and `currency` (ISO 4217 code). Interpretation depends on `taxBehavior`: when `exclusive`, `basePrice` is the net amount and tax is added at checkout; when `inclusive`, `basePrice` already includes tax. | | `taxBehavior` | `string` | Whether `basePrice` is tax-exclusive (`exclusive`, B2B convention; tax added on top at checkout) or tax-inclusive (`inclusive`, B2C convention; price already includes tax). Immutable after product creation. A checkout may not mix products with different `taxBehavior` values. | | `productType` | `string` | Tax product classification. One of `saas` (software supplied as a service) or `ebook` (an electronic publication supplied as a download or stream). | | `status` | `string` | Current status of the product. Can be `active` (product is active and can be purchased), `pending` (awaiting approval), or `rejected` (has been rejected). | | `archivedAt` | `string | null` | When this product was archived (ISO 8601), or `null` while it is on sale. Always present. An archived product is hidden from `GET /v1/one-off-products` and refused by `POST /v1/checkouts`. | | `pendingUpdates` | `object | null` | The changes that will take effect once a submitted update is approved, or `null` when there is no pending update. Only the fields that differ from the live product are present. | | `updateStatus` | `string | null` | Lifecycle of a pending update, or `null` when there is none. Can be `pending` (an update was submitted and is awaiting review) or `reviewing` (the update is being reviewed). | | `createdAt` | `string` | When this product was created (ISO 8601 format). | | `links` | `object` | HATEOAS links to related resources. Contains `self` link. | --- ## List all one-off products `GET /v1/one-off-products` This endpoint retrieves a paginated list of all one-off products. Only products with `active` status can be used in checkouts. Archived products are excluded unless `includeArchived=true` is passed. ### Optional parameters | Name | Type | Description | | ----------------- | --------- | ---------------------------------------------------------------------------------------------------------- | | `limit` | `integer` | The number of products to return (default: 10, max: 100). | | `startingAfter` | `string` | A cursor for use in pagination. Returns results after this product ID. | | `endingBefore` | `string` | A cursor for use in pagination. Returns results before this product ID. | | `includeArchived` | `boolean` | Include archived products in the listing (default: `false`). Tell them apart by the non-null `archivedAt`. | ::code-group{sync="api"} ```bash [cURL] curl -G https://api.vatly.com/v1/one-off-products \ -H "Authorization: Bearer live_your_api_key_here" \ -d limit=10 ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $products = $vatly->oneOffProducts->page(); ``` ```json [Response] { "data": [ { "id": "one_off_product_Vr8kQdFhSrG4Y3DnfsdqH", "resource": "one_off_product", "testmode": false, "name": "Premium License", "description": "Lifetime access to all premium features", "basePrice": { "value": "299.00", "currency": "EUR" }, "taxBehavior": "exclusive", "productType": "saas", "status": "active", "archivedAt": null, "createdAt": "2024-01-15T10:30:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/one-off-products/one_off_product_Vr8kQdFhSrG4Y3DnfsdqH", "type": "application/json" } } } ], "count": 1, "links": { "self": { "href": "https://api.vatly.com/v1/one-off-products", "type": "application/json" }, "next": null, "prev": null } } ``` :: --- ## Create a one-off product `POST /v1/one-off-products` Creates a new one-off product for the authenticated merchant, in the testmode determined from the API token. A product created with a `live_` token starts in `pending` status and must be approved by Vatly before it can be used in checkouts, the same review that applies to products created in the dashboard. A product created with a `test_` token is auto-approved (`active`) so you can trial checkout immediately. ### Required attributes | Name | Type | Description | | ------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string` | Display name of the product (3 to 255 characters). | | `description` | `string` | Detailed description of the product. | | `basePrice` | `Money` | Price of the product. A Money object whose `value` is a decimal string with exactly two decimals. Currently only `EUR` is accepted; any other currency returns a `422`. | | `productType` | `string` | Tax product classification. One of `saas` (Software as a Service) or `ebook` (electronic book). | ### Optional attributes | Name | Type | Description | | ------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `taxBehavior` | `string` | Whether `basePrice` is tax-exclusive (`exclusive`, B2B convention) or tax-inclusive (`inclusive`, B2C convention). Defaults to `exclusive`. Immutable after product creation. | ::code-group{sync="api"} ```bash [cURL] curl https://api.vatly.com/v1/one-off-products \ -H "Authorization: Bearer live_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "name": "Premium License", "description": "Lifetime access to all premium features", "basePrice": { "value": "299.00", "currency": "EUR" }, "productType": "saas" }' ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $product = $vatly->oneOffProducts->create([ 'name' => 'Premium License', 'description' => 'Lifetime access to all premium features', 'basePrice' => ['value' => '299.00', 'currency' => 'EUR'], 'productType' => 'saas', ]); ``` ```json [Response] { "id": "one_off_product_Vr8kQdFhSrG4Y3DnfsdqH", "resource": "one_off_product", "testmode": false, "name": "Premium License", "description": "Lifetime access to all premium features", "basePrice": { "value": "299.00", "currency": "EUR" }, "taxBehavior": "exclusive", "productType": "saas", "status": "pending", "archivedAt": null, "createdAt": "2024-01-15T10:30:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/one-off-products/one_off_product_Vr8kQdFhSrG4Y3DnfsdqH", "type": "application/json" } } } ``` :: --- ## Get a specific one-off product `GET /v1/one-off-products/:oneOffProductId` This endpoint retrieves a specific one-off product by its ID. ### Parameters | Name | Type | Description | | ----------------- | -------- | ------------------------------------------ | | `oneOffProductId` | `string` | The ID of the one-off product to retrieve. | ::code-group{sync="api"} ```bash [cURL] curl https://api.vatly.com/v1/one-off-products/one_off_product_Vr8kQdFhSrG4Y3DnfsdqH \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $product = $vatly->oneOffProducts->get('one_off_product_Vr8kQdFhSrG4Y3DnfsdqH'); ``` ```json [Response] { "id": "one_off_product_Vr8kQdFhSrG4Y3DnfsdqH", "resource": "one_off_product", "testmode": false, "name": "Premium License", "description": "Lifetime access to all premium features", "basePrice": { "value": "299.00", "currency": "EUR" }, "taxBehavior": "exclusive", "productType": "saas", "status": "active", "archivedAt": null, "createdAt": "2024-01-15T10:30:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/one-off-products/one_off_product_Vr8kQdFhSrG4Y3DnfsdqH", "type": "application/json" } } } ``` :: --- ## Request an update to a one-off product `PATCH /v1/one-off-products/:oneOffProductId` Submits an update to a live one-off product. Because products drive VAT-bearing sales, the change is held as a pending update and reviewed by Vatly before it takes effect (`updateStatus` moves `pending` → `reviewing` → applied). In test mode the update is approved automatically. Each request is the **complete set of changes** relative to the current live product. Fields equal to the live value are ignored, and a request that nets to no change clears any pending update. A new request replaces the not-yet-reviewed one; while an update is being reviewed, further requests return `409`. ### Parameters | Name | Type | Description | | ----------------- | -------- | ---------------------------------------- | | `oneOffProductId` | `string` | The ID of the one-off product to update. | ### Optional attributes At least one attribute must be provided. `taxBehavior` is immutable and cannot be changed here. | Name | Type | Description | | ------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string` | New display name of the product (3 to 255 characters). | | `description` | `string` | New description of the product. | | `basePrice` | `Money` | New price of the product. A Money object whose `value` is a decimal string with exactly two decimals. Currently only `EUR` is accepted; any other currency returns a `422`. | | `productType` | `string` | New tax product classification. One of `saas` or `ebook`. | ::code-group{sync="api"} ```bash [cURL] curl -X PATCH https://api.vatly.com/v1/one-off-products/one_off_product_Vr8kQdFhSrG4Y3DnfsdqH \ -H "Authorization: Bearer live_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "name": "Premium License v2", "basePrice": { "value": "349.00", "currency": "EUR" } }' ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $product = $vatly->oneOffProducts->update('one_off_product_Vr8kQdFhSrG4Y3DnfsdqH', [ 'name' => 'Premium License v2', 'basePrice' => ['value' => '349.00', 'currency' => 'EUR'], ]); ``` ```json [Response] { "id": "one_off_product_Vr8kQdFhSrG4Y3DnfsdqH", "resource": "one_off_product", "testmode": false, "name": "Premium License", "description": "Lifetime access to all premium features", "basePrice": { "value": "299.00", "currency": "EUR" }, "taxBehavior": "exclusive", "productType": "saas", "status": "active", "archivedAt": null, "pendingUpdates": { "name": "Premium License v2", "basePrice": { "value": "349.00", "currency": "EUR" } }, "updateStatus": "pending", "createdAt": "2024-01-15T10:30:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/one-off-products/one_off_product_Vr8kQdFhSrG4Y3DnfsdqH", "type": "application/json" } } } ``` :: --- ## Archive a one-off product `POST /v1/one-off-products/:oneOffProductId/archive` Archives the product so it can no longer be sold. It is hidden from `GET /v1/one-off-products` (unless `includeArchived=true`) and refused by `POST /v1/checkouts`; existing orders and refunds are untouched. Archiving applies to *new* checkouts only. A checkout created before the product was archived snapshots its product data at creation time and can still be completed, the same window that applies when a product is rejected after a checkout was opened. Nothing is deleted: the product remains readable by ID, now carrying a non-null `archivedAt`. Archiving is not queued behind Vatly's product review, and leaves any pending update in place. Repeating the request is a no-op that returns `204` and does not move `archivedAt`. Reverse it with `DELETE /v1/one-off-products/:oneOffProductId/archive`. ### Parameters | Name | Type | Description | | ----------------- | -------- | ----------------------------------------- | | `oneOffProductId` | `string` | The ID of the one-off product to archive. | ::code-group{sync="api"} ```bash [cURL] curl -X POST https://api.vatly.com/v1/one-off-products/one_off_product_Vr8kQdFhSrG4Y3DnfsdqH/archive \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $vatly->oneOffProducts->archive('one_off_product_Vr8kQdFhSrG4Y3DnfsdqH'); ``` :: Returns `204 No Content` on success (or when the product is already archived). --- ## Unarchive a one-off product `DELETE /v1/one-off-products/:oneOffProductId/archive` Puts an archived product back on sale: it reappears in `GET /v1/one-off-products` and can be added to checkouts again. Calling it on a product that is not archived is a no-op. ### Parameters | Name | Type | Description | | ----------------- | -------- | ------------------------------------------- | | `oneOffProductId` | `string` | The ID of the one-off product to unarchive. | ::code-group{sync="api"} ```bash [cURL] curl -X DELETE https://api.vatly.com/v1/one-off-products/one_off_product_Vr8kQdFhSrG4Y3DnfsdqH/archive \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $product = $vatly->oneOffProducts->unarchive('one_off_product_Vr8kQdFhSrG4Y3DnfsdqH'); ``` ```json [Response] { "id": "one_off_product_Vr8kQdFhSrG4Y3DnfsdqH", "resource": "one_off_product", "testmode": false, "name": "Premium License", "description": "Lifetime access to all premium features", "basePrice": { "value": "299.00", "currency": "EUR" }, "taxBehavior": "exclusive", "productType": "saas", "status": "active", "archivedAt": null, "createdAt": "2024-01-15T10:30:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/one-off-products/one_off_product_Vr8kQdFhSrG4Y3DnfsdqH", "type": "application/json" } } } ``` :: # Subscriptions ## The Subscription API Resource The subscription model contains all the information about recurring billing relationships with customers. ### Properties | Name | Type | Description | | -------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier for the subscription (starts with `subscription_`). | | `resource` | `string` | The resource type. Always `subscription`. | | `customerId` | `string` | ID of the customer who owns this subscription. | | `subscriptionPlanId` | `string` | ID of the subscription plan this subscription is based on (starts with `subscription_plan_`). | | `testmode` | `boolean` | Whether this resource is in test mode. | | `name` | `string` | The name for the subscription (from the plan). | | `description` | `string` | The description for the subscription. | | `billingAddress` | `object` | The customer billing address for the subscription. Includes `fullName`, `companyName`, `taxId`, `streetAndNumber`, `streetAdditional`, `city`, `region`, `postalCode`, and `country`. | | `basePrice` | `Money` | The base price per billing cycle before taxes. A Money object with `value` (decimal string) and `currency` (ISO 4217 code). | | `quantity` | `integer` | The quantity for the subscription (e.g., number of seats). | | `interval` | `string` | The billing interval: `month` or `year`. A subscription on a plan created earlier on another interval may still return `day` or `week`. | | `intervalCount` | `integer` | The interval count. Always `1` for new plans; a subscription on an older plan may return a higher value, such as `3` for charging every 3 months. | | `status` | `string` | The status for the subscription. Can be `created`, `trial`, `active`, `canceled`, `on_grace_period`, or `paused`. | | `cancellationReason` | `string | null` | Why the subscription was canceled. Can be `payment_failure` (payment recovery was exhausted after failed renewals), `merchant_request` (the merchant canceled the subscription), or `customer_request` (the customer canceled from the self-service portal). Null unless a cancellation has been requested. | | `mandate` | `object | null` | The payment method (mandate) on file. Contains `method` (e.g. `card`, `sepa_debit`, `paypal`, `bacs_debit`) and `maskedIdentifier` (e.g. the last 4 digits). Null if no mandate is set. | | `startedAt` | `string | null` | When the subscription started (ISO 8601 format). | | `endedAt` | `string | null` | When the subscription actually ended (ISO 8601 format). Stays `null` during a cancellation grace period; it is only set once the subscription has fully ended. | | `canceledAt` | `string | null` | When the subscription was canceled (ISO 8601 format). Set while in `on_grace_period`, and cleared again if the subscription is resumed. Null if not canceled. | | `renewedAt` | `string | null` | When the subscription was last renewed (ISO 8601 format). | | `renewedUntil` | `string | null` | Current billing period end date (ISO 8601 format). | | `nextRenewalAt` | `string | null` | When the next renewal will be attempted (ISO 8601 format). Null if subscription is canceled or ended. | | `trialUntil` | `string | null` | When the trial period ends (ISO 8601 format). Null if not in trial or trial has ended. | | `scheduledUpdate` | `object | null` | The target values for a plan/price/quantity change scheduled to take effect at the subscription's next billing cycle, set by an [update](https://docs.vatly.com/#update-a-subscription) with `applyImmediately: false`. The rest of the resource reflects the subscription's *current* state; `scheduledUpdate` is what it will become. Contains `subscriptionPlanId`, `name`, `description`, `basePrice`, `quantity`, `interval`, `intervalCount`, and `effectiveAt` (the next renewal date when the change applies, or `null` if there is no scheduled renewal). Null when nothing is pending. This is the authoritative way to reconcile a pending change: always present on the resource, so you don't need to rely on the `subscription.update_scheduled` webhook. Cleared when the change is applied at renewal, and when it is discarded because the subscription was canceled before that renewal. | | `links` | `object` | HATEOAS links to related resources. Contains `self` and `customer` links. | --- ## List all subscriptions `GET /v1/subscriptions` This endpoint allows you to retrieve a paginated list of all subscriptions across your account. ### Optional attributes | Name | Type | Description | | --------------- | --------- | ---------------------------------------------------------------------------- | | `limit` | `integer` | The number of subscriptions to return (default: 10, max: 100). | | `startingAfter` | `string` | A cursor for use in pagination. Returns results after this subscription ID. | | `endingBefore` | `string` | A cursor for use in pagination. Returns results before this subscription ID. | ::code-group{sync="api"} ```bash [cURL] curl -G https://api.vatly.com/v1/subscriptions \ -H "Authorization: Bearer live_your_api_key_here" \ -d limit=10 ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $subscriptions = $vatly->subscriptions->page(); ``` ```json [Response] { "data": [ { "id": "subscription_Lp3mNvBxKw7RjTgYcZaE", "resource": "subscription", "customerId": "customer_Lp3mNvBxKw7RjTgYcZaE", "subscriptionPlanId": "subscription_plan_Rk5pQrSvWm8NjLhYbUcP", "testmode": false, "name": "Pro Monthly", "description": "Full access to all Pro features", "billingAddress": { "fullName": "John Doe", "companyName": "Acme Corp", "taxId": null, "streetAndNumber": "123 Main Street", "streetAdditional": null, "city": "Berlin", "region": null, "postalCode": "10115", "country": "DE" }, "basePrice": { "value": "29.00", "currency": "EUR" }, "quantity": 1, "interval": "month", "intervalCount": 1, "status": "active", "cancellationReason": null, "mandate": { "method": "card", "maskedIdentifier": "4242" }, "startedAt": "2024-01-15T10:30:00Z", "endedAt": null, "canceledAt": null, "renewedAt": "2024-02-15T10:30:00Z", "renewedUntil": "2024-03-15T10:30:00Z", "nextRenewalAt": "2024-03-15T10:30:00Z", "trialUntil": null, "scheduledUpdate": null, "links": { "self": { "href": "https://api.vatly.com/v1/subscriptions/subscription_Lp3mNvBxKw7RjTgYcZaE", "type": "application/json" }, "customer": { "href": "https://api.vatly.com/v1/customers/customer_Lp3mNvBxKw7RjTgYcZaE", "type": "application/json" } } }, { "id": "subscription_Wt5mNvBxKw7YcZaEjLhR", "resource": "subscription", "customerId": "customer_Mn6xBtPvKw2RjTgYcZaE", "subscriptionPlanId": "subscription_plan_Wt5mNvBxKw7YcZaEjLhR", "testmode": false, "name": "Enterprise Yearly", "description": "Enterprise features with priority support", "billingAddress": { "fullName": "Jane Smith", "companyName": "TechCorp Ltd", "taxId": "GB123456789", "streetAndNumber": "456 Tech Lane", "streetAdditional": null, "city": "London", "region": null, "postalCode": "EC1A 1BB", "country": "GB" }, "basePrice": { "value": "990.00", "currency": "EUR" }, "quantity": 5, "interval": "year", "intervalCount": 1, "status": "active", "cancellationReason": null, "mandate": { "method": "sepa_debit", "maskedIdentifier": "3000" }, "startedAt": "2024-01-01T00:00:00Z", "endedAt": null, "canceledAt": null, "renewedAt": "2024-01-01T00:00:00Z", "renewedUntil": "2025-01-01T00:00:00Z", "nextRenewalAt": "2025-01-01T00:00:00Z", "trialUntil": null, "scheduledUpdate": null, "links": { "self": { "href": "https://api.vatly.com/v1/subscriptions/subscription_Wt5mNvBxKw7YcZaEjLhR", "type": "application/json" }, "customer": { "href": "https://api.vatly.com/v1/customers/customer_Mn6xBtPvKw2RjTgYcZaE", "type": "application/json" } } } ], "count": 2, "links": { "self": { "href": "https://api.vatly.com/v1/subscriptions", "type": "application/json" }, "next": null, "prev": null } } ``` :: --- ## Get a subscription `GET /v1/subscriptions/:id` This endpoint allows you to retrieve a specific subscription by its ID. ### Parameters | Name | Type | Description | | ---------------- | -------- | ------------------------------------------ | | `subscriptionId` | `string` | The unique identifier of the subscription. | ::code-group{sync="api"} ```bash [cURL] curl https://api.vatly.com/v1/subscriptions/subscription_Lp3mNvBxKw7RjTgYcZaE \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $subscription = $vatly->subscriptions->get('subscription_Lp3mNvBxKw7RjTgYcZaE'); ``` ```json [Response] { "id": "subscription_Lp3mNvBxKw7RjTgYcZaE", "resource": "subscription", "customerId": "customer_Lp3mNvBxKw7RjTgYcZaE", "subscriptionPlanId": "subscription_plan_Rk5pQrSvWm8NjLhYbUcP", "testmode": false, "name": "Pro Monthly", "description": "Full access to all Pro features", "billingAddress": { "fullName": "John Doe", "companyName": "Acme Corp", "taxId": null, "streetAndNumber": "123 Main Street", "streetAdditional": null, "city": "Berlin", "region": null, "postalCode": "10115", "country": "DE" }, "basePrice": { "value": "29.00", "currency": "EUR" }, "quantity": 1, "interval": "month", "intervalCount": 1, "status": "active", "cancellationReason": null, "mandate": { "method": "card", "maskedIdentifier": "4242" }, "startedAt": "2024-01-15T10:30:00Z", "endedAt": null, "canceledAt": null, "renewedAt": "2024-02-15T10:30:00Z", "renewedUntil": "2024-03-15T10:30:00Z", "nextRenewalAt": "2024-03-15T10:30:00Z", "trialUntil": null, "scheduledUpdate": null, "links": { "self": { "href": "https://api.vatly.com/v1/subscriptions/subscription_Lp3mNvBxKw7RjTgYcZaE", "type": "application/json" }, "customer": { "href": "https://api.vatly.com/v1/customers/customer_Lp3mNvBxKw7RjTgYcZaE", "type": "application/json" } } } ``` :: --- ## List customer subscriptions `GET /v1/customers/:customerId/subscriptions` This endpoint allows you to retrieve a paginated list of all subscriptions for a specific customer. ### Parameters | Name | Type | Description | | --------------- | --------- | ---------------------------------------------------------------------------- | | `customerId` | `string` | The unique identifier of the customer. | | `limit` | `integer` | The number of subscriptions to return (default: 10, max: 100). | | `startingAfter` | `string` | A cursor for use in pagination. Returns results after this subscription ID. | | `endingBefore` | `string` | A cursor for use in pagination. Returns results before this subscription ID. | ::code-group{sync="api"} ```bash [cURL] curl -G https://api.vatly.com/v1/customers/customer_Lp3mNvBxKw7RjTgYcZaE/subscriptions \ -H "Authorization: Bearer live_your_api_key_here" \ -d limit=10 ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $subscriptions = $vatly->customers->subscriptions('customer_Lp3mNvBxKw7RjTgYcZaE')->page(); ``` ```json [Response] { "data": [ { "id": "subscription_Lp3mNvBxKw7RjTgYcZaE", "resource": "subscription", "customerId": "customer_Lp3mNvBxKw7RjTgYcZaE", "subscriptionPlanId": "subscription_plan_Rk5pQrSvWm8NjLhYbUcP", "testmode": false, "name": "Pro Monthly", "description": "Full access to all Pro features", "billingAddress": { "fullName": "John Doe", "companyName": "Acme Corp", "taxId": null, "streetAndNumber": "123 Main Street", "streetAdditional": null, "city": "Berlin", "region": null, "postalCode": "10115", "country": "DE" }, "basePrice": { "value": "29.00", "currency": "EUR" }, "quantity": 1, "interval": "month", "intervalCount": 1, "status": "active", "cancellationReason": null, "mandate": { "method": "card", "maskedIdentifier": "4242" }, "startedAt": "2024-01-15T10:30:00Z", "endedAt": null, "canceledAt": null, "renewedAt": "2024-02-15T10:30:00Z", "renewedUntil": "2024-03-15T10:30:00Z", "nextRenewalAt": "2024-03-15T10:30:00Z", "trialUntil": null, "scheduledUpdate": null, "links": { "self": { "href": "https://api.vatly.com/v1/subscriptions/subscription_Lp3mNvBxKw7RjTgYcZaE", "type": "application/json" }, "customer": { "href": "https://api.vatly.com/v1/customers/customer_Lp3mNvBxKw7RjTgYcZaE", "type": "application/json" } } } ], "count": 1, "links": { "self": { "href": "https://api.vatly.com/v1/customers/customer_Lp3mNvBxKw7RjTgYcZaE/subscriptions", "type": "application/json" }, "next": null, "prev": null } } ``` :: --- ## Get a customer subscription `GET /v1/customers/:customerId/subscriptions/:subscriptionId` This endpoint allows you to retrieve a specific subscription for a specific customer. ### Parameters | Name | Type | Description | | ---------------- | -------- | ------------------------------------------ | | `customerId` | `string` | The unique identifier of the customer. | | `subscriptionId` | `string` | The unique identifier of the subscription. | ::code-group{sync="api"} ```bash [cURL] curl https://api.vatly.com/v1/customers/customer_Lp3mNvBxKw7RjTgYcZaE/subscriptions/subscription_Lp3mNvBxKw7RjTgYcZaE \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $subscription = $vatly->customers->subscriptions('customer_Lp3mNvBxKw7RjTgYcZaE')->get('subscription_Lp3mNvBxKw7RjTgYcZaE'); ``` ```json [Response] { "id": "subscription_Lp3mNvBxKw7RjTgYcZaE", "resource": "subscription", "customerId": "customer_Lp3mNvBxKw7RjTgYcZaE", "subscriptionPlanId": "subscription_plan_Rk5pQrSvWm8NjLhYbUcP", "testmode": false, "name": "Pro Monthly", "description": "Full access to all Pro features", "billingAddress": { "fullName": "John Doe", "companyName": "Acme Corp", "taxId": null, "streetAndNumber": "123 Main Street", "streetAdditional": null, "city": "Berlin", "region": null, "postalCode": "10115", "country": "DE" }, "basePrice": { "value": "29.00", "currency": "EUR" }, "quantity": 1, "interval": "month", "intervalCount": 1, "status": "active", "cancellationReason": null, "mandate": { "method": "card", "maskedIdentifier": "4242" }, "startedAt": "2024-01-15T10:30:00Z", "endedAt": null, "canceledAt": null, "renewedAt": "2024-02-15T10:30:00Z", "renewedUntil": "2024-03-15T10:30:00Z", "nextRenewalAt": "2024-03-15T10:30:00Z", "trialUntil": null, "scheduledUpdate": null, "links": { "self": { "href": "https://api.vatly.com/v1/subscriptions/subscription_Lp3mNvBxKw7RjTgYcZaE", "type": "application/json" }, "customer": { "href": "https://api.vatly.com/v1/customers/customer_Lp3mNvBxKw7RjTgYcZaE", "type": "application/json" } } } ``` :: --- ## Update a subscription `PATCH /v1/subscriptions/:id` This endpoint allows you to update a subscription. You can change the plan, quantity, or recurring price, and control proration and timing. ### Optional attributes At least one of `subscriptionPlanId`, `quantity`, or `price` must be provided. | Name | Type | Description | | -------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `subscriptionPlanId` | `string` | The ID of the subscription plan to update to (starts with `subscription_plan_`). Must match the testmode of the current subscription. | | `quantity` | `integer` | The new total quantity for the subscription (e.g. number of seats). This sets the quantity to the given value; it is not added to the current quantity. Must be at least 1. | | `price` | `object` | Set a new recurring price while keeping the current plan. A Money object with `value` (decimal string) and `currency` (`EUR` or `USD`); the currency must match the subscription's own currency. Sent alongside `subscriptionPlanId`, it overrides the new plan's default price. | | `prorate` | `boolean` | How an immediate change is priced. When `true`, the customer pays the new price for the time left on the cycle, minus a credit for the old price over that same time. A prorated downgrade applied immediately is not accepted while time is left on the cycle (see below). When `false`, the customer pays the full new price for the current cycle on top of what they already paid. **`false` does not skip the charge:** use `prorationCharge: false` for that. Ignored when `prorationCharge` is `false`. Default: `true`. | | `prorationCharge` | `boolean` | Whether an immediate change is charged at all. When `true`, it is charged as set by `prorate` and `invoiceImmediately`. When `false`, the change applies now and nothing is charged for it: an upgrade costs nothing until the next renewal and a downgrade gets no credit. The next renewal bills the new price, unless a change is already scheduled for that renewal: that change still applies. With `false`, sending `invoiceImmediately: true`, `anchor`, `resetAnchor`, `trialUntil` or a plan with a different interval returns `422`, because each would start or bill a new cycle now. Default: `true`. | | `applyImmediately` | `boolean` | Whether to apply changes immediately or at the end of the current billing period. When `true`, changes take effect immediately (with proration if enabled). When `false`, the change is scheduled for the end of the current period and surfaced on the subscription's `scheduledUpdate`. During a trial, `true` ends the trial and starts the first paid cycle, which is charged right away (see below). Default: `false`. | | `invoiceImmediately` | `boolean` | Whether to invoice and charge the proration now instead of on the next renewal. Only applies when `applyImmediately` and `prorate` are both true. The proration order is created and charged asynchronously, typically within 15 to 30 minutes (see below). When `false` (the default), the proration delta is parked on the current cycle and billed as a line on the next renewal invoice: the customer gets one invoice and one payment covering both. If the subscription is canceled before that renewal, the parked amount is waived, so a customer is never charged at the moment they cancel. **Set this to `true` on yearly and other long-interval plans**, where the deferred delta may not be billed for many months and is waived entirely if the customer cancels in between. An immediate update during a trial is always charged right away, whatever this is set to, because it starts the first paid cycle. This does not apply to a subscription that is `on_grace_period`. Default: `false`. | | `anchor` | `date` | Set the billing anchor to a specific calendar date (`YYYY-MM-DD`, interpreted in UTC); the billing cycle is recalculated around it. Cannot be combined with `resetAnchor`. | | `resetAnchor` | `boolean` | Reset the billing anchor to "now": the moment the update is processed becomes the new cycle anchor and future renewals align to it. Cannot be combined with `anchor`. Default: `false`. | | `trialUntil` | `string` | Extend or set a trial period until this date (ISO 8601 format). Cannot be combined with `anchor`. | **Scheduling and proration behavior:** - With `applyImmediately: false` (the default), the change is scheduled for the next billing cycle and returned on the subscription's `scheduledUpdate`. Scheduled updates are applied at renewal (they are no longer silently discarded) and are cleared only if the subscription is canceled before that renewal. - A subscription whose `status` is `on_grace_period` has no next billing period. Scheduling an update for it returns `422`; resume the subscription first, or set `applyImmediately: true` to apply the change to the remaining period. - An immediate update on an `on_grace_period` subscription can change the plan, price, or quantity for the remaining period, but not when that period ends: `anchor`, `resetAnchor`, and switching to a plan with a different interval each return `422`, because each would move the already-communicated end date. - When `invoiceImmediately` is `true`, the proration order is created and charged asynchronously, typically within 15 to 30 minutes of the update, so the update response does not include it. Vatly waits briefly so that other charges for the same customer made around the same time are combined into one order and one payment, instead of several separate orders and charges. Follow the `order.paid` webhook (or `order.payment_failed` if the payment fails): the order's line has `relatedResources.subscriptionId` set to the subscription. In test mode, a card payment settles right away and a SEPA Direct Debit payment after 10 to 15 minutes; use [Simulate an order payment](https://docs.vatly.com/api-reference/test-helpers#simulate-an-order-payment) to settle or decline a pending payment on that order. - When `invoiceImmediately` is `false`, the proration delta is parked on the current cycle and billed on the next renewal invoice. If the subscription is canceled before that renewal, the parked charge is waived. - On an immediate prorated update (`applyImmediately: true`, `prorate: true`) that keeps the billing anchor, the customer pays the new price for the time left on the cycle, minus a credit for the old price over that same time. - A prorated downgrade, price decrease or seat reduction applied immediately is not accepted while time is left on the cycle. It would give a negative charge, and the difference is not refunded mid-cycle, so the request returns `422`. - **Recommended:** schedule the change for the next renewal (`applyImmediately: false`). The customer keeps their current plan until the cycle ends, and the lower price takes effect at renewal with no extra charge. - To switch now with no credit and no charge, set `prorationCharge: false`. This also works for a downgrade while time is left on the cycle. The next renewal bills the new price, unless a change is already scheduled for that renewal: that change still applies. - `prorationCharge: false` changes what the customer has, never when they are billed. Sending `invoiceImmediately: true`, `anchor`, `resetAnchor`, `trialUntil` or a plan with a different interval with it returns `422`. To move to a plan with a different interval, schedule the change instead (`applyImmediately: false`). - Only switch immediately without proration (`prorate: false`) if the customer must lose access to the higher plan right away. This charges the full price of the new plan for the current cycle, without crediting what was already paid. It is billed right away with `invoiceImmediately: true`, otherwise on the next renewal invoice. `prorate: false` does not skip the charge: to apply a change without charging for it, use `prorationCharge: false`. **Updating during a trial:** - An immediate update (`applyImmediately: true`) during a trial ends the trial. The first paid cycle starts that day and is charged right away at the full new price, whatever `prorate` and `invoiceImmediately` are set to. The next renewal is one billing interval later, not at the original end of the trial. For example, a €30 monthly plan with a trial from 1 to 15 October that is changed on 5 October is charged €30 on 5 October and renews on 5 November. - With `anchor`, the first paid cycle runs to that date instead. It is charged right away, priced per `prorate`, and renews on the anchor. Changed on 5 October with `anchor` set to 20 October, the same plan is charged €15 for 5 to 20 October with `prorate: true`, or the full €30 with `prorate: false`, and renews on 20 October. - A scheduled update (`applyImmediately: false`) keeps the trial. The change applies from the first paid cycle, when the trial ends. - An immediate update with `prorationCharge: false` also keeps the trial. The change applies now, the trial end date stays, and the trial end bills the new plan. - A subscription whose `status` is `on_grace_period` still ends on the date it was given. An immediate update ends its trial without starting a paid cycle, and is not charged right away unless `invoiceImmediately` is `true`. ::code-group{sync="api"} ```bash [cURL] curl -X PATCH https://api.vatly.com/v1/subscriptions/subscription_Lp3mNvBxKw7RjTgYcZaE \ -H "Authorization: Bearer live_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "subscriptionPlanId": "subscription_plan_Wt5mNvBxKw7YcZaEjLhR", "prorate": true, "applyImmediately": true }' ``` ```bash [cURL (switch without a charge)] curl -X PATCH https://api.vatly.com/v1/subscriptions/subscription_Lp3mNvBxKw7RjTgYcZaE \ -H "Authorization: Bearer live_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "subscriptionPlanId": "subscription_plan_Wt5mNvBxKw7YcZaEjLhR", "applyImmediately": true, "prorationCharge": false }' ``` ```bash [cURL (change price)] curl -X PATCH https://api.vatly.com/v1/subscriptions/subscription_Lp3mNvBxKw7RjTgYcZaE \ -H "Authorization: Bearer live_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "price": { "value": "29.00", "currency": "EUR" }, "applyImmediately": true }' ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $subscription = $vatly->subscriptions->update('subscription_Lp3mNvBxKw7RjTgYcZaE', [ 'subscriptionPlanId' => 'subscription_plan_Wt5mNvBxKw7YcZaEjLhR', 'prorate' => true, 'applyImmediately' => true, ]); ``` ```json [Response] { "id": "subscription_Lp3mNvBxKw7RjTgYcZaE", "resource": "subscription", "customerId": "customer_Lp3mNvBxKw7RjTgYcZaE", "subscriptionPlanId": "subscription_plan_Rk5pQrSvWm8NjLhYbUcP", "testmode": false, "name": "Pro Yearly", "description": "Full access to all Pro features, billed yearly", "billingAddress": { "fullName": "John Doe", "companyName": "Acme Corp", "taxId": null, "streetAndNumber": "123 Main Street", "streetAdditional": null, "city": "Berlin", "region": null, "postalCode": "10115", "country": "DE" }, "basePrice": { "value": "290.00", "currency": "EUR" }, "quantity": 1, "interval": "year", "intervalCount": 1, "status": "active", "cancellationReason": null, "mandate": { "method": "card", "maskedIdentifier": "4242" }, "startedAt": "2024-01-15T10:30:00Z", "endedAt": null, "canceledAt": null, "renewedAt": "2024-02-15T10:30:00Z", "renewedUntil": "2025-02-15T10:30:00Z", "nextRenewalAt": "2025-02-15T10:30:00Z", "trialUntil": null, "scheduledUpdate": null, "links": { "self": { "href": "https://api.vatly.com/v1/subscriptions/subscription_Lp3mNvBxKw7RjTgYcZaE", "type": "application/json" }, "customer": { "href": "https://api.vatly.com/v1/customers/customer_Lp3mNvBxKw7RjTgYcZaE", "type": "application/json" } } } ``` :: --- ## Create billing update link `POST /v1/subscriptions/:id/billing-update-link` Creates a signed link that the customer can use to update the billing details for this subscription (billing address, VAT number, and company name) via a hosted flow. ### Required attributes | Name | Type | Description | | --------------------- | -------- | ------------------------------------------------ | | `redirectUrlSuccess` | `string` | URL to redirect after successful billing update. | | `redirectUrlCanceled` | `string` | URL to redirect if customer cancels the update. | ### Optional attributes | Name | Type | Description | | ---------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `billingAddress` | `object` | Optional editable prefill for the hosted billing update form. When supplied, it **replaces** the subscription's stored billing details as the prefill, so send every field you want shown; empty strings give a blank form. Omit it, or send `null` or `{}`, to prefill the stored details. `country` must be an ISO 3166-1 alpha-2 code. A supplied `taxId` is only a prefill; it is not registered until the customer submits the form. | ::code-group{sync="api"} ```bash [cURL] curl -X POST https://api.vatly.com/v1/subscriptions/subscription_Lp3mNvBxKw7RjTgYcZaE/billing-update-link \ -H "Authorization: Bearer live_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "redirectUrlSuccess": "https://example.com/billing-updated", "redirectUrlCanceled": "https://example.com/account/billing", "billingAddress": { "companyName": "Acme Corp", "taxId": "DE123456789" } }' ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $response = $vatly->subscriptions->createBillingUpdateLink('subscription_Lp3mNvBxKw7RjTgYcZaE', [ 'redirectUrlSuccess' => 'https://example.com/billing-updated', 'redirectUrlCanceled' => 'https://example.com/account/billing', 'billingAddress' => [ 'companyName' => 'Acme Corp', 'taxId' => 'DE123456789', ], ]); // Redirect the customer to the hosted billing update page header('Location: ' . $response->href, true, 303); ``` ```json [Response] { "href": "https://vatly.com/subscriptions/subscription_Lp3mNvBxKw7RjTgYcZaE/billing?token=xyz...", "type": "text/html" } ``` :: --- ## Cancel a subscription `DELETE /v1/subscriptions/:id` This endpoint allows you to cancel a subscription. By default, the subscription will remain active until the end of the current billing period (grace period), after which it will be fully canceled. Set `immediately=true` to cancel immediately. During the grace period the subscription's `status` is `on_grace_period` and `canceledAt` is set, while `endedAt` stays `null`. A grace-period cancellation can still be reversed with [Resume a subscription](https://docs.vatly.com/#resume-a-subscription) until the period lapses. A subscription canceled with `immediately=true` (status `canceled`) cannot be reactivated; create a new subscription instead. ### Optional query parameters | Name | Type | Description | | ------------- | --------- | -------------------------------------------------------------- | | `immediately` | `boolean` | Cancel immediately instead of at period end. Default: `false`. | ::code-group ```bash [cURL] curl -X DELETE https://api.vatly.com/v1/subscriptions/subscription_Lp3mNvBxKw7RjTgYcZaE \ -H "Authorization: Bearer live_your_api_key_here" ``` ```bash [cURL (immediate)] curl -X DELETE "https://api.vatly.com/v1/subscriptions/subscription_Lp3mNvBxKw7RjTgYcZaE?immediately=true" \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $vatly->subscriptions->cancel('subscription_Lp3mNvBxKw7RjTgYcZaE'); ``` :: Returns `204 No Content` on success. --- ## Resume a subscription `POST /v1/subscriptions/:id/resume` Resumes a subscription that was canceled **with a grace period**, while it is still within that period. **When this works:** - The subscription's `status` is `on_grace_period`. - `endedAt` stays `null` throughout the grace period; resumability is keyed off `status`, not `endedAt`. **Result:** - Status returns to `active`. - The existing billing cycle and renewal schedule are preserved (no new charge fires immediately) and the original payment mandate remains in effect. - `canceledAt` is cleared and a `subscription.resumed` webhook is delivered. - The refreshed subscription is returned in the response body. **When this does *not* work** (returns `422`): - The subscription was canceled immediately (`status` is `canceled`). - The grace period has already lapsed (`status` is now `canceled` and `endedAt` is set). - The subscription is already active (the no-op is rejected for clarity, not silently ignored). In all of those cases, create a new subscription instead. ### Parameters | Name | Type | Description | | ---- | -------- | ------------------------------------------ | | `id` | `string` | The unique identifier of the subscription. | ::code-group{sync="api"} ```bash [cURL] curl -X POST https://api.vatly.com/v1/subscriptions/subscription_Lp3mNvBxKw7RjTgYcZaE/resume \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $subscription = $vatly->subscriptions->resume('subscription_Lp3mNvBxKw7RjTgYcZaE'); ``` ```json [Response] { "id": "subscription_Lp3mNvBxKw7RjTgYcZaE", "resource": "subscription", "customerId": "customer_Lp3mNvBxKw7RjTgYcZaE", "subscriptionPlanId": "subscription_plan_Rk5pQrSvWm8NjLhYbUcP", "testmode": false, "name": "Pro Monthly", "description": "Full access to all Pro features", "billingAddress": { "fullName": "John Doe", "companyName": "Acme Corp", "taxId": null, "streetAndNumber": "123 Main Street", "streetAdditional": null, "city": "Berlin", "region": null, "postalCode": "10115", "country": "DE" }, "status": "active", "cancellationReason": null, "mandate": { "method": "card", "maskedIdentifier": "4242" }, "basePrice": { "value": "29.00", "currency": "EUR" }, "quantity": 1, "interval": "month", "intervalCount": 1, "startedAt": "2024-01-15T10:30:00Z", "endedAt": null, "canceledAt": null, "renewedAt": "2024-02-15T10:30:00Z", "renewedUntil": "2024-03-15T10:30:00Z", "nextRenewalAt": "2024-03-15T10:30:00Z", "trialUntil": null, "scheduledUpdate": null, "links": { "self": { "href": "https://api.vatly.com/v1/subscriptions/subscription_Lp3mNvBxKw7RjTgYcZaE", "type": "application/json" }, "customer": { "href": "https://api.vatly.com/v1/customers/customer_Lp3mNvBxKw7RjTgYcZaE", "type": "application/json" } } } ``` :: # Subscription Plans ## The subscription plan model The subscription plan model contains all the information about the subscription plans you create, including the name, description, price, and billing interval. ### Properties | Name | Type | Description | | ---------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier for the subscription plan (always starts with `subscription_plan_`). | | `resource` | `string` | The resource type. Always `subscription_plan`. | | `testmode` | `boolean` | Whether this plan is in test mode. | | `name` | `string` | Display name of the plan. | | `description` | `string` | Detailed description of the plan. | | `basePrice` | `Money` | Price per billing interval. A Money object with `value` (decimal string) and `currency` (ISO 4217 code). Interpretation depends on `taxBehavior`: when `exclusive`, `basePrice` is the net amount and tax is added at checkout; when `inclusive`, `basePrice` already includes tax and the net is back-computed from the buyer's jurisdiction. | | `taxBehavior` | `string` | Whether `basePrice` is tax-exclusive (`exclusive`, the B2B convention) or tax-inclusive (`inclusive`, the B2C convention). Immutable after plan creation: create a new plan for the other mode. A checkout may not mix products with different `taxBehavior` values. | | `interval` | `string` | Billing interval unit. `month` or `year` for new plans. A plan created earlier on another interval may still return `day` or `week`; it keeps working. | | `intervalCount` | `integer` | Number of interval units between billing cycles. Always `1` for new plans. A plan created earlier may still return a higher value, such as `3` for a plan that bills every 3 months. | | `productType` | `string` | What kind of product this plan sells. Always `saas`: an e-book is a one-time purchase, so sell it as a one-off product instead. Set when the plan is created. | | `status` | `string` | Current status of the plan. Can be `active` (plan is active and can be subscribed to), `pending` (plan is awaiting approval), or `rejected` (plan has been rejected). | | `archivedAt` | `string | null` | When this plan was archived (ISO 8601), or `null` while it is open to new business. Always present. An archived plan is hidden from `GET /v1/subscription-plans`, refused by `POST /v1/checkouts`, and cannot be switched to from `PATCH /v1/subscriptions/:id`. | | `pendingUpdates` | `object | null` | The changes that will take effect once a submitted update is approved, or `null` when there is no pending update. Only the fields that actually differ from the live plan are present. | | `updateStatus` | `string | null` | Lifecycle of a pending update, or `null` when there is none. Can be `pending` (an update was submitted and is awaiting review) or `reviewing` (the update is being reviewed). | | `createdAt` | `string` | When this plan was created (ISO 8601 format). | | `links` | `object` | HATEOAS links to related resources. Contains `self` link. | --- ## List all subscription plans `GET /v1/subscription-plans` This endpoint retrieves a paginated list of all subscription plans. Only plans with `active` status can be used in checkouts. Archived plans are excluded unless `includeArchived=true` is passed. ### Optional query parameters | Name | Type | Description | | ----------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `limit` | `integer` | The number of subscription plans to return (default: 10, max: 100). | | `startingAfter` | `string` | A cursor for use in pagination. Returns results after this plan ID. | | `endingBefore` | `string` | A cursor for use in pagination. Returns results before this plan ID. | | `includeArchived` | `boolean` | Include archived plans in the listing. Archived plans are hidden by default because they cannot be sold; set this to `true` to see them alongside the live ones (tell them apart by the non-null `archivedAt`). Default: `false`. | ::code-group{sync="api"} ```bash [cURL] curl -G https://api.vatly.com/v1/subscription-plans \ -H "Authorization: Bearer live_your_api_key_here" \ -d limit=10 ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $plans = $vatly->subscriptionPlans->page(); ``` ```json [Response] { "data": [ { "id": "subscription_plan_Bm7xNvPwKr3YjTgHcZaE", "resource": "subscription_plan", "testmode": false, "name": "Pro Monthly", "description": "Full access to all Pro features, billed monthly", "basePrice": { "value": "29.00", "currency": "EUR" }, "taxBehavior": "exclusive", "interval": "month", "intervalCount": 1, "productType": "saas", "status": "active", "archivedAt": null, "createdAt": "2024-01-15T10:30:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/subscription-plans/subscription_plan_Bm7xNvPwKr3YjTgHcZaE", "type": "application/json" } } }, { "id": "subscription_plan_Wt5mNvBxKw7YcZaEjLhR", "resource": "subscription_plan", "testmode": false, "name": "Pro Yearly", "description": "Full access to all Pro features, billed yearly", "basePrice": { "value": "290.00", "currency": "EUR" }, "taxBehavior": "exclusive", "interval": "year", "intervalCount": 1, "productType": "saas", "status": "active", "archivedAt": null, "createdAt": "2024-01-15T10:30:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/subscription-plans/subscription_plan_Wt5mNvBxKw7YcZaEjLhR", "type": "application/json" } } } ], "count": 2, "links": { "self": { "href": "https://api.vatly.com/v1/subscription-plans", "type": "application/json" }, "next": null, "prev": null } } ``` :: --- ## Create a subscription plan `POST /v1/subscription-plans` Creates a new subscription plan for the authenticated merchant, in the testmode determined from the API token. A plan created with a `live_` token starts in `pending` status and must be approved by Vatly before it can be used in checkouts, the same review that applies to plans created in the dashboard. A plan created with a `test_` token is auto-approved (`active`) so you can trial checkout immediately. **Constraints:** - `productType` must be `saas`: e-books are one-off purchases and cannot be sold on a recurring basis. - The plan must bill monthly (`interval: month`, `intervalCount: 1`) or yearly (`interval: year`, `intervalCount: 1`), in both live and test mode. Any other combination returns a `422`. ### Required attributes | Name | Type | Description | | --------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string` | Display name of the plan (3 to 255 characters). | | `description` | `string` | Detailed description of the plan. | | `basePrice` | `Money` | Price per billing interval. A Money object whose `value` is a decimal string with exactly two decimals. Currently only `EUR` is accepted; any other currency returns a `422`. | | `productType` | `string` | Tax product classification. Must be `saas`. | | `interval` | `string` | Billing interval unit. Either `month` or `year`. | | `intervalCount` | `integer` | Number of interval units between billing cycles. Must be `1`. | ### Optional attributes | Name | Type | Description | | ------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `taxBehavior` | `string` | Whether `basePrice` is tax-exclusive (`exclusive`, the B2B convention) or tax-inclusive (`inclusive`, the B2C convention). Defaults to `exclusive`. Immutable after plan creation: create a new plan for the other mode. | ::code-group{sync="api"} ```bash [cURL] curl https://api.vatly.com/v1/subscription-plans \ -H "Authorization: Bearer live_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "name": "Pro Monthly", "description": "Full access to all Pro features, billed monthly", "basePrice": { "value": "29.00", "currency": "EUR" }, "productType": "saas", "interval": "month", "intervalCount": 1 }' ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $plan = $vatly->subscriptionPlans->create([ 'name' => 'Pro Monthly', 'description' => 'Full access to all Pro features, billed monthly', 'basePrice' => ['value' => '29.00', 'currency' => 'EUR'], 'productType' => 'saas', 'interval' => 'month', 'intervalCount' => 1, ]); ``` ```json [Response] { "id": "subscription_plan_Bm7xNvPwKr3YjTgHcZaE", "resource": "subscription_plan", "testmode": false, "name": "Pro Monthly", "description": "Full access to all Pro features, billed monthly", "basePrice": { "value": "29.00", "currency": "EUR" }, "taxBehavior": "exclusive", "interval": "month", "intervalCount": 1, "productType": "saas", "status": "pending", "archivedAt": null, "createdAt": "2024-01-15T10:30:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/subscription-plans/subscription_plan_Bm7xNvPwKr3YjTgHcZaE", "type": "application/json" } } } ``` :: --- ## Retrieve a subscription plan `GET /v1/subscription-plans/:id` This endpoint retrieves a specific subscription plan by its ID. ### URL parameters | Name | Type | Description | | ---- | -------- | -------------------------------------------- | | `id` | `string` | The ID of the subscription plan to retrieve. | ::code-group{sync="api"} ```bash [cURL] curl https://api.vatly.com/v1/subscription-plans/subscription_plan_Bm7xNvPwKr3YjTgHcZaE \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $plan = $vatly->subscriptionPlans->get('subscription_plan_Bm7xNvPwKr3YjTgHcZaE'); ``` ```json [Response] { "id": "subscription_plan_Bm7xNvPwKr3YjTgHcZaE", "resource": "subscription_plan", "testmode": false, "name": "Pro Monthly", "description": "Full access to all Pro features, billed monthly", "basePrice": { "value": "29.00", "currency": "EUR" }, "taxBehavior": "exclusive", "interval": "month", "intervalCount": 1, "productType": "saas", "status": "active", "archivedAt": null, "createdAt": "2024-01-15T10:30:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/subscription-plans/subscription_plan_Bm7xNvPwKr3YjTgHcZaE", "type": "application/json" } } } ``` :: --- ## Update a subscription plan `PATCH /v1/subscription-plans/:id` Submits an update to a live subscription plan. Because plans drive VAT-bearing recurring sales, the change is held as a pending update and reviewed by Vatly before it takes effect (`updateStatus` moves `pending` → `reviewing` → applied). In test mode the update is approved automatically. Each request is the **complete set of changes** relative to the current live plan, and must contain at least one field. Fields equal to the live value are ignored, and a request that nets to no change clears any pending update. A new request replaces the not-yet-reviewed one; while an update is being reviewed, further requests return `409`. Changing the interval on a plan that has ever been used by a subscription (active or not) also returns `409`. The price stays changeable. To change the billing interval, send `interval` and `intervalCount` together, set to monthly (`month`, `1`) or yearly (`year`, `1`). Anything else returns a `422`, in both live and test mode. A plan that already bills on another interval keeps working, and you can still update its other fields without sending the interval. The submitted change is surfaced on the plan resource as `pendingUpdates` (only the fields that differ), with `updateStatus` tracking the review. Approval is signalled by the `subscription_plan.update_submitted`, `subscription_plan.update_approved`, and `subscription_plan.update_rejected` webhook events. ### URL parameters | Name | Type | Description | | ---- | -------- | ------------------------------------------ | | `id` | `string` | The ID of the subscription plan to update. | ### Optional attributes At least one field must be provided. | Name | Type | Description | | --------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string` | New display name of the plan (3 to 255 characters). | | `description` | `string` | New description of the plan. | | `basePrice` | `Money` | New price per billing interval. A Money object whose `value` is a decimal string with exactly two decimals. Currently only `EUR` is accepted; any other currency returns a `422`. | | `productType` | `string` | Tax product classification. Must be `saas`. | | `interval` | `string` | New billing interval unit. Either `month` or `year`. Must be sent together with `intervalCount`. | | `intervalCount` | `integer` | Number of interval units between billing cycles. Must be `1`. Must be sent together with `interval`. | ::code-group{sync="api"} ```bash [cURL] curl -X PATCH https://api.vatly.com/v1/subscription-plans/subscription_plan_Bm7xNvPwKr3YjTgHcZaE \ -H "Authorization: Bearer live_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "name": "Pro Yearly", "basePrice": { "value": "290.00", "currency": "EUR" }, "interval": "year", "intervalCount": 1 }' ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $plan = $vatly->subscriptionPlans->update('subscription_plan_Bm7xNvPwKr3YjTgHcZaE', [ 'name' => 'Pro Yearly', 'basePrice' => ['value' => '290.00', 'currency' => 'EUR'], 'interval' => 'year', 'intervalCount' => 1, ]); ``` ```json [Response] { "id": "subscription_plan_Bm7xNvPwKr3YjTgHcZaE", "resource": "subscription_plan", "testmode": false, "name": "Pro Monthly", "description": "Full access to all Pro features, billed monthly", "basePrice": { "value": "29.00", "currency": "EUR" }, "taxBehavior": "exclusive", "interval": "month", "intervalCount": 1, "productType": "saas", "status": "active", "archivedAt": null, "pendingUpdates": { "name": "Pro Yearly", "basePrice": { "value": "290.00", "currency": "EUR" }, "interval": "year", "intervalCount": 1 }, "updateStatus": "pending", "createdAt": "2024-01-15T10:30:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/subscription-plans/subscription_plan_Bm7xNvPwKr3YjTgHcZaE", "type": "application/json" } } } ``` :: --- ## Archive a subscription plan `POST /v1/subscription-plans/:id/archive` Closes the plan to new business. It is hidden from `GET /v1/subscription-plans` (unless `includeArchived=true`), refused by `POST /v1/checkouts`, and can no longer be switched to from `PATCH /v1/subscriptions/:id`. Subscribers already on the plan are deliberately untouched: a subscription snapshots its plan at signup and renews off that snapshot, so archiving never cancels anyone or changes what they are billed. To end a subscription, cancel it with `DELETE /v1/subscriptions/:id`. Likewise a checkout created before the plan was archived snapshots its product data at creation time and can still be completed. Archiving applies to *new* checkouts only. Nothing is deleted: the plan remains readable by id, now carrying a non-null `archivedAt`. Repeating the request is a no-op that returns `204` and does not move `archivedAt`. Reverse it by [unarchiving the plan](https://docs.vatly.com/#unarchive-a-subscription-plan). ### URL parameters | Name | Type | Description | | ---- | -------- | ------------------------------------------- | | `id` | `string` | The ID of the subscription plan to archive. | ::code-group{sync="api"} ```bash [cURL] curl -X POST https://api.vatly.com/v1/subscription-plans/subscription_plan_Bm7xNvPwKr3YjTgHcZaE/archive \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $vatly->subscriptionPlans->archive('subscription_plan_Bm7xNvPwKr3YjTgHcZaE'); ``` :: Returns `204 No Content` on success (or if the plan was already archived). --- ## Unarchive a subscription plan `DELETE /v1/subscription-plans/:id/archive` Re-opens an archived plan to new business: it reappears in `GET /v1/subscription-plans` and can be added to checkouts and switched to again. Calling it on a plan that is not archived is a no-op. The refreshed plan is returned in the response body. ### URL parameters | Name | Type | Description | | ---- | -------- | --------------------------------------------- | | `id` | `string` | The ID of the subscription plan to unarchive. | ::code-group{sync="api"} ```bash [cURL] curl -X DELETE https://api.vatly.com/v1/subscription-plans/subscription_plan_Wt5mNvBxKw7YcZaEjLhR/archive \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $plan = $vatly->subscriptionPlans->unarchive('subscription_plan_Wt5mNvBxKw7YcZaEjLhR'); ``` ```json [Response] { "id": "subscription_plan_Wt5mNvBxKw7YcZaEjLhR", "resource": "subscription_plan", "testmode": false, "name": "Pro Monthly", "description": "Full access to all Pro features, billed monthly", "basePrice": { "value": "29.00", "currency": "EUR" }, "taxBehavior": "exclusive", "interval": "month", "intervalCount": 1, "productType": "saas", "status": "active", "archivedAt": null, "createdAt": "2024-01-15T10:30:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/subscription-plans/subscription_plan_Wt5mNvBxKw7YcZaEjLhR", "type": "application/json" } } } ``` :: # Orders ## The order model The order model contains all the information about your orders, including the order details, customer information, line items, and tax information. ### Properties | Name | Type | Description | | -------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier for the order (starts with `order_`). | | `resource` | `string` | The resource type. Always `order`. | | `customerId` | `string | null` | ID of the customer who made this purchase. Always present, but `null` for orders with no associated customer. | | `testmode` | `boolean` | Whether this order is in test mode. | | `metadata` | `object | null` | Arbitrary key-value metadata for your application. | | `paymentMethod` | `string | null` | Payment method used for this order (e.g., `ideal`, `creditcard`, `bancontact`, `paypal`). | | `status` | `string` | The current status of the order. Can be `created`, `pending`, `paid`, `canceled`, or `expired`. | | `cancellationReason` | `string | null` | Why the order was canceled. `null` unless `status` is `canceled`, and `null` for orders canceled before this field existed. Currently `payment_failure` (payment recovery for this unpaid order was exhausted). | | `invoiceNumber` | `string | null` | Invoice number for this order (assigned after payment). | | `total` | `Money` | Total amount including taxes. A Money object with `value` (decimal string) and `currency` (ISO 4217 code). | | `subtotal` | `Money` | Subtotal amount before taxes. | | `reversedSubtotal` | `Money` | Amount of the captured payment already returned to the customer, before taxes, via refund or chargeback (settled). | | `refundableSubtotal` | `Money` | Remaining amount that can still be refunded, before taxes. | | `taxSummary` | `array` | Tax breakdown by rate. Each item contains a `taxRate` object (`name`, `percentage`, `taxablePercentage`) and an `amount` Money object. | | `lines` | `array` | Array of line items in this order. See OrderLine properties below. | | `customerDetails` | `BillingDetails` | Customer billing details (buyer). Includes `fullName`, `companyName`, `taxId`, `streetAndNumber`, `streetAdditional`, `city`, `region`, `postalCode`, `country`, and `email`. | | `createdAt` | `string` | When this order was created (ISO 8601 format). | | `links` | `object` | HATEOAS links to related resources. Contains `self`, `customer` (`null` for orders without a customer) and `customerInvoice`, the invoice in the customer portal (`text/html`). On a refund or chargeback order, `customerInvoice` opens the credit note. The link is signed and expires after 72 hours; the customer can request a new one from the page. | ### OrderLine Properties | Name | Type | Description | | ------------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier for this line item (starts with `order_item_`). | | `resource` | `string` | The resource type. Always `orderline`. | | `description` | `string` | Description of the item. | | `quantity` | `integer` | Number of units. | | `basePrice` | `Money` | Price per unit before taxes. | | `total` | `Money` | Total price including taxes (basePrice x quantity + taxes). | | `subtotal` | `Money` | Subtotal before taxes (basePrice x quantity). | | `taxes` | `array` | Tax breakdown by rate for this line. Each item contains a `taxRate` object and an `amount` Money object. | | `productType` | `string | null` | The product type this line links to. One of `one_off_product`, `subscription_plan`, `subscription`, `billing_details_verification`, `auth_request_product`, or `null` when the line has no product link. | | `productId` | `string | null` | The linked product's id (e.g. `subscription_...` for a `subscription` line). `null` when the line has no product link. | --- ## List all orders `GET /v1/orders` This endpoint allows you to retrieve a paginated list of all your orders. By default, a maximum of ten orders are shown per page. ### Optional parameters | Name | Type | Description | | --------------- | --------- | --------------------------------------------------------------------- | | `limit` | `integer` | The number of orders to return (default: 10, max: 100). | | `startingAfter` | `string` | A cursor for use in pagination. Returns results after this order ID. | | `endingBefore` | `string` | A cursor for use in pagination. Returns results before this order ID. | ::code-group{sync="api"} ```bash [cURL] curl -G https://api.vatly.com/v1/orders \ -H "Authorization: Bearer live_your_api_key_here" \ -d limit=10 ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $orders = $vatly->orders->page(); ``` ```json [Response] { "data": [ { "id": "order_Hn5xWqVfKm8RjTgYbUcP", "resource": "order", "customerId": "customer_Xk9pQrSvWm4NjLhYbUcP", "testmode": false, "metadata": {}, "paymentMethod": "ideal", "status": "paid", "cancellationReason": null, "invoiceNumber": "INV-2024-0001", "total": { "value": "35.09", "currency": "EUR" }, "subtotal": { "value": "29.00", "currency": "EUR" }, "reversedSubtotal": { "value": "0.00", "currency": "EUR" }, "refundableSubtotal": { "value": "29.00", "currency": "EUR" }, "taxSummary": [ { "taxRate": { "name": "VAT", "percentage": 21, "taxablePercentage": 100 }, "amount": { "value": "6.09", "currency": "EUR" } } ], "lines": [ { "id": "order_item_Mn6xBtPvKw2RjTgYcZaE", "resource": "orderline", "description": "Pro Monthly Subscription", "quantity": 1, "basePrice": { "value": "29.00", "currency": "EUR" }, "total": { "value": "35.09", "currency": "EUR" }, "subtotal": { "value": "29.00", "currency": "EUR" }, "taxes": [ { "taxRate": { "name": "VAT", "percentage": 21, "taxablePercentage": 100 }, "amount": { "value": "6.09", "currency": "EUR" } } ], "productType": "subscription", "productId": "subscription_Qp7mNvBxKw3RjTgYcZaE" } ], "customerDetails": { "fullName": "John Doe", "companyName": "Acme Corp", "taxId": null, "streetAndNumber": "123 Main Street", "streetAdditional": null, "city": "Berlin", "region": null, "postalCode": "10115", "country": "DE", "email": "john@acme.com" }, "createdAt": "2024-01-15T10:30:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/orders/order_Hn5xWqVfKm8RjTgYbUcP", "type": "application/json" }, "customer": { "href": "https://api.vatly.com/v1/customers/customer_Xk9pQrSvWm4NjLhYbUcP", "type": "application/json" } } } ], "count": 1, "links": { "self": { "href": "https://api.vatly.com/v1/orders", "type": "application/json" }, "next": null, "prev": null } } ``` :: --- ## Get an order `GET /v1/orders/:orderId` This endpoint allows you to retrieve a specific order by its ID. ### Parameters | Name | Type | Description | | --------- | -------- | ----------------------------------- | | `orderId` | `string` | The unique identifier of the order. | ::code-group{sync="api"} ```bash [cURL] curl https://api.vatly.com/v1/orders/order_Hn5xWqVfKm8RjTgYbUcP \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $order = $vatly->orders->get('order_Hn5xWqVfKm8RjTgYbUcP'); ``` ```json [Response] { "id": "order_Hn5xWqVfKm8RjTgYbUcP", "resource": "order", "customerId": "customer_Xk9pQrSvWm4NjLhYbUcP", "testmode": false, "metadata": {}, "paymentMethod": "ideal", "status": "paid", "cancellationReason": null, "invoiceNumber": "INV-2024-0001", "total": { "value": "35.09", "currency": "EUR" }, "subtotal": { "value": "29.00", "currency": "EUR" }, "reversedSubtotal": { "value": "0.00", "currency": "EUR" }, "refundableSubtotal": { "value": "29.00", "currency": "EUR" }, "taxSummary": [ { "taxRate": { "name": "VAT", "percentage": 21, "taxablePercentage": 100 }, "amount": { "value": "6.09", "currency": "EUR" } } ], "lines": [ { "id": "order_item_Jk4pQrSvWm8NjLhYbUcP", "resource": "orderline", "description": "Pro Monthly Subscription", "quantity": 1, "basePrice": { "value": "29.00", "currency": "EUR" }, "total": { "value": "35.09", "currency": "EUR" }, "subtotal": { "value": "29.00", "currency": "EUR" }, "taxes": [ { "taxRate": { "name": "VAT", "percentage": 21, "taxablePercentage": 100 }, "amount": { "value": "6.09", "currency": "EUR" } } ], "productType": "subscription", "productId": "subscription_Jk4pQrSvWm8NjLhYbUcP" } ], "customerDetails": { "fullName": "John Doe", "companyName": "Acme Corp", "taxId": null, "streetAndNumber": "123 Main Street", "streetAdditional": null, "city": "Berlin", "region": null, "postalCode": "10115", "country": "DE", "email": "john@acme.com" }, "createdAt": "2024-01-15T10:30:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/orders/order_Hn5xWqVfKm8RjTgYbUcP", "type": "application/json" }, "customer": { "href": "https://api.vatly.com/v1/customers/customer_Xk9pQrSvWm4NjLhYbUcP", "type": "application/json" }, "customerInvoice": { "href": "https://vatly.com/invoices/order_Hn5xWqVfKm8RjTgYbUcP", "type": "text/html" } } } ``` :: --- ## Create invoice update link `POST /v1/orders/:orderId/invoice-update-link` Creates a signed link that customers can use to update the invoice details for this order: billing address, VAT number, and company name. The link is valid for a limited time (typically 24 hours). ### Parameters | Name | Type | Description | | --------- | -------- | ----------------------------------- | | `orderId` | `string` | The unique identifier of the order. | ::code-group{sync="api"} ```bash [cURL] curl -X POST https://api.vatly.com/v1/orders/order_Hn5xWqVfKm8RjTgYbUcP/invoice-update-link \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $link = $vatly->orders->createInvoiceUpdateLink('order_Hn5xWqVfKm8RjTgYbUcP'); ``` ```json [Response] { "href": "https://vatly.com/invoices/order_Hn5xWqVfKm8RjTgYbUcP/edit?signature=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "type": "text/html" } ``` :: # Order Refunds ## The refund model The refund model contains all the information about order refunds, including the refund lines, amounts, and tax information. ### Properties | Name | Type | Description | | ----------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier for the refund (starts with `refund_`). | | `resource` | `string` | The resource type. Always `refund`. | | `orderId` | `string | null` | ID of the credit note order created for this refund. Always present; `null` until the refund is processed. | | `customerId` | `string` | ID of the customer receiving the refund. | | `testmode` | `boolean` | Whether this refund is in test mode. | | `status` | `string` | The current status of the refund. Can be `pending`, `queued`, `processing`, `refunded`, `failed`, or `canceled`. | | `originalOrderId` | `string` | ID of the original order being refunded. | | `total` | `Money` | Total refund amount including taxes. A Money object with `value` (decimal string) and `currency` (ISO 4217 code). | | `subtotal` | `Money` | Refund subtotal before taxes. | | `taxSummary` | `array` | Tax breakdown by rate being refunded. Array of objects with `taxRate` (`name`, `percentage`, `taxablePercentage`) and `amount` (Money). | | `lines` | `array` | Array of refund line items. See RefundLine properties below. | | `createdAt` | `string` | When this refund was created (ISO 8601 format). | | `links` | `object` | HATEOAS links to related resources. Contains `self`, `originalOrder`, `order` (the credit note order) and `customerInvoice` (the credit note in the customer portal, `text/html`). `order` and `customerInvoice` are always present and are `null` until the refund is processed. The `customerInvoice` link is signed and expires after 72 hours; the customer can request a new one from the page. | #### Status values | Status | Description | | ------------ | ------------------------------------------------------------ | | `pending` | Refund is ready to be sent to the bank. | | `queued` | Refund is queued due to a lack of balance. | | `processing` | Refund is being processed (cancellation no longer possible). | | `refunded` | Refund has been processed successfully. | | `failed` | Refund has failed after processing. | | `canceled` | Refund was canceled. | ### RefundLine Properties | Name | Type | Description | | ------------- | --------- | ----------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier for this refund line (starts with `refund_item_`). | | `resource` | `string` | The resource type. Always `refundline`. | | `description` | `string` | Description of the refunded item. | | `quantity` | `integer` | Number of units being refunded. | | `basePrice` | `Money` | Refund amount per unit before taxes. | | `total` | `Money` | Total refund amount including taxes. | | `subtotal` | `Money` | Refund subtotal before taxes. | | `taxes` | `array` | Tax breakdown by rate being refunded. Array of objects with `taxRate` and `amount`. | --- ## Create a refund `POST /v1/orders/:orderId/refunds` This endpoint allows you to create a partial refund for a specific order. You specify which order line items to refund and the amount for each. If another refund of the same order is still being created, the request returns `409` with `details.retry_with_new_idempotency_key` set to `true`. Retry with a new `Idempotency-Key`. See [Understanding `409 Conflict`](https://docs.vatly.com/guides/idempotency#understanding-409-conflict). ### Parameters | Name | Type | Description | | --------- | -------- | ----------------------------------- | | `orderId` | `string` | The unique identifier of the order. | ### Request body | Name | Type | Description | | ---------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `items` | `array` | **(Required)** Array of items to refund. Each item has: `itemId` (string, required) - ID of the order line item, `amount` (Money, required) - amount to refund before taxes, `description` (string, optional) - custom description, `descriptionAdditionalLine` (string, optional) - additional description line. | | `metadata` | `object` | Arbitrary key-value metadata for your application. | ::code-group{sync="api"} ```bash [cURL] curl -X POST https://api.vatly.com/v1/orders/order_Fp2kQrSvWm8NjLhYbUcP/refunds \ -H "Authorization: Bearer live_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "items": [ { "itemId": "order_item_Jk4pQrSvWm8NjLhYbUcP", "amount": { "value": "15.00", "currency": "EUR" }, "description": "50% refund for service issue" } ] }' ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $refund = $vatly->orders->refunds('order_Fp2kQrSvWm8NjLhYbUcP')->create([ 'items' => [ [ 'itemId' => 'order_item_Jk4pQrSvWm8NjLhYbUcP', 'amount' => [ 'value' => '15.00', 'currency' => 'EUR', ], 'description' => '50% refund for service issue', ], ], ]); ``` ```json [Response] { "id": "refund_Mn6xBtPvKw2RjTgYcZaE", "resource": "refund", "orderId": null, "customerId": "customer_Lp3mNvBxKw7RjTgYcZaE", "testmode": false, "status": "pending", "originalOrderId": "order_Fp2kQrSvWm8NjLhYbUcP", "total": { "value": "18.15", "currency": "EUR" }, "subtotal": { "value": "15.00", "currency": "EUR" }, "taxSummary": [ { "taxRate": { "name": "VAT", "percentage": 21, "taxablePercentage": 100 }, "amount": { "value": "3.15", "currency": "EUR" } } ], "lines": [ { "id": "refund_item_Tk7mNvBxKw2RjTgYcZaE", "resource": "refundline", "description": "50% refund for service issue", "quantity": 1, "basePrice": { "value": "15.00", "currency": "EUR" }, "total": { "value": "18.15", "currency": "EUR" }, "subtotal": { "value": "15.00", "currency": "EUR" }, "taxes": [ { "taxRate": { "name": "VAT", "percentage": 21, "taxablePercentage": 100 }, "amount": { "value": "3.15", "currency": "EUR" } } ] } ], "createdAt": "2024-01-15T10:30:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/refunds/refund_Mn6xBtPvKw2RjTgYcZaE", "type": "application/json" }, "originalOrder": { "href": "https://api.vatly.com/v1/orders/order_Fp2kQrSvWm8NjLhYbUcP", "type": "application/json" }, "order": null, "customerInvoice": null } } ``` :: --- ## Create a full refund `POST /v1/orders/:orderId/refunds/full` This endpoint allows you to create a full refund for a specific order. This will refund the entire remaining amount of the order. If another refund of the same order is still being created, the request returns `409` with `details.retry_with_new_idempotency_key` set to `true`. Retry with a new `Idempotency-Key`. See [Understanding `409 Conflict`](https://docs.vatly.com/guides/idempotency#understanding-409-conflict). ### Parameters | Name | Type | Description | | --------- | -------- | ----------------------------------- | | `orderId` | `string` | The unique identifier of the order. | ### Request body (optional) | Name | Type | Description | | ---------- | -------- | -------------------------------------------------- | | `metadata` | `object` | Arbitrary key-value metadata for your application. | ::code-group{sync="api"} ```bash [cURL] curl -X POST https://api.vatly.com/v1/orders/order_Fp2kQrSvWm8NjLhYbUcP/refunds/full \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $refund = $vatly->orders->refunds('order_Fp2kQrSvWm8NjLhYbUcP')->full(); ``` ```json [Response] { "id": "refund_Rk5pQrSvWm8NjLhYbUcP", "resource": "refund", "orderId": null, "customerId": "customer_Wt5mNvBxKw7YcZaEjLhR", "testmode": false, "status": "pending", "originalOrderId": "order_Fp2kQrSvWm8NjLhYbUcP", "total": { "value": "35.09", "currency": "EUR" }, "subtotal": { "value": "29.00", "currency": "EUR" }, "taxSummary": [ { "taxRate": { "name": "VAT", "percentage": 21, "taxablePercentage": 100 }, "amount": { "value": "6.09", "currency": "EUR" } } ], "lines": [ { "id": "refund_item_Bm7xNvPwKr3YjTgHcZaE", "resource": "refundline", "description": "Pro Monthly Subscription (Full Refund)", "quantity": 1, "basePrice": { "value": "29.00", "currency": "EUR" }, "total": { "value": "35.09", "currency": "EUR" }, "subtotal": { "value": "29.00", "currency": "EUR" }, "taxes": [ { "taxRate": { "name": "VAT", "percentage": 21, "taxablePercentage": 100 }, "amount": { "value": "6.09", "currency": "EUR" } } ] } ], "createdAt": "2024-01-21T09:00:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/refunds/refund_Rk5pQrSvWm8NjLhYbUcP", "type": "application/json" }, "originalOrder": { "href": "https://api.vatly.com/v1/orders/order_Fp2kQrSvWm8NjLhYbUcP", "type": "application/json" }, "order": null, "customerInvoice": null } } ``` :: --- ## List order refunds `GET /v1/orders/:orderId/refunds` This endpoint allows you to retrieve a list of all refunds for a specific order. ### Parameters | Name | Type | Description | | --------------- | --------- | ---------------------------------------------------------------------- | | `orderId` | `string` | The unique identifier of the order. | | `limit` | `integer` | The number of refunds to return (default: 10, max: 100). | | `startingAfter` | `string` | A cursor for use in pagination. Returns results after this refund ID. | | `endingBefore` | `string` | A cursor for use in pagination. Returns results before this refund ID. | ::code-group{sync="api"} ```bash [cURL] curl https://api.vatly.com/v1/orders/order_Fp2kQrSvWm8NjLhYbUcP/refunds \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $refunds = $vatly->orders->refunds('order_Fp2kQrSvWm8NjLhYbUcP')->page(); ``` ```json [Response] { "data": [ { "id": "refund_Bm7xNvPwKr3YjTgHcZaE", "resource": "refund", "orderId": null, "customerId": "customer_Wt5mNvBxKw7YcZaEjLhR", "testmode": false, "status": "pending", "originalOrderId": "order_Fp2kQrSvWm8NjLhYbUcP", "total": { "value": "12.10", "currency": "EUR" }, "subtotal": { "value": "10.00", "currency": "EUR" }, "taxSummary": [ { "taxRate": { "name": "VAT", "percentage": 21, "taxablePercentage": 100 }, "amount": { "value": "2.10", "currency": "EUR" } } ], "lines": [ { "id": "refund_item_Jk4pQrSvWm8NjLhYbUcP", "resource": "refundline", "description": "Partial refund for service issue", "quantity": 1, "basePrice": { "value": "10.00", "currency": "EUR" }, "total": { "value": "12.10", "currency": "EUR" }, "subtotal": { "value": "10.00", "currency": "EUR" }, "taxes": [ { "taxRate": { "name": "VAT", "percentage": 21, "taxablePercentage": 100 }, "amount": { "value": "2.10", "currency": "EUR" } } ] } ], "createdAt": "2024-01-20T14:00:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/refunds/refund_Bm7xNvPwKr3YjTgHcZaE", "type": "application/json" }, "originalOrder": { "href": "https://api.vatly.com/v1/orders/order_Fp2kQrSvWm8NjLhYbUcP", "type": "application/json" }, "order": null, "customerInvoice": null } } ], "count": 1, "links": { "self": { "href": "https://api.vatly.com/v1/orders/order_Fp2kQrSvWm8NjLhYbUcP/refunds", "type": "application/json" }, "next": null, "prev": null } } ``` :: --- ## Get an order refund `GET /v1/orders/:orderId/refunds/:refundId` This endpoint allows you to retrieve details of a specific refund for a specific order. ### Parameters | Name | Type | Description | | ---------- | -------- | ------------------------------------ | | `orderId` | `string` | The unique identifier of the order. | | `refundId` | `string` | The unique identifier of the refund. | ::code-group{sync="api"} ```bash [cURL] curl https://api.vatly.com/v1/orders/order_Fp2kQrSvWm8NjLhYbUcP/refunds/refund_Xk9pQrSvWm4NjLhYbUcP \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $refund = $vatly->orders->refunds('order_Fp2kQrSvWm8NjLhYbUcP')->get('refund_Xk9pQrSvWm4NjLhYbUcP'); ``` ```json [Response] { "id": "refund_Xk9pQrSvWm4NjLhYbUcP", "resource": "refund", "orderId": "order_Bm7xNvPwKr3YjTgHcZaE", "customerId": "customer_Wt5mNvBxKw7YcZaEjLhR", "testmode": false, "status": "refunded", "originalOrderId": "order_Fp2kQrSvWm8NjLhYbUcP", "total": { "value": "18.15", "currency": "EUR" }, "subtotal": { "value": "15.00", "currency": "EUR" }, "taxSummary": [ { "taxRate": { "name": "VAT", "percentage": 21, "taxablePercentage": 100 }, "amount": { "value": "3.15", "currency": "EUR" } } ], "lines": [ { "id": "refund_item_Mn6xBtPvKw2RjTgYcZaE", "resource": "refundline", "description": "Pro Monthly Subscription (Refund)", "quantity": 1, "basePrice": { "value": "15.00", "currency": "EUR" }, "total": { "value": "18.15", "currency": "EUR" }, "subtotal": { "value": "15.00", "currency": "EUR" }, "taxes": [ { "taxRate": { "name": "VAT", "percentage": 21, "taxablePercentage": 100 }, "amount": { "value": "3.15", "currency": "EUR" } } ] } ], "createdAt": "2024-01-20T14:00:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/refunds/refund_Xk9pQrSvWm4NjLhYbUcP", "type": "application/json" }, "originalOrder": { "href": "https://api.vatly.com/v1/orders/order_Fp2kQrSvWm8NjLhYbUcP", "type": "application/json" }, "order": { "href": "https://api.vatly.com/v1/orders/order_Bm7xNvPwKr3YjTgHcZaE", "type": "application/json" }, "customerInvoice": { "href": "https://vatly.com/invoices/order_Bm7xNvPwKr3YjTgHcZaE", "type": "text/html" } } } ``` :: --- ## Cancel an order refund `DELETE /v1/orders/:orderId/refunds/:refundId` This endpoint allows you to cancel a pending refund for a specific order. Only pending refunds can be cancelled. ### Parameters | Name | Type | Description | | ---------- | -------- | ---------------------------------------------- | | `orderId` | `string` | The unique identifier of the order. | | `refundId` | `string` | The unique identifier of the refund to cancel. | ::code-group{sync="client"} ```bash [cURL] curl -X DELETE https://api.vatly.com/v1/orders/order_Fp2kQrSvWm8NjLhYbUcP/refunds/refund_Mn6xBtPvKw2RjTgYcZaE \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $vatly->orders->refunds('order_Fp2kQrSvWm8NjLhYbUcP')->cancel('refund_Mn6xBtPvKw2RjTgYcZaE'); ``` :: Returns `204 No Content` on success. # Refunds ## The refund model The refund model contains all the information about refunds, including the refund lines, amounts, and tax information. ### Properties | Name | Type | Description | | ----------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier for the refund (starts with `refund_`). | | `resource` | `string` | The resource type. Always `refund`. | | `orderId` | `string | null` | ID of the credit note order created for this refund. Always present; `null` until the refund is processed. | | `customerId` | `string` | ID of the customer receiving the refund. | | `testmode` | `boolean` | Whether this refund is in test mode. | | `status` | `string` | The current status of the refund. Can be `pending`, `queued`, `processing`, `refunded`, `failed`, or `canceled`. | | `originalOrderId` | `string` | ID of the original order being refunded. | | `total` | `Money` | Total refund amount including taxes. A Money object with `value` (decimal string) and `currency` (ISO 4217 code). | | `subtotal` | `Money` | Refund subtotal before taxes. | | `taxSummary` | `array` | Tax breakdown by rate being refunded. Each entry contains a `taxRate` object (`name`, `percentage`, `taxablePercentage`) and an `amount` Money object. | | `lines` | `array` | Array of refund line items. Each line includes `id` (starts with `refund_item_`), `resource`, `description`, `quantity`, `basePrice`, `total`, `subtotal`, and `taxes`. | | `createdAt` | `string` | When this refund was created (ISO 8601 format). | | `links` | `object` | HATEOAS links to related resources. Contains `self`, `originalOrder`, `order` (the credit note order) and `customerInvoice` (the credit note in the customer portal, `text/html`). `order` and `customerInvoice` are always present and are `null` until the refund is processed. The `customerInvoice` link is signed and expires after 72 hours; the customer can request a new one from the page. | --- ## List all refunds `GET /v1/refunds` This endpoint allows you to retrieve a paginated list of all refunds across your account. ### Optional parameters | Name | Type | Description | | --------------- | --------- | ---------------------------------------------------------------------- | | `limit` | `integer` | The number of refunds to return (default: 10, max: 100). | | `startingAfter` | `string` | A cursor for use in pagination. Returns results after this refund ID. | | `endingBefore` | `string` | A cursor for use in pagination. Returns results before this refund ID. | ::code-group{sync="api"} ```bash [cURL] curl -G https://api.vatly.com/v1/refunds \ -H "Authorization: Bearer live_your_api_key_here" \ -d limit=10 ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $refunds = $vatly->refunds->page(); ``` ```json [Response] { "data": [ { "id": "refund_Xk9pQrSvWm4NjLhYbUcP", "resource": "refund", "orderId": "order_Bm7xNvPwKr3YjTgHcZaE", "customerId": "customer_Wt5mNvBxKw7YcZaEjLhR", "testmode": false, "createdAt": "2024-01-20T14:00:00Z", "status": "refunded", "originalOrderId": "order_Fp2kQrSvWm8NjLhYbUcP", "total": { "value": "18.15", "currency": "EUR" }, "subtotal": { "value": "15.00", "currency": "EUR" }, "taxSummary": [ { "taxRate": { "name": "VAT", "percentage": 21, "taxablePercentage": 100 }, "amount": { "value": "3.15", "currency": "EUR" } } ], "lines": [ { "id": "refund_item_Mn6xBtPvKw2RjTgYcZaE", "resource": "refundline", "description": "Pro Monthly Subscription (Refund)", "quantity": 1, "basePrice": { "value": "15.00", "currency": "EUR" }, "total": { "value": "18.15", "currency": "EUR" }, "subtotal": { "value": "15.00", "currency": "EUR" }, "taxes": [ { "taxRate": { "name": "VAT", "percentage": 21, "taxablePercentage": 100 }, "amount": { "value": "3.15", "currency": "EUR" } } ] } ], "links": { "self": { "href": "https://api.vatly.com/v1/refunds/refund_Xk9pQrSvWm4NjLhYbUcP", "type": "application/json" }, "originalOrder": { "href": "https://api.vatly.com/v1/orders/order_Fp2kQrSvWm8NjLhYbUcP", "type": "application/json" }, "order": { "href": "https://api.vatly.com/v1/orders/order_Bm7xNvPwKr3YjTgHcZaE", "type": "application/json" }, "customerInvoice": { "href": "https://vatly.com/invoices/order_Bm7xNvPwKr3YjTgHcZaE", "type": "text/html" } } } ], "count": 1, "links": { "self": { "href": "https://api.vatly.com/v1/refunds", "type": "application/json" }, "next": null, "prev": null } } ``` :: --- ## Get a refund `GET /v1/refunds/:refundId` This endpoint allows you to retrieve details of a specific refund. ### Parameters | Name | Type | Description | | ---------- | -------- | ------------------------------------ | | `refundId` | `string` | The unique identifier of the refund. | ::code-group{sync="api"} ```bash [cURL] curl https://api.vatly.com/v1/refunds/refund_Xk9pQrSvWm4NjLhYbUcP \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $refund = $vatly->refunds->get('refund_Xk9pQrSvWm4NjLhYbUcP'); ``` ```json [Response] { "id": "refund_Xk9pQrSvWm4NjLhYbUcP", "resource": "refund", "orderId": "order_Bm7xNvPwKr3YjTgHcZaE", "customerId": "customer_Wt5mNvBxKw7YcZaEjLhR", "testmode": false, "createdAt": "2024-01-20T14:00:00Z", "status": "refunded", "originalOrderId": "order_Fp2kQrSvWm8NjLhYbUcP", "total": { "value": "18.15", "currency": "EUR" }, "subtotal": { "value": "15.00", "currency": "EUR" }, "taxSummary": [ { "taxRate": { "name": "VAT", "percentage": 21, "taxablePercentage": 100 }, "amount": { "value": "3.15", "currency": "EUR" } } ], "lines": [ { "id": "refund_item_Mn6xBtPvKw2RjTgYcZaE", "resource": "refundline", "description": "Pro Monthly Subscription (Refund)", "quantity": 1, "basePrice": { "value": "15.00", "currency": "EUR" }, "total": { "value": "18.15", "currency": "EUR" }, "subtotal": { "value": "15.00", "currency": "EUR" }, "taxes": [ { "taxRate": { "name": "VAT", "percentage": 21, "taxablePercentage": 100 }, "amount": { "value": "3.15", "currency": "EUR" } } ] } ], "links": { "self": { "href": "https://api.vatly.com/v1/refunds/refund_Xk9pQrSvWm4NjLhYbUcP", "type": "application/json" }, "originalOrder": { "href": "https://api.vatly.com/v1/orders/order_Fp2kQrSvWm8NjLhYbUcP", "type": "application/json" }, "order": { "href": "https://api.vatly.com/v1/orders/order_Bm7xNvPwKr3YjTgHcZaE", "type": "application/json" }, "customerInvoice": { "href": "https://vatly.com/invoices/order_Bm7xNvPwKr3YjTgHcZaE", "type": "text/html" } } } ``` :: # Chargebacks ## The chargeback model The chargeback model contains all the information about payment disputes, including the disputed amount, settlement amount, reason, and related order information. Chargebacks are created automatically when a payment provider initiates a dispute. They are read-only resources. ### Properties | Name | Type | Description | | ------------------ | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier for the chargeback (starts with `chargeback_`). | | `resource` | `string` | The resource type. Always `chargeback`. | | `customerId` | `string` | ID of the customer the chargeback was raised against. | | `testmode` | `boolean` | Whether this chargeback is in test mode. | | `status` | `string` | The current status of the chargeback dispute. Can be `pending`, `requires_amount_review`, `accepted`, `rejected`, `evidence_submitted`, `won`, or `lost`. `requires_amount_review` means the provider's disputed amount exceeds the original order, so financial completion is held (quarantined) pending review. | | `amount` | `Money` | Amount of the chargeback. A Money object with `value` (decimal string) and `currency` (ISO 4217 code). | | `settlementAmount` | `Money` | Amount that was deducted from the merchant's settlement. May differ from `amount` due to currency conversion or fees. | | `total` | `Money` | Total chargeback amount including taxes. | | `subtotal` | `Money` | Chargeback subtotal before taxes. | | `taxSummary` | `array` | Tax breakdown by rate for the chargeback. Array of objects with `taxRate` (`name`, `percentage`, `taxablePercentage`) and `amount` (Money). | | `reason` | `string` | Reason code or description for the chargeback. Common reasons include `fraud`, `product_not_received`, `product_unacceptable`, `duplicate`, or `subscription_canceled`. | | `originalOrderId` | `string` | ID of the original order that was charged back (starts with `order_`). | | `orderId` | `string | null` | ID of the credit note order created for this chargeback (starts with `order_`). Always present; `null` until the chargeback is processed. | | `createdAt` | `string` | When this chargeback was created (ISO 8601 format). | | `links` | `object` | HATEOAS links to related resources. Contains `self`, `originalOrder`, `order` (the credit note order) and `customerInvoice` (the credit note in the customer portal, `text/html`). `order` and `customerInvoice` are always present and are `null` until the chargeback is lost. The `customerInvoice` link is signed and expires after 72 hours; the customer can request a new one from the page. | --- ## List all chargebacks `GET /v1/chargebacks` This endpoint allows you to retrieve a paginated list of all chargebacks across all orders. ### Optional parameters | Name | Type | Description | | --------------- | --------- | -------------------------------------------------------------------------- | | `limit` | `integer` | The number of chargebacks to return (default: 10, max: 100). | | `startingAfter` | `string` | A cursor for use in pagination. Returns results after this chargeback ID. | | `endingBefore` | `string` | A cursor for use in pagination. Returns results before this chargeback ID. | ::code-group{sync="api"} ```bash [cURL] curl -G https://api.vatly.com/v1/chargebacks \ -H "Authorization: Bearer live_your_api_key_here" \ -d limit=10 ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $chargebacks = $vatly->chargebacks->page(); ``` ```json [Response] { "data": [ { "id": "chargeback_Mn6xBtPvKw2RjTgYcZaE", "resource": "chargeback", "customerId": "customer_Lp3mNvBxKw7RjTgYcZaE", "testmode": false, "status": "lost", "amount": { "value": "35.09", "currency": "EUR" }, "settlementAmount": { "value": "35.09", "currency": "EUR" }, "total": { "value": "35.09", "currency": "EUR" }, "subtotal": { "value": "29.00", "currency": "EUR" }, "taxSummary": [ { "taxRate": { "name": "VAT", "percentage": 21, "taxablePercentage": 100 }, "amount": { "value": "6.09", "currency": "EUR" } } ], "reason": "fraud", "originalOrderId": "order_Fp2kQrSvWm8NjLhYbUcP", "orderId": "order_Rk5pQrSvWm8NjLhYbUcP", "createdAt": "2024-01-15T10:30:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/chargebacks/chargeback_Mn6xBtPvKw2RjTgYcZaE", "type": "application/json" }, "originalOrder": { "href": "https://api.vatly.com/v1/orders/order_Fp2kQrSvWm8NjLhYbUcP", "type": "application/json" }, "order": { "href": "https://api.vatly.com/v1/orders/order_Rk5pQrSvWm8NjLhYbUcP", "type": "application/json" }, "customerInvoice": { "href": "https://vatly.com/invoices/order_Rk5pQrSvWm8NjLhYbUcP", "type": "text/html" } } } ], "count": 1, "links": { "self": { "href": "https://api.vatly.com/v1/chargebacks", "type": "application/json" }, "next": null, "prev": null } } ``` :: --- ## Get a chargeback `GET /v1/chargebacks/:chargebackId` This endpoint allows you to retrieve a specific chargeback by its ID. ### Parameters | Name | Type | Description | | -------------- | -------- | ---------------------------------------- | | `chargebackId` | `string` | The unique identifier of the chargeback. | ::code-group{sync="api"} ```bash [cURL] curl https://api.vatly.com/v1/chargebacks/chargeback_Mn6xBtPvKw2RjTgYcZaE \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $chargeback = $vatly->chargebacks->get('chargeback_Mn6xBtPvKw2RjTgYcZaE'); ``` ```json [Response] { "id": "chargeback_Mn6xBtPvKw2RjTgYcZaE", "resource": "chargeback", "customerId": "customer_Lp3mNvBxKw7RjTgYcZaE", "testmode": false, "status": "lost", "amount": { "value": "35.09", "currency": "EUR" }, "settlementAmount": { "value": "35.09", "currency": "EUR" }, "total": { "value": "35.09", "currency": "EUR" }, "subtotal": { "value": "29.00", "currency": "EUR" }, "taxSummary": [ { "taxRate": { "name": "VAT", "percentage": 21, "taxablePercentage": 100 }, "amount": { "value": "6.09", "currency": "EUR" } } ], "reason": "fraud", "originalOrderId": "order_Fp2kQrSvWm8NjLhYbUcP", "orderId": "order_Rk5pQrSvWm8NjLhYbUcP", "createdAt": "2024-01-25T16:45:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/chargebacks/chargeback_Mn6xBtPvKw2RjTgYcZaE", "type": "application/json" }, "originalOrder": { "href": "https://api.vatly.com/v1/orders/order_Fp2kQrSvWm8NjLhYbUcP", "type": "application/json" }, "order": { "href": "https://api.vatly.com/v1/orders/order_Rk5pQrSvWm8NjLhYbUcP", "type": "application/json" }, "customerInvoice": { "href": "https://vatly.com/invoices/order_Rk5pQrSvWm8NjLhYbUcP", "type": "text/html" } } } ``` :: --- ## List order chargebacks `GET /v1/orders/:orderId/chargebacks` This endpoint allows you to retrieve a paginated list of chargebacks for a specific order. ### Parameters | Name | Type | Description | | --------------- | --------- | -------------------------------------------------------------------------- | | `orderId` | `string` | The unique identifier of the order. | | `limit` | `integer` | The number of chargebacks to return (default: 10, max: 100). | | `startingAfter` | `string` | A cursor for use in pagination. Returns results after this chargeback ID. | | `endingBefore` | `string` | A cursor for use in pagination. Returns results before this chargeback ID. | ::code-group{sync="api"} ```bash [cURL] curl -G https://api.vatly.com/v1/orders/order_Fp2kQrSvWm8NjLhYbUcP/chargebacks \ -H "Authorization: Bearer live_your_api_key_here" \ -d limit=10 ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $chargebacks = $vatly->orders->chargebacks('order_Fp2kQrSvWm8NjLhYbUcP')->page(); ``` ```json [Response] { "data": [ { "id": "chargeback_Fp2kQrSvWm8NjLhYbUcP", "resource": "chargeback", "customerId": "customer_Lp3mNvBxKw7RjTgYcZaE", "testmode": false, "status": "lost", "amount": { "value": "35.09", "currency": "EUR" }, "settlementAmount": { "value": "35.09", "currency": "EUR" }, "total": { "value": "35.09", "currency": "EUR" }, "subtotal": { "value": "29.00", "currency": "EUR" }, "taxSummary": [ { "taxRate": { "name": "VAT", "percentage": 21, "taxablePercentage": 100 }, "amount": { "value": "6.09", "currency": "EUR" } } ], "reason": "product_not_received", "originalOrderId": "order_Fp2kQrSvWm8NjLhYbUcP", "orderId": "order_Rk5pQrSvWm8NjLhYbUcP", "createdAt": "2024-01-25T16:45:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/chargebacks/chargeback_Fp2kQrSvWm8NjLhYbUcP", "type": "application/json" }, "originalOrder": { "href": "https://api.vatly.com/v1/orders/order_Fp2kQrSvWm8NjLhYbUcP", "type": "application/json" }, "order": { "href": "https://api.vatly.com/v1/orders/order_Rk5pQrSvWm8NjLhYbUcP", "type": "application/json" }, "customerInvoice": { "href": "https://vatly.com/invoices/order_Rk5pQrSvWm8NjLhYbUcP", "type": "text/html" } } } ], "count": 1, "links": { "self": { "href": "https://api.vatly.com/v1/orders/order_Fp2kQrSvWm8NjLhYbUcP/chargebacks", "type": "application/json" }, "next": null, "prev": null } } ``` :: --- ## Get an order chargeback `GET /v1/orders/:orderId/chargebacks/:chargebackId` This endpoint allows you to retrieve a specific chargeback within an order context. ### Parameters | Name | Type | Description | | -------------- | -------- | ---------------------------------------- | | `orderId` | `string` | The unique identifier of the order. | | `chargebackId` | `string` | The unique identifier of the chargeback. | ::code-group{sync="api"} ```bash [cURL] curl https://api.vatly.com/v1/orders/order_Fp2kQrSvWm8NjLhYbUcP/chargebacks/chargeback_Mn6xBtPvKw2RjTgYcZaE \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $chargeback = $vatly->orders->chargebacks('order_Fp2kQrSvWm8NjLhYbUcP')->get('chargeback_Mn6xBtPvKw2RjTgYcZaE'); ``` ```json [Response] { "id": "chargeback_Mn6xBtPvKw2RjTgYcZaE", "resource": "chargeback", "customerId": "customer_Lp3mNvBxKw7RjTgYcZaE", "testmode": false, "status": "lost", "amount": { "value": "35.09", "currency": "EUR" }, "settlementAmount": { "value": "35.09", "currency": "EUR" }, "total": { "value": "35.09", "currency": "EUR" }, "subtotal": { "value": "29.00", "currency": "EUR" }, "taxSummary": [ { "taxRate": { "name": "VAT", "percentage": 21, "taxablePercentage": 100 }, "amount": { "value": "6.09", "currency": "EUR" } } ], "reason": "fraud", "originalOrderId": "order_Fp2kQrSvWm8NjLhYbUcP", "orderId": "order_Rk5pQrSvWm8NjLhYbUcP", "createdAt": "2024-01-25T16:45:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/chargebacks/chargeback_Mn6xBtPvKw2RjTgYcZaE", "type": "application/json" }, "originalOrder": { "href": "https://api.vatly.com/v1/orders/order_Fp2kQrSvWm8NjLhYbUcP", "type": "application/json" }, "order": { "href": "https://api.vatly.com/v1/orders/order_Rk5pQrSvWm8NjLhYbUcP", "type": "application/json" }, "customerInvoice": { "href": "https://vatly.com/invoices/order_Rk5pQrSvWm8NjLhYbUcP", "type": "text/html" } } } ``` :: # Webhook Events ## The webhook event model Webhook events let you inspect the exact payload Vatly generated for a domain event. This is the **persisted** event, the record returned by this endpoint. The `webhook.setup` verification call is a delivery-only handshake and is never persisted, so it does not appear here. For the full list of events and the live delivery envelope, see the [Webhooks guide](https://docs.vatly.com/guides/webhooks). ### Properties | Name | Type | Description | | ------------ | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier for the webhook event (starts with `webhook_event_`). | | `resource` | `string` | The resource type. Always `webhook_event`. | | `eventName` | `string` | The event name, such as `order.paid`, `refund.completed`, or `subscription_plan.update_approved`. See the [Webhooks guide](https://docs.vatly.com/guides/webhooks#event-types) for the full list. | | `reason` | `string | null` | Why the event fired, for events with more than one cause. Always present; `null` for every event except `subscription.updated`, where it is `updated_immediately`, `updated_on_renewal`, or `renewed`. New values may be added over time. | | `entityType` | `string` | The resource type the event refers to, such as `order`, `refund`, `subscription`, `checkout`, `one_off_product`, or `subscription_plan`. | | `entityId` | `string` | The ID of the related resource. | | `object` | `object` | The full resource payload as it existed when the event occurred (an Order, Chargeback, Refund, Subscription, Checkout, OneOffProduct, or SubscriptionPlan), keyed by its own `resource` field. Note `object.resource` can differ from `entityType`: chargeback events carry `entityType: order` but a Chargeback `object`. | | `createdAt` | `string` | When the event occurred (ISO 8601 format). | | `testmode` | `boolean` | Whether the event originated from a test-mode resource. | | `links` | `object` | HATEOAS links. Contains `self`. | --- ## Get a webhook event `GET /v1/webhook-events/:eventId` This endpoint returns the full webhook event payload for a specific event ID. ### Parameters | Name | Type | Description | | --------- | -------- | ------------------------------------------- | | `eventId` | `string` | The unique identifier of the webhook event. | ::code-group{sync="api"} ```bash [cURL] curl https://api.vatly.com/v1/webhook-events/webhook_event_Qk8pRtSvWm2NjLhYcZaE \ -H "Authorization: Bearer live_your_api_key_here" ``` ```php [PHP] $vatly = new \Vatly\API\VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); $event = $vatly->webhookEvents->get('webhook_event_Qk8pRtSvWm2NjLhYcZaE'); ``` ```json [Response] { "id": "webhook_event_Qk8pRtSvWm2NjLhYcZaE", "resource": "webhook_event", "eventName": "order.paid", "reason": null, "entityType": "order", "entityId": "order_Hn5xWqVfKm8RjTgYbUcP", "createdAt": "2024-01-15T10:30:00Z", "testmode": false, "object": { "id": "order_Hn5xWqVfKm8RjTgYbUcP", "resource": "order", "testmode": false, "status": "paid", "total": { "value": "29.99", "currency": "EUR" }, "subtotal": { "value": "24.79", "currency": "EUR" } }, "links": { "self": { "href": "https://api.vatly.com/v1/webhook-events/webhook_event_Qk8pRtSvWm2NjLhYcZaE", "type": "application/json" } } } ``` :: # PHP SDK ![Vatly API client for PHP](https://raw.githubusercontent.com/Vatly/vatly-api-php/main/art/banner.png) Official PHP SDK for the Vatly API. Handle subscriptions, one-off payments, tax compliance, and billing for your SaaS. > **Looking for the exact field list?** These guides cover the common paths. The authoritative, machine-readable schema for every endpoint lives in the [OpenAPI spec](https://docs.vatly.com/openapi.yaml){rel=""nofollow""} — point your AI assistant or codegen tooling at it when an example leaves a field ambiguous. ## Installation The SDK is in alpha, and every alpha release may include breaking changes. Allow alpha releases, then install the SDK via Composer. `prefer-stable` keeps your other dependencies on stable releases. ```bash composer config minimum-stability alpha composer config prefer-stable true composer require vatly/vatly-api-php ``` --- ## Quick start Initialize the client with your API key and create a checkout. ### API Keys Get your API keys from the [Vatly Dashboard](https://my.vatly.com){rel=""nofollow""} under **Settings > API**. | Name | Type | Description | | ------- | -------- | -------------------------------------- | | `live_` | `prefix` | Production transactions, real charges. | | `test_` | `prefix` | Sandbox testing, no real charges. | ```php use Vatly\API\VatlyApiClient; $vatly = new VatlyApiClient(); $vatly->setApiKey('live_your_api_key_here'); // Create a checkout $checkout = $vatly->checkouts->create([ 'products' => [ ['id' => 'subscription_plan_abc123', 'quantity' => 1] ], 'redirectUrlSuccess' => 'https://yourapp.com/success', 'redirectUrlCanceled' => 'https://yourapp.com/canceled', ]); // Redirect customer to checkout header('Location: ' . $checkout->links->checkoutUrl->href); ``` --- ## Idempotency The SDK automatically adds an `Idempotency-Key` header to every `POST` and `PATCH` request. This is enabled by default, so checkout creation and subscription updates are already protected without extra configuration. `GET` and `DELETE` requests do not include an idempotency header. ### Override the next mutating request Use `setIdempotencyKey()` when you want to supply the key yourself. The value is used for the next `POST` or `PATCH` request and then cleared automatically. ```php $vatly->setIdempotencyKey('checkout-create-123'); $checkout = $vatly->checkouts->create([ 'products' => [ ['id' => 'subscription_plan_abc123', 'quantity' => 1], ], 'redirectUrlSuccess' => 'https://yourapp.com/success', 'redirectUrlCanceled' => 'https://yourapp.com/canceled', ]); ``` This also works with resource methods that do not expose request options directly: ```php $vatly->setIdempotencyKey('subscription-update-123'); $subscription->update([ 'quantity' => 2, ]); ``` ### Per-request options on supported endpoint methods Methods that accept a second or third options array can override the header with `idempotencyKey`. ```php $checkout = $vatly->checkouts->create([...], [ 'idempotencyKey' => 'checkout-create-123', ]); $subscription = $vatly->subscriptions->update('subscription_123', [ 'quantity' => 2, ], [ 'idempotencyKey' => 'subscription-update-123', ]); ``` ### Custom generator or disable auto-generation If you need a specific key format, provide your own generator implementation. ```php use Vatly\API\HttpClient\Idempotency\IdempotencyKeyGeneratorContract; final class MyIdempotencyKeyGenerator implements IdempotencyKeyGeneratorContract { public function generate(): string { return bin2hex(random_bytes(16)); } } $vatly->setIdempotencyKeyGenerator(new MyIdempotencyKeyGenerator()); ``` To stop the SDK from generating keys automatically: ```php $vatly->clearIdempotencyKeyGenerator(); ``` --- ## Resources The SDK provides access to all Vatly API resources. | Resource | Description | | --------------------------------------------------------------------------- | ----------------------------- | | [Checkouts](https://docs.vatly.com/packages/php/checkouts) | Create hosted payment pages | | [Customers](https://docs.vatly.com/packages/php/customers) | Manage customer records | | [Subscriptions](https://docs.vatly.com/packages/php/subscriptions) | Recurring billing | | [Subscription Plans](https://docs.vatly.com/packages/php/subscriptionplans) | Define subscription products | | [One-Off Products](https://docs.vatly.com/packages/php/oneoffproducts) | Single purchase products | | [Orders](https://docs.vatly.com/packages/php/orders) | Transaction records | | [Refunds](https://docs.vatly.com/packages/php/refunds) | Process refunds | | [Chargebacks](https://docs.vatly.com/packages/php/chargebacks) | Handle disputes | | [Webhooks](https://docs.vatly.com/packages/php/webhooks) | Real-time event notifications | | [Webhook Endpoints](https://docs.vatly.com/packages/php/webhookendpoints) | Register delivery endpoints | --- ## Error handling The SDK throws specific exceptions for different error types. ### Exception types | Name | Type | Description | | -------------- | ----------- | ------------------------------------------------------------------------- | | `ApiException` | `exception` | API errors, including authentication, validation, and transport failures. | ```php use Vatly\API\Exceptions\ApiException; try { $checkout = $vatly->checkouts->create([...]); } catch (ApiException $e) { // API error (network, auth, validation, etc.) echo $e->getMessage(); } ``` --- ## Requirements - PHP 8.0+ - cURL extension - JSON extension # Customers Customers represent your end users who purchase products through Vatly. ## The Customer Resource Below you'll find all properties for the Vatly Customer resource. ### Properties | Name | Type | Description | | ----------- | --------------- | ---------------------------------------------------- | | `id` | `string` | Unique identifier for the customer (`customer_...`). | | `resource` | `string` | Always `customer`. | | `email` | `string` | Customer's email address. | | `name` | `string | null` | Customer's name. | | `testmode` | `bool` | Whether this is a test customer. | | `metadata` | `array` | Your custom metadata. | | `createdAt` | `string` | Creation timestamp (ISO 8601). | | `links` | `CustomerLinks` | Link to this customer. | --- ## Create a customer `POST /v1/customers` Create a new customer. ### Required attributes | Name | Type | Description | | ------- | -------- | ----------------------------- | | `email` | `string` | The customer's email address. | ### Optional attributes | Name | Type | Description | | ---------- | -------- | --------------------- | | `name` | `string` | The customer's name. | | `metadata` | `array` | Your custom metadata. | ```php $customer = $vatly->customers->create([ 'email' => 'john@example.com', 'name' => 'John Doe', 'metadata' => [ 'user_id' => '12345', ], ]); echo $customer->id; // customer_abc123 ``` --- ## Retrieve a customer `GET /v1/customers/:id` Retrieve a customer by their ID. ```php $customer = $vatly->customers->get('customer_abc123'); echo $customer->email; echo $customer->name; ``` --- ## Update a customer `PATCH /v1/customers/:id` Update a customer's identity fields. Only `name` and `email` may be changed, and both are optional — send whichever you want to update. Billing-address details (company name, tax ID, street, city, country, etc.) are **not** editable here; amend those through the hosted billing-update flow. ### Optional attributes | Name | Type | Description | | ------- | --------------- | --------------------------------------------- | | `name` | `string | null` | The customer's name. Pass `null` to clear it. | | `email` | `string` | The customer's email address. | ```php $customer = $vatly->customers->update('customer_abc123', [ 'name' => 'Jane Doe', 'email' => 'jane@example.com', ]); echo $customer->name; // Jane Doe ``` If you already have a `Customer` resource instance: ```php $customer->update([ 'name' => 'Jane Doe', ]); ``` The SDK generates an idempotency key automatically for the `PATCH` request, or you can set your own via `$vatly->setIdempotencyKey(...)` beforehand. --- ## List all customers `GET /v1/customers` Retrieve a paginated list of all your customers. ### Optional attributes | Name | Type | Description | | --------------- | --------- | ----------------------------------------------------------------- | | `startingAfter` | `string` | A cursor for pagination: return the page after this customer ID. | | `endingBefore` | `string` | A cursor for pagination: return the page before this customer ID. | | `limit` | `integer` | The number of customers to return (default: 10, max: 100). | ```php $customers = $vatly->customers->page(); foreach ($customers as $customer) { echo $customer->email; } // Pass the cursors and limit in order: startingAfter, endingBefore, limit $customers = $vatly->customers->page('customer_last_id', null, 25); ``` --- ## Recover a customer by email `GET /v1/customers?email=...` Look up customers by email address — the way back to a customer id you no longer have (after a re-sync or reset). The address is canonicalized before matching, exactly as on write. An address can be held by more than one customer, so this always returns a (possibly empty) collection. ```php $customers = $vatly->customers->listByEmail('john@example.com'); if (count($customers) > 0) { echo $customers[0]->id; // customer_abc123 } ``` You can also recover in a single call by creating the customer again: create is get-or-create on the email, so posting a known address returns the existing customer (`200`) rather than a validation error, while a genuinely new address is created (`201`). Either way you get the customer back: ```php $customer = $vatly->customers->create(['email' => 'john@example.com']); echo $customer->id; // the existing customer id, if the email was already known ``` --- ## Create a customer portal session `POST /v1/customers/:id/portal-sessions` Create a short-lived, single-use link that sends an authenticated customer straight to your storefront in Vatly's hosted portal (where they can manage their subscriptions, billing details, and invoices). The session is locked to the customer, storefront, merchant, and live/test mode of the API token: the customer lands directly in that one storefront's portal — never a storefront picker or any other store. If your account has multiple storefronts, each API token mints portal links for its own store. Redirect the customer's browser to the returned `url`. It expires after roughly 15 minutes and can be consumed once, so create a fresh one per visit. The link is credential-bearing — do not cache or log it. ### Optional attributes | Name | Type | Description | | ----------- | -------- | ------------------------------------------------------------------------------------------------------------------------- | | `returnUrl` | `string` | Absolute HTTPS URL (max 2048 bytes) rendered as a return link in the portal. Vatly never fetches or auto-redirects to it. | The returned `PortalSession` has three properties: | Name | Type | Description | | ----------- | --------------- | ------------------------------------------------- | | `url` | `string` | Single-use HTTPS URL to redirect the customer to. | | `expiresAt` | `string` | Expiry of the one-time entry link (ISO 8601). | | `returnUrl` | `string | null` | The validated return URL you supplied, or `null`. | ```php $session = $vatly->customers->createPortalSession('customer_abc123', [ 'returnUrl' => 'https://yourapp.com/account/billing', ]); // Redirect the customer's browser to the hosted portal. header('Location: ' . $session->url); ``` The body is optional — omit it to create a session without a return link: ```php $session = $vatly->customers->createPortalSession('customer_abc123'); ``` # Checkouts Checkouts create hosted payment pages for your customers. When a checkout completes successfully, an Order is created. > **Authoritative field reference.** This page covers the common cases. The complete, canonical request/response schema — every accepted field, its type, and its validation rules — lives in the [OpenAPI spec](https://docs.vatly.com/openapi.yaml){rel=""nofollow""} (see the `Checkout`, `CheckoutProduct`, and `Money` schemas). When in doubt about what a field is named or whether it exists, trust the spec, not an example. ## The Checkout Resource Below you'll find all properties for the Vatly Checkout resource. ### Properties | Name | Type | Description | | --------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `id` | `string` | Unique identifier for the checkout (`checkout_...`). | | `resource` | `string` | Always `checkout`. | | `status` | `string` | The status of the checkout: `created`, `paid`, `canceled`, `failed`, or `expired`. | | `customerId` | `string | null` | The customer ID, or `null` when the checkout has no associated customer yet. | | `orderId` | `string | null` | Order ID (available after successful payment). | | `testmode` | `bool` | Whether this is a test checkout. | | `redirectUrlSuccess` | `string` | Success redirect URL. | | `redirectUrlCanceled` | `string` | Cancel redirect URL. | | `metadata` | `array` | Your custom metadata. | | `locale` | `string | null` | The language the hosted checkout is presented in (`en`, `de`, `fr`, `nl`, `es`, `it`, `pt`, `pl`), echoed back as the folded language. `null` means none was specified and the checkout picks a language from the shopper's browser. | | `expiresAt` | `string | null` | Expiration timestamp (ISO 8601). | | `createdAt` | `string` | Creation timestamp (ISO 8601). | | `links` | `CheckoutLinks` | Links to this checkout, the hosted checkout page (`checkoutUrl`) and the order (`null` until there is one). | --- ## Create a checkout `POST /v1/checkouts` Create a new hosted checkout for your customer. ### Required attributes | Name | Type | Description | | --------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------- | | `products` | `array` | An array of product items. See [Product items](https://docs.vatly.com/#product-items) below for the accepted per-item fields. | | `redirectUrlSuccess` | `string` | The URL to redirect after successful payment. | | `redirectUrlCanceled` | `string` | The URL to redirect if the customer cancels. | ### Optional attributes | Name | Type | Description | | ---------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `customerId` | `string` | Existing customer ID to associate with this checkout. | | `billingAddress` | `array` | Editable prefill for the billing address fields on the hosted checkout (`fullName`, `companyName`, `taxId`, `streetAndNumber`, `streetAdditional`, `city`, `region`, `postalCode`, `country`, `email`). A supplied `country` takes precedence over the shopper's IP address for determining their country. A supplied `taxId` is only a prefill, and is not registered until the buyer submits the checkout. | | `metadata` | `array` | Your custom metadata to store with the checkout. | | `locale` | `string` | Language to present the hosted checkout in — set this when you already know the customer's language. Accepts a bare language code (`de`), a BCP 47 tag (`de-AT`), or a POSIX/ISO 15897 locale (`de_DE`); all three fold to the language. Supported: `en`, `de`, `fr`, `nl`, `es`, `it`, `pt`, `pl` (anything else returns `422`). Omit (or `null`) to detect the language from the shopper's `Accept-Language` header, falling back to English. The response echoes back the folded language. | ```php $checkout = $vatly->checkouts->create([ 'products' => [ [ 'id' => 'subscription_plan_abc123', 'quantity' => 1, 'trialDays' => 14, ] ], 'redirectUrlSuccess' => 'https://yourapp.com/success', 'redirectUrlCanceled' => 'https://yourapp.com/canceled', 'customerId' => 'customer_xyz789', 'locale' => 'de', // optional; present the hosted checkout in German 'metadata' => [ 'user_id' => '12345', ], ]); echo $checkout->locale; // 'de' // Redirect to hosted checkout $checkoutUrl = $checkout->links->checkoutUrl->href; ``` If you want to provide your own idempotency key for this request, pass it in the optional second argument: ```php $checkout = $vatly->checkouts->create([ 'products' => [ [ 'id' => 'subscription_plan_abc123', 'quantity' => 1, ], ], 'redirectUrlSuccess' => 'https://yourapp.com/success', 'redirectUrlCanceled' => 'https://yourapp.com/canceled', ], [ 'idempotencyKey' => 'checkout-create-123', ]); ``` If you omit `idempotencyKey`, the SDK generates an `Idempotency-Key` header automatically. ### Product items Each entry in `products` references a product you have **already created in the [Vatly dashboard](https://my.vatly.com){rel=""nofollow""}** — there is no API endpoint to create products on the fly. The `id` is either a `one_off_product_…` or `subscription_plan_…` id. To charge an amount other than the product's dashboard price, set a `price` override (a `Money` object). For the full list of accepted item fields and their validation rules, see the `CheckoutProduct` schema in the [OpenAPI spec](https://docs.vatly.com/openapi.yaml){rel=""nofollow""}. ```php // Override the price of a pre-configured product at checkout time. $checkout = $vatly->checkouts->create([ 'products' => [ [ 'id' => 'one_off_product_Vr8kQdFhSrG4Y3DnfsdqH', 'quantity' => 2, 'price' => [ 'value' => '49.99', 'currency' => 'EUR', ], ], ], 'redirectUrlSuccess' => 'https://yourapp.com/success', 'redirectUrlCanceled' => 'https://yourapp.com/canceled', ]); ``` ```json { "id": "checkout_abc123", "status": "created", "merchantId": "merchant_xyz", "orderId": null, "testmode": false, "redirectUrlSuccess": "https://yourapp.com/success", "redirectUrlCanceled": "https://yourapp.com/canceled", "metadata": {"user_id": "12345"}, "createdAt": "2024-12-14T13:32:24.000Z", "_links": { "checkoutUrl": "https://pay.vatly.com/checkout_abc123" } } ``` --- ## Retrieve a checkout `GET /v1/checkouts/:id` Retrieve a checkout by its ID. ```php $checkout = $vatly->checkouts->get('checkout_abc123'); echo $checkout->id; echo $checkout->status; echo $checkout->links->checkoutUrl->href; if ($checkout->isPaid()) { $orderId = $checkout->orderId; } ``` --- ## List all checkouts `GET /v1/checkouts` Retrieve a paginated list of all your checkouts. ### Optional attributes | Name | Type | Description | | --------------- | --------- | ----------------------------------------------------------------- | | `startingAfter` | `string` | A cursor for pagination: return the page after this checkout ID. | | `endingBefore` | `string` | A cursor for pagination: return the page before this checkout ID. | | `limit` | `integer` | The number of checkouts to return (default: 10, max: 100). | ```php // Get all checkouts (paginated) $checkouts = $vatly->checkouts->page(); foreach ($checkouts as $checkout) { echo $checkout->id . ': ' . $checkout->status; } // Pass the cursors and limit in order: startingAfter, endingBefore, limit $checkouts = $vatly->checkouts->page('checkout_last_id', null, 25); ``` --- ## Checkout statuses | Status | Description | | ---------- | ------------------------------------ | | `created` | Checkout is active, awaiting payment | | `paid` | Payment successful, order created | | `canceled` | Customer canceled the checkout | | `failed` | Payment failed | | `expired` | Checkout expired without completion | --- ## Helper methods The Checkout object provides convenient helper methods. ```php $checkout->isCreated(); // true if status is 'created' $checkout->isPaid(); // true if status is 'paid' $checkout->isCanceled(); // true if status is 'canceled' $checkout->isFailed(); // true if status is 'failed' $checkout->isExpired(); // true if status is 'expired' ``` # Subscriptions Subscriptions are created automatically when a customer completes a checkout for a subscription plan. You can then manage the subscription lifecycle through the API. ## The Subscription Resource Below you'll find all properties for the Vatly Subscription resource. ### Properties | Name | Type | Description | | -------------------- | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier for the subscription (`subscription_...`). | | `resource` | `string` | Resource type, always `subscription`. | | `customerId` | `string` | ID of the customer who owns this subscription. | | `subscriptionPlanId` | `string` | ID of the subscription plan this subscription is based on. | | `testmode` | `bool` | Whether this subscription is in test mode. | | `name` | `string` | Name of the subscription (from the plan). | | `description` | `string` | Description of the subscription. | | `billingAddress` | `Address` | Customer's billing address for this subscription. | | `basePrice` | `Money` | Price per billing cycle before taxes. | | `quantity` | `int` | Number of subscription units (e.g. seats). | | `interval` | `string` | Billing interval unit: `day`, `week`, `month`, or `year`. | | `intervalCount` | `int` | Number of interval units between billing cycles. | | `status` | `string` | The subscription status (see [Subscription statuses](https://docs.vatly.com/#subscription-statuses)). | | `cancellationReason` | `string | null` | Why the subscription was canceled — `payment_failure` (recovery exhausted after failed renewals), `merchant_request`, or `customer_request` (self-service portal) — or `null` unless a cancellation has been requested. See `Vatly\API\Types\CancellationReason`. | | `startedAt` | `string` | When the subscription started (ISO 8601). | | `endedAt` | `string | null` | When the subscription ended (ISO 8601). | | `canceledAt` | `string | null` | When the subscription was canceled (ISO 8601). | | `renewedAt` | `string | null` | When the subscription was last renewed (ISO 8601). | | `renewedUntil` | `string | null` | Current billing period end date (ISO 8601). | | `nextRenewalAt` | `string | null` | When the next renewal will be attempted (ISO 8601). Null if canceled or ended. | | `trialUntil` | `string | null` | When the trial period ends (ISO 8601). Null if not in trial or trial has ended. | | `mandate` | `Mandate | null` | Payment method on file (`method`, `maskedIdentifier`). Null when the subscription has no mandate yet. | | `scheduledUpdate` | `ScheduledSubscriptionUpdate | null` | The target values for a change scheduled to take effect at the next billing cycle — set by an update with `applyImmediately: false` — or `null` when nothing is pending. A typed [`ScheduledSubscriptionUpdate`](https://github.com/Vatly/vatly-api-php/blob/main/src/API/Types/ScheduledSubscriptionUpdate.php){rel=""nofollow""} carrying `subscriptionPlanId`, `name`, `description`, `basePrice` (`Money`), `quantity`, `interval`, `intervalCount`, and `effectiveAt` (next-renewal date the change applies, nullable). Always present on both the REST resource and webhook deliveries, so this is the authoritative way to reconcile a pending change. | | `links` | `SubscriptionLinks` | HATEOAS links to related resources (`self`, `customer`). | --- ## Retrieve a subscription `GET /v1/subscriptions/:id` Retrieve a subscription by its ID. ```php $subscription = $vatly->subscriptions->get('subscription_abc123'); echo $subscription->status; echo $subscription->subscriptionPlanId; if ($subscription->isActive()) { echo 'Subscription is active'; } ``` --- ## List all subscriptions `GET /v1/subscriptions` Retrieve a paginated list of all subscriptions. ### Optional attributes | Name | Type | Description | | --------------- | --------- | --------------------------------------------------------------------- | | `startingAfter` | `string` | A cursor for pagination: return the page after this subscription ID. | | `endingBefore` | `string` | A cursor for pagination: return the page before this subscription ID. | | `limit` | `integer` | The number of subscriptions to return (default: 10, max: 100). | ```php $subscriptions = $vatly->subscriptions->page(); foreach ($subscriptions as $subscription) { echo $subscription->id . ': ' . $subscription->status; } // Pass the cursors and limit in order: startingAfter, endingBefore, limit $subscriptions = $vatly->subscriptions->page('subscription_last_id', null, 25); // One customer's subscriptions (GET /v1/customers/:customerId/subscriptions) $subscriptions = $vatly->customerSubscriptions->pageForCustomerId('customer_abc123'); ``` --- ## Update a subscription `PATCH /v1/subscriptions/:id` Change a subscription's plan, quantity and/or price. **At least one of `subscriptionPlanId`, `quantity`, or `price` is required.** ### Optional attributes | Name | Type | Description | | -------------------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `subscriptionPlanId` | `string` | Switch to a new plan (`subscription_plan_...`). Must match the subscription's testmode. | | `quantity` | `int` | The **new total** quantity (e.g. number of seats). This sets the quantity to the given value — it is not added to the current quantity. | | `price` | `array` | Override the recurring price: `['value' => '99.99', 'currency' => 'EUR']`. The `currency` must match the subscription's currency. Provide `price` alone to change the price in place, or combine it with `subscriptionPlanId` to switch plans at a custom price (overriding the new plan's default). | | `prorate` | `bool` | How an immediate change is priced (default `true`). `true` charges the new price for the time left on the cycle, minus a credit for the old price over that same time. `false` charges the full new price for the current cycle on top of what was already paid. **`false` does not skip the charge:** use `prorationCharge` for that. Ignored when `prorationCharge` is `false`. | | `prorationCharge` | `bool` | Whether an immediate change is charged at all (default `true`). With `false`, the change applies now and nothing is charged for it: a downgrade gets no credit. The next renewal bills the new price, unless a change is already scheduled for that renewal: that change still applies. During a trial, the trial keeps running and its end bills the new plan. Sending `invoiceImmediately: true`, `anchor`, `resetAnchor`, `trialUntil` or a plan with a different interval with `false` returns `422`. | | `applyImmediately` | `bool` | Apply the change now (`true`) or at the end of the current period (`false`, default). | | `invoiceImmediately` | `bool` | Invoice and charge the proration now instead of on the next renewal. Only applies when `applyImmediately` and `prorate` are both `true`. The proration order is created and charged asynchronously, typically within 15 to 30 minutes, so `update()` does not return it. Vatly waits briefly so that other charges for the same customer made around the same time are combined into one order and one payment instead of several. Follow the `order.paid` webhook (or `order.payment_failed`), whose order line has `relatedResources->subscriptionId` set to the subscription. In test mode, settle or decline its pending payment with `$vatly->testHelpers->simulateOrderPayment()`. Defaults to `false`, which parks the proration delta on the current cycle and bills it as a line on the next renewal invoice (and waives it if the subscription is cancelled first). **Set this to `true` on yearly and other long-interval plans**, where the deferral to the next renewal costs you the most. | | `anchor` | `string | null` | Set the billing anchor to a specific date (`YYYY-MM-DD`, UTC). Cannot be combined with `resetAnchor`. | | `resetAnchor` | `bool` | Reset the billing anchor to now. Cannot be combined with `anchor`. | | `trialUntil` | `string | null` | Extend or set a trial until this date (ISO 8601). Cannot be combined with `anchor`. | ```php // Change the quantity (new total) and pass a custom idempotency key. $subscription = $vatly->subscriptions->update('subscription_123', [ 'quantity' => 2, ], [ 'idempotencyKey' => 'subscription-update-123', ]); // Switch plan at a custom price (currency must match the subscription). $subscription = $vatly->subscriptions->update('subscription_123', [ 'subscriptionPlanId' => 'subscription_plan_Wt5mNvBxKw7YcZaEjLhR', 'price' => ['value' => '99.99', 'currency' => 'EUR'], 'applyImmediately' => true, ]); // Switch plan now without charging for the change. The next renewal bills the new price. $subscription = $vatly->subscriptions->update('subscription_123', [ 'subscriptionPlanId' => 'subscription_plan_Wt5mNvBxKw7YcZaEjLhR', 'applyImmediately' => true, 'prorationCharge' => false, ]); ``` If you already have a `Subscription` resource instance, set the key on the client before calling the resource method: ```php $vatly->setIdempotencyKey('subscription-update-123'); $subscription->update([ 'quantity' => 2, ]); ``` If you do not provide a custom key, the SDK generates one automatically for the `PATCH` request. --- ## Cancel a subscription `DELETE /v1/subscriptions/:id` Cancel a subscription. The subscription will remain active until the end of the current billing period. ```php $subscription = $vatly->subscriptions->cancel('subscription_abc123'); // Subscription is now on grace period until current period ends echo $subscription->status; // 'on_grace_period' echo $subscription->renewedUntil; // Current billing period end ``` --- ## Resume a subscription `POST /v1/subscriptions/:id/resume` Reverse a pending cancellation while the subscription is still on its grace period. Once a subscription has fully ended it cannot be resumed. ```php $subscription = $vatly->subscriptions->resume('subscription_abc123'); echo $subscription->status; // 'active' ``` If you already have a `Subscription` resource instance: ```php $subscription->resume(); ``` --- ## Subscription statuses | Status | Description | | ----------------- | --------------------------------------------------------------- | | `active` | Subscription is active and will renew | | `created` | Subscription has been created but not yet started | | `trial` | Subscription is in trial period | | `on_grace_period` | Subscription is canceled but still active until the period ends | | `paused` | Subscription is temporarily paused | | `canceled` | Subscription has been canceled | --- ## Helper methods The Subscription object provides convenient helper methods. ```php $subscription->isActive(); // true if status is 'active' $subscription->isTrial(); // true if status is 'trial' $subscription->isOnGracePeriod(); // true if status is 'on_grace_period' $subscription->isCanceled(); // true if status is 'canceled' ``` # Subscription Plans Subscription plans define recurring billing products. Create them in the Vatly dashboard or through the API, then use them in checkouts. Live plans are reviewed and approved by Vatly before they can be added to checkouts. ## The Subscription Plan Resource Below you'll find all properties for the Vatly Subscription Plan resource. ### Properties | Name | Type | Description | | ---------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier for the plan (`subscription_plan_...`). | | `name` | `string` | Display name of the plan. | | `description` | `string | null` | Description of the plan. | | `basePrice` | `Money` | Price per interval as a `Money` object — read `->value` (decimal string) and `->currency` (ISO 4217 code). | | `taxBehavior` | `string` | Whether `basePrice` is tax-`exclusive` (B2B) or tax-`inclusive` (B2C). Immutable after creation. See `Vatly\API\Types\TaxBehavior`. | | `interval` | `string` | Billing interval: `day`, `week`, `month`, or `year`. | | `intervalCount` | `integer` | Number of intervals between billings. | | `productType` | `string` | Tax classification. Always `saas` for plans. | | `testmode` | `bool` | Whether this is a test plan. | | `status` | `string` | The status: `active` (subscribable), `pending` (awaiting approval), or `rejected`. | | `archivedAt` | `string | null` | When the plan was archived (ISO 8601), or `null` while it is open to new business. Use `$plan->isArchived()` for a boolean. | | `pendingUpdates` | `object | null` | The changes that will take effect once a submitted update is approved, or `null` when there is none. Only the fields that differ from the live plan are present. | | `updateStatus` | `string | null` | Lifecycle of a pending update: `pending`, `reviewing`, or `null`. See `Vatly\API\Types\UpdateStatus`. | | `createdAt` | `string` | Creation timestamp (ISO 8601). | --- ## Create a plan `POST /v1/subscription-plans` Create a subscription plan. A plan created with a `live_` token starts in `pending` status and must be approved by Vatly before it can be added to checkouts; a plan created with a `test_` token is auto-approved (`active`). ### Required attributes | Name | Type | Description | | --------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------ | | `name` | `string` | Display name (3–255 characters). | | `description` | `string` | Detailed description of the plan. | | `basePrice` | `array` | Price per interval as `['value' => '29.00', 'currency' => 'EUR']`. | | `productType` | `string` | Tax classification. Only `saas` is billable on a recurring basis. | | `interval` | `string` | Billing interval unit. `day` is sandbox-only; live plans support `week`, `month`, `year`. | | `intervalCount` | `integer` | Interval units between billings (≤ 365 days / 52 weeks / 12 months). For `year`, billing is always annual and this is ignored. | ### Optional attributes | Name | Type | Description | | ------------- | -------- | --------------------------------------------------------------- | | `taxBehavior` | `string` | `exclusive` (default) or `inclusive`. Immutable after creation. | ```php $plan = $vatly->subscriptionPlans->create([ 'name' => 'Pro Monthly', 'description' => 'Full access to all Pro features, billed monthly', 'basePrice' => ['value' => '29.00', 'currency' => 'EUR'], 'productType' => 'saas', 'interval' => 'month', 'intervalCount' => 1, 'taxBehavior' => 'exclusive', // optional; defaults to 'exclusive' ]); echo $plan->id; // subscription_plan_... echo $plan->status; // 'pending' (live) or 'active' (test) ``` --- ## Update a plan `PATCH /v1/subscription-plans/:id` Submit an update to a live plan. Each request is the **complete set of changes** relative to the current live plan and must contain at least one field. In live mode the change is held as a pending update and reviewed by Vatly before it takes effect (`updateStatus` moves `pending` → `reviewing` → applied); in test mode it is approved automatically. A request that nets to no change clears any pending update; while an update is being reviewed, further requests return `409`. The `interval` cannot be changed once the plan has ever been used by a subscription (active or not) — that returns `409`. The price stays changeable. ### Optional attributes | Name | Type | Description | | --------------- | --------- | --------------------------------------------------------------------- | | `name` | `string` | New display name (3–255 characters). | | `description` | `string` | New description. | | `basePrice` | `array` | New price per interval as `['value' => '9.00', 'currency' => 'EUR']`. | | `interval` | `string` | New billing interval. Requires `intervalCount`. | | `intervalCount` | `integer` | Required when `interval` is provided. | | `productType` | `string` | `saas`. | ```php $plan = $vatly->subscriptionPlans->update('subscription_plan_abc123', [ 'name' => 'Pro Weekly', 'basePrice' => ['value' => '9.00', 'currency' => 'EUR'], 'interval' => 'week', 'intervalCount' => 1, ]); echo $plan->updateStatus; // 'pending' echo $plan->pendingUpdates->interval; // 'week' ``` --- ## Archive a plan `POST /v1/subscription-plans/:id/archive` Close a plan to new business. It is hidden from list calls (unless `includeArchived=true`), refused by new checkouts, and can no longer be switched to from a subscription update. Subscribers already on the plan are deliberately untouched — a subscription snapshots its plan at signup and renews off that snapshot, so archiving never cancels anyone or changes what they are billed. Nothing is deleted; the plan keeps a non-null `archivedAt`. The call returns no content. ```php $vatly->subscriptionPlans->archive('subscription_plan_abc123'); // or, on a resource you already hold: $plan->archive(); ``` --- ## Unarchive a plan `DELETE /v1/subscription-plans/:id/archive` Re-open an archived plan to new business. It reappears in listings and can be added to checkouts and switched to again. Returns the plan, now open to new business (`archivedAt` is `null`). ```php $plan = $vatly->subscriptionPlans->unarchive('subscription_plan_abc123'); ``` --- ## Retrieve a plan `GET /v1/subscription-plans/:id` Retrieve a subscription plan by its ID. ```php $plan = $vatly->subscriptionPlans->get('subscription_plan_abc123'); echo $plan->name; echo $plan->basePrice->value . ' ' . $plan->basePrice->currency; echo $plan->interval; ``` --- ## List all plans `GET /v1/subscription-plans` Retrieve a paginated list of all subscription plans. ### Optional attributes | Name | Type | Description | | ----------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `limit` | `integer` | The number of plans to return (default: 10, max: 100). | | `startingAfter` | `string` | A cursor for pagination. | | `includeArchived` | `boolean` | Include archived plans in the list. Archived plans are hidden by default; pass `true` to see them (tell them apart by the non-null `archivedAt`). | ```php $plans = $vatly->subscriptionPlans->page(); foreach ($plans as $plan) { echo $plan->name . ': ' . $plan->basePrice->value . ' ' . $plan->basePrice->currency; } // Include archived plans in the listing: $all = $vatly->subscriptionPlans->page(null, null, null, ['includeArchived' => true]); ``` # Orders Orders are created automatically when a checkout completes successfully or when a subscription renews. ## The Order Resource Below you'll find all properties for the Vatly Order resource. ### Properties | Name | Type | Description | | -------------------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier for the order (`order_...`). | | `resource` | `string` | Always `order`. | | `customerId` | `string | null` | The customer ID, or `null` for orders with no associated customer. | | `status` | `string` | The order status (see [Order statuses](https://docs.vatly.com/#order-statuses)). | | `cancellationReason` | `string | null` | Why the order was canceled: `payment_failure` when payment recovery for this unpaid order was exhausted. `null` unless the status is `canceled`, and `null` for orders canceled before this field existed. | | `total` | `Money` | Total amount including taxes. | | `subtotal` | `Money` | Subtotal amount before taxes. | | `reversedSubtotal` | `Money` | Amount of the captured payment returned to the customer, before taxes, via refund or chargeback (settled). | | `refundableSubtotal` | `Money` | Remaining amount that can still be refunded, before taxes. | | `taxSummary` | `TaxSummaryCollection` | Tax breakdown by rate. | | `lines` | `array` | The order lines. Use `$order->lines()` for a collection of `OrderLine` objects. | | `customerDetails` | `Address` | Customer billing details. | | `paymentMethod` | `string | null` | The payment method used, for example `ideal` or `creditcard`. | | `invoiceNumber` | `string | null` | The invoice number, assigned after payment. | | `testmode` | `bool` | Whether this is a test order. | | `metadata` | `array` | Your custom metadata. | | `createdAt` | `string` | Creation timestamp (ISO 8601). | | `links` | `OrderLinks` | Links to this order, the customer (`null` for orders with no associated customer) and the customer invoice. The `customerInvoice` URL is signed and expires after 72 hours (the customer then sees a page to request a new link). | ### Order line properties | Name | Type | Description | | ---------------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `id` | `string` | Unique identifier for the order line. | | `description` | `string` | Line description. | | `quantity` | `int` | Quantity. On a subscription line this is the quantity of one subscription, not a count of subscriptions. | | `basePrice` | `Money` | Price per unit before taxes. | | `total` | `Money` | Line total including taxes. | | `subtotal` | `Money` | Line subtotal before taxes. | | `taxes` | `TaxSummaryCollection` | Tax breakdown for this line. | | `productType` | `string | null` | The linked resource type: `subscription_plan` on an initial subscription signup line, `subscription` on a renewal or immediate-update line, `one_off_product` for a one-off product. `null` when the line has no product link. | | `productId` | `string | null` | The linked resource's ID: a plan ID for `subscription_plan`, a subscription ID for `subscription`. | | `relatedResources` | `OrderLineRelatedResources | null` | Additional relationships for this line. `null` on historical lines and on lines unrelated to a subscription. | | `relatedResources->subscriptionId` | `string | null` | The subscription this line belongs to, on signup, renewal and immediate-update lines alike. `null` on a signup line while the subscription is not available yet; retrieve the order again later to read it. | To find the subscription a paid checkout created, follow the checkout's `orderId` and read the lines' `relatedResources`: ```php $order = $vatly->orders->get($checkout->orderId); foreach ($order->lines() as $line) { $subscriptionId = $line->relatedResources?->subscriptionId; } ``` A subscription ID alone does not mean the subscription is active. Check the subscription's status before granting access. --- ## Retrieve an order `GET /v1/orders/:id` Retrieve an order by its ID. ```php $order = $vatly->orders->get('order_abc123'); echo $order->status; echo $order->total->value . ' ' . $order->total->currency; if ($order->isPaid()) { echo 'Invoice: ' . $order->invoiceNumber; } if ($order->isCanceled()) { echo 'Canceled because: ' . ($order->cancellationReason ?? 'unknown'); } ``` --- ## List all orders `GET /v1/orders` Retrieve a paginated list of all orders. ### Optional attributes | Name | Type | Description | | --------------- | --------- | -------------------------------------------------------------- | | `startingAfter` | `string` | A cursor for pagination: return the page after this order ID. | | `endingBefore` | `string` | A cursor for pagination: return the page before this order ID. | | `limit` | `integer` | The number of orders to return (default: 10, max: 100). | ```php $orders = $vatly->orders->page(); foreach ($orders as $order) { echo $order->id . ': ' . $order->total->value . ' ' . $order->total->currency; } // Pass the cursors and limit in order: startingAfter, endingBefore, limit $orders = $vatly->orders->page('order_abc123', null, 25); ``` --- ## Order statuses | Status | Description | | ---------- | --------------------------- | | `created` | Order has just been created | | `pending` | Payment is being processed | | `paid` | Payment successful | | `canceled` | Order has been canceled | | `expired` | Order has expired | A failed payment does not change the order to a status of its own. You receive the `order.payment_failed` webhook while Vatly tries to recover the payment. If recovery is exhausted, the order is `canceled` with `cancellationReason: payment_failure`, and you receive `order.canceled`. --- ## Helper methods The Order object provides convenient helper methods. ```php $order->isCreated(); // true if status is 'created' $order->isPending(); // true if status is 'pending' $order->isPaid(); // true if status is 'paid' $order->isCanceled(); // true if status is 'canceled' $order->isExpired(); // true if status is 'expired' $order->isReversed(); // true if any of the payment was returned to the customer $order->isPartiallyReversed(); // true if some, but not all, of the payment was returned $order->isFullyReversed(); // true if the full payment was returned ``` # One-Off Products One-off products are single-purchase items (not recurring subscriptions). Create them in the Vatly dashboard or through the API, then use them in checkouts. Live products are reviewed and approved by Vatly before they can be added to checkouts. ## The One-Off Product Resource Below you'll find all properties for the Vatly One-Off Product resource. ### Properties | Name | Type | Description | | ---------------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier for the product (`one_off_product_...`). | | `name` | `string` | Display name of the product. | | `description` | `string | null` | Description of the product. | | `basePrice` | `Money` | The price as a `Money` object — read `->value` (decimal string) and `->currency` (ISO 4217 code). | | `taxBehavior` | `string` | Whether `basePrice` is tax-`exclusive` (B2B; tax added at checkout) or tax-`inclusive` (B2C; price already includes tax). Immutable after creation. See `Vatly\API\Types\TaxBehavior`. | | `productType` | `string` | Tax classification: `saas` or `ebook`. | | `testmode` | `bool` | Whether this is a test product. | | `status` | `string` | The status: `active` (purchasable), `pending` (awaiting approval), or `rejected`. | | `archivedAt` | `string | null` | When the product was archived (ISO 8601), or `null` while it is on sale. Use `$product->isArchived()` for a boolean. | | `pendingUpdates` | `object | null` | The changes that will take effect once a submitted update is approved, or `null` when there is none. Only the fields that differ from the live product are present. | | `updateStatus` | `string | null` | Lifecycle of a pending update: `pending`, `reviewing`, or `null`. See `Vatly\API\Types\UpdateStatus`. | | `createdAt` | `string` | Creation timestamp (ISO 8601). | --- ## Create a product `POST /v1/one-off-products` Create a one-off product. A product created with a `live_` token starts in `pending` status and must be approved by Vatly before it can be added to checkouts; a product created with a `test_` token is auto-approved (`active`) so you can trial checkout immediately. ### Required attributes | Name | Type | Description | | ------------- | -------- | ------------------------------------------------------ | | `name` | `string` | Display name (3–255 characters). | | `description` | `string` | Detailed description of the product. | | `basePrice` | `array` | Price as `['value' => '299.00', 'currency' => 'EUR']`. | | `productType` | `string` | Tax classification: `saas` or `ebook`. | ### Optional attributes | Name | Type | Description | | ------------- | -------- | --------------------------------------------------------------- | | `taxBehavior` | `string` | `exclusive` (default) or `inclusive`. Immutable after creation. | ```php $product = $vatly->oneOffProducts->create([ 'name' => 'Premium License', 'description' => 'Lifetime access to all premium features', 'basePrice' => ['value' => '299.00', 'currency' => 'EUR'], 'productType' => 'saas', 'taxBehavior' => 'exclusive', // optional; defaults to 'exclusive' ]); echo $product->id; // one_off_product_... echo $product->status; // 'pending' (live) or 'active' (test) ``` --- ## Update a product `PATCH /v1/one-off-products/:id` Submit an update to a live product. Each request is the **complete set of changes** relative to the current live product and must contain at least one field. In live mode the change is held as a pending update and reviewed by Vatly before it takes effect (`updateStatus` moves `pending` → `reviewing` → applied); in test mode it is approved automatically. A request that nets to no change clears any pending update; while an update is being reviewed, further requests return `409`. The returned product carries `pendingUpdates` and `updateStatus`. ### Optional attributes | Name | Type | Description | | ------------- | -------- | ---------------------------------------------------------- | | `name` | `string` | New display name (3–255 characters). | | `description` | `string` | New description. | | `basePrice` | `array` | New price as `['value' => '349.00', 'currency' => 'EUR']`. | | `productType` | `string` | `saas` or `ebook`. | ```php $product = $vatly->oneOffProducts->update('one_off_product_abc123', [ 'name' => 'Premium License v2', 'basePrice' => ['value' => '349.00', 'currency' => 'EUR'], ]); echo $product->updateStatus; // 'pending' echo $product->pendingUpdates->basePrice->value; // '349.00' ``` --- ## Archive a product `POST /v1/one-off-products/:id/archive` Archive the product so it can no longer be sold. It is hidden from list calls (unless `includeArchived=true`) and refused by new checkouts; existing orders and refunds are untouched. Nothing is deleted — the product remains readable by id, now carrying a non-null `archivedAt`. The call returns no content. ```php $vatly->oneOffProducts->archive('one_off_product_abc123'); // or, on a resource you already hold: $product->archive(); ``` --- ## Unarchive a product `DELETE /v1/one-off-products/:id/archive` Put an archived product back on sale. It reappears in listings and can be added to checkouts again. Returns the product, now on sale (`archivedAt` is `null`). ```php $product = $vatly->oneOffProducts->unarchive('one_off_product_abc123'); echo $product->isArchived() ? 'archived' : 'on sale'; // on sale ``` --- ## Retrieve a product `GET /v1/one-off-products/:id` Retrieve a one-off product by its ID. ```php $product = $vatly->oneOffProducts->get('one_off_product_abc123'); echo $product->name; echo $product->basePrice->value . ' ' . $product->basePrice->currency; ``` --- ## List all products `GET /v1/one-off-products` Retrieve a paginated list of all one-off products. ### Optional attributes | Name | Type | Description | | ----------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | `limit` | `integer` | The number of products to return (default: 10, max: 100). | | `startingAfter` | `string` | A cursor for pagination. | | `includeArchived` | `boolean` | Include archived products in the list. Archived products are hidden by default; pass `true` to see them (tell them apart by the non-null `archivedAt`). | ```php $products = $vatly->oneOffProducts->page(); foreach ($products as $product) { echo $product->name . ': ' . $product->basePrice->value . ' ' . $product->basePrice->currency; } // Include archived products in the listing: $all = $vatly->oneOffProducts->page(null, null, null, ['includeArchived' => true]); ``` # Refunds Refunds allow you to return money to your customers for orders. ## The Refund Resource Below you'll find all properties for the Vatly Refund resource. ### Properties | Name | Type | Description | | ----------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier for the refund (`refund_...`). | | `resource` | `string` | Always `refund`. | | `status` | `string` | The refund status (see [Refund statuses](https://docs.vatly.com/#refund-statuses)). | | `customerId` | `string` | ID of the customer who receives the refund. | | `originalOrderId` | `string` | The ID of the order being refunded. | | `orderId` | `string | null` | The credit note order ID, `null` until the refund is processed. | | `total` | `Money` | Total amount including taxes. | | `subtotal` | `Money` | Subtotal amount before taxes. | | `taxSummary` | `TaxSummaryCollection` | Tax breakdown by rate. | | `lines` | `array` | The refund lines. Use `$refund->lines()` for a collection of `RefundLine` objects. | | `testmode` | `bool` | Whether this is a test refund. | | `createdAt` | `string` | Creation timestamp (ISO 8601). | | `links` | `RefundLinks` | Links to this refund, the original order, the credit note order (`null` until there is one) and `customerInvoice`, the customer-portal page of the refund's credit note (`null` until the refund is processed). The `customerInvoice` URL is signed and expires after 72 hours (the customer then sees a page to request a new link). | --- ## Create a partial refund `POST /v1/orders/:orderId/refunds` Refund part of an order, line by line. ### Required attributes | Name | Type | Description | | ------- | ------- | ------------------------------------------------------------------------------------------ | | `items` | `array` | The order lines to refund. See [Refund items](https://docs.vatly.com/#refund-items) below. | ### Optional attributes | Name | Type | Description | | ---------- | ------- | --------------------- | | `metadata` | `array` | Your custom metadata. | ### Refund items | Name | Type | Required | Description | | --------------------------- | --------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | `itemId` | `string` | Yes | The ID of the order line to refund. | | `amount` | `array` | Yes | Amount to refund for this line before taxes: `['value' => '10.00', 'currency' => 'EUR']`. Cannot exceed what is left to refund for the line. | | `description` | `string | null` | No | Custom description for this refund line. | | `descriptionAdditionalLine` | `string | null` | No | Additional description line. | ```php $refund = $vatly->orderRefunds->createForOrderId('order_abc123', [ 'items' => [ [ 'itemId' => 'order_item_abc123', 'amount' => ['value' => '10.00', 'currency' => 'EUR'], 'description' => 'Partial refund', ], ], ]); echo $refund->id; echo $refund->status; ``` --- ## Create a full refund `POST /v1/orders/:orderId/refunds/full` Refund everything that can still be refunded on an order. ### Optional attributes | Name | Type | Description | | ---------- | ------- | --------------------- | | `metadata` | `array` | Your custom metadata. | ```php $refund = $vatly->orderRefunds->createFullRefundForOrderId('order_abc123', []); // Or from an order you already fetched $refund = $order->fullRefund([]); ``` --- ## Retrieve a refund `GET /v1/refunds/:id` Retrieve a refund by its ID. ```php $refund = $vatly->refunds->get('refund_abc123'); echo $refund->status; echo $refund->total->value . ' ' . $refund->total->currency; ``` --- ## List all refunds `GET /v1/refunds` Retrieve a paginated list of all refunds. ### Optional attributes | Name | Type | Description | | --------------- | --------- | --------------------------------------------------------------- | | `startingAfter` | `string` | A cursor for pagination: return the page after this refund ID. | | `endingBefore` | `string` | A cursor for pagination: return the page before this refund ID. | | `limit` | `integer` | The number of refunds to return (default: 10, max: 100). | ```php $refunds = $vatly->refunds->page(); foreach ($refunds as $refund) { echo $refund->id . ': ' . $refund->status; } // Pass the cursors and limit in order: startingAfter, endingBefore, limit $refunds = $vatly->refunds->page('refund_last_id', null, 25); // One order's refunds (GET /v1/orders/:orderId/refunds) $refunds = $vatly->orderRefunds->pageForOrderId('order_abc123'); ``` --- ## Cancel a refund `DELETE /v1/orders/:orderId/refunds/:refundId` Cancel a refund that has not been processed yet. Once it is `processing`, cancellation is no longer possible. ```php $vatly->orderRefunds->cancelRefundForOrderId('order_abc123', 'refund_abc123'); // Or from a refund you already fetched $refund->cancel(); ``` --- ## Refund statuses | Status | Description | | ------------ | -------------------------------------------------------------- | | `pending` | Refund is ready to be sent to the bank | | `queued` | Refund is queued due to a lack of balance | | `processing` | Refund is being processed (cancellation is no longer possible) | | `refunded` | Refund has been processed successfully | | `failed` | Refund failed after processing | | `canceled` | Refund was canceled | The Refund object has no status helper methods. Compare `$refund->status` against the `Vatly\API\Types\RefundStatus` constants: ```php use Vatly\API\Types\RefundStatus; if ($refund->status === RefundStatus::REFUNDED) { // The money is on its way back to the customer } ``` # Chargebacks Chargebacks occur when a customer disputes a payment with their bank. Vatly notifies you via webhooks when chargebacks happen. ## The Chargeback Resource Below you'll find all properties for the Vatly Chargeback resource. ### Properties | Name | Type | Description | | ------------------ | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier for the chargeback (`chargeback_...`). | | `resource` | `string` | Always `chargeback`. | | `customerId` | `string` | ID of the customer who disputed the payment. | | `testmode` | `bool` | Whether this is a test chargeback. | | `status` | `string` | The dispute status (see [Chargeback statuses](https://docs.vatly.com/#chargeback-statuses)). | | `amount` | `Money` | Amount of the chargeback. | | `settlementAmount` | `Money` | Amount deducted from settlement (may differ from `amount` due to currency conversion or fees). | | `total` | `Money` | Total amount including taxes. | | `subtotal` | `Money` | Subtotal amount before taxes. | | `taxSummary` | `TaxSummaryCollection` | Tax breakdown by rate. | | `reason` | `string` | Reason code for the dispute (e.g. `fraud`, `product_not_received`, `duplicate`). | | `originalOrderId` | `string` | The ID of the original order that was disputed. | | `orderId` | `string | null` | The credit note order ID, `null` until the chargeback is processed. | | `createdAt` | `string` | Creation timestamp (ISO 8601). | | `links` | `ChargebackLinks` | Links to this chargeback, the original order, the credit note order (`null` until there is one) and `customerInvoice`, the customer-portal page of the chargeback's credit note (`null` until the chargeback is lost). The `customerInvoice` URL is signed and expires after 72 hours (the customer then sees a page to request a new link). | --- ## Retrieve a chargeback `GET /v1/chargebacks/:id` Retrieve a chargeback by its ID. ```php $chargeback = $vatly->chargebacks->get('chargeback_abc123'); echo $chargeback->reason; echo $chargeback->amount->value . ' ' . $chargeback->amount->currency; echo $chargeback->originalOrderId; ``` --- ## List all chargebacks `GET /v1/chargebacks` Retrieve a paginated list of all chargebacks. ### Optional attributes | Name | Type | Description | | --------------- | --------- | ------------------------------------------------------------------- | | `startingAfter` | `string` | A cursor for pagination: return the page after this chargeback ID. | | `endingBefore` | `string` | A cursor for pagination: return the page before this chargeback ID. | | `limit` | `integer` | The number of chargebacks to return (default: 10, max: 100). | ```php $chargebacks = $vatly->chargebacks->page(); foreach ($chargebacks as $chargeback) { echo $chargeback->id . ': ' . $chargeback->reason; } // Pass the cursors and limit in order: startingAfter, endingBefore, limit $chargebacks = $vatly->chargebacks->page('chargeback_last_id', null, 25); ``` --- ## Chargeback statuses | Status | Description | | ------------------------ | ------------------------------------------------------------------------------------ | | `pending` | Dispute received, awaiting action | | `requires_amount_review` | The disputed amount exceeds the original order, so completion is held pending review | | `accepted` | The dispute was accepted | | `rejected` | The dispute was rejected | | `evidence_submitted` | Evidence submitted, awaiting a decision | | `won` | Dispute resolved in the merchant's favor | | `lost` | Dispute resolved in the customer's favor | # Webhooks Vatly sends webhooks to notify your application when events happen — for example, an order being paid, a refund completing, or a subscription being canceled. ## Webhook events The `eventName` field on a delivery identifies what happened. See [`Vatly\API\Types\WebhookEventName`](https://github.com/Vatly/vatly-api-php/blob/main/src/API/Types/WebhookEventName.php){rel=""nofollow""} for the constants. | Event | Description | | -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `order.paid` | Order payment was successful. | | `order.canceled` | Order was canceled. `object` carries `cancellationReason`: `payment_failure` when payment recovery for the unpaid order was exhausted, otherwise `null`. | | `order.chargeback_received` | Chargeback was received for an order. | | `order.chargeback_reversed` | Chargeback was reversed. | | `order.payment_failed` | A payment failed and the order entered payment recovery (dunning); sent once per failed order. | | `refund.completed` | Refund was processed successfully. | | `refund.failed` | Refund processing failed. | | `refund.canceled` | Refund was canceled. | | `subscription.started` | Subscription was started. | | `subscription.canceled_immediately` | Subscription was canceled immediately. `object` carries `cancellationReason` (typically `merchant_request`). | | `subscription.canceled_for_nonpayment` | Payment recovery was exhausted, so the subscription was canceled. `object` carries `cancellationReason: payment_failure`. | | `subscription.canceled_with_grace_period` | Subscription was canceled, customer keeps access until the period ends. `object` carries `cancellationReason` (`customer_request` or `merchant_request`). | | `subscription.cancellation_grace_period_completed` | Grace period after cancellation ended. | | `subscription.resumed` | A canceled subscription was resumed during its grace period. | | `subscription.updated` | A subscription changed immediately (plan, price, interval or quantity). `object` is the subscription with its new values. | | `subscription.update_scheduled` | A change was scheduled for the next billing cycle. `object` is the subscription's current state; the target values are in `object.scheduledUpdate` (`subscriptionPlanId`, `name`, `description`, `basePrice`, `quantity`, `interval`, `intervalCount`, `effectiveAt`). | | `checkout.paid` | Checkout was paid successfully. | | `checkout.failed` | Checkout payment failed. | | `checkout.canceled` | Checkout was canceled. | | `checkout.expired` | Checkout session expired. | | `one_off_product.update_submitted` | An update to a one-off product was submitted for review. | | `one_off_product.update_approved` | A submitted one-off product update was approved and applied. | | `one_off_product.update_rejected` | A submitted one-off product update was rejected. | | `one_off_product.archived` | A one-off product was archived (it can no longer be sold). | | `one_off_product.unarchived` | An archived one-off product was put back on sale. | | `subscription_plan.update_submitted` | An update to a subscription plan was submitted for review. | | `subscription_plan.update_approved` | A submitted subscription plan update was approved and applied. | | `subscription_plan.update_rejected` | A submitted subscription plan update was rejected. | | `subscription_plan.archived` | A subscription plan was archived (closed to new business). | | `subscription_plan.unarchived` | An archived subscription plan was re-opened to new business. | | `webhook.setup` | Verification call sent when an endpoint is registered or its URL is updated. `entityType` is `webhook`; `object` is the (secret-free) endpoint config. | The ten product events (`one_off_product.*` and `subscription_plan.*`) ship dedicated typed event DTOs, just like the order/subscription/refund/checkout events. `WebhookEventFactory` hydrates each one's `object` — byte-identical to the corresponding `GET` body — straight into the matching resource, with **no follow-up API call**: | Event | Typed DTO | Hydrated resource | | ------------------------------------ | --------------------------------- | ----------------------------------------------- | | `one_off_product.update_submitted` | `OneOffProductUpdateSubmitted` | `$event->oneOffProduct` (`OneOffProduct`) | | `one_off_product.update_approved` | `OneOffProductUpdateApproved` | `$event->oneOffProduct` | | `one_off_product.update_rejected` | `OneOffProductUpdateRejected` | `$event->oneOffProduct` | | `one_off_product.archived` | `OneOffProductArchived` | `$event->oneOffProduct` | | `one_off_product.unarchived` | `OneOffProductUnarchived` | `$event->oneOffProduct` | | `subscription_plan.update_submitted` | `SubscriptionPlanUpdateSubmitted` | `$event->subscriptionPlan` (`SubscriptionPlan`) | | `subscription_plan.update_approved` | `SubscriptionPlanUpdateApproved` | `$event->subscriptionPlan` | | `subscription_plan.update_rejected` | `SubscriptionPlanUpdateRejected` | `$event->subscriptionPlan` | | `subscription_plan.archived` | `SubscriptionPlanArchived` | `$event->subscriptionPlan` | | `subscription_plan.unarchived` | `SubscriptionPlanUnarchived` | `$event->subscriptionPlan` | Each DTO also exposes the resource id (`$event->oneOffProductId` / `$event->subscriptionPlanId`) and `$event->testmode` at the top level, and carries a `VATLY_EVENT_NAME` constant for matching (all live under `Vatly\API\Webhooks\Events\`). ```php $event = $factory->createFromWebhook($webhook); if ($event instanceof OneOffProductUpdateApproved) { // The approved product, already hydrated — no extra GET needed. echo $event->oneOffProduct->name; echo $event->oneOffProduct->basePrice->value; } if ($event instanceof SubscriptionPlanArchived) { echo $event->subscriptionPlan->archivedAt; // non-null } ``` ### The `webhook.setup` event When you register a webhook endpoint (or change its URL), Vatly sends a signed `webhook.setup` event to confirm the endpoint is reachable. It is delivered as a normal webhook — same envelope, same signature, same `Vatly-Event-Id` header — so there is **nothing special to parse**: `Webhook::parse()` returns an ordinary `WebhookPayload`. Just acknowledge it with a `2xx` and take no action. For strongly-typed handling, this package ships a [`WebhookSetupReceived`](https://github.com/Vatly/vatly-api-php/blob/main/src/API/Webhooks/Events/WebhookSetupReceived.php){rel=""nofollow""} event DTO (`Vatly\API\Webhooks\Events\WebhookSetupReceived`) that carries the webhook envelope (`id`, `resource`, `eventName`, `entityType`, `entityId`, `testmode`, `createdAt`, `object`). Build it from a `WebhookReceived` via `WebhookSetupReceived::fromWebhook()`; `object` is the (secret-free) endpoint config and may be empty. --- ## The WebhookEvent resource Every delivery carries a [`WebhookEvent`](https://github.com/Vatly/vatly-api-php/blob/main/src/API/Resources/WebhookEvent.php){rel=""nofollow""} JSON object in the request body. This is the same shape returned by `GET /v1/webhook-events/:id`. ### Properties | Name | Type | Description | | ------------ | ------------- | ---------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier for the webhook event (`webhook_event_...`). | | `resource` | `string` | Always `webhook_event`. | | `eventName` | `string` | One of the events listed above (e.g. `order.paid`). | | `entityType` | `string` | Type of the related resource (e.g. `order`, `refund`, `subscription`). | | `entityId` | `string` | ID of the related resource (e.g. `order_Hn5xWqVfKm8RjTgYbUcP`). | | `object` | `object|null` | The full resource payload at the time of the event. Shape depends on `entityType`. | | `createdAt` | `string` | When the event occurred (ISO 8601). | | `testmode` | `bool` | Whether this event was generated in test mode. | | `links` | `object` | HATEOAS links — `links.self.href` points to this webhook event. | ### Example payload ```json { "id": "webhook_event_Qk8pRtSvWm2NjLhYcZaE", "resource": "webhook_event", "eventName": "order.paid", "entityType": "order", "entityId": "order_Hn5xWqVfKm8RjTgYbUcP", "object": { "id": "order_Hn5xWqVfKm8RjTgYbUcP", "resource": "order", "status": "paid", "total": { "value": "29.99", "currency": "EUR" } }, "createdAt": "2026-01-11T10:50:50+02:00", "testmode": true, "links": { "self": { "href": "https://api.vatly.com/v1/webhook-events/webhook_event_Qk8pRtSvWm2NjLhYcZaE", "type": "application/json" } } } ``` --- ## Delivery headers Each webhook request includes two Vatly-specific headers. | Header | Description | | ----------------- | ---------------------------------------------------------------------------------------------------------------- | | `Vatly-Signature` | Structured signature value: `t=,v1=`. Verify this before trusting the payload. | | `Vatly-Event-Id` | The `id` of the underlying webhook event. Stable across retry attempts — use it as your idempotency / dedup key. | The signature scheme prefix (`v1=`) leaves room for future algorithm versions; receivers that verify against `v1` will keep working if additional versions appear alongside it. --- ## Handling webhooks The SDK ships [`Webhook::parse()`](https://github.com/Vatly/vatly-api-php/blob/main/src/API/Webhooks/Webhook.php){rel=""nofollow""} — a one-shot helper that verifies the signature, decodes the JSON, and returns a typed [`WebhookPayload`](https://github.com/Vatly/vatly-api-php/blob/main/src/API/Webhooks/WebhookPayload.php){rel=""nofollow""} ready to dispatch on. Verification is performed against the **raw request body bytes**. JSON that is parsed and re-encoded will not match the signature — read the body directly (e.g. `file_get_contents('php://input')`) before any framework deserialises it. ```php use Vatly\API\Exceptions\InvalidSignatureException; use Vatly\API\Exceptions\WebhookSecretNotConfiguredException; use Vatly\API\Webhooks\Webhook; $payload = file_get_contents('php://input'); $signature = $_SERVER['HTTP_VATLY_SIGNATURE'] ?? ''; // getenv() returns false when the variable is unset; treat that as "no secret". $secret = (string) getenv('VATLY_WEBHOOK_SECRET'); try { $event = Webhook::parse($payload, $signature, $secret); } catch (WebhookSecretNotConfiguredException $e) { // No secret configured yet: refuse, and let Vatly retry later. http_response_code(503); exit('Webhook secret not configured'); } catch (InvalidSignatureException $e) { http_response_code(401); exit('Invalid signature'); } // Dedupe with Vatly-Event-Id (stable across retry attempts). $eventId = $_SERVER['HTTP_VATLY_EVENT_ID'] ?? $event->id; if (alreadyProcessed($eventId)) { http_response_code(200); exit; } match ($event->eventName) { 'order.paid' => handleOrderPaid($event), 'refund.completed' => handleRefundCompleted($event), 'checkout.expired' => handleCheckoutExpired($event), default => null, }; markProcessed($eventId); http_response_code(200); ``` Webhooks are refused until a secret is configured: `Webhook::parse()` throws `Vatly\API\Exceptions\WebhookSecretNotConfiguredException` (a subclass of `InvalidSignatureException`) when the secret is empty or blank. It throws `Vatly\API\Exceptions\InvalidSignatureException` when the signature header is malformed, the timestamp is outside the tolerance window, or the HMAC does not match. It throws `InvalidArgumentException` when the body is not valid JSON or is missing required fields. ### Typed event DTOs `Webhook::parse()` returns the raw, generic [`WebhookPayload`](https://github.com/Vatly/vatly-api-php/blob/main/src/API/Webhooks/WebhookPayload.php){rel=""nofollow""}. For consumers that prefer a strongly-typed, per-event object, this package also owns immutable event DTOs under [`Vatly\API\Webhooks\Events`](https://github.com/Vatly/vatly-api-php/blob/main/src/API/Webhooks/Events){rel=""nofollow""}. Each DTO: - exposes a `VATLY_EVENT_NAME` constant (a [`WebhookEventName`](https://github.com/Vatly/vatly-api-php/blob/main/src/API/Types/WebhookEventName.php){rel=""nofollow""} value) for matching; - carries `from*()` factory methods — `fromApiOrder()`, `fromApiRefund()`, `fromApiChargeback()`, `fromApiSubscription()` to build from an enriched API resource, and/or `fromWebhook(WebhookReceived $webhook)` to build from the raw payload; - carries money as [`Money`](https://github.com/Vatly/vatly-api-php/blob/main/src/API/Types/Money.php){rel=""nofollow""} values (decimal-string + currency) and the per-rate VAT breakdown as a [`TaxSummaryCollection`](https://github.com/Vatly/vatly-api-php/blob/main/src/API/Types/TaxSummaryCollection.php){rel=""nofollow""}. Flatten to integer cents at your persistence edge via [`Money::toCents()`](https://github.com/Vatly/vatly-api-php/blob/main/src/API/Types/Money.php){rel=""nofollow""}. ```php use Vatly\API\Resources\Order; use Vatly\API\Webhooks\Events\OrderPaid; // $order is a fully-hydrated API Order resource (e.g. from $vatly->orders->get(...)) $event = OrderPaid::fromApiOrder($order); $event->total; // Vatly\API\Types\Money $event->total->value; // decimal string, e.g. "49.99" $event->total->currency; // e.g. "USD" $event->total->toCents(); // int cents, e.g. 4999 $event->taxSummary; // Vatly\API\Types\TaxSummaryCollection $event->lines; // Vatly\API\Types\OrderLineData[] $event->testmode; // bool — test (true) vs live (false), mirrored from the source record ``` Every business event (order/subscription/refund/chargeback/checkout) carries `testmode`, sourced from the enriched resource (`$resource->testmode`) or the webhook envelope (`$webhook->testmode`). Persist it alongside the record so test and live data stay segregated and the matching API key can be selected per record. These DTOs are the canonical, framework-agnostic event shapes that higher-level integrations (e.g. `vatly-fluent-php`) build on. The line-item DTO lives at [`Vatly\API\Types\OrderLineData`](https://github.com/Vatly/vatly-api-php/blob/main/src/API/Types/OrderLineData.php){rel=""nofollow""}; its `basePrice`/`total`/`subtotal` are `Money` too. The full set of incoming webhook payloads is also described in the [webhooks OpenAPI spec](https://docs.vatly.com/openapi.yaml){rel=""nofollow""} under the top-level `webhooks:` section — one entry per `WebhookEventName`, each referencing the `WebhookDelivery` envelope. ### Replay-window tolerance The signed timestamp (`t=...`) lets receivers reject stale deliveries. By default signatures more than **300 seconds** old are rejected. If you need a custom window — for example when replaying captured fixtures in a test suite — instantiate [`WebhookSignatureValidator`](https://github.com/Vatly/vatly-api-php/blob/main/src/API/Webhooks/WebhookSignatureValidator.php){rel=""nofollow""} directly: ```php use Vatly\API\Webhooks\WebhookSignatureValidator; $validator = new WebhookSignatureValidator($secret, toleranceSeconds: 60); $validator->verify($payload, $signature); ``` Keep the default in production. A tighter window makes a leaked signature less useful; a much wider window weakens the replay-defense guarantee. ### Lower-level access If you only need signature verification (e.g. handling the decoded body yourself, or operating on a non-standard payload shape), use [`WebhookSignatureValidator`](https://github.com/Vatly/vatly-api-php/blob/main/src/API/Webhooks/WebhookSignatureValidator.php){rel=""nofollow""} directly. It exposes `verify()`, `isValid()`, and `calculateSignature()`, plus header-name constants: ```php WebhookSignatureValidator::SIGNATURE_HEADER_NAME; // 'Vatly-Signature' WebhookSignatureValidator::EVENT_ID_HEADER_NAME; // 'Vatly-Event-Id' ``` --- ## Best practices 1. **Always verify signatures** before processing webhook payloads. 2. **Verify against the raw body**, not parsed-and-reserialised JSON. 3. **Dedupe with `Vatly-Event-Id`** — retries reuse the same event id, while the signature deliberately rotates per attempt. 4. **Return 200 quickly** to avoid timeout retries. Offload long-running work to a queue. 5. **Log webhook events** for debugging and auditing. # Webhook Endpoints A webhook endpoint is the HTTPS URL Vatly POSTs event deliveries to — registered from code (or infrastructure-as-code) rather than the dashboard. A storefront can have **up to five endpoints per mode** (test and live are set by the API token), each with a URL unique within that storefront and mode. A duplicate URL or a sixth endpoint is rejected with `422`. Each endpoint has its own `enabledEvents` set — the public event names it receives (see [`WebhookSubscriptionEventName`](https://github.com/Vatly/vatly-api-php/blob/main/src/API/Types/WebhookSubscriptionEventName.php){rel=""nofollow""}). An empty set makes it dormant; `webhook.setup` is never subscribable and is always sent when Vatly verifies the endpoint. The signing `secret` is **write-only**: sent on create/update, never returned. Store the value you send — you use it to verify the `Vatly-Signature` HMAC on deliveries (see [Webhooks](https://docs.vatly.com/packages/php/webhooks)). ## The WebhookEndpoint Resource Below you'll find all properties for the Vatly WebhookEndpoint resource. ### Properties | Name | Type | Description | | --------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier for the endpoint (`webhook_...`). | | `resource` | `string` | Resource type, always `webhook_endpoint`. | | `testmode` | `bool` | Whether this endpoint receives test-mode events. | | `url` | `string` | The HTTPS URL deliveries are POSTed to. | | `enabledEvents` | `string[]` | The event names this endpoint is subscribed to. An empty array means dormant (no domain events); `webhook.setup` is still sent. | | `createdAt` | `string` | Creation timestamp (ISO 8601). | | `links` | `WebhookEndpointLinks` | HATEOAS links (`self`). | --- ## Register a webhook endpoint `POST /v1/webhook-endpoints` Register an endpoint for the token's mode. Vatly sends a `webhook.setup` verification ping and validates the URL's SSL certificate; if either fails, registration is rejected with `422`. ### Required attributes | Name | Type | Description | | -------- | -------- | ---------------------------------------------------------------------------------------------------------- | | `url` | `string` | Publicly reachable HTTPS URL with a valid SSL certificate. `localhost`/loopback addresses are not allowed. | | `secret` | `string` | Signing secret (min 10 chars). Write-only — keep it, the API never returns it. | ### Optional attributes | Name | Type | Description | | --------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `enabledEvents` | `string[]` | The events to deliver (`WebhookSubscriptionEventName` values). Omit to subscribe to every event available at registration (not updated afterwards); send `[]` for a dormant endpoint. `webhook.setup` is not selectable. | ```php use Vatly\API\Types\WebhookSubscriptionEventName; $endpoint = $vatly->webhookEndpoints->create([ 'url' => 'https://merchant.example/webhooks/vatly', 'secret' => getenv('VATLY_WEBHOOK_SECRET'), 'enabledEvents' => [ WebhookSubscriptionEventName::ORDER_PAID, WebhookSubscriptionEventName::REFUND_COMPLETED, ], ]); echo $endpoint->id; // webhook_... ``` --- ## Retrieve a webhook endpoint `GET /v1/webhook-endpoints/:id` Retrieve an endpoint by its ID. The signing secret is never included. ```php $endpoint = $vatly->webhookEndpoints->get('webhook_QdEpFhdSrG4Y3DnfsdqsH'); echo $endpoint->url; ``` --- ## List webhook endpoints `GET /v1/webhook-endpoints` List all endpoints for the token's mode. ```php $endpoints = $vatly->webhookEndpoints->page(); foreach ($endpoints as $endpoint) { echo $endpoint->url; } ``` --- ## Update a webhook endpoint `PATCH /v1/webhook-endpoints/:id` Repoint the endpoint (`url`), rotate the signing `secret`, and/or replace its `enabledEvents` set. A new URL is revalidated for reachability and SSL just like on creation. An empty body is a no-op that returns the current endpoint. ### Optional attributes | Name | Type | Description | | --------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `url` | `string` | New HTTPS delivery URL. | | `secret` | `string` | New signing secret (min 10 chars). Write-only. | | `enabledEvents` | `string[]` | Replaces the **complete** subscription set (`WebhookSubscriptionEventName` values). Omit to preserve the current set; send `[]` to make the endpoint dormant. | ```php use Vatly\API\Types\WebhookSubscriptionEventName; $endpoint = $vatly->webhookEndpoints->update('webhook_QdEpFhdSrG4Y3DnfsdqsH', [ 'url' => 'https://merchant.example/webhooks/vatly-v2', 'enabledEvents' => [ WebhookSubscriptionEventName::CHECKOUT_PAID, WebhookSubscriptionEventName::ORDER_PAID, ], ]); ``` If you already have a `WebhookEndpoint` resource instance: ```php $endpoint->update([ 'secret' => getenv('VATLY_WEBHOOK_SECRET_NEXT'), ]); ``` --- ## Delete a webhook endpoint `DELETE /v1/webhook-endpoints/:id` Delete an endpoint. Vatly stops sending deliveries to it immediately. To receive events again, register a new endpoint. Returns no content. ```php $vatly->webhookEndpoints->delete('webhook_QdEpFhdSrG4Y3DnfsdqsH'); // Or, from a resource instance: $endpoint->delete(); ``` # FluentCart Accept payments through Vatly in FluentCart, the WordPress e-commerce plugin. Vatly is the European Merchant of Record for AI, software and digital products. This plugin registers Vatly as a FluentCart payment gateway and builds on PHP Fluent and the PHP SDK. ::warning **Alpha.** The plugin works end to end with Vatly test mode on FluentCart 2.3, but it can still change in ways that need you to update your setup. Try it in Vatly test mode before you take live payments with it. :: ## What it does - **Merchant-of-Record checkout** for one-off products and subscriptions, including free trials carried over from FluentCart. - **Official Vatly invoices** on the FluentCart receipt and as shortcodes. FluentCart's own competing receipt email is suppressed for Vatly orders, so customers never receive two invoices for one purchase. - **Refunds routed through Vatly**, so Vatly issues the credit note and its VAT, and the result is recorded on the FluentCart order. - **FluentCart's own events** for every payment and subscription change, including renewals, failed payments, refunds, cancellations and chargebacks, so other plugins that listen to FluentCart keep working. - **Per-record test and live mode**, frozen at checkout, so refunds always use the API key that matches the original order. ## Requirements - WordPress 6.2 or newer - PHP 8.1 or newer - [FluentCart](https://fluentcart.com){rel=""nofollow""} 2.3 or newer, installed and active - A [Vatly](https://vatly.com){rel=""nofollow""} account with test-mode API credentials ## Installation 1. Download the zip from the [latest alpha release](https://github.com/vatly/vatly-fluentcart-wp/releases/latest){rel=""nofollow""}. It includes the plugin's dependencies, so you don't need Composer. 2. In WordPress, go to **Plugins → Add New → Upload Plugin**, choose the zip, and activate it. To build the zip yourself, run `bin/build-release.sh` in a clone of the repository. It produces `build/vatly-for-fluentcart.zip` with a namespace-scoped copy of the dependencies, and needs PHP, Composer, curl and zip. For development, run `composer install` in the clone instead, then place or symlink the directory in `wp-content/plugins/`. ## Setup 1. **Add your API credentials.** Go to **FluentCart → Settings → Payment Methods → Vatly**, choose **Test** mode, and paste the test **API key** and **Webhook secret** from the **Developers** section of your Vatly dashboard. 2. **Register the webhook in Vatly.** Under **Developers** in the Vatly dashboard, add a webhook endpoint pointing at: ```text https://your-site.com/wp-admin/admin-ajax.php?action=fluent_cart_vatly_webhook ``` :brUse the webhook secret you entered above. Vatly's `order.paid` webhook stamps the official invoice onto each order. 3. **Map your products to Vatly.** Edit a FluentCart product and fill in the **Vatly mapping** box with the IDs from **Manage Products** in your Vatly dashboard: - **Vatly product ID**: the `one_off_product_…` ID, for one-time products. - **Vatly plan ID**: the `subscription_plan_…` ID, for subscription products. :brA checkout fails with a clear error when the product it sells has no matching Vatly ID. ## Invoices Vatly issues the legally valid VAT invoice and, for refunds, the credit note. When a Vatly `order.paid` webhook arrives, the plugin stores the Vatly invoice URL on the FluentCart order and the credit-note URL on refunds. Show the invoice anywhere FluentCart accepts shortcodes: | Shortcode | Output | | ------------------------ | ----------------------------------------------- | | `[vatly_invoice_link]` | A plain "Download official Vatly invoice" link. | | `[vatly_invoice_button]` | The same link, styled as a button. | Both accept an optional `order_id`, for example `[vatly_invoice_link order_id="123"]`; otherwise they use FluentCart's current order. They render nothing for orders without a Vatly invoice, so they are safe in templates shared with other gateways. The invoice button also appears automatically on the FluentCart receipt page. For the FluentCart hooks the invoicing relies on, see [Merchant-of-Record invoicing](https://docs.vatly.com/packages/fluentcart/merchant-of-record). ## Refunds Refunds issued from the FluentCart admin go through Vatly, then are recorded on the FluentCart transaction. - **Full refunds** are supported. - **Partial refunds on single-item orders** are refunded against the order's line. - **Partial refunds on multi-item orders** are not supported from FluentCart. Issue a full refund, or refund a specific line from the Vatly dashboard. Vatly refunds are asynchronous: the FluentCart refund starts with Vatly's initial status, usually `pending`, and moves to `refunded` once Vatly confirms it. Each FluentCart transaction keeps the mode (test or live) it had at checkout. Refunds use the API key for that record's mode, not the gateway's current setting. ## Data the plugin stores For your records of processing and for access and deletion requests: - **Settings:** your Vatly API keys and webhook secrets, encrypted, in FluentCart's settings. - **Customer links:** the table `{prefix}vatly_customer_bindings` maps each Vatly customer ID to its FluentCart customer ID. It holds no names or contact details. - **Webhook log:** the table `{prefix}vatly_webhook_calls` keeps each webhook Vatly sends, for debugging. Personal fields (customer name, email, address, tax ID, payment method details) are redacted before it is stored, so they read `[redacted]`; the event's IDs, statuses, amounts, tax and order lines are kept. Entries are deleted after 30 days. Change that with the `vatly_fluentcart_webhook_log_retention_days` filter, for example `add_filter('vatly_fluentcart_webhook_log_retention_days', fn () => 7);`. Orders, subscriptions and transactions are FluentCart's own records. Deleting the plugin removes both tables, its settings and its scheduled jobs, and leaves those records in place. ## Development ```bash composer install composer test:unit # PHPUnit unit suite composer test:integration # integration suite (see docker/ for a WordPress + FluentCart environment) composer analyse # PHPStan composer phpcs # WordPress coding standards ``` The source and issue tracker are on [GitHub](https://github.com/vatly/vatly-fluentcart-wp){rel=""nofollow""}. # Merchant-of-Record invoicing: implementation notes How the plugin makes Vatly the single source of truth for invoices on FluentCart orders, and the FluentCart integration points it relies on. This is reference material for maintainers; end users only need the [README](https://github.com/vatly/vatly-fluentcart-wp/blob/main/README.md){rel=""nofollow""}. ## The problem Vatly is the Merchant of Record, so the legally valid VAT invoice (and, for refunds, the credit note) is the one **Vatly** issues. FluentCart also generates its own receipt/invoice. Left alone, a customer paying via Vatly would receive **two competing invoices** for one purchase. The plugin therefore (a) surfaces Vatly's invoice and (b) suppresses FluentCart's own invoicing, but only for orders paid via the Vatly gateway (`payment_method === 'vatly'`). Every guard callback is a strict no-op for non-Vatly orders. The guard lives in `src/Support/MoRInvoiceGuard.php`. ## Hooks used > **FluentCart version note.** The gateway integration (registration, checkout, > refunds, and the `order.paid` confirmation + Vatly-invoice stamping) has been > ported to and verified against **FluentCart free 2.2.0**. The two > Merchant-of-Record email/receipt guard hooks in the table below still carry > their original `// verified: FluentCart free 1.3.28` file\:line references and > have **not** yet been re-verified against 2.2.0: the hook names and line > numbers may have moved, so re-confirm they still exist and fire before relying > on the email-suppression guard on 2.2.0. The guard wires only hooks confirmed to exist **and fire**. Each wired hook carries a `// verified: …` file\:line comment in the source. | Intent | FluentCart hook | Notes | | --------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Suppress FluentCart's competing customer receipt/invoice email (and its PDF attachment) | `fluent_cart/should_send_email_notification` (filter, `EmailNotificationMailer::mailEmailsOfEvent`) | Returns `false` for the `order_paid_customer` notification (event `order_paid`, subject "Purchase Receipt #{{ order.invoice_no }}") on Vatly orders: the only customer mail that doubles as FluentCart's invoice and the only one that can attach FluentCart's PDF receipt. No email ⇒ no competing invoice and no attached PDF (covers Pro too). All other notifications (refunds, shipping, subscription, and every admin copy) pass through untouched. | | Surface the Vatly invoice link on the customer receipt page | `fluent_cart/receipt/thank_you/after_order_items` (action, `ThankYouRender`) | Auto-renders the Vatly invoice button (reusing the shortcode renderer) beneath the order items for Vatly orders. | ## Why some surfaces aren't hooked - **FluentCart Pro PDF receipt** (`fluent_cart/pdf/generate_receipt`) only fires under Pro + FluentPDF (`OrderService::canGenerateReceiptPdf()` + `defined('FLUENT_PDF')`), so it never runs on free. Suppressing the receipt *email* already drops its PDF attachment on Pro, so no separate handler is needed. - **Refund PDF / refund URL**: FluentCart free exposes no hook to redirect a refund PDF, and there is no free refund-PDF surface to gate. - **Admin billing-detail edits**: FluentCart free fires no action or filter around `CustomerAddressResource::update` or the admin `CustomerController::updateAddress`, so an admin edit of an order's/customer's billing address cannot be blocked or mirrored. These FluentCart-side artifacts remain FluentCart-local and **non-authoritative**; Vatly's invoice and credit note are the legal record of account. For subscriptions, point staff to the Vatly customer portal (`SubscriptionService::updateBillingUrl()`) when billing details must change; a FluentCart-local edit never reaches Vatly's already-issued invoice. > Earlier revisions referenced several FluentCart hook names that don't exist in > core; those have been removed. If you extend the guard, confirm any new hook > actually fires in the FluentCart version you target before relying on it. # Paid Memberships Pro Sell Paid Memberships Pro (PMPro) memberships through Vatly. Vatly is the European Merchant of Record for AI, software and digital products: it is the legal seller on every sale and handles payments, tax and compliance. This plugin adds Vatly as a payment gateway to PMPro. ::warning **Alpha.** The plugin can still change in ways that need you to update your setup. Try it in Vatly test mode before you take live payments with it. :: ## What it does - **Hosted checkout.** Members pay at Vatly's hosted checkout (cards, PayPal, iDEAL, Apple Pay, SEPA). - **VAT handled for you.** Vatly collects VAT per country, applies the right rate on every renewal, and issues compliant invoices as the seller. You no longer need the `pmpro-vat-tax` add-on or `pmpro_tax` filter snippets. - **Membership sync.** Webhooks keep PMPro in step: levels are assigned on payment, changed when a member switches plan, and revoked on cancellation. - **PMPro keeps the rest.** Membership levels, content gating, member dashboards and discount codes work as before. ## Requirements - WordPress 6.5 or newer - PHP 8.1 or newer - [Paid Memberships Pro](https://wordpress.org/plugins/paid-memberships-pro/){rel=""nofollow""} 3.x, installed and active - A [Vatly](https://vatly.com){rel=""nofollow""} account ## Installation The plugin is not on WordPress.org or Packagist. Install it from GitHub: 1. Download the zip from the [latest release](https://github.com/vatly/vatly-pmpro/releases/latest){rel=""nofollow""}. It includes the plugin's dependencies, so you don't need Composer. 2. In WordPress, go to **Plugins → Add New → Upload Plugin**, choose the zip, and activate it. ## Setup 1. **Add your credentials.** Go to **Memberships → Settings → Payments** and open the **Vatly** gateway. Enter your **Live API key**, **Test API key** and **Webhook signing secret** from the **Developers** section of your Vatly dashboard, and save. 2. **Register the webhook in Vatly.** The settings screen shows your webhook URL: ```text https://your-site.com/wp-json/vatly/v1/webhook ``` :brPaste it into your Vatly dashboard under **Developers → Webhooks**, using the signing secret you entered above. 3. **Map each membership level to a Vatly plan.** Edit each membership level you want billed through Vatly and paste the matching plan ID from **Manage Products** in your Vatly dashboard into the **Vatly plan ID** field. Members pay the price of the Vatly plan, not the PMPro level price, so set both to the same amount. Selling to consumers? Create the plan as tax-inclusive, so buyers pay exactly the price you show and the VAT comes out of it. Tax-exclusive plans add VAT at checkout, so show those prices as "excl. VAT". ## Webhooks Webhooks are refused until a webhook signing secret is saved. Until then the endpoint answers `503` and processes nothing; Vatly retries the delivery once the secret is saved. The endpoint is only registered while Paid Memberships Pro is active. ## Saved keys and secrets The API keys and webhook signing secret are stored encrypted, keyed from your WordPress salts or a `VATLY_PMPRO_ENCRYPTION_KEY` constant in `wp-config.php`. The settings screen never shows saved values: - Leave a field blank to keep its saved value. - Tick **Remove saved value** to delete it. If the WordPress salts or the encryption key change, enter the API keys and webhook secret again. ## Invoices and credit notes Vatly issues the VAT invoice and, for refunds, the credit note. Links to them appear on the checkout confirmation page, on the member's order (invoice) page, and on the admin order screen. The links are fetched fresh from Vatly when shown and never stored. A completed refund marks the PMPro order as refunded and keeps the membership. ## Cancellations Cancelling a membership in WordPress cancels the subscription at Vatly, so renewals stop being charged. ## Support The source and issue tracker are on [GitHub](https://github.com/vatly/vatly-pmpro){rel=""nofollow""}. # PHP Fluent Sell a download, start a subscription, and keep your app's billing records in step with Vatly. Vatly is the European Merchant of Record for AI, software and digital products. > **Alpha — under active development. Every alpha release may include breaking changes. Lock the version you install and review the release notes before upgrading.** Fluent adds checkout builders, subscription operations, customer bindings, and a webhook processing pipeline to `vatly/vatly-api-php`. You keep your database and framework. Fluent calls your storage contracts to save orders and subscriptions. ## Start a subscription Install the package using [Configuration](https://docs.vatly.com/packages/fluent-php/configuration). This function creates a hosted checkout and returns the URL to send to the browser: ```php use Vatly\Fluent\CustomerProfile; use Vatly\Fluent\Vatly; function subscriptionCheckout(string $apiKey, string $customerId, string $planId): string { $vatly = Vatly::apiOnly($apiKey); $checkout = $vatly->subscriptionBuilder(new CustomerProfile(vatlyId: $customerId)) ->toPlan($planId) ->withRedirectUrlSuccess('https://app.example.com/billing/return') ->withRedirectUrlCanceled('https://app.example.com/billing/canceled') ->create(); return $checkout->links->checkoutUrl->href; } ``` Use a customer and plan from the same storefront and mode as your key. Authorize the signed-in user's access to that customer first. Redirect to the returned URL, then use [Webhooks](https://docs.vatly.com/packages/fluent-php/webhooks) to confirm the subscription and grant access. The return page alone is not proof of payment. ## Choose your layer | You need | Use | | ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | Billing in a Laravel app | [vatly-laravel](https://github.com/vatly/vatly-laravel){rel=""nofollow""}. It wires Fluent into Laravel for you. | | Fluent billing flows in plain PHP, Symfony, WordPress, or a custom driver | This package. Start without storage; add repositories when you need local records. | | A few direct API calls, without local billing state | [vatly-api-php](https://docs.vatly.com/packages/php/readme){rel=""nofollow""}. No Fluent layer required. | With the raw SDK you assemble checkout payloads and coordinate webhook persistence yourself. Fluent gives those common tasks names: `toPlan()`, `swapAndInvoice()`, `updateBilling()`, and `webhookProcessor()->handle()`. It does not supply tables, routes, authorization, transactions, or exactly-once delivery. ## Guides | Task | Page | | ------------------------------------------------- | ------------------------------------------------------------------------------ | | Install, set keys, redirects, and handle errors | [Configuration](https://docs.vatly.com/packages/fluent-php/configuration) | | Connect billables and storage | [Core concepts](https://docs.vatly.com/packages/fluent-php/coreconcepts) | | Link your users to Vatly customers | [Customers](https://docs.vatly.com/packages/fluent-php/customers) | | Sell one-off products and subscriptions | [Checkouts](https://docs.vatly.com/packages/fluent-php/checkouts) | | Swap, cancel, resume, and update billing | [Subscriptions](https://docs.vatly.com/packages/fluent-php/subscriptions) | | Open hosted self-service billing | [Customer portal](https://docs.vatly.com/packages/fluent-php/customerportal) | | Verify deliveries and handle retries safely | [Webhooks](https://docs.vatly.com/packages/fluent-php/webhooks) | | Choose which events to persist or listen for | [Event flow](https://docs.vatly.com/packages/fluent-php/webhook-flow) | | Show invoices, lines, refunds, and chargebacks | [Orders](https://docs.vatly.com/packages/fluent-php/orders) | | Test without charging a customer | [Testing](https://docs.vatly.com/packages/fluent-php/testing) | | Reuse your existing order and subscription tables | [Host tables](https://docs.vatly.com/packages/fluent-php/host-owns-its-tables) | For request and response fields, see the [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""}. # Configuration Install Fluent on your server with PHP 8.1 or newer and Composer. Keep API keys out of browser code and source control. ```sh composer config minimum-stability alpha composer config prefer-stable true composer require vatly/vatly-fluent-php ``` > **Alpha — under active development. Every alpha release may include breaking changes. Lock the version you install and review the release notes before upgrading.** Fluent and the underlying `vatly/vatly-api-php` SDK are alpha, and Composer's default stable-only policy rejects them. The two `config` commands allow alpha releases while `prefer-stable` keeps your other dependencies on stable releases. Composer installs the latest alpha and records it in `composer.lock`. ## Set keys and return URLs Load `vendor/autoload.php` at your application's entry point. Set `VATLY_API_KEY` and `VATLY_WEBHOOK_SECRET` in your server environment. Get a test key from the [dashboard](https://my.vatly.com){rel=""nofollow""}. ```php use Vatly\Fluent\Configuration\ArrayConfiguration; use Vatly\Fluent\Vatly; use Vatly\Fluent\Wiring; $config = new ArrayConfiguration([ 'api_key' => (string) getenv('VATLY_API_KEY'), 'webhook_secret' => getenv('VATLY_WEBHOOK_SECRET') ?: null, 'redirect_url_success' => 'https://app.example.com/billing/return', 'redirect_url_canceled' => 'https://app.example.com/billing/canceled', ]); $vatly = new Vatly(new Wiring(config: $config)); ``` `test_` keys use test mode; `live_` keys can charge real money. Keep products, customers, and local records separated by mode. Missing environment variables are configuration errors: validate them at application startup. `getenv()` returns `false` for an unset variable, so the example maps it to `null`. Webhooks are refused until a secret is configured. The default API URL is `https://api.vatly.com` and the version is `v1`. `ArrayConfiguration` also accepts `api_url` and `api_version`. Implement `ConfigurationInterface` instead if your framework already owns configuration. ## Add storage only when you need it The instance above can create checkouts, operate on products, and open customer portal sessions. `Vatly::apiOnly($apiKey)` is the shortcut when you do not need redirect defaults. `customers()` needs customer bindings. `subscription($localSubscription)` needs a subscription repository. `webhookProcessor()` needs subscription, order, binding, and webhook-call repositories plus an event dispatcher. Missing dependencies raise `IncompleteWiringException`; see [Core concepts](https://docs.vatly.com/packages/fluent-php/coreconcepts) for the wiring example. Subscription checkout and billing-update flows use configured redirect defaults. One-off `CheckoutBuilder::create()` takes both redirect URLs explicitly. ## Handle a failed API call This function accepts the configured `$vatly`, an authorized customer ID, and a plan ID. Return a retry message to the customer when it returns `null`: ```php use Vatly\Fluent\CustomerProfile; use Vatly\Fluent\Exceptions\VatlyException; use Vatly\Fluent\Vatly; function tryCheckout(Vatly $vatly, string $customerId, string $planId): ?string { try { $checkout = $vatly->subscriptionBuilder(new CustomerProfile(vatlyId: $customerId)) ->toPlan($planId)->create(); return $checkout->links->checkoutUrl->href; } catch (VatlyException $error) { error_log('Vatly checkout failed: ' . $error->getCode()); return null; } } ``` Fluent wraps SDK failures in `ApiCallFailedException`, which implements `VatlyException` and preserves the error code. `apiException()` gives you the original SDK exception. Calls made directly through `getApiClient()` use the SDK's own exception types instead. See [Checkouts](https://docs.vatly.com/packages/fluent-php/checkouts) next. For field details, see the [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""}. # Core concepts Connect Fluent to your database without replacing your models. Build a driver by implementing the storage contracts, then pass those implementations to `Wiring`: ```php use Vatly\Fluent\Contracts\ConfigurationInterface; use Vatly\Fluent\Contracts\CustomerBindingRepository; use Vatly\Fluent\Contracts\EventDispatcherInterface; use Vatly\Fluent\Contracts\OrderRepositoryInterface; use Vatly\Fluent\Contracts\SubscriptionRepositoryInterface; use Vatly\Fluent\Contracts\WebhookCallRepositoryInterface; use Vatly\Fluent\Vatly; use Vatly\Fluent\Wiring; function billing( ConfigurationInterface $config, CustomerBindingRepository $bindings, SubscriptionRepositoryInterface $subscriptions, OrderRepositoryInterface $orders, WebhookCallRepositoryInterface $webhookCalls, EventDispatcherInterface $events, ): Vatly { return new Vatly(new Wiring( config: $config, subscriptions: $subscriptions, orders: $orders, webhookCalls: $webhookCalls, events: $events, customerBindings: $bindings, )); } ``` Register that instance in your application's container. Fluent does not ship a database driver or migrations. Laravel users should use [vatly-laravel](https://github.com/vatly/vatly-laravel){rel=""nofollow""} instead of writing this wiring. ## Choose the billable Your billable is the user, team, company, or tenant that pays. There is no `Billable` interface or required base model. Give Fluent a `CustomerProfile` with a Vatly customer ID, or use [Customers](https://docs.vatly.com/packages/fluent-php/customers) to create and bind one to your host ID. A profile is input, not a stored customer. Supplying only its email to a checkout builder does not create or bind a customer. Create the customer explicitly, or use an empty profile for an anonymous checkout. ## Save local billing state | Contract | Your implementation does | | --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `CustomerBindingRepository` | Maps host IDs to Vatly customer IDs in both directions; records unattributed customers. | | `SubscriptionRepositoryInterface` | Finds by Vatly ID, stores a subscription, updates it. | | `OrderRepositoryInterface` | Finds by Vatly ID, stores an order, updates it. | | `WebhookCallRepositoryInterface` | Records received deliveries and cleans up old audit rows. It does not skip duplicate processing. The recorded `object` has the customer's personal data (`customerDetails`, `billingAddress`, `shippingAddress`, `mandate`) redacted to `[redacted]`; keys and nesting are kept. | | `EventDispatcherInterface` | Dispatches typed events to your listeners. `NullEventDispatcher` is available if you need no listeners. | Repositories return your objects implementing `SubscriptionInterface` or `OrderInterface`. Wrap existing host records rather than copying them; see [Host tables](https://docs.vatly.com/packages/fluent-php/host-owns-its-tables). Reader and writer contracts are also available separately when a component needs only one role. Enforce unique Vatly IDs in storage and binding uniqueness in both directions. Accept `hostCustomerId: null` on store data: anonymous payments may arrive before a customer is linked. Entity `store()` methods may return `null` when a record genuinely does not belong to your integration. Throw on a storage failure so the delivery can retry. ## Apply partial updates correctly `Store*Data` and `Update*Data` carry local persistence data. Amounts are integer cents with a separate currency. SDK resources and money-bearing webhook events use `Money` objects instead; use `toCents()` at your own persistence boundary. In updates, `null` normally means leave the stored value alone. Subscription updates have explicit `clearEndsAt` and `clearMandate` flags. A non-null mandate replaces both its method and masked identifier; do not keep an old card's last four digits when a new mandate has no identifier. Persist `testmode` from store data and expose it through the entity's `isTestmode()`. Select the matching key in your application; storing the flag does not switch keys automatically. `DerivesSubscriptionState` implements the subscription state predicates from `getEndsAt()`: no end date means active, a future end date means a valid grace period, a past date means ended. These predicates are not a full entitlement policy for trials, failed payments, or disputes. Your app decides access. ## Add optional records `Wiring` also accepts `refunds`, `chargebacks`, and `orderLines`. Refund and chargeback repositories enable their persistence reactions. Order lines need your order writer to persist the `StoreOrderData::$lines` supplied on a new paid order; wiring a line reader alone does not save lines. Use [Webhooks](https://docs.vatly.com/packages/fluent-php/webhooks) for transactions and [Event flow](https://docs.vatly.com/packages/fluent-php/webhook-flow) for the event-to-storage mapping. Field details live in the [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""}. # Customers Create a Vatly customer for the account that pays, then save the link to your own ID. Here `$vatly` has a `CustomerBindingRepository` wired in, and `user_42` is an authenticated account in your app: ```php use Vatly\Fluent\CustomerProfile; $customer = $vatly->customers()->findByHostCustomerId('user_42'); if ($customer === null) { $customer = $vatly->customers()->createFor( hostCustomerId: 'user_42', profile: new CustomerProfile(email: 'buyer@example.com', name: 'Alex'), additionalPayload: ['locale' => 'nl_NL'], ); } $profile = new CustomerProfile(vatlyId: $customer->id); ``` Use `$profile` in a [checkout](https://docs.vatly.com/packages/fluent-php/checkouts). `createFor()` always creates a new remote customer and then calls your binding repository. It throws if that host ID is already bound. Serialize concurrent creation for the same host account; a lookup followed by create is not an atomic lock. Remote creation and your database write are not one transaction. Reconcile the remote ID if binding fails rather than blindly creating again. ## Link an existing customer After checking ownership, call `attribute($vatlyCustomerId, $hostCustomerId)`. Repeating the same pair is safe. Linking a host already bound to another customer raises `CustomerAlreadyBoundException`. Your repository must also prevent one remote customer from being assigned to two host accounts. For anonymous checkout, use `new CustomerProfile()`. After payment you can call `claimCustomerFromCheckout($checkoutId, $hostCustomerId)`: it returns `false` if no customer can be resolved yet. Only claim checkouts your server recorded for this user or session. A checkout ID supplied by a browser is not proof of ownership. Claiming the binding does not reassign earlier anonymous order rows; your driver must do that if needed. ## Update account identity This uses the same authorized customer from above: ```php use Vatly\Fluent\Data\UpdateCustomerData; $handle = $vatly->customer($customer->id); $handle->update(new UpdateCustomerData(name: 'Alex Example')); $identity = $handle->identity(); ``` Identity updates cover name and email. To clear a name explicitly, pass `['name' => null]` instead of a DTO. Billing addresses, company details, and VAT numbers go through the hosted [billing-update flow](https://docs.vatly.com/packages/fluent-php/subscriptions#update-billing). `findByEmail()` returns a collection, not a unique match. `findOneByEmail()` returns the first match or `null`. Email search is a recovery tool, not authorization or an automatic binding rule. Next: [Customer portal](https://docs.vatly.com/packages/fluent-php/customerportal). For field details, see the [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""}. # Checkouts Create a hosted payment page, then redirect the browser to its URL. These examples use a configured `$vatly` and a customer your signed-in user is allowed to use. ## Sell a one-off product ```php use Vatly\Fluent\CustomerProfile; $checkout = $vatly->checkoutBuilder(new CustomerProfile(vatlyId: 'customer_example')) ->withLocale('nl') ->withMetadata(['host_order_id' => 'order_42']) ->create( [['id' => 'one_off_product_example', 'quantity' => 2]], 'https://app.example.com/orders/return', 'https://app.example.com/cart', ); $url = $checkout->links->checkoutUrl->href; ``` Replace the example product and customer IDs with records from your storefront and mode. Product IDs refer to configured products, not names or arbitrary SKUs. Create products in the dashboard or through `oneOffProducts()` and `subscriptionPlans()`. The `create()` URLs are required even if you set configuration defaults. Build a fresh builder for each checkout; reusing one can accumulate items. Metadata should contain server-chosen routing IDs, not secrets or untrusted ownership claims. ## Start a subscription Set redirect defaults in [Configuration](https://docs.vatly.com/packages/fluent-php/configuration), or override them on the builder: ```php use Vatly\Fluent\CustomerProfile; $checkout = $vatly->subscriptionBuilder(new CustomerProfile(vatlyId: 'customer_example')) ->toPlan('subscription_plan_example') ->withQuantity(3) ->withTrialDays(14) ->withBillingAddress([ 'companyName' => 'Example BV', 'city' => 'Amsterdam', 'country' => 'NL', ]) ->create(['metadata' => ['host_account_id' => 'team_42']]); $url = $checkout->links->checkoutUrl->href; ``` The result is a checkout, not a local subscription. `subscription.started` creates the local record through your repository. `withTrialDays()` requires a positive whole number. `withTrialEndsAt()` rounds a future end time up to whole days. If you omit the trial, the API applies any plan-level default. Both builders support `withLocale()` and `withBillingAddress()`. Address values prefill hosted fields; the customer can still edit them. A supplied country takes precedence over IP detection. A supplied tax ID is registered only when checkout is submitted. ## Override a price Use decimal strings, not floats or integer cents, in an API product price: ```php use Vatly\Fluent\CustomerProfile; $checkout = $vatly->checkoutBuilder(new CustomerProfile(vatlyId: 'customer_example')) ->create( [[ 'id' => 'one_off_product_example', 'quantity' => 1, 'price' => ['value' => '49.99', 'currency' => 'EUR'], ]], 'https://app.example.com/orders/return', 'https://app.example.com/cart', ); ``` Choose amounts on the server. An override still needs a configured product. Use the [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""} for allowed product combinations and fields. ## Confirm payment, not the redirect Keep the checkout ID against your server-side cart or session. The success page may load before a webhook, or never load at all. Confirm payment through [Webhooks](https://docs.vatly.com/packages/fluent-php/webhooks), then fulfill once. `checkout.paid` is useful for checkout analytics; `order.paid` supplies the order and tax data for persistence and fulfillment. # Subscriptions Change a subscription using a local record that implements `SubscriptionInterface`. These examples assume `$vatly` has your subscription repository wired and `$localSubscription` belongs to the signed-in account. ## Change the plan Choose one policy for a plan change; do not call all three for the same request: ```php $subscription = $vatly->subscription($localSubscription); $subscription->swap('subscription_plan_pro'); $pending = $subscription->scheduledUpdate(); ``` `swap()` schedules the change for the next billing cycle by default. The current plan remains in effect until then. `scheduledUpdate()` makes a live API call and returns a nullable `ScheduledSubscriptionUpdate`; read its `subscriptionPlanId`, `quantity`, and `effectiveAt` to show the pending change. `hasScheduledUpdate()` also makes a live call, so do not call both just to get the same data. To apply the change now and invoice the prorated difference: ```php $vatly->subscription($localSubscription)->swapAndInvoice('subscription_plan_pro'); ``` To apply it now without charging for the change: ```php $vatly->subscription($localSubscription)->swapWithoutCharge('subscription_plan_pro'); ``` The next renewal uses the new price. Each method also accepts an options array for API update fields. Fluent updates local plan and quantity from the API response; webhooks reconcile subsequent changes. Use the [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""} for proration and update options. ## Cancel and resume Request cancellation: ```php $vatly->subscription($localSubscription)->cancel(); ``` `cancel()` takes no options and does not set the local end date itself. The cancellation webhook carries the confirmed end date. Keep access through a valid grace period; do not revoke access just because a cancellation was requested. While the local subscription is on its grace period, reverse the pending cancellation: ```php $subscription = $vatly->subscription($localSubscription); if ($subscription->isOnGracePeriod()) { $subscription->resume(); } ``` `resume()` clears the local end date after the API succeeds. It is not a way to restart an already-ended subscription. `cancellationReason()` fetches the live reason, such as `customer_request`, `merchant_request`, or `payment_failure`. ## Update billing Send the customer to Vatly to change billing details, including their address or VAT number: ```php $url = $vatly->subscription($localSubscription)->updateBilling([ 'billingAddress' => [ 'companyName' => 'Example BV', 'country' => 'NL', ], ]); ``` Redirect to `$url`. Each call returns a fresh time-bounded link; do not cache it. Redirect defaults come from configuration, and the array can override `redirectUrlSuccess` and `redirectUrlCanceled`. Missing URLs raise `IncompleteInformationException`. The `subscription.billing_updated` reaction refreshes the locally stored mandate summary. The [customer portal](https://docs.vatly.com/packages/fluent-php/customerportal) is an alternative for broader self-service billing. ## Read local state carefully `isValid()`, `isOnGracePeriod()`, and `isEnded()` delegate to your local model. They are only as current as your webhook handling. The optional `DerivesSubscriptionState` trait derives them from the end date, not payment status. Handle payment recovery and entitlement rules explicitly; see [Event flow](https://docs.vatly.com/packages/fluent-php/webhook-flow). # Orders Show an invoice for a local order without rebuilding Vatly's invoice UI. Here `$localOrder` implements `OrderInterface` and belongs to the signed-in account: ```php $order = $vatly->order($localOrder); $invoiceUrl = $order->invoiceUrl(); $totalCents = $order->getTotal(); $currency = $order->getCurrency(); ``` Render an invoice link only when `$invoiceUrl` is not `null`. `getTotal()` and `getCurrency()` read local state. `invoiceUrl()` fetches the live API order; it may have no invoice yet. Escape URLs and text in your templates. Persist orders through [Webhooks](https://docs.vatly.com/packages/fluent-php/webhooks). `order.paid` includes tax details and lines; your order writer owns how they map to your database. Do not create a second local order just because a delivery is retried. ## Show refunds and chargebacks Read the net subtotal returned to the customer, regardless of whether it was a refund or chargeback: ```php $order = $vatly->order($localOrder); $reversedCents = $order->reversedSubtotal(); $remainingCents = $order->refundableSubtotal(); $partlyReversed = $order->isPartiallyReversed(); $fullyReversed = $order->isFullyReversed(); $refunds = $order->refunds(); $chargebacks = $order->chargebacks(); $lines = $order->lines(); ``` Reversal amounts are net of tax, in integer cents. They come from the live API, not a sum of your local records. The handle fetches the API order once and shares that snapshot with invoice and reversal helpers. Build a new handle when you need a fresh snapshot. The order remains `paid` after a reversal; do not invent a refunded order status. Your application decides what a refund or dispute means for access. `refunds()`, `chargebacks()`, and `lines()` are local reads. Each returns an empty array if its optional repository is not wired. That does not prove the API has no such records. Wire refund and chargeback repositories to persist their events. Persist lines in your order writer and supply an order-line repository to read them back. ## Find a subscription's orders List the local lines of every order a subscription generated, including the initial signup order, through the order-line repository you wired: ```php $lines = $orderLines->listForSubscription($subscriptionId); $orderIds = array_unique(array_map(fn ($line) => $line->getOrderId(), $lines)); ``` Each line's `getSubscriptionId()` names its subscription, whatever its product. An initial signup line keeps referencing the plan (`productType` is `subscription_plan`); renewals reference the subscription. When your writer stores a line, save `$line->relatedResources?->subscriptionId` with it. It is `null` on one-off lines, on lines Vatly created before it carried the link, and on a signup line whose subscription was not yet available when the order was paid. `listForSubscription()` also returns renewal lines whose `productType` is `subscription` and `productId` is the subscription id, so renewals stored without the link still appear. For refund creation, credit-note fields, and the full order schema, use the underlying SDK through `getApiClient()` and the [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""}. See [Event flow](https://docs.vatly.com/packages/fluent-php/webhook-flow) for persistence behavior. # Customer portal Let a customer manage billing on Vatly's hosted portal instead of building those screens yourself. This works in API-only mode. Pass an authorized customer ID, never an unchecked ID from a query string: ```php use Vatly\Fluent\Vatly; function customerPortal(Vatly $vatly, string $customerId): string { $session = $vatly->customer($customerId)->portalSession([ 'returnUrl' => 'https://app.example.com/account', ]); return $session->url; } ``` Redirect the browser to the returned URL. Create a fresh session when the signed-in customer clicks your billing button. The session URL is short-lived and single-use; do not cache it, log it, email it, or share it between users. The result also exposes `expiresAt` and `returnUrl`. The portal provides hosted invoice history and billing controls. Your app must still receive [Webhooks](https://docs.vatly.com/packages/fluent-php/webhooks) to update local subscriptions when a customer makes a change there. A return to your app does not confirm that anything changed. For a focused address or VAT update on one subscription, use [updateBilling()](https://docs.vatly.com/packages/fluent-php/subscriptions#update-billing). For session fields and available controls, see the [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""}. # Webhooks Keep local billing records current after checkout, renewals, and portal changes. Read the raw request body and the `Vatly-Signature` header, then pass both unchanged to Fluent. This receiver function uses the fully wired instance from [Core concepts](https://docs.vatly.com/packages/fluent-php/coreconcepts): ```php use Vatly\Fluent\Exceptions\InvalidWebhookSignatureException; use Vatly\Fluent\Vatly; function receiveWebhook(Vatly $vatly, string $rawBody, string $signature): int { try { $vatly->webhookProcessor()->handle($rawBody, $signature); return 201; } catch (InvalidWebhookSignatureException $e) { // 503 while no secret is configured, so Vatly retries once it is set. return $e->isSecretNotConfigured() ? 503 : 403; } } ``` Use the returned integer as your HTTP response status. Other failures must produce a non-2xx response so Vatly can retry. Register your public HTTPS receiver in Vatly, set its signing secret in your configuration, and exempt only that route from browser CSRF checks. Never disable signature verification. Webhooks are refused until a secret is configured: with an empty or missing secret, `handle()` throws an `InvalidWebhookSignatureException` whose `isSecretNotConfigured()` returns `true`. ## Verify the exact bytes The header format is `t=,v1=`. The signed message is the timestamp, a dot, and the raw body. The SDK checks the signature and timestamp replay window, then validates the envelope. Do not decode and re-encode JSON before verification. Use the endpoint's signing secret, not your API key. Valid deliveries are recorded, mapped to typed events, passed through built-in reactions, then dispatched to your event bus. The signed resource snapshot supplies the data; built-in reactions do not make enrichment API calls. See [Event flow](https://docs.vatly.com/packages/fluent-php/webhook-flow) for the storage mapping. ## Make retries transactional The simple receiver above does not guarantee idempotency. Fluent's audit repository is not a processed-event ledger, and listeners can run again on redelivery. Use a durable event claim in the same database transaction as the audit log, billing writes, and outbox writes. Here is a complete SQLite transaction boundary. Create this table once in your application's migrations: ```sql CREATE TABLE processed_vatly_events ( event_id TEXT PRIMARY KEY ); ``` Use a PDO connection in exception mode. Every repository and your outbox dispatcher must share this connection and must not commit independently. Supply the same `$secret` that is configured on `$vatly`: ```php use Vatly\API\Exceptions\InvalidSignatureException; use Vatly\API\Exceptions\WebhookSecretNotConfiguredException; use Vatly\API\Webhooks\Webhook; use Vatly\Fluent\Vatly; function receiveOnce(PDO $db, Vatly $vatly, string $body, string $signature, string $secret): int { try { $verified = Webhook::parse($body, $signature, $secret); } catch (WebhookSecretNotConfiguredException) { return 503; } catch (InvalidSignatureException | InvalidArgumentException) { return 403; } $db->beginTransaction(); try { $claim = $db->prepare('INSERT OR IGNORE INTO processed_vatly_events (event_id) VALUES (?)'); $claim->execute([$verified->id]); if ($claim->rowCount() === 0) { $db->commit(); return 201; } $vatly->webhookProcessor()->handle($body, $signature); $db->commit(); return 201; } catch (Throwable $error) { $db->rollBack(); throw $error; } } ``` The second parse inside Fluent is intentional: the first verifies the event ID before deduplication; the processor still verifies every delivery it handles. Adapt the insert to your database's conflict syntax. A lock timeout or deadlock must fail the request and retry, not return success. Queue emails, provisioning, and other external effects through an outbox committed with the billing writes. Do not send an email inside the transaction: a rollback cannot unsend it. Make outbox consumers idempotent too. Event-ID deduplication handles redelivery of one event; unique entity IDs and idempotent fulfillment rules also protect against different events for the same payment. Deliveries can arrive out of order. Store-or-update does not prevent an older snapshot overwriting a newer one, and find-or-skip events cannot repair a missing row. Define reconciliation and stale-event handling in your driver. Persist test mode and keep test deliveries away from live access rules. ## Add application reactions Pass `WebhookReactionInterface` implementations in `Wiring(additionalWebhookReactions: [...])`. They run after built-ins and before the final event dispatch. Typed webhook events live in `Vatly\API\Webhooks\Events`; local-row-created events live in `Vatly\Fluent\Events`. Use [Testing](https://docs.vatly.com/packages/fluent-php/testing) to test signatures, rollback, and retries. For payload fields, see the [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""}. # Event flow Choose the event that matches your task. To listen for a paid order, implement your event dispatcher and register it in `Wiring`. This small adapter forwards typed events to an application callback: ```php use Vatly\Fluent\Contracts\EventDispatcherInterface; final class BillingEvents implements EventDispatcherInterface { public function __construct(private Closure $listener) {} public function dispatch(object $event): void { ($this->listener)($event); } } ``` In production, let that callback write outbox jobs on the same transaction as your repositories. It receives the typed event after the built-in reactions have run. Follow [Webhooks](https://docs.vatly.com/packages/fluent-php/webhooks) for verification, deduplication, and the transaction boundary. ## Events that save records | Event | Built-in persistence | | ------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `order.paid` | Find by Vatly ID; store a new order or update the existing one. New store data includes lines. | | `order.payment_failed` | Store or update the order with the payload's status, usually `pending` during recovery. It does not invent a `failed` order status. New store data includes lines, so a renewal paid on retry keeps its lines. | | `order.canceled` | Update an existing order's status and cancellation reason; skip if missing. | | `subscription.started` | Store a new subscription or update an existing one. | | `subscription.updated` | Update an existing subscription's plan, name, and quantity for an immediate change. | | `subscription.billing_updated` | Update an existing subscription's mandate summary. | | `subscription.resumed` | Clear the end date on an existing subscription. | | `subscription.canceled_immediately`, `subscription.canceled_with_grace_period` | Update the existing subscription's confirmed end date and reason. | | `subscription.canceled_for_nonpayment` | End the existing subscription after recovery is exhausted, with reason `payment_failure`. | | `subscription.cancellation_grace_period_completed` | Stamp the actual end date on an existing subscription. | | `refund.completed`, `refund.failed`, `refund.canceled` | Store or update only when a refund repository is wired. | | `order.chargeback_received`, `order.chargeback_reversed` | Store or update only when a chargeback repository is wired. The order stays `paid`. | Order and subscription creation resolve `hostCustomerId` through your binding repository. It can be `null`. The store DTOs carry `testmode`; persist it. Order, refund, and chargeback store DTOs also carry totals, currency, and tax details. All entity stores can return `null` for an unroutable record. Successful new paid-order and subscription stores dispatch `OrderWasCreatedFromWebhook` and `SubscriptionWasCreatedFromWebhook`. Updates do not dispatch those local-created events. This distinction is not a concurrency lock: enforce unique IDs and transactions in storage. Partial updates use `null` for no change. Persist cancellation reasons if your host needs them. Subscription resume uses `clearEndsAt: true`; honor it in your writer. ## Events your app handles | Event | Useful for | | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------- | | `subscription.update_scheduled` | Showing a pending next-cycle change from the typed `scheduledUpdate`. No current local plan change. | | `checkout.paid` | Checkout analytics or handoff. Use `order.paid` for full order persistence. | | `checkout.failed`, `checkout.canceled`, `checkout.expired` | Retry and abandoned-cart flows. | | `webhook.setup` | Endpoint setup verification; acknowledge with 2xx. | | Product update, approval, rejection, archive, and unarchive events | Catalog notifications; no built-in storage. | | Unknown event names | `UnsupportedWebhookReceived`, so you can observe new events without inventing a handler. | Refund and chargeback events still dispatch when their optional repositories are absent. Checkout events do not create local orders or bindings on their own. Anonymous checkout events may have no customer ID yet. ## Money and snapshots Typed event classes are owned by `vatly-api-php` in `Vatly\API\Webhooks\Events`. Money-bearing events use `Money`, not integer amounts. For paid orders and refunds, read currency from `total->currency`; use `total->toCents()` for local integer cents. Chargeback amounts are nullable at the event contract level and retain a separate currency field. Fluent builds events from the signed resource snapshot without a follow-up GET. Its reactions flatten money to integer cents in persistence DTOs. They do not save subscription prices or build entitlement policy for you. Reversal totals are read live through the [order handle](https://docs.vatly.com/packages/fluent-php/orders), not synthesized into order statuses. See [Host tables](https://docs.vatly.com/packages/fluent-php/host-owns-its-tables) for routing initial payments and renewals, and the [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""} for complete payload fields. # Host tables Reuse an application's existing orders instead of creating parallel Fluent tables. Wrap its record in `OrderInterface`, then let your repository confirm that record when the payment webhook arrives. This example uses PDO and an existing `host_orders` table with `id`, `vatly_id`, `status`, `invoice_number`, `total`, `currency`, `payment_method`, and `testmode` columns. `id` is the host primary key; make `vatly_id` unique. `$db` uses exception mode. Keep additional ownership, tax, and fulfillment fields required by your application. ## Wrap the host record ```php use Vatly\Fluent\Contracts\OrderInterface; final class HostOrder implements OrderInterface { public function __construct(public readonly array $row) {} public function getVatlyId(): string { return $this->row['vatly_id']; } public function getStatus(): string { return $this->row['status']; } public function getInvoiceNumber(): ?string { return $this->row['invoice_number']; } public function getTotal(): int { return (int) $this->row['total']; } public function getCurrency(): string { return $this->row['currency']; } public function getPaymentMethod(): ?string { return $this->row['payment_method']; } public function isPaid(): bool { return $this->getStatus() === 'paid'; } public function isTestmode(): bool { return (bool) $this->row['testmode']; } } ``` ## Confirm once, reconcile on retry Create your host order before checkout. Stamp its server-chosen ID in `withMetadata(['host_order_id' => ...])`, as shown in [Checkouts](https://docs.vatly.com/packages/fluent-php/checkouts). Wire this repository as `Wiring(orders: ...)`: ```php use Vatly\Fluent\Contracts\OrderInterface; use Vatly\Fluent\Contracts\OrderRepositoryInterface; use Vatly\Fluent\Data\StoreOrderData; use Vatly\Fluent\Data\UpdateOrderData; final class HostOrders implements OrderRepositoryInterface { public function __construct(private PDO $db) {} public function findByVatlyId(string $vatlyId): ?OrderInterface { $query = $this->db->prepare('SELECT * FROM host_orders WHERE vatly_id = ?'); $query->execute([$vatlyId]); $row = $query->fetch(PDO::FETCH_ASSOC); return $row === false ? null : new HostOrder($row); } public function store(StoreOrderData $data): ?OrderInterface { $hostId = $data->metadata['host_order_id'] ?? null; if ($hostId === null) { return null; } $query = $this->db->prepare( 'UPDATE host_orders SET vatly_id = ?, status = ?, invoice_number = ?, ' . 'total = ?, currency = ?, payment_method = ?, testmode = ? ' . 'WHERE id = ? AND vatly_id IS NULL AND testmode = ?' ); $query->execute([ $data->vatlyId, $data->status, $data->invoiceNumber, $data->total, $data->currency, $data->paymentMethod, (int) $data->testmode, $hostId, (int) $data->testmode, ]); return $this->findByVatlyId($data->vatlyId); } public function update(OrderInterface $order, UpdateOrderData $data): OrderInterface { $query = $this->db->prepare( 'UPDATE host_orders SET status = ?, invoice_number = ?, total = ?, ' . 'currency = ?, payment_method = ? WHERE vatly_id = ?' ); $query->execute([ $data->status ?? $order->getStatus(), $data->invoiceNumber ?? $order->getInvoiceNumber(), $data->total ?? $order->getTotal(), $data->currency ?? $order->getCurrency(), $data->paymentMethod ?? $order->getPaymentMethod(), $order->getVatlyId(), ]); return $this->findByVatlyId($order->getVatlyId()) ?? throw new RuntimeException('Host order disappeared during update'); } } ``` `store()` here means attach the Vatly ID and confirm an existing row, not insert. Once attached, the built-in reaction finds that ID and calls `update()` on redelivery. The wrapper includes every current `OrderInterface` method, including `isTestmode()`. This minimal adapter stores order summary fields only. Extend your writer to save subtotal, tax summary, metadata, cancellation reason, and lines if your host needs them. Do not overwrite fields when an update DTO leaves them `null`. Use [Webhooks](https://docs.vatly.com/packages/fluent-php/webhooks) to make attachment, audit, and fulfillment atomic. Missing routing data may return `null`; database failures must throw. ## Route renewals separately An initial payment often points to a host order already created by checkout. A renewal may need a new host order. Confirm the initial row when its metadata ID matches. Otherwise, resolve the host customer from `$data->hostCustomerId` and use your host's renewal service only when you can establish the subscription and payment relationship. Missing metadata alone is not proof of a renewal. It can also mean an anonymous payment, a deleted order, or another integration. Check storefront, mode, and ownership; return `null` or send the event for reconciliation when it cannot be routed. Give renewal creation a unique Vatly order ID so retries cannot insert twice. Use the same pattern for subscriptions: a wrapper implementing `SubscriptionInterface`, a unique Vatly ID, and a repository that applies partial updates and explicit clear flags. See [Core concepts](https://docs.vatly.com/packages/fluent-php/coreconcepts) and [Event flow](https://docs.vatly.com/packages/fluent-php/webhook-flow). Full payload fields are in the [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""}. # Testing Test your application's checkout decisions without making a request to Vatly. Inject `FakeVatly` where your application expects `Vatly`, then call your real checkout handler with it. ```php use Vatly\Fluent\CustomerProfile; use Vatly\Fluent\Testing\FakeCheckout; use Vatly\Fluent\Testing\FakeVatly; $fake = (new FakeVatly())->onSubscriptionCreate( fn (string $planId) => FakeCheckout::make('https://checkout.vatly.test/example'), ); $checkout = $fake->subscriptionBuilder(new CustomerProfile(vatlyId: 'customer_example')) ->toPlan('subscription_plan_pro') ->withQuantity(3) ->create(); \PHPUnit\Framework\Assert::assertSame( 'https://checkout.vatly.test/example', $checkout->links->checkoutUrl->href, ); $fake->assertSubscriptionCreated('subscription_plan_pro'); $fake->assertNothingCanceled(); ``` Install PHPUnit as a development dependency to use the `assert*` helpers. `withDefaultCheckout()` sets a shared result; `onCheckoutCreate()` scripts one-off checkout results. The fake also records swaps and cancellations routed through its subscription handles. Fakes test your application branches, not API validation, signature checking, or database behavior. Only use the fake surfaces you have scripted; it is not a sandbox for every SDK operation. ## Test your webhook receiver Use a local fixture and an independent HMAC signature. This sends no request to Vatly: ```php $secret = 'local-fixture-secret'; $payload = json_encode([ 'id' => 'event_fixture', 'resource' => 'webhook_event', 'eventName' => 'webhook.setup', 'entityType' => 'webhook_endpoint', 'entityId' => 'webhook_endpoint_fixture', 'testmode' => true, 'createdAt' => '2026-01-01T00:00:00Z', 'object' => ['id' => 'webhook_endpoint_fixture'], ], JSON_THROW_ON_ERROR); $timestamp = time(); $signature = 't=' . $timestamp . ',v1=' . hash_hmac('sha256', $timestamp . '.' . $payload, $secret); $verifier = new \Vatly\Fluent\Webhooks\SignatureVerifier(); \PHPUnit\Framework\Assert::assertTrue($verifier->isValid($signature, $payload, $secret)); \PHPUnit\Framework\Assert::assertFalse($verifier->isValid($signature, $payload . ' ', $secret)); ``` Configure your test processor with that secret and pass the raw body and header through your HTTP handler. Assert a valid delivery is committed, an invalid signature writes nothing, and redelivery does not fulfill twice. Force a repository error after the audit write and prove the whole transaction rolls back. Test two concurrent deliveries against your real database, not just an in-memory repository. For subscription access, cover a future grace end, a past end, resume clearing the date, and nonpayment cancellation. For orders, cover initial payment, renewal, duplicate delivery, and a reversal without changing `paid` to a made-up status. ## Exercise the Vatly sandbox With a test key, `testHelpers()->advanceRenewal($id)`, `forceRenewalPaid($id)`, and `forceRenewalFailed($id, 'card_expired')` advance real test-mode state and provoke webhooks. Unlike the fakes above, these make remote writes. Use them only in a dedicated sandbox integration test, never with live records. For sandbox fields, see the [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""}. For receiver design, see [Webhooks](https://docs.vatly.com/packages/fluent-php/webhooks). # Laravel ![Vatly for Laravel](https://raw.githubusercontent.com/Vatly/vatly-laravel/main/art/banner.png) Vatly Laravel provides a Cashier-like integration for [Vatly](https://vatly.com){rel=""nofollow""} billing in your Laravel application. It handles subscriptions, checkouts, customers, webhooks, and payment method updates. ::note **Evaluating Vatly, or moving from another biller?** - [How Vatly compares to Cashier (Stripe, Paddle) & Lemon Squeezy](https://docs.vatly.com/packages/laravel/comparison) — for a greenfield app. - [Migrating from Cashier](https://docs.vatly.com/packages/laravel/migrating-to-vatly) — run it alongside your current one and move customers over gradually. :: ## Requirements - PHP 8.3+ - Laravel 12 or 13 - A Vatly API key ## Installation ```bash composer config minimum-stability alpha composer config prefer-stable true composer require vatly/vatly-laravel ``` ::warning This package is in alpha, and every alpha release may include breaking changes. The two `config` commands let Composer install alpha releases while `prefer-stable` keeps your other dependencies on stable releases. Composer installs the latest alpha and records it in `composer.lock` . :: ## Configuration Publish the config file: ```bash php artisan vendor:publish --tag=vatly-config ``` Add your credentials to `.env`: ```env VATLY_KEY=test_xxxxxxxxxxxxxxxxxxxx VATLY_WEBHOOK_SECRET=your-webhook-secret VATLY_REDIRECT_URL_SUCCESS=https://your-app.com/checkout/success VATLY_REDIRECT_URL_CANCELED=https://your-app.com/checkout/canceled ``` ### Available config options | Key | Env variable | Default | | ----------------------- | ----------------------------- | ------------------------ | | `api_key` | `VATLY_KEY` | (required) | | `api_url` | `VATLY_API_URL` | `https://api.vatly.com` | | `api_version` | `VATLY_API_VERSION` | `v1` | | `webhook_secret` | `VATLY_WEBHOOK_SECRET` | (required for webhooks) | | `billable_model` | `VATLY_BILLABLE_MODEL` | `App\Models\User` | | `redirect_url_success` | `VATLY_REDIRECT_URL_SUCCESS` | (required for checkouts) | | `redirect_url_canceled` | `VATLY_REDIRECT_URL_CANCELED` | (required for checkouts) | ::note Testmode is automatically determined from your API key prefix. Keys starting with `test_` use testmode; keys starting with `live_` use production mode. No configuration needed. :: ## Database setup Publish and run the migrations: ```bash php artisan vendor:publish --tag=vatly-billable-migrations php artisan vendor:publish --tag=vatly-migrations php artisan migrate ``` This creates: - A `vatly_id` column on your users table - A `vatly_subscriptions` table - A `vatly_webhook_calls` table ## Billable model Add the `Billable` trait and implement `BillableInterface` on your User model: ```php use Vatly\Laravel\Contracts\BillableInterface; use Vatly\Laravel\Billable; class User extends Authenticatable implements BillableInterface { use Billable; } ``` This gives your User model access to all Vatly billing methods: customer management, subscriptions, checkouts, and orders. # Configuration Vatly Laravel needs your API credentials, webhook secret, and default redirect URLs. ## Publish the config file ```bash php artisan vendor:publish --tag=vatly-config ``` This publishes `config/vatly.php` so you can customize the package defaults. ## Environment variables Add your credentials to `.env`: ```env VATLY_KEY=test_xxxxxxxxxxxxxxxxxxxx VATLY_WEBHOOK_SECRET=your-webhook-secret VATLY_REDIRECT_URL_SUCCESS=https://your-app.com/checkout/success VATLY_REDIRECT_URL_CANCELED=https://your-app.com/checkout/canceled ``` ## Available config options | Config key | Env variable | Description | | ----------------------- | ----------------------------- | ----------------------------------------------------------------------- | | `api_key` | `VATLY_KEY` | Your Vatly API key. Use `test_` in test mode and `live_` in production. | | `webhook_secret` | `VATLY_WEBHOOK_SECRET` | Secret used to verify incoming webhook signatures. | | `redirect_url_success` | `VATLY_REDIRECT_URL_SUCCESS` | Default success URL for hosted checkout and billing flows. | | `redirect_url_canceled` | `VATLY_REDIRECT_URL_CANCELED` | Default cancel URL for hosted checkout and billing flows. | ## Example config file ```php return [ 'api_key' => env('VATLY_KEY'), 'webhook_secret' => env('VATLY_WEBHOOK_SECRET'), 'redirect_url_success' => env('VATLY_REDIRECT_URL_SUCCESS'), 'redirect_url_canceled' => env('VATLY_REDIRECT_URL_CANCELED'), ]; ``` ## Test mode vs live mode The package uses whatever API key you configure: - `test_...` keys talk to your Vatly test environment - `live_...` keys talk to your live environment Use test credentials while building your integration. Switch to your live key only when your products, Mollie onboarding, and webhook handling are ready for production. ## Webhook configuration Make sure your webhook secret in `.env` matches the webhook endpoint configured in Vatly. The package uses this secret to verify the `Vatly-Signature` header on incoming webhooks. For the full webhook setup flow, see [Webhooks](https://docs.vatly.com/packages/laravel/webhooks). # Customers Every billable model can be linked to a Vatly customer. Customers are created automatically by Vatly during checkout and synced to your application via webhooks. You can also create customers explicitly if needed. ## Creating a customer ```php // Create a Vatly customer for this user $user->createAsVatlyCustomer(); // Create with extra data $user->createAsVatlyCustomer([ 'locale' => 'nl_NL', 'metadata' => ['internal_id' => $user->id], ]); ``` ## Checking customer status ```php // Check if the user has a Vatly customer ID $user->hasVatlyId(); // bool // Get the Vatly customer ID $user->getVatlyId(); // string|null ``` ## Retrieving customer data ```php // Get the full customer object from the Vatly API $customer = $user->asVatlyCustomer(); ``` ## Updating customer identity Update the customer's `name` and/or `email` at Vatly (both optional — send whichever changed). Billing-address details (company name, tax id, street, …) are **not** editable here; send the customer through the hosted billing-update flow for those. ```php $customer = $user->updateVatlyCustomer([ 'name' => 'Jane Doe', 'email' => 'jane@example.com', ]); ``` Throws `NoVatlyCustomerException` if the user has no Vatly customer yet. ## Customer portal Vatly hosts a self-service customer portal where a customer manages their own billing — payment method, invoices, subscription self-service. Generate a single-use entry link for the current user and redirect to it: ```php // The one-liner: redirect to the hosted portal return redirect($user->vatlyPortalUrl()); // Render a "back to your app" link inside the portal return redirect($user->vatlyPortalUrl(returnUrl: route('billing'))); ``` Need the expiry as well as the URL, call `vatlyPortalSession()`: ```php $session = $user->vatlyPortalSession(returnUrl: route('billing')); $session->url; // single-use HTTPS entry link $session->expiresAt; // ISO 8601 — the link expires after ~15 minutes ``` The link is locked to this customer **and to the storefront your configured Vatly API token is issued for** — the customer lands directly in that one storefront's portal, never a storefront picker or any other store. (If your Vatly account has multiple storefronts, each API token mints portal links for its own store.) It expires after roughly 15 minutes and can be used once. It is credential-bearing, so **never cache or log it** — generate a fresh one each time you send the customer to the portal. Both helpers throw `NoVatlyCustomerException` if the user has no Vatly customer yet. Both are available under the same names on the coexistence-friendly `VatlyBillable` trait (they already carry the `vatly` prefix, so there's no collision with another Cashier-style biller). Under the hood these delegate to the framework-agnostic customer handle, which you can also reach directly for a customer id you already hold: ```php use Vatly\Laravel\Facades\Vatly; $session = Vatly::customer($vatlyCustomerId)->portalSession(['returnUrl' => route('billing')]); ``` ## How it works The `vatly_id` column on your billable model stores the Vatly customer identifier. When you call `createAsVatlyCustomer()`, it: 1. Sends a `POST` request to the Vatly API to create a customer 2. Stores the returned customer ID in the `vatly_id` column 3. Returns the customer response If the user already has a `vatly_id`, calling `createAsVatlyCustomer()` will throw a `CustomerAlreadyBoundException`. ## Automatic customer creation When a user starts a checkout without an existing Vatly customer ID, Vatly creates the customer automatically during the checkout flow. The customer ID is synced back to your application via webhooks. This means you don't need to call `createAsVatlyCustomer()` before starting a checkout — just redirect the user directly. ## Anonymous / guest checkouts A common flow: a visitor buys *before* they sign up — checkout completes, Vatly fires `order.paid` / `subscription.started` webhooks, and your app has no `User` row to attribute the purchase to yet. The package handles this without losing data: - The `vatly_subscriptions` and `vatly_orders` tables both have a nullable `owner_id`/`owner_type` plus a `customer_id` column. The webhook writes the row with `owner_id = null` but populates `customer_id` with the Vatly customer id (`cus_…`). - When the visitor returns on the checkout-success redirect, call `claimVatlyCustomerFromReturn()` to link those rows to the now-known user. ### Learning the checkout on the redirect back: the `{CHECKOUT_ID}` placeholder The one hard part of guest checkout is: *how does your app know which Vatly customer to claim when the buyer lands back on your site?* You don't have to plumb the `cus_…` through a session or cookie yourself (that approach breaks under multi-tab / double-click — the last write wins, and the buyer may finish the checkout that *isn't* in the session). Instead, put the literal `{CHECKOUT_ID}` placeholder in your return URL. Vatly substitutes it with the checkout's id at creation: ```php $user->checkout()->create( items: [['id' => 'product_abc123', 'quantity' => 1]], redirectUrlSuccess: route('vatly.return').'?checkout_id={CHECKOUT_ID}', redirectUrlCanceled: route('billing'), ); ``` On the return route, hand the request to `claimVatlyCustomerFromReturn()`: ```php public function return(Request $request) { // Reads ?checkout_id=…, resolves that checkout's Vatly customer, and // (if there is one) claims it for the authenticated user. $request->user()->claimVatlyCustomerFromReturn($request); return redirect()->route('dashboard'); } ``` It returns `true` when a claim happened and `false` for a missing / unknown checkout id or a checkout with no customer yet — so it's safe to call unconditionally. Pass a second argument to read a different query key: ```php $user->claimVatlyCustomerFromReturn($request, 'cid'); // reads ?cid=… ``` This is **multi-tab safe by construction**: each tab carries its own checkout id in its own redirect URL, so two checkouts in flight resolve independently — there is no shared carrier whose last write wins. ::note The checkout id travels in the URL, so it may also appear in the `Referer` header and your server logs. It is low-sensitivity — it only names a checkout the buyer just completed — but treat it like any URL parameter. :: Under the hood `claimVatlyCustomerFromReturn()` resolves the checkout's customer id via the Vatly API and then runs `claimVatlyCustomer()`, which: 1. Binds the Vatly customer id to this host entity via the configured `CustomerBindingRepository` (default impl: writes `vatly_id` on the billable table). 2. Saves the model. 3. Backfills `owner_type` / `owner_id` on every `vatly_subscriptions` and `vatly_orders` row that carries the same `customer_id` but had no owner yet. The `order.paid` / `subscription.started` webhook usually lands *before* the buyer is redirected back, so those rows already exist (with `owner_id = null`) by the time you claim — step 3 simply backfills them. The reverse order works too: if the claim runs first, it binds the customer, and a later webhook for the same `customer_id` finds the binding and writes `owner_id` directly. Either way the purchase ends up attributed. If you already hold the `cus_…` by other means, you can still call `claimVatlyCustomer($vatlyCustomerId)` directly; it returns the number of rows re-attributed. ::note **Out of scope:** buyers who never come back via the redirect link (closed the tab, switched device). Recovering those is the email-based recovery story — a separate concern this helper does not cover. :: Need the email / name on the customer to surface a "would you like to claim purchase X?" prompt at signup? Fetch the customer via the Vatly API: ```php $customer = app(\Vatly\Fluent\Vatly::class) ->customers() ->findByVatlyCustomerId($vatlyCustomerId); $customer->email; $customer->name; ``` # Checkouts Checkouts redirect your customer to Vatly's hosted payment page. After payment, the customer is redirected back to your application. ## Creating a checkout ```php $checkout = $user->checkout()->create( items: [['id' => 'product_abc123', 'quantity' => 1]], redirectUrlSuccess: 'https://your-app.com/success', redirectUrlCanceled: 'https://your-app.com/canceled', ); return redirect($checkout->links->checkoutUrl->href); ``` `$checkout` is a `Vatly\API\Resources\Checkout` — see [vatly-api-php](https://github.com/Vatly/vatly-api-php){rel=""nofollow""} for the full resource shape. ## Subscription checkouts For subscriptions, use the `subscribe()` builder. Redirect URLs default to those in `config/vatly.php` so the call can be just one line: ```php $checkout = $user->subscribe() ->toPlan('subscription_plan_monthly') ->create(); return redirect($checkout->links->checkoutUrl->href); ``` ## Checkout with metadata ```php $checkout = $user->checkout() ->withMetadata(['campaign' => 'summer-2025']) ->create( items: [['id' => 'product_abc123', 'quantity' => 1]], redirectUrlSuccess: 'https://your-app.com/success', redirectUrlCanceled: 'https://your-app.com/canceled', ); ``` ## Checkout language (locale) Set `locale` to present the hosted checkout — including its validation and error messages — in the customer's language. Do this when you already know their language: it is a better signal than their browser's, and it carries through to the payment provider's own hosted page. `create()` takes a fourth argument, `payloadOverrides`, that is merged into the checkout payload, so pass `locale` there: ```php $checkout = $user->checkout()->create( items: [['id' => 'product_abc123', 'quantity' => 1]], redirectUrlSuccess: 'https://your-app.com/success', redirectUrlCanceled: 'https://your-app.com/canceled', payloadOverrides: ['locale' => 'de'], ); ``` For the subscription flow, `subscribe()->create()` takes the same overrides: ```php $checkout = $user->subscribe() ->toPlan('subscription_plan_monthly') ->create(['locale' => 'de']); ``` Send a bare language code (`de`), a BCP 47 tag (`de-AT`), or a POSIX / ISO 15897 locale (`de_DE`) — whichever your stack already stores. All three fold to the language, so `de`, `de-AT` and `de_DE` are the same request; there are no region-specific variants. Leave `locale` unset to let Vatly fall back to the customer's browser language. ## Prefill the billing address If you already know the customer's billing details, prefill them with `withBillingAddress()`. It is on both `checkout()` and `subscribe()`: ```php $checkout = $user->subscribe() ->toPlan('subscription_plan_monthly') ->withBillingAddress([ 'companyName' => 'Acme BV', 'streetAndNumber' => 'Damrak 1', 'postalCode' => '1012 LG', 'city' => 'Amsterdam', 'country' => 'NL', 'taxId' => 'NL123456789B01', ]) ->create(); ``` The accepted fields are `fullName`, `companyName`, `streetAndNumber`, `streetAdditional`, `postalCode`, `city`, `region`, `country` (ISO 3166-1 alpha-2) and `taxId`; send only the ones you have. The customer can still edit every field. A supplied `country` takes precedence over the customer's IP address for determining their country, and a `taxId` is only registered once the customer submits the checkout. ## How it works The checkout flow: 1. Your app creates a checkout session via the Vatly API (customer is created automatically if needed) 2. The customer is redirected to Vatly's hosted payment page 3. After payment, the customer returns to your `redirectUrlSuccess` 4. Vatly sends a webhook to confirm the payment (see [Webhooks](https://docs.vatly.com/packages/laravel/webhooks)) 5. If this was a new customer, the customer ID is synced to your local database via webhook The redirect URLs default to the values in your `vatly.php` config but can be overridden per checkout. # Subscriptions Vatly Laravel provides a full subscription lifecycle: creating, checking, swapping plans, canceling, and syncing with the Vatly API. ## Starting a subscription ```php $checkout = $user->subscribe() ->toPlan('subscription_plan_annual') ->create(); return redirect($checkout->links->checkoutUrl->href); ``` ### With a free trial Trials defer the first charge until the trial elapses. Set them on the builder, in whole days or by end date: ```php // Whole days from checkout creation $user->subscribe() ->toPlan('subscription_plan_annual') ->withTrialDays(14) ->create(); // Or an end date — the remaining time is rounded *up* to whole days, so the // trial never ends earlier than requested (Vatly's trial input is day-granular) $user->subscribe() ->toPlan('subscription_plan_annual') ->withTrialEndsAt(now()->addMonth()) ->create(); ``` `withTrialDays()` throws for a length below 1 day; `withTrialEndsAt()` throws for a date that isn't in the future. When no trial is set the checkout payload omits `trialDays` entirely, so any plan-level default at Vatly still applies. ## Checking subscription status ```php // Check if the user is subscribed $user->subscribed(); // bool $user->subscribed('premium'); // check a specific subscription type // Get the subscription as a fluent handle (operations live here) $subscription = $user->subscription(); // default type, returns ?SubscriptionHandle $subscription = $user->subscription('premium'); // Get all subscriptions as Eloquent models (state-only) $subscriptions = $user->subscriptions; // Collection ``` `$user->subscription('default')` returns a `Vatly\Fluent\SubscriptionHandle` — a lightweight wrapper around the underlying Eloquent model that exposes API-driven operations (`swap`, `cancel`, `sync`, `updateBilling`). Reach the Eloquent model via `$subscription->model()` if you need it directly. ## Subscription state ```php $subscription->active(); // currently active (including grace period) $subscription->cancelled(); // has been cancelled $subscription->onGracePeriod(); // cancelled but still active until ends_at ``` ## Swapping plans ```php // Swap to a new plan (takes effect at the end of the current period by default) $user->subscription()->swap('subscription_plan_annual'); // Swap and invoice immediately (applies now, charges the prorated delta now) $user->subscription()->swapAndInvoice('subscription_plan_annual'); // Swap now without charging for the change (the next renewal bills the new price) $user->subscription()->swapWithoutCharge('subscription_plan_premium'); ``` ### Proration options `swap()` takes an optional `$options` array that is passed straight through to the Vatly API. Four flags control how the change is timed and billed: | Option | Default | Effect | | -------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `applyImmediately` | `false` | `true` applies the change now; `false` applies it when the current period ends | | `prorate` | `true` | `true` credits unused time on the old plan and charges remaining time on the new plan. `false` charges the full new price for the current cycle on top of what was already paid: it does **not** skip the charge. Ignored when `prorationCharge` is `false` | | `prorationCharge` | `true` | Whether an immediate change is charged at all. `false` applies the change now and charges nothing for it; the next renewal bills the new price, unless a change is already scheduled for that renewal: that change still applies | | `invoiceImmediately` | `false` | Only applies when `applyImmediately` and `prorate` are both `true`. `true` raises a separate invoice for the proration delta right away; `false` parks the delta on the current cycle and bills it as a line on the **next renewal invoice** | ```php // Apply the change now, but defer the prorated charge to the next renewal (the default proration behavior) $user->subscription()->swap('subscription_plan_annual', ['applyImmediately' => true]); // Apply now and charge the prorated delta on a separate invoice immediately $user->subscription()->swap('subscription_plan_annual', [ 'applyImmediately' => true, 'invoiceImmediately' => true, ]); // Apply now without charging for the change (the plan must keep the same billing interval). // The next renewal bills the new price $user->subscription()->swap('subscription_plan_premium', [ 'applyImmediately' => true, 'prorationCharge' => false, ]); ``` Vatly only reads `prorationCharge` on an immediate change: without `applyImmediately: true`, the change is scheduled for the end of the period and nothing is charged now anyway. `swapWithoutCharge()` sets both for you. With `prorationCharge: false`, a downgrade gets no credit, and during a trial the trial keeps running and its end bills the new plan. Sending `invoiceImmediately: true`, `anchor`, `resetAnchor`, `trialUntil` or a plan with a different interval with it returns a `422`, so don't pass it to `swapAndInvoice()`. `swapAndInvoice()` is exactly `swap()` with `applyImmediately` and `invoiceImmediately` both forced to `true`. `swapWithoutCharge()` is exactly `swap()` with `applyImmediately` forced to `true` and `prorationCharge` forced to `false`. **When to charge immediately.** With the default `invoiceImmediately: false`, the customer gets one invoice and one payment covering both the renewal and the parked delta — and if they cancel before that renewal, the parked amount is waived (a customer is never charged at the moment they cancel). That default suits **monthly** billing, where the delta is collected within weeks. **Set `invoiceImmediately: true` on yearly and other long-interval plans:** an upgrade in month 2 of a yearly plan would otherwise not be billed until month 12 (and is waived entirely if the customer cancels in between), so the longer the interval the more the deferral costs you. ### Immediate vs. scheduled changes However the swap is applied, Vatly confirms the outcome over webhooks, and the package keeps the local `plan_id` / `name` / `quantity` in step: - An **immediate** change (`applyImmediately: true`) raises a `subscription.updated` webhook → the `SubscriptionUpdated` event; the local plan/name/quantity are refreshed. - A change **scheduled for the next cycle** (`applyImmediately: false`) raises a `subscription.update_scheduled` webhook → the `SubscriptionUpdateScheduled` event. Nothing changes locally yet; the target values ride in the event's `scheduledUpdate` (a typed `Vatly\API\Types\ScheduledSubscriptionUpdate` exposing `subscriptionPlanId`, `name`, `description`, `basePrice`, `quantity`, `interval`, `intervalCount` and `effectiveAt` — the timestamp the change takes effect), and the eventual switch arrives as a later `subscription.updated`. See [Webhooks](https://docs.vatly.com/packages/laravel/webhooks) for the full event list. ## Canceling ```php // Cancel the subscription at Vatly $user->subscription()->cancel(); ``` The actual cancellation is processed via webhooks. Depending on the Vatly configuration, the subscription may: - End immediately (`SubscriptionCanceledImmediately` event) - Enter a grace period (`SubscriptionCanceledWithGracePeriod` event) A subscription can also be canceled **by Vatly**, not by your `cancel()` call: when payment recovery for a failed renewal is exhausted, Vatly hard-cancels it and sends `subscription.canceled_for_nonpayment` (`SubscriptionCanceledForNonpayment`). The package ends the local subscription exactly as it does for an immediate cancellation — its `ends_at` is stamped, `canceled()` flips to `true` — so you don't need any special handling to keep local state correct. ### Cancellation reason Vatly tags each cancellation with a reason. The package **persists it locally**: on any cancellation webhook (`subscription.canceled_immediately`, `subscription.canceled_with_grace_period`, `subscription.canceled_for_nonpayment`) the reason is written to the `cancellation_reason` column on the `vatly_subscriptions` row, so you can read it straight off the model: ```php $user->subscription()->model()->cancellation_reason; // e.g. "payment_failure", or null if not canceled ``` The same value is on the dispatched event as `$event->cancellationReason` (`Vatly\API\Types\CancellationReason`): | Value | Meaning | | ------------------ | ----------------------------------------------------------------------------------------------------- | | `payment_failure` | Payment recovery was exhausted after failed renewals (carried by `SubscriptionCanceledForNonpayment`) | | `merchant_request` | The merchant canceled the subscription | | `customer_request` | The customer canceled from the self-service portal | Listen for the cancellation event to branch dunning / win-back flows off the reason: ```php use Illuminate\Support\Facades\Event; use Vatly\API\Types\CancellationReason; use Vatly\API\Webhooks\Events\SubscriptionCanceledForNonpayment; Event::listen(SubscriptionCanceledForNonpayment::class, function (SubscriptionCanceledForNonpayment $event) { // $event->subscriptionId // $event->customerId // $event->endsAt // $event->cancellationReason === CancellationReason::PAYMENT_FAILURE // Trigger a win-back email, flag the account for re-collection, etc. }); ``` The local `cancellation_reason` is only ever set, never cleared, by the webhook reactions — a `null` reason on an incoming update leaves the stored value untouched. If you also need the live value from Vatly, it's on the API resource as `Vatly\API\Resources\Subscription::$cancellationReason` (fetched via `Vatly::getSubscription()->execute($vatlyId)`). ## Updating billing details ```php // Create a signed URL where the customer can update their billing details // (address, VAT number, company name). Going through the hosted flow also // refreshes the Mollie mandate as a side effect. $url = $user->subscription()->updateBilling(); return redirect($url); ``` ## Syncing with Vatly Pull the latest subscription data from the Vatly API: ```php $user->subscription()->sync(); ``` This updates the local `plan_id`, `name`, `quantity`, `ends_at`, and `trial_ends_at` fields. ## Subscription types You can have multiple subscriptions per user by using types: ```php // A user with both a "default" and "addon" subscription $user->subscription('default'); // main plan $user->subscription('addon'); // additional features ``` The default type is `'default'`. # Orders Orders represent completed transactions in Vatly. They are created automatically when a checkout completes or a subscription renews. ## Listing orders ```php // Get all orders for a user $orders = $user->orders; // Orders are sorted by most recent first $latestOrder = $user->orders->first(); ``` ## Why an order was canceled Vatly tags an order with a reason when payment recovery for the unpaid order is exhausted. On the `order.canceled` webhook the package stores it in the `cancellation_reason` column on the `vatly_orders` row: ```php $order->status; // "canceled" $order->cancellation_reason; // "payment_failure", or null for any other order ``` The same value is on the dispatched `Vatly\API\Webhooks\Events\OrderCanceled` event as `$event->cancellationReason`. Compare it against `Vatly\API\Types\CancellationReason::PAYMENT_FAILURE`. Existing installations need the new column. Publish the migrations again with `php artisan vendor:publish --tag=vatly-migrations`, keep the new `add_cancellation_reason_to_vatly_orders_table` migration, delete the other newly published copies, and run `php artisan migrate`. ## A subscription's order lines Each line stored from an `order.paid` webhook records the subscription it belongs to in the `subscription_id` column on `vatly_order_lines`, including the initial signup line, which references the plan (`product_type` is `subscription_plan`). List every line of a subscription, initial order included, through the order-line repository: ```php use Vatly\Fluent\Contracts\OrderLineRepositoryInterface; $lines = app(OrderLineRepositoryInterface::class)->listForSubscription($subscription->vatly_id); $orderIds = array_unique(array_map(fn ($line) => $line->getOrderId(), $lines)); ``` `subscription_id` is null on one-off lines, on lines Vatly created before it carried the link, and on a signup line whose subscription was not yet available when the order was paid. Lines are written once, so such a line stays unlinked. `listForSubscription()` also returns renewal lines whose `product_type` is `subscription` and `product_id` is the subscription id, so renewals stored without the link still appear. Existing installations need the new column. Publish the migrations again with `php artisan vendor:publish --tag=vatly-migrations`, keep the new `add_subscription_id_to_vatly_order_lines_table` migration, delete the other newly published copies, and run `php artisan migrate`. ## How it works Orders are synced from Vatly via webhooks. The `orders()` relationship returns all orders associated with the billable model through a polymorphic relationship. # Webhooks Vatly sends webhooks to notify your application of events like subscription starts, cancellations, and payment updates. Vatly Laravel handles webhook verification, storage, and event dispatching automatically. ## Endpoint The package registers a webhook endpoint at: ```text POST /webhooks/vatly ``` Configure this URL in your Vatly dashboard. Make sure to set your `VATLY_WEBHOOK_SECRET` in `.env`. Webhooks are refused until a secret is configured: while `VATLY_WEBHOOK_SECRET` is empty or unset, the endpoint answers `503 webhook_secret_not_configured` and processes nothing, and Vatly retries the delivery once the secret is set. ## CSRF protection Exclude the webhook route from CSRF verification. In Laravel 11+, this is typically done in `bootstrap/app.php`: ```php ->withMiddleware(function (Middleware $middleware) { $middleware->validateCsrfTokens(except: [ 'webhooks/vatly', ]); }) ``` ## Events When a webhook is received, the driver's `LaravelEventDispatcher` forwards the typed domain events straight onto Laravel's event bus, so you listen for the DTO classes directly. The webhook event DTOs live in `vatly-api-php` under the `Vatly\API\Webhooks\Events\` namespace (so a payload change is a single api-php release); the exceptions are `SubscriptionWasCreatedFromWebhook` and `OrderWasCreatedFromWebhook`, internal fluent signals under `Vatly\Fluent\Events\`: | Event (`Vatly\API\Webhooks\Events\…`) | Dispatched when | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `SubscriptionStarted` | A `subscription.started` webhook is received | | `SubscriptionBillingUpdated` | A `subscription.billing_updated` webhook is received — the stored mandate is refreshed | | `SubscriptionUpdated` | A `subscription.updated` webhook is received — an immediate plan/price/interval/quantity change; the local `plan_id` / `name` / `quantity` are refreshed | | `SubscriptionUpdateScheduled` | A `subscription.update_scheduled` webhook is received — a change scheduled for the next cycle; dispatched only (no local change), target values in `scheduledUpdate` | | `SubscriptionResumed` | A `subscription.resumed` webhook is received — the stored end date is cleared | | `SubscriptionCanceledImmediately` | A `subscription.canceled_immediately` webhook is received — the local subscription's `ends_at` is stamped | | `SubscriptionCanceledForNonpayment` | A `subscription.canceled_for_nonpayment` webhook is received — a **hard cancellation** after payment recovery for a failed renewal is exhausted. Handled exactly like `subscription.canceled_immediately` (the local subscription's `ends_at` is stamped), and additionally carries `cancellationReason: payment_failure` (`customerId`, `subscriptionId`, `endsAt`) | | `SubscriptionCanceledWithGracePeriod` | A `subscription.canceled_with_grace_period` webhook is received | | `SubscriptionCancellationGracePeriodCompleted` | A `subscription.cancellation_grace_period_completed` webhook is received — the grace period stamped by the cancellation has now elapsed (carries `customerId`, `subscriptionId`, `endsAt`) | | `OrderPaid` | An `order.paid` webhook is received (enriched with the full tax breakdown) | | `OrderCanceled` | An `order.canceled` webhook is received. The local order status is mirrored to `canceled` and its `cancellation_reason` is stored (`payment_failure` when payment recovery for the unpaid order was exhausted, otherwise left `null`) | | `OrderPaymentFailed` | An `order.payment_failed` webhook is received — typically the start of dunning (enriched with the full tax breakdown) | | `OrderChargebackReceived` / `OrderChargebackReversed` | An `order.chargeback_received` / `order.chargeback_reversed` webhook is received — enriched with `customerId`, dispute `status`, totals and `taxSummary`; persisted to `vatly_chargebacks` | | `RefundCompleted` / `RefundFailed` / `RefundCanceled` | A `refund.completed` / `refund.failed` / `refund.canceled` webhook is received — each carries the full `taxSummary`; persisted to `vatly_refunds` | | `CheckoutPaid` | A `checkout.paid` webhook is received — the hosted checkout was paid (fires before `order.paid`'s enrichment GET; carries `checkoutId`, nullable `customerId` / `orderId`, `status`, `metadata`) | | `CheckoutFailed` | A `checkout.failed` webhook is received — the hosted checkout's payment failed (route into a retry flow) | | `CheckoutCanceled` | A `checkout.canceled` webhook is received — the customer abandoned the hosted checkout (cart-abandonment hook) | | `CheckoutExpired` | A `checkout.expired` webhook is received — the hosted checkout session timed out without completion | | `WebhookSetupReceived` | A `webhook.setup` verification call is received — Vatly confirms a newly registered (or re-pointed) endpoint is reachable. There's no resource to enrich and no local row to touch; just acknowledge with a `2xx`. Carries only the webhook envelope (`eventName` / `object`) | | `OneOffProductUpdateSubmitted` / `OneOffProductUpdateApproved` / `OneOffProductUpdateRejected` / `OneOffProductArchived` / `OneOffProductUnarchived` | The `one_off_product.*` product-moderation events — see [Product moderation events](https://docs.vatly.com/#product-moderation-events) below | | `SubscriptionPlanUpdateSubmitted` / `SubscriptionPlanUpdateApproved` / `SubscriptionPlanUpdateRejected` / `SubscriptionPlanArchived` / `SubscriptionPlanUnarchived` | The `subscription_plan.*` product-moderation events — see [Product moderation events](https://docs.vatly.com/#product-moderation-events) below | | `UnsupportedWebhookReceived` | A webhook arrives that has no typed mapping (carries the raw `eventName` / `object`) | | `SubscriptionWasCreatedFromWebhook` (in `Vatly\Fluent\Events\`) | A new local `Subscription` row was just created from a `subscription.started` webhook (application-level event; carries the stored `$subscription`) | | `OrderWasCreatedFromWebhook` (in `Vatly\Fluent\Events\`) | The order analogue of `SubscriptionWasCreatedFromWebhook`: a new local `Order` row was just created from an `order.paid` webhook (fires once on a brand-new order; carries the stored `$order`). A clean hook for receipts / fulfillment | **Money fields.** On the order and refund events (`OrderPaid`, `OrderPaymentFailed`, `RefundCompleted` / `RefundFailed` / `RefundCanceled`), `total` and `subtotal` are non-null `Vatly\API\Types\Money` value objects (a decimal-string `value` plus a `currency`); read the currency via `$event->total->currency` and minor units via `$event->total->toCents()`. These events no longer carry a standalone `currency` field. The chargeback events (`OrderChargebackReceived` / `OrderChargebackReversed`) carry nullable `?Money` `total` / `subtotal` and **keep** their standalone `currency` field. Exactly one of the webhook events above is dispatched per incoming webhook (`UnsupportedWebhookReceived` is the fallback for unmapped events). `SubscriptionWasCreatedFromWebhook` and `OrderWasCreatedFromWebhook` fire additionally, from the subscription- and order-sync reactions, only when a brand-new local row is created. ## Product moderation events Vatly emits ten product events for the one-off-product and subscription-plan approval workflow (the "Manage Products" surface). Each is a typed event under `Vatly\API\Webhooks\Events\`, hydrated straight from the fat webhook payload — its `object` is the full `OneOffProduct` / `SubscriptionPlan` resource, carrying `pendingUpdates` (the proposed changes) and `updateStatus` (`pending` while an edit awaits approval, back to `null` once it's approved or rejected): | Event | `eventName` | Meaning | | --------------------------------- | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------- | | `OneOffProductUpdateSubmitted` | `one_off_product.update_submitted` | An edit to a one-off product was submitted for approval — `pendingUpdates` holds the proposed values, `updateStatus: pending` | | `OneOffProductUpdateApproved` | `one_off_product.update_approved` | A submitted edit was approved and applied — `pendingUpdates: null` | | `OneOffProductUpdateRejected` | `one_off_product.update_rejected` | A submitted edit was rejected — the product is unchanged, `pendingUpdates: null` | | `OneOffProductArchived` | `one_off_product.archived` | A one-off product was archived (`archivedAt` set) | | `OneOffProductUnarchived` | `one_off_product.unarchived` | A previously archived one-off product was restored | | `SubscriptionPlanUpdateSubmitted` | `subscription_plan.update_submitted` | An edit to a subscription plan was submitted for approval | | `SubscriptionPlanUpdateApproved` | `subscription_plan.update_approved` | A submitted plan edit was approved and applied | | `SubscriptionPlanUpdateRejected` | `subscription_plan.update_rejected` | A submitted plan edit was rejected | | `SubscriptionPlanArchived` | `subscription_plan.archived` | A subscription plan was archived | | `SubscriptionPlanUnarchived` | `subscription_plan.unarchived` | A previously archived subscription plan was restored | These are product-management signals, not billing events: they carry no customer and there is no local row for the package to keep in sync, so **no built-in reaction touches them**. They are still fully received — signature-verified, recorded in `vatly_webhook_calls` (with `entity_type` `one_off_product` / `subscription_plan` and `vatly_customer_id` `null`), and dispatched onto the event bus — so you can drive your own cache-busting or product-mirroring off them. Each one-off-product event exposes `$event->oneOffProductId`, `$event->testmode`, and the hydrated `$event->oneOffProduct` (a `Vatly\API\Resources\OneOffProduct`); each subscription-plan event exposes `$event->subscriptionPlanId`, `$event->testmode`, and `$event->subscriptionPlan` (a `Vatly\API\Resources\SubscriptionPlan`). ```php use Illuminate\Support\Facades\Event; use Vatly\API\Webhooks\Events\SubscriptionPlanUpdateApproved; Event::listen(SubscriptionPlanUpdateApproved::class, function (SubscriptionPlanUpdateApproved $event) { // $event->subscriptionPlanId // e.g. "subscription_plan_7Hd9Kf2Lm" // $event->subscriptionPlan->pendingUpdates // null once approved // Bust your local plan cache, re-pull your products, etc. }); ``` ## Built-in reactions Before the event is dispatched, the package keeps your local tables in sync automatically via fluent's standard webhook *reactions*. These are wired by `WebhookProcessorFactory` inside the `Vatly` composition root — no registration needed on your side. They live under `Vatly\Fluent\Webhooks\Reactions\`: - **`SyncSubscriptionOnStarted`** -- On `SubscriptionStarted`, creates (or updates) the local `Subscription` row, then dispatches `SubscriptionWasCreatedFromWebhook` for newly-created rows. - **`CancelSubscriptionOnCanceled`** -- On `SubscriptionCanceledImmediately` / `SubscriptionCanceledForNonpayment` / `SubscriptionCanceledWithGracePeriod`, sets the local subscription's `ends_at` **and** stores its `cancellation_reason` (`merchant_request` / `payment_failure` / `customer_request`). The nonpayment case (a hard cancellation after payment recovery is exhausted) ends the subscription just like an immediate cancellation. Read the persisted reason off the model (`$subscription->cancellation_reason`), or `$event->cancellationReason` on the dispatched event, to branch your own dunning/win-back UI off it. - **`StoreOrderOnPaid`** -- On `OrderPaid`, stores (or updates) the local `Order` row, then dispatches `OrderWasCreatedFromWebhook` for newly-created rows. - **`StoreOrderOnPaymentFailed`** -- On `OrderPaymentFailed`, stores (or updates) the local `Order` row, mirroring the upstream order status verbatim. - **`EndSubscriptionOnGracePeriodCompleted`** -- On `SubscriptionCancellationGracePeriodCompleted`, stamps the actual `ends_at` onto the local subscription. Usually an idempotent re-write of what `CancelSubscriptionOnCanceled` already stored, but it self-heals a missed/out-of-order `subscription.canceled_with_grace_period` webhook (which would otherwise leave `ends_at` null and the subscription looking active forever) and corrects any drift between the scheduled and actual end. The checkout events (`CheckoutPaid` / `CheckoutFailed` / `CheckoutCanceled` / `CheckoutExpired`) ship no built-in reaction — they touch no local table. The checkout payloads carry the full Checkout resource (so they're dispatched without an enrichment GET), and there is no local checkout entity to keep in sync. Listen for them directly to drive receipt/retry/cart-abandonment UI or to flip your own application-level state. `SubscriptionCancellationGracePeriodCompleted` is likewise dispatched (on top of the reaction above) for consumers that want to flip their own application-level "fully ended" status. ## Custom listeners Listen for the events in your `EventServiceProvider` or using the `Event` facade: ```php use Illuminate\Support\Facades\Event; use Vatly\API\Webhooks\Events\SubscriptionStarted; Event::listen(SubscriptionStarted::class, function (SubscriptionStarted $event) { // $event->customerId // $event->subscriptionId // $event->planId // $event->type // $event->name // $event->quantity // Send welcome email, provision features, etc. }); ``` Order events (`OrderPaid` / `OrderPaymentFailed`) carry the full, API-enriched order — including the tax breakdown — so you can materialize an invoice without a follow-up API call: ```php use Illuminate\Support\Facades\Event; use Vatly\API\Webhooks\Events\OrderPaid; Event::listen(OrderPaid::class, function (OrderPaid $event) { // $event->orderId // $event->customerId // $event->status // $event->total // Vatly\API\Types\Money // $event->subtotal // Vatly\API\Types\Money // $event->total->currency // e.g. "EUR" // $event->total->value // decimal string, e.g. "99.00" // $event->total->toCents() // minor units (cents), e.g. 9900 // $event->taxSummary // $event->invoiceNumber // $event->paymentMethod // $event->metadata }); ``` ## Webhook call storage Every webhook is recorded in the `vatly_webhook_calls` table with: - `vatly_id` -- The webhook event ID (unique; use this as your dedup key) - `resource` -- The wrapper resource type (always `webhook_event`) - `event_name` -- The webhook event type (e.g., `subscription.started`) - `entity_type` -- The resource type the event relates to (e.g., `subscription`) - `entity_id` -- The Vatly resource ID the event relates to - `testmode` -- Whether the event was raised against a testmode entity - `vatly_created_at` -- When the webhook event was created at Vatly - `vatly_customer_id` -- The associated customer ID, when present - `object` -- The full resource payload at the time of the event (JSON) ## Pruning stored webhook calls `vatly_webhook_calls` is an append-only record of every webhook received, so it grows over time. The package never prunes it for you — schedule the cleanup yourself. The `Vatly` facade deletes rows older than the default retention window (7 days): ```php use Vatly\Laravel\Facades\Vatly; Vatly::cleanUp(); // delete webhook-call rows older than 7 days ``` For a different window, call the model directly — it returns the number of rows deleted: ```php use Vatly\Laravel\Models\VatlyWebhookCall; $deleted = VatlyWebhookCall::cleanUp(daysToRetain: 30); // keep 30 days ``` Rows are pruned by their local `created_at` (when the row was stored), not `vatly_created_at`. The window isn't a config value — it's the `$daysToRetain` argument (default `VatlyWebhookCall::DEFAULT_DAYS_TO_RETAIN`, which is 7). Run it on a schedule — for example in `routes/console.php`: ```php use Illuminate\Support\Facades\Schedule; use Vatly\Laravel\Facades\Vatly; Schedule::call(fn () => Vatly::cleanUp())->daily(); ``` The rows are an audit trail, not an idempotency guard, so pruning is safe. (`vatly_id` is unique if you'd rather build your own dedup on top — in that case keep a window comfortably longer than a webhook might be redelivered within.) # Vs Cashier (Stripe, Paddle) & Lemon Squeezy Picking the billing layer for a new Laravel app? If you've reached for Laravel Cashier before, Vatly will feel immediately familiar — a `Billable` trait, `subscribed()`, `subscription()->swap()`, a wired-up webhook endpoint. The difference is what sits *behind* the API: Vatly is a **Merchant of Record**, so it is the legal seller and handles VAT, invoicing, and payment compliance for you — and it's **Europe-first**, operating under EU jurisdiction. This page is an honest, side-by-side look at how `vatly-laravel` stacks up against the Cashier-style packages you might otherwise reach for — [Laravel Cashier (Stripe)](https://laravel.com/docs/12.x/billing){rel=""nofollow""}, [Laravel Cashier (Paddle)](https://laravel.com/docs/12.x/cashier-paddle){rel=""nofollow""}, and [Lemon Squeezy for Laravel](https://github.com/lmsqueezy/laravel){rel=""nofollow""} — gaps included. ::note **Already running one of these in an existing app?** This page helps you choose. Once you have, [Migrating from Cashier](https://docs.vatly.com/packages/laravel/migrating-to-vatly) shows how to add Vatly next to your current biller and migrate customers over gradually. :: --- ## At a glance | | Cashier (Stripe Billing) | Cashier (Paddle) | Lemon Squeezy | **Vatly** | | -------------------------- | ---------------------------------------------- | ----------------------------------------------- | ------------------------------------ | ---------------------------------------------------------- | | Composer package | `laravel/cashier` | `laravel/cashier-paddle` | `lemonsqueezy/laravel` | `vatly/vatly-laravel` | | Billable trait | `Laravel\Cashier\Billable` | `Laravel\Paddle\Billable` | `LemonSqueezy\Laravel\Billable` | `Vatly\Laravel\Billable` | | Merchant of Record | **No** — you are the seller | Yes | Yes | **Yes (full)** | | Entity / jurisdiction | *You* (wherever you're registered) | Paddle, **UK** | Lemon Squeezy, **US** (Stripe-owned) | **EEA / EU jurisdiction** | | Who remits VAT/sales tax | **You** (Stripe Tax only *calculates*) | Provider | Provider | **Provider** | | Customer stored as | columns on the billable model (`stripe_id`, …) | `customers` table (`paddle_id`) | `lemon_squeezy_customers` table | `vatly_id` column on the billable model + `vatly_*` tables | | Checkout | Stripe Checkout (hosted) / Elements | Paddle.js **overlay / inline** (client-side JS) | Lemon.js overlay / hosted URL | **Vatly-hosted redirect** (+ guest claim) | | Webhook route | `/stripe/webhook` | `/paddle/webhook` | `/lemon-squeezy/webhook` | `/webhooks/vatly` | | Coupons / promo codes | Yes | Yes | Yes | **On the roadmap** (workaround below) | | License keys | No | No | Yes | **On the roadmap** (rarely needed for SaaS) | | Refunds & chargebacks | wire it yourself | events | events | **first-class models + events** | | Trials, swap, grace/resume | Yes | Yes | Yes | **Yes** | Two takeaways: 1. **With `laravel/cashier`, *you're* the seller of record.** It runs on classic Stripe Billing, so you register for VAT, file, and remit in every market you sell into — the compliance and the liability sit with your company. (Stripe's own Merchant-of-Record product, [Managed Payments](https://stripe.com/managed-payments){rel=""nofollow""}, is a separate, US-based service you'd integrate instead — not the Cashier subscriptions you're building on.) 2. **So the real difference between MoRs is jurisdiction.** Paddle is UK, Lemon Squeezy and Stripe are US, Vatly is EEA — your seller-of-record entity and customer data stay under EU law. That, not the API, is the reason to choose one over another. --- ## The developer experience For a greenfield app, Vatly is your only biller — so you use the plain `Billable` trait, and the code reads like Cashier: ```php use Vatly\Laravel\Billable; class User extends Authenticatable { use Billable; } ``` ```php // Start a subscription — redirect to Vatly's hosted checkout $checkout = $user->subscribe() ->toPlan('subscription_plan_7Hd9Kf2Lm') ->withTrialDays(14) ->create(); return redirect($checkout->links->checkoutUrl->href); // Gate features on subscription state if ($user->subscribed()) { // … } $user->subscription()->swap('subscription_plan_other'); $user->subscription()->cancel(); // Vatly decides immediate vs. grace $user->subscription()->resume(); // while on the grace period // One-off purchase $user->checkout()->create( items: [['id' => 'one_off_product_3Qb8Wz1Yt', 'quantity' => 1]], redirectUrlSuccess: route('billing.success'), redirectUrlCanceled: route('billing'), ); // Receipts — hosted invoice URLs, no PDF plumbing foreach ($user->orders as $order) { echo $order->invoiceUrl(); } ``` No VAT logic, no tax tables, no invoice templates, no client-side checkout widget to embed — the checkout is a server-side redirect, like Stripe Checkout. See [Subscriptions](https://docs.vatly.com/packages/laravel/subscriptions) and [Checkouts](https://docs.vatly.com/packages/laravel/checkouts) for the full surface. --- ## Feature parity, and what's still on the roadmap Vatly covers what a SaaS needs to start selling: subscriptions with trials, plan swaps, cancellation with grace and resume, one-off purchases, hosted checkout, refunds and chargebacks, and — because it's a Merchant of Record — VAT, invoicing and tax compliance handled for you. A few capabilities you may use elsewhere aren't in the box yet. Here's the honest picture, and how to bridge it. | Capability | Vatly today | Notes | | ------------------------------------------ | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Subscriptions, trials, swap, grace, resume | ✅ | Full lifecycle, Cashier-shaped API | | One-off / multi-item checkout | ✅ | `checkout()->create(items: …)` | | VAT, invoicing, tax remittance | ✅ | Handled — it's the point of a MoR. With Cashier (classic Stripe Billing) this is *your* job. | | Refunds & chargebacks | ✅ | First-class models + events (more than most provide) | | Test / live segregation | ✅ | Every record carries `testmode`; key prefix selects the mode | | **Coupons / promo codes** | 🔜 Roadmap | Until native codes land, model a promo as a dedicated `subscription_plan_…` at the discounted price and point that cohort at it. A couple of extra plans in the dashboard — not a blocker for launching offers. | | **License keys** | 🔜 Roadmap | Vatly is built for SaaS, where entitlement follows subscription state — `subscribed()` *is* your license check. Per-seat keys for downloadable/offline software (Lemon Squeezy's signature feature) aren't here yet. If you ship license-activated desktop binaries, that's the one workflow to keep elsewhere for now. | The shape of the trade is deliberate: Vatly does the compliance-heavy core that's genuinely hard to build — being the seller of record, VAT across the EU, invoicing, disputes — and is filling in the conveniences (coupons next) in the open. For a subscription SaaS selling into Europe and the world, there's enough here to launch today. --- ## Why teams choose Vatly A Merchant of Record makes the tax burden disappear — it becomes the legal seller, so VAT, invoicing and remittance stop being your problem. The real question is *whose* entity you hand that to, and that's where Vatly stands apart: - **Europe-first, by design.** EEA-based, EU jurisdiction, customer data kept in Europe. The other MoRs sit in the UK (Paddle) or the US (Lemon Squeezy, Stripe Managed Payments) — jurisdiction is the one axis that genuinely separates them, and the reason Vatly exists. - **No exposure to US policy.** Your seller-of-record relationship and your customers' data stay under EU law — a clean answer when an enterprise buyer, or your own board, asks where they sit. - **One familiar API.** The Cashier-shaped surface means there's little to learn and little to rewrite. > **You Just Ship.** --- ## Next steps - **Starting fresh:** [Getting started](https://docs.vatly.com/packages/laravel/readme) wires up the trait, config, migrations and webhook in a few minutes. - **Already running another provider:** [Migrating from Cashier](https://docs.vatly.com/packages/laravel/migrating-to-vatly) shows how to add Vatly beside your current biller and migrate customers over gradually. - **Reference:** [Configuration](https://docs.vatly.com/packages/laravel/configuration) · [Customers](https://docs.vatly.com/packages/laravel/customers) · [Checkouts](https://docs.vatly.com/packages/laravel/checkouts) · [Subscriptions](https://docs.vatly.com/packages/laravel/subscriptions) · [Orders](https://docs.vatly.com/packages/laravel/orders) · [Webhooks](https://docs.vatly.com/packages/laravel/webhooks) Compared against, at time of writing: [Laravel Cashier (Stripe)](https://laravel.com/docs/12.x/billing){rel=""nofollow""} · [Laravel Cashier (Paddle)](https://laravel.com/docs/12.x/cashier-paddle){rel=""nofollow""} · [Lemon Squeezy for Laravel](https://github.com/lmsqueezy/laravel){rel=""nofollow""}. Their method names and table layouts follow those packages' current releases — verify against the version you have pinned before relying on a specific signature. # Migrating from Cashier You don't swap a Merchant of Record overnight. The payment mandate for every active customer lives with your *current* seller of record, and the only way to move a customer is to have them re-authorize at the new one. So in practice you run two billing stacks side by side for a while: existing customers keep paying through the old provider until they re-subscribe, new signups go straight to Vatly, and you retire the old integration once the tail has migrated. This is the integration playbook for exactly that — adding Vatly beside an existing Cashier-style integration ([Stripe](https://laravel.com/docs/12.x/billing){rel=""nofollow""} / [Paddle](https://laravel.com/docs/12.x/cashier-paddle){rel=""nofollow""} / [Lemon Squeezy](https://github.com/lmsqueezy/laravel){rel=""nofollow""}): the one thing you have to resolve, the things that *don't* need resolving, and the step-by-step. ::note **Still deciding whether to switch?** Start with [How Vatly compares](https://docs.vatly.com/packages/laravel/comparison) — the side-by-side on the Merchant-of-Record model, features, and what's on the roadmap. This page assumes you've decided to run Vatly alongside what you already have. :: --- ## The one thing that actually collides: the `Billable` trait Every package here is modelled on Cashier, so every one ships a `Billable` trait that defines the *same* method names: | Method | Stripe | Paddle | Lemon Squeezy | Vatly | | ---------------------------- | :----: | :----: | :-----------: | :---: | | `subscribed()` | ✓ | ✓ | ✓ | ✓ | | `subscription()` | ✓ | ✓ | ✓ | ✓ | | `subscriptions()` (relation) | ✓ | ✓ | ✓ | ✓ | | `checkout()` | ✓ | ✓ | ✓ | ✓ | | `subscribe()` | — | ✓ | ✓ | ✓ | | `orders()` (relation) | — | — | ✓ | ✓ | PHP does not let two traits define the same method on one class — you get a fatal *"trait method collision"* the moment you write `use LemonSqueezyBillable, VatlyBillable;`. So you have to decide, deliberately, **which provider owns the unprefixed method names**. ::tip **The cleanest fix is often to not share a model at all.** None of these `Billable` traits is tied to `User` — they work on any Eloquent model ( `Team` , `Account` , `Organization` , …), and Vatly's records are polymorphic ( `owner_type` / `owner_id` ). If your app bills a model that isn't already carrying a Cashier-style trait — or you can introduce one — put Vatly's `Billable` there and the collision disappears entirely. When both providers genuinely must live on the *same* model, read on. :: ::warning **The self-call trap.** Plain trait aliasing ( `insteadof` / `as` ) is *not* enough here, and it fails quietly. Vatly's `subscription()` and `subscribed()` call `$this->subscriptions()` internally. If you alias `subscriptions` to the legacy provider with `insteadof` , then `vatlySubscription()` will read the *legacy* subscriptions table and silently return the wrong thing. Aliasing is safe only for the *builder* methods ( `subscribe` , `checkout` ) that don't self-call a relation; the *state readers* ( `subscription` , `subscribed` ) need their relation to stay wired to Vatly. :: Because of that trap, the recommended approach below uses Vatly's purpose-built `VatlyBillable` trait, which exposes the whole Vatly surface under `vatly*` names and owns its *own*`vatlySubscriptions()` relation — so there's nothing to alias and nothing to cross-wire. ### Which provider owns the unprefixed names? Pick the one most of your code already calls. - **During a migration, that's almost always the legacy provider.** Don't churn working call sites — keep `$user->subscribed()` meaning "subscribed via your existing provider" and give Vatly a `vatly*` prefix. This is the default below. - **Once Vatly is your default** for new signups and the legacy tail is winding down, flip it: make Vatly the plain trait and reach the shrinking legacy cohort through the old provider's models directly. --- ## What *doesn't* collide — and why that's deliberate The trait is the only friction. Everything underneath is namespaced so the two stacks never fight: **Database tables.** Vatly prefixes every table — `vatly_subscriptions`, `vatly_orders`, `vatly_order_lines`, `vatly_refunds`, `vatly_chargebacks`, `vatly_webhook_calls` — and adds a single `vatly_id` column to your billable model's table. Nothing of Vatly's overlaps a Cashier table. (Worth knowing: Cashier/Stripe and Cashier/Paddle *both* claim the unprefixed `subscriptions` table, so they can't run side by side without overriding models. Vatly never contends for a table name with anyone.) **Webhooks.** Each provider registers its own route, verified with its own secret, pointed at its own dashboard. Run all of them at once: | Provider | Route | Signature secret | | ------------- | ----------------------------- | ------------------------------ | | Stripe | `POST /stripe/webhook` | `STRIPE_WEBHOOK_SECRET` | | Paddle | `POST /paddle/webhook` | `PADDLE_WEBHOOK_SECRET` | | Lemon Squeezy | `POST /lemon-squeezy/webhook` | `LEMON_SQUEEZY_SIGNING_SECRET` | | **Vatly** | `POST /webhooks/vatly` | `VATLY_WEBHOOK_SECRET` | Vatly uses its own `VATLY_*` environment variables and its own route name (`vatly.webhook`), so it never collides with Cashier's `CASHIER_WEBHOOK` env or anyone else's config. **Config & service bindings.** Vatly binds its services under its own namespace via `VatlyServiceProvider`; nothing is rebound out from under your existing provider. In short: two sets of tables, two webhook endpoints, two dashboards, one model. The only line of code you have to think about is the trait. --- ## Add Vatly beside your current provider ### 1. Install and migrate ```bash composer config minimum-stability alpha composer config prefer-stable true composer require vatly/vatly-laravel php artisan vendor:publish --tag=vatly-config php artisan vendor:publish --tag=vatly-migrations php artisan vendor:publish --tag=vatly-billable-migrations php artisan migrate ``` This creates the `vatly_*` tables and adds one nullable `vatly_id` column to your billable model's table. It's purely additive — no existing column or data is changed. Add the Vatly credentials alongside your current ones in `.env`: ```env # existing provider stays exactly as-is — its own keys, untouched # new, additive: VATLY_KEY=test_xxxxxxxxxxxx VATLY_WEBHOOK_SECRET=your-webhook-secret VATLY_REDIRECT_URL_SUCCESS=https://your-app.test/checkout/success VATLY_REDIRECT_URL_CANCELED=https://your-app.test/checkout/canceled ``` ### 2. Add the `VatlyBillable` trait `vatly-laravel` ships a second trait, **`VatlyBillable`**, built for exactly this. It exposes the full Vatly surface under `vatly*`-prefixed names — `vatlySubscribe()`, `vatlySubscribed()`, `vatlySubscription()`, `vatlyCheckout()`, `vatlyOrder()`, plus the `vatlySubscriptions` / `vatlyOrders` / `vatlyRefunds` / `vatlyChargebacks` relations — so it drops in beside any Cashier-style `Billable` with no collision and no aliasing. Add it next to the trait you already have: ```php // app/Models/User.php use LemonSqueezy\Laravel\Billable; // your existing provider — unchanged use Vatly\Laravel\VatlyBillable; // Vatly, under vatly* names class User extends Authenticatable { use Billable; // $user->subscribed(), $user->checkout(), … → existing provider use VatlyBillable; // $user->vatlySubscribed(), $user->vatlyCheckout(), … → Vatly } ``` That's the whole integration step. Two things make it safe by construction: - **The state readers query their own relation.** `vatlySubscribed()` / `vatlySubscription()` read `vatlySubscriptions()`, never an unprefixed `subscriptions()` the other provider owns — so the self-call trap can't bite. - **The customer helpers are shared, not duplicated.** Methods whose names already carry "Vatly" — `createAsVatlyCustomer()`, `claimVatlyCustomerFromReturn()`, `asVatlyCustomer()`, `findBillable()` — don't collide, so `VatlyBillable` and the standalone `Billable` share one tested implementation; a fix to the claim / re-attribution logic reaches both. ::note **Vatly is your only biller?** Use the plain `Billable` trait instead ( `subscribe()` , `subscribed()` , …) — see [Getting started](https://docs.vatly.com/packages/laravel/readme) . `VatlyBillable` exists purely for running beside another provider. :: Under the hood — the equivalent hand-written concern You never need this; `VatlyBillable` ships with the package. But if you'd rather own the code — to rename methods, narrow the surface, or add behavior — it's essentially this trait over Vatly's composition root: ```php // app/Billing/VatlyBilling.php namespace App\Billing; use Illuminate\Database\Eloquent\Relations\MorphMany; use Illuminate\Http\Request; use Vatly\Fluent\Builders\CheckoutBuilder; use Vatly\Fluent\Builders\SubscriptionBuilder; use Vatly\Fluent\CustomerProfile; use Vatly\Fluent\SubscriptionHandle; use Vatly\Fluent\Vatly; use Vatly\Laravel\Models\Order as VatlyOrder; use Vatly\Laravel\Models\Subscription as VatlySubscription; trait VatlyBilling { /** @return MorphMany */ public function vatlySubscriptions(): MorphMany { return $this->morphMany(VatlySubscription::class, 'owner')->orderByDesc('created_at'); } public function vatlySubscribe(): SubscriptionBuilder { return app(Vatly::class)->subscriptionBuilder($this->vatlyProfile()); } public function vatlyCheckout(): CheckoutBuilder { return app(Vatly::class)->checkoutBuilder($this->vatlyProfile()); } public function vatlySubscribed(string $type = VatlySubscription::DEFAULT_TYPE): bool { // Uses our own relation — never the legacy one. $sub = $this->vatlySubscriptions()->where('type', $type)->first(); return $sub !== null && $sub->isActive(); } public function vatlySubscription(string $type = VatlySubscription::DEFAULT_TYPE): ?SubscriptionHandle { $sub = $this->vatlySubscriptions()->where('type', $type)->first(); return $sub !== null ? app(Vatly::class)->subscription($sub) : null; } /** * Claim an anonymous Vatly customer on the checkout-success redirect. * Mirrors Vatly\Laravel\VatlyBillable::claimVatlyCustomerFromReturn(). */ public function claimVatlyCustomerFromReturn(Request $request, string $key = 'checkout_id'): bool { $checkoutId = $request->query($key); if (! is_string($checkoutId) || $checkoutId === '') { return false; } $customerId = app(Vatly::class)->customerIdFromCheckout($checkoutId); if ($customerId === null) { return false; } app(Vatly::class)->customers()->attribute($customerId, (string) $this->getKey()); $this->forceFill(['vatly_id' => $customerId])->save(); // Re-attribute rows the webhook persisted during the anonymous flow. $owner = ['owner_type' => $this->getMorphClass(), 'owner_id' => $this->getKey()]; VatlySubscription::query()->whereNull('owner_id')->where('customer_id', $customerId)->update($owner); VatlyOrder::query()->whereNull('owner_id')->where('customer_id', $customerId)->update($owner); return true; } private function vatlyProfile(): CustomerProfile { return new CustomerProfile( vatlyId: $this->vatly_id, email: $this->email, name: $this->name, ); } } ``` **Alternative — trait aliasing** (only if you're making Vatly primary) `VatlyBillable` keeps the incumbent on the unprefixed names — what you want during a migration. If instead you're making **Vatly** primary and pushing the legacy provider under a prefix, use Vatly's standalone `Billable` and resolve the collision with `insteadof` / `as`: ```php use LemonSqueezy\Laravel\Billable as LegacyBillable; use Vatly\Laravel\Billable as VatlyBaseBillable; class User extends Authenticatable { use VatlyBaseBillable, LegacyBillable { // Vatly OWNS the unprefixed names — including subscriptions(), so its // internal self-calls stay correct. VatlyBaseBillable::subscriptions insteadof LegacyBillable; VatlyBaseBillable::subscription insteadof LegacyBillable; VatlyBaseBillable::subscribed insteadof LegacyBillable; VatlyBaseBillable::subscribe insteadof LegacyBillable; VatlyBaseBillable::checkout insteadof LegacyBillable; VatlyBaseBillable::orders insteadof LegacyBillable; // Legacy provider moves under a prefix; update its call sites accordingly. LegacyBillable::subscriptions as legacySubscriptions; LegacyBillable::subscription as legacySubscription; LegacyBillable::subscribed as legacySubscribed; LegacyBillable::subscribe as legacySubscribe; LegacyBillable::checkout as legacyCheckout; LegacyBillable::orders as legacyOrders; } } ``` Don't hand-alias the inverse (legacy keeps `subscriptions`, Vatly pushed under a prefix) — the prefixed Vatly readers would then read the wrong relation, the self-call trap above. That case is exactly what `VatlyBillable` is built for, so reach for it instead of aliasing. ### 3. Decide who bills through whom Add a column that records which provider owns a given user, and default new signups to Vatly: ```php // migration $table->string('billing_provider')->default('vatly'); // existing rows: backfill to 'legacy' ``` ```php // a single gate your UI and middleware can read public function billsThroughVatly(): bool { return $this->billing_provider === 'vatly'; } ``` Your billing screen then branches on it: ```php if ($user->billsThroughVatly()) { $checkout = $user->vatlySubscribe()->toPlan('subscription_plan_7Hd9Kf2Lm')->create(); return redirect($checkout->links->checkoutUrl->href); } // legacy cohort keeps its current flow until they choose to move return redirect($user->checkout('variant-id')); // your existing provider ``` ### 4. Run both webhook endpoints Nothing special — register Vatly's webhook URL and secret in the Vatly dashboard, keep your existing provider's webhook pointed where it already is. Subscriptions and orders from each provider sync into their own tables. Listen for Vatly events on Laravel's event bus the usual way (see [Webhooks](https://docs.vatly.com/packages/laravel/webhooks)): ```php use Vatly\API\Webhooks\Events\SubscriptionStarted; Event::listen(SubscriptionStarted::class, function (SubscriptionStarted $event) { // a customer is now live on Vatly — safe to wind down their legacy subscription }); ``` ### 5. Migrate a customer: the re-authorization flow A MoR mandate belongs to the legal seller — your old provider's mandate is theirs, Vatly's is Vatly's. You **cannot** transfer a mandate between Merchants of Record; the customer has to authorize payment at the new seller. So a migration is a re-subscribe, sequenced to avoid both a double charge and a gap in access: 1. Show the legacy-active customer a "move to Vatly" prompt (a re-authentication, in plain language: "confirm your payment details to switch"). 2. They complete a fresh Vatly checkout — `vatlySubscribe()->toPlan(...)->create()` — which creates the new mandate at Vatly. 3. On return, `claimVatlyCustomerFromReturn($request)` links the new Vatly customer to the user (guest-checkout and multi-tab safe). 4. **When Vatly's `SubscriptionStarted` webhook lands** — not before — cancel the legacy subscription at period end (`$user->subscription()->cancel()` on the legacy trait) so the customer is never double-billed and never loses access mid-period. 5. Flip `billing_provider` to `vatly`. Order matters: start Vatly only after the customer opts in (no surprise charge), cancel legacy only after Vatly is active (no service gap). --- ## Translation cheat-sheet (Cashier → Vatly) Mapping for the engineer or agent porting a flow. Vatly ids are prefixed — `subscription_plan_…` for plans, `one_off_product_…` for one-offs. The Vatly column uses the `vatly*` methods from the `VatlyBillable` trait (step 2). | Task | Cashier (Stripe) | Cashier (Paddle) | Lemon Squeezy | **Vatly** | | ------------------------ | ------------------------------------------------- | -------------------------------- | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | Start a subscription | `newSubscription('default','price')->create($pm)` | `subscribe('pri_123','default')` | `subscribe('variant')` | `vatlySubscribe()->toPlan('subscription_plan_…')->create()` | | Redirect to checkout | `->checkout([...])` | `->returnTo($url)` (Paddle.js) | redirect / `` | `redirect($checkout->links->checkoutUrl->href)` | | Free trial | `->trialDays(14)` | plan-level / `->trialDays()` | plan-level | `->withTrialDays(14)` or `->withTrialEndsAt($date)` | | Is subscribed? | `subscribed('default')` | `subscribed()` | `subscribed()` | `vatlySubscribed()` | | Get the subscription | `subscription('default')` | `subscription()` | `subscription()` | `vatlySubscription()` | | In grace period? | `subscription()->onGracePeriod()` | `->onGracePeriod()` | `->onGracePeriod()` | `vatlySubscription()->onGracePeriod()` | | Swap plan | `subscription()->swap('price')` | `->swap('pri')` | `->swap('prod','variant')` | `vatlySubscription()->swap('subscription_plan_…')` | | Swap + invoice now | `->swapAndInvoice('price')` | — | `->swapAndInvoice(...)` | `vatlySubscription()->swapAndInvoice('subscription_plan_…')` | | Swap now, no charge | `->noProrate()->swap('price')` | `->noProrate()->swap('pri')` | `->noProrate()->swap(...)` | `vatlySubscription()->swapWithoutCharge('subscription_plan_…')` | | Cancel (grace) | `subscription()->cancel()` | `->cancel()` | `->cancel()` | `vatlySubscription()->cancel()` | | Resume | `subscription()->resume()` | `->resume()` | `->resume()` | `vatlySubscription()->resume()` | | One-off purchase | `checkout(['price'=>1])` | `checkout('pri_123')` | `checkout('variant')` | `vatlyCheckout()->create(items: [['id'=>'one_off_product_…','quantity'=>1]], redirectUrlSuccess: …, redirectUrlCanceled: …)` | | Update payment / billing | `redirectToBillingPortal()` | hosted update | `redirect($portalUrl)` | `vatlySubscription()->updateBilling()` | | List orders / receipts | `invoices()` | `transactions()` | `orders()` | `$user->vatlyOrders` → `$order->invoiceUrl()` | | Customer id field | `stripe_id` | `paddle_id` | (relation) | `vatly_id` | A couple of shape differences worth flagging for whoever's implementing: - **Vatly checkout is a server-side redirect**, like Stripe Checkout — you build the checkout server-side and `redirect()` to a hosted URL. Paddle and Lemon Squeezy lean on a client-side JS overlay (`@paddleJS`, `@lemonJS`). If you're moving off an overlay, you're removing front-end JS, not adding it. - **Guest checkout** is first-class in Vatly: put `{CHECKOUT_ID}` in your return URL and call `claimVatlyCustomerFromReturn()` on the way back to link the purchase — no session plumbing, multi-tab safe. See [Customers](https://docs.vatly.com/packages/laravel/customers). - **Refunds and chargebacks are real models** in Vatly (`$user->vatlyRefunds`, `$order->chargebacks`, reversal helpers like `$order->isFullyReversed()`), with dedicated webhook events — not something you reconstruct from raw payloads. --- ## Reference - **Deciding / comparing:** [How Vatly compares](https://docs.vatly.com/packages/laravel/comparison) (Merchant-of-Record model, feature parity, roadmap) - **Getting started:** [Getting started](https://docs.vatly.com/packages/laravel/readme) · [Configuration](https://docs.vatly.com/packages/laravel/configuration) - **API surface:** [Customers](https://docs.vatly.com/packages/laravel/customers) · [Checkouts](https://docs.vatly.com/packages/laravel/checkouts) · [Subscriptions](https://docs.vatly.com/packages/laravel/subscriptions) · [Orders](https://docs.vatly.com/packages/laravel/orders) · [Webhooks](https://docs.vatly.com/packages/laravel/webhooks) Compared against, at time of writing: [Laravel Cashier (Stripe)](https://laravel.com/docs/12.x/billing){rel=""nofollow""} · [Laravel Cashier (Paddle)](https://laravel.com/docs/12.x/cashier-paddle){rel=""nofollow""} · [Lemon Squeezy for Laravel](https://github.com/lmsqueezy/laravel){rel=""nofollow""}. Method names and table layouts follow those packages' current releases — verify against the version you have pinned before relying on a specific signature. # JavaScript SDK ![Vatly SDK for JavaScript & TypeScript](https://raw.githubusercontent.com/vatly/vatly-api-js/main/art/banner.png) > **Alpha — under active development. Every alpha release may include breaking changes. Lock the version you install and review the release notes before upgrading.** Official TypeScript SDK for Vatly, the European Merchant of Record for AI, software and digital products. Create checkouts and manage customers, subscriptions, and orders from your server. For all endpoint fields and options, see the [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""}. The [OpenAPI spec](https://docs.vatly.com/openapi.yaml){rel=""nofollow""} is also available for tooling. ## Installation Install the latest alpha; `--save-exact` pins the installed version in `package.json`: ```bash npm install --save-exact @getvatly/sdk # or: pnpm add --save-exact @getvatly/sdk ``` The package ships ESM + CommonJS builds and its own TypeScript types. It uses the platform `fetch` and Web Crypto — no `axios`, `node-fetch`, or `node:crypto` — so it can run on Node and modern edge hosts. Keep API keys on the server. ## Quick start Initialize the client with your API key and create a checkout. ### API Keys Get your API keys from the [Vatly Dashboard](https://my.vatly.com){rel=""nofollow""} under **Settings > API**. | Name | Type | Description | | ------- | -------- | -------------------------------------- | | `live_` | `prefix` | Production transactions, real charges. | | `test_` | `prefix` | Sandbox testing, no real charges. | The client validates the key format at construction and exposes the detected mode on `client.mode` (`"live"` or `"test"`). ```ts import { VatlyClient } from "@getvatly/sdk"; const vatly = new VatlyClient({ apiKey: process.env.VATLY_API_KEY, // live_… or test_… }); // Create a checkout const checkout = await vatly.checkouts.create({ redirectUrlSuccess: "https://yourapp.com/success", redirectUrlCanceled: "https://yourapp.com/canceled", products: [{ id: "subscription_plan_abc123", quantity: 1 }], }); // Redirect the customer to the hosted checkout page console.log(checkout.links.checkoutUrl.href); ``` On Node, `VATLY_API_KEY` is read from `process.env` as a fallback. On edge runtimes without `process`, pass `apiKey` explicitly. ## Idempotency The SDK automatically attaches an `Idempotency-Key` header to every `POST`, `PATCH`, and `DELETE` request (a UUID v4). Checkout creation, subscription updates, and refund cancellations are protected out of the box, and the key is reused across automatic retries so a retried call is deduped server-side. Separate method calls generate separate keys. Reuse an explicit key when your application retries the same operation after an uncertain result. ### Override the key per call Pass `idempotencyKey` in the request options when you have your own request ID: ```ts await vatly.checkouts.create(body, { idempotencyKey: "checkout-create-123" }); await vatly.subscriptions.update("subscription_123", { quantity: 2 }, { idempotencyKey: "subscription-update-123", }); ``` ### Custom generator or disable auto-generation ```ts // Custom generator (e.g. tie keys to a tracing span) new VatlyClient({ idempotencyKeyGenerator: () => span.context().traceId }); // Disable entirely — caller must supply opts.idempotencyKey for retries to work new VatlyClient({ idempotencyKeyGenerator: false }); ``` ## Retries GETs and keyed mutations retry `429`, `5xx`, timeouts, and network failures with exponential backoff and jitter (default `maxRetries: 2`), honoring `Retry-After`. Keyed `409` errors retry only when `details.idempotency_outcome` is `in_progress`. An `unknown` outcome requires reading/reconciling the resource before any further mutation. ## Pagination List endpoints are cursor-paginated. Use `list()` for a single page or `listAll()` to walk every page with `for await`: ```ts const page = await vatly.orders.list({ limit: 25 }); for await (const order of vatly.orders.listAll({ limit: 100 })) { // ... } ``` ## Resources The SDK provides access to all Vatly API resources. The complete method and return-type inventory is in the [operation reference](https://docs.vatly.com/packages/javascript/api). | Resource | Description | | ---------------------------------------------------------------------------------- | ----------------------------------------------------- | | [Checkouts](https://docs.vatly.com/packages/javascript/checkouts) | Create hosted payment pages | | [Customers](https://docs.vatly.com/packages/javascript/customers) | Manage customer records | | [Subscriptions](https://docs.vatly.com/packages/javascript/subscriptions) | Recurring billing | | [Subscription Plans](https://docs.vatly.com/packages/javascript/subscriptionplans) | Define subscription products | | [One-Off Products](https://docs.vatly.com/packages/javascript/oneoffproducts) | Single-purchase products | | [Orders](https://docs.vatly.com/packages/javascript/orders) | Transaction records | | [Refunds](https://docs.vatly.com/packages/javascript/refunds) | Process refunds | | [Chargebacks](https://docs.vatly.com/packages/javascript/chargebacks) | Handle disputes | | [Webhooks](https://docs.vatly.com/packages/javascript/webhooks) | Endpoint management and real-time event notifications | ## Error handling Every non-2xx response maps to a typed error extending `VatlyError`. | Name | Status | Description | | -------------------------------------------- | ------ | ------------------------------------------------------------- | | `VatlyAuthError` | `401` | Missing or invalid API key. | | `VatlyForbiddenError` | `403` | Authenticated but not allowed. | | `VatlyNotFoundError` | `404` | Resource does not exist. | | `VatlyConflictError` | `409` | Conflict; inspect `.details` and `.retryAfter`. | | `VatlyValidationError` | `422` | Invalid request; exposes `.errors: Record`. | | `VatlyRateLimitError` | `429` | Rate limited; exposes `.retryAfter` (seconds). | | `VatlyApiError` | other | Any other API error. | | `VatlyConnectionError` / `VatlyTimeoutError` | — | Network failure / timeout. | Errors include the request method and URL. Resource and list methods also raise `VatlyApiError` for malformed JSON, empty bodies, unexpected 204 responses, or JSON `null`. Documented no-content operations accept empty success responses; other resource fields are not runtime schema-validated. ```ts import { VatlyValidationError } from "@getvatly/sdk"; try { await vatly.customers.create({ email: "" }); } catch (err) { if (err instanceof VatlyValidationError) { console.error(err.errors.email); } else { throw err; } } ``` ## Money Monetary amounts are `Money` objects — `{ value, currency }` where `value` is a **decimal string** to preserve precision. Never coerce `value` to a JavaScript `number`. Helpers convert to/from integer minor units: ```ts import { toMinorUnits, fromMinorUnits } from "@getvatly/sdk"; toMinorUnits({ value: "29.00", currency: "EUR" }); // → 2900n fromMinorUnits(2900n, "EUR"); // → { value: "29.00", currency: "EUR" } ``` ## Requirements - Node 20+, Cloudflare Workers, Vercel Edge, Deno, or Bun - Platform `fetch` and Web Crypto (built in on all supported runtimes) # Customers Customers represent the end users who purchase products through Vatly. For all fields and options, see the [Customers API reference](https://docs.vatly.com/api-reference/customers){rel=""nofollow""}. The [OpenAPI spec](https://docs.vatly.com/openapi.yaml){rel=""nofollow""} is also available for tooling. ## The Customer resource | Name | Type | Description | | ----------- | --------------- | --------------------------------------------------- | | `id` | `string` | Unique identifier for the customer (`customer_…`). | | `resource` | `string` | Always `customer`. | | `email` | `string` | Customer's email address (ASCII / Punycode domain). | | `metadata` | `object | null` | Your custom key/value metadata. | | `createdAt` | `string` | Creation timestamp (ISO 8601). | | `testmode` | `boolean` | Whether this is a test customer. | ## Create a customer `POST /v1/customers` ### Required attributes | Name | Type | Description | | ------- | -------- | ----------------------------- | | `email` | `string` | The customer's email address. | ### Optional attributes | Name | Type | Description | | ---------- | -------- | -------------------------- | | `metadata` | `object` | Custom key/value metadata. | ```ts const customer = await vatly.customers.create({ email: "ada@example.com", metadata: { plan: "pro" }, }); ``` Unicode domains are accepted directly; Vatly lowercases the local part and canonicalizes the domain to lowercase Punycode. Creating an already-known email returns the existing customer unchanged. To encode a domain yourself, optionally use: ```ts import { encodeEmail } from "@getvatly/sdk"; encodeEmail("user@bücher.de"); // → "user@xn--bcher-kva.de" ``` ## Retrieve a customer `GET /v1/customers/{customerId}` ```ts const customer = await vatly.customers.get("customer_abc123"); ``` ## Update identity and open the hosted portal ```ts await vatly.customers.update("customer_abc123", { name: "Ada", email: "ada@example.com" }); const session = await vatly.customers.createPortalSession("customer_abc123", { returnUrl: "https://yourapp.com/account", }); // Redirect the customer's browser to session.url. It is short-lived and single-use. ``` Updates accept name/email, not billing addresses. Portal settings are optional; `returnUrl` must be an absolute HTTPS URL without credentials, sent in the JSON body (not query params), at most 2,048 UTF-8 bytes. Authenticate your own customer before issuing a portal session, and never log or persist its credential URL. ## List customers `GET /v1/customers` ```ts const page = await vatly.customers.list({ limit: 25 }); for await (const customer of vatly.customers.listAll()) { // ... } ``` ## A customer's subscriptions `GET /v1/customers/{customerId}/subscriptions` ```ts // One page: const page = await vatly.customers.listSubscriptions("customer_abc123", { limit: 10 }); // Every subscription: for await (const sub of vatly.customers.listAllSubscriptions("customer_abc123")) { // ... } // A single nested subscription: const sub = await vatly.customers.getSubscription("customer_abc123", "subscription_abc123"); ``` # Checkouts Checkouts create hosted payment pages for your customers. When a checkout completes successfully, an Order is created. For all fields and options, see the [Checkouts API reference](https://docs.vatly.com/api-reference/checkouts){rel=""nofollow""}. The [OpenAPI spec](https://docs.vatly.com/openapi.yaml){rel=""nofollow""} is also available for tooling. ## The Checkout resource | Name | Type | Description | | --------------------- | --------------- | ------------------------------------------------------ | | `id` | `string` | Unique identifier for the checkout (`checkout_…`). | | `resource` | `string` | Always `checkout`. | | `status` | `string` | `created`, `paid`, `canceled`, `failed`, or `expired`. | | `customerId` | `string | null` | The customer this checkout is for, if known. | | `orderId` | `string | null` | Order ID, available after successful payment. | | `redirectUrlSuccess` | `string` | Where the customer returns on success. | | `redirectUrlCanceled` | `string` | Where the customer returns on cancel. | | `metadata` | `object | null` | Your custom key/value metadata. | | `expiresAt` | `string | null` | Expiration timestamp (ISO 8601). | | `createdAt` | `string` | Creation timestamp (ISO 8601). | | `testmode` | `boolean` | Whether this is a test checkout. | | `links.checkoutUrl` | `Link` | The hosted page to send the customer to. | ## Create a checkout `POST /v1/checkouts` ### Required attributes | Name | Type | Description | | --------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------ | | `products` | `array` | Product items to sell. Each item is `{ id, quantity }`, where `id` is a `subscription_plan_…` or `one_off_product_…` id. | | `redirectUrlSuccess` | `string` | Success redirect URL. | | `redirectUrlCanceled` | `string` | Cancel redirect URL. | ### Optional attributes | Name | Type | Description | | ------------ | -------- | ---------------------------------------------------------------- | | `customerId` | `string` | Attach the checkout to an existing customer. | | `metadata` | `object` | Custom metadata echoed back on the checkout and resulting order. | ```ts const checkout = await vatly.checkouts.create({ redirectUrlSuccess: "https://yourapp.com/success", redirectUrlCanceled: "https://yourapp.com/canceled", products: [{ id: "subscription_plan_abc123", quantity: 1 }], customerId: "customer_abc123", metadata: { signupId: "su_42" }, }); // Send the customer here: redirect(checkout.links.checkoutUrl.href); ``` ## Retrieve a checkout `GET /v1/checkouts/{checkoutId}` ```ts const checkout = await vatly.checkouts.get("checkout_abc123"); ``` ## List checkouts `GET /v1/checkouts` ```ts const page = await vatly.checkouts.list({ limit: 25 }); for await (const checkout of vatly.checkouts.listAll()) { // ... } ``` # Subscriptions Subscriptions are recurring billing relationships. They renew automatically according to their plan's interval until canceled. For all fields and options, see the [Subscriptions API reference](https://docs.vatly.com/api-reference/subscriptions){rel=""nofollow""}. The [OpenAPI spec](https://docs.vatly.com/openapi.yaml){rel=""nofollow""} is also available for tooling. ## The Subscription resource | Name | Type | Description | | -------------------------------------- | ------------------- | ---------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier (`subscription_…`). | | `customerId` | `string` | The customer this subscription belongs to. | | `subscriptionPlanId` | `string` | The plan this subscription is based on. | | `name` | `string` | Display name. | | `quantity` | `number` | Number of units. | | `status` | `string` | `active`, `created`, `trial`, `on_grace_period`, `paused`, or `canceled`. | | `interval` / `intervalCount` | `string` / `number` | Billing cadence (e.g. `month` × 1). | | `mandate` | `Mandate | null` | Payment method on file: `{ method, maskedIdentifier }`. `null` until one is bound. | | `startedAt` / `endedAt` / `canceledAt` | `string | null` | Lifecycle timestamps (ISO 8601). | | `nextRenewalAt` / `renewedUntil` | `string | null` | Renewal timestamps. | | `testmode` | `boolean` | Whether this is a test subscription. | ## Retrieve a subscription `GET /v1/subscriptions/{subscriptionId}` ```ts const subscription = await vatly.subscriptions.get("subscription_abc123"); console.log(subscription.mandate?.maskedIdentifier); ``` ## List subscriptions `GET /v1/subscriptions` ```ts const page = await vatly.subscriptions.list({ limit: 25 }); for await (const sub of vatly.subscriptions.listAll()) { // ... } ``` ## Update a subscription `PATCH /v1/subscriptions/{subscriptionId}` Common attributes: `quantity`, `subscriptionPlanId` (plan change), `prorate`, `applyImmediately`, `trialUntil`. Include at least one of `subscriptionPlanId`, `price`, or `quantity`; `trialUntil` cannot be sent alone. See the [API reference](https://docs.vatly.com/api-reference/subscriptions){rel=""nofollow""} for all options. ```ts const subscription = await vatly.subscriptions.update("subscription_abc123", { quantity: 2, }); ``` ## Cancel a subscription `DELETE /v1/subscriptions/{subscriptionId}` (204: no return value) ```ts await vatly.subscriptions.cancel("subscription_abc123"); // period end await vatly.subscriptions.cancel("subscription_other", { immediately: true }); ``` The default schedules cancellation at period end (with a grace period); `immediately: true` cancels immediately. Listen for the `subscription.canceled_*` webhooks to react. ## Resume a subscription `POST /v1/subscriptions/{subscriptionId}/resume` Resume a subscription that was canceled with a grace period, while that grace period is still active. ```ts const subscription = await vatly.subscriptions.resume("subscription_abc123"); ``` ## Update billing details (hosted link) `POST /v1/subscriptions/{subscriptionId}/billing-update-link` Returns a hosted link where the customer can update their payment method (mandate) or billing address. Redirect the customer to it. ```ts const link = await vatly.subscriptions.createBillingUpdateLink("subscription_abc123", { redirectUrlSuccess: "https://yourapp.com/billing/updated", redirectUrlCanceled: "https://yourapp.com/billing", }); redirect(link.href); ``` When the mandate changes, Vatly emits a `subscription.billing_updated` webhook so you can refresh the masked payment method shown to the customer. # Subscription Plans Subscription plans define recurring products, prices, and billing intervals. The API supports creation, updates, archive and unarchive. For all fields and options, see the [Subscription Plans API reference](https://docs.vatly.com/api-reference/subscription-plans){rel=""nofollow""}. The [OpenAPI spec](https://docs.vatly.com/openapi.yaml){rel=""nofollow""} is also available for tooling. ## The Subscription Plan resource | Name | Type | Description | | ---------------------------- | ------------------- | -------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier (`subscription_plan_…`). | | `resource` | `string` | Always `subscription_plan`. | | `name` | `string` | Display name. | | `description` | `string | null` | Optional description. | | `basePrice` | `Money` | Price per interval, e.g. `{ value: "29.00", currency: "EUR" }`. | | `interval` / `intervalCount` | `string` / `number` | Billing cadence: `month` × 1 or `year` × 1. Plans created earlier may still return `day`, `week`, or a higher count. | | `status` | `string` | `active`, `pending`, or `rejected`. Archive state is separate in `archivedAt`. | | `createdAt` | `string` | Creation timestamp (ISO 8601). | | `testmode` | `boolean` | Whether this is a test plan. | ## Retrieve a subscription plan `GET /v1/subscription-plans/{subscriptionPlanId}` ```ts const plan = await vatly.subscriptionPlans.get("subscription_plan_abc123"); console.log(plan.basePrice.value, plan.basePrice.currency); ``` ## List subscription plans `GET /v1/subscription-plans` ```ts const page = await vatly.subscriptionPlans.list({ limit: 25 }); for await (const plan of vatly.subscriptionPlans.listAll()) { // ... } ``` To sell a plan, pass its `id` in a [checkout](https://docs.vatly.com/packages/javascript/checkouts)'s `products`. ## Create, update and archive ```ts const plan = await vatly.subscriptionPlans.create({ name: "Pro Monthly", description: "Pro features", productType: "saas", basePrice: { value: "29.00", currency: "EUR" }, interval: "month", intervalCount: 1, }); await vatly.subscriptionPlans.update(plan.id, { interval: "year", intervalCount: 1 }); await vatly.subscriptionPlans.archive(plan.id); // 204: no return value const restored = await vatly.subscriptionPlans.unarchive(plan.id); const all = await vatly.subscriptionPlans.list({ includeArchived: true }); ``` New prices are EUR-only. `taxBehavior` defaults to `exclusive` and is immutable. Plans sell `saas` only. New and updated plans bill monthly (`interval: "month"`, `intervalCount: 1`) or yearly (`interval: "year"`, `intervalCount: 1`), in both live and test mode; anything else returns `422`. When updating, send `interval` and `intervalCount` together. Plans already on another interval keep working and can be updated without sending the interval. Creation and updates may require approval; inspect `status`, `pendingUpdates`, and `updateStatus`. # Orders Orders record checkout purchases and subscription renewals, including pending payments. They carry invoice links and tax breakdowns, and let you create refunds and inspect chargebacks. For all fields and options, see the [Orders API reference](https://docs.vatly.com/api-reference/orders){rel=""nofollow""}. The [OpenAPI spec](https://docs.vatly.com/openapi.yaml){rel=""nofollow""} is also available for tooling. ## The Order resource | Name | Type | Description | | -------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | `id` | `string` | Unique identifier (`order_…`). | | `customerId` | `string | null` | The customer this order belongs to. | | `status` | `string` | `created`, `pending`, `paid`, `canceled`, or `expired`. Payment recovery is signaled by `order.payment_failed`, not a status of that name. | | `total` | `Money` | Gross amount (incl. tax). | | `subtotal` | `Money` | Net amount (excl. tax). | | `reversedSubtotal` | `Money` | Net amount already reversed via refunds/chargebacks. | | `refundableSubtotal` | `Money` | Net amount still refundable. | | `taxSummary` | `array` | Per-rate VAT breakdown. | | `lines` | `OrderLine[]` | Line items, incl. `productType` / `productId` and `relatedResources`. | | `invoiceNumber` | `string | null` | Assigned once the invoice is issued. | | `paymentMethod` | `string | null` | Payment method used. | | `metadata` | `object | null` | Custom metadata carried from the checkout. | | `testmode` | `boolean` | Whether this is a test order. | ### Subscription on an order line `lines[].relatedResources.subscriptionId` names the subscription a signup, renewal or immediate-update line belongs to. `productType` / `productId` keep their meaning: a signup line references the plan (`subscription_plan`), a renewal or update line the subscription (`subscription`). - `relatedResources` is `null` on historical lines and on unrelated lines (one-off products, billing verification, authorization minimums). Older payloads may omit it. - `subscriptionId` is `null` on a signup line while its subscription is not yet available. A later `orders.get` returns the ID once it is. - An ID is not proof of activation or entitlement. Retrieve the subscription and check its status before granting access. ```ts // For a paid checkout, use checkout.orderId. const order = await vatly.orders.get("order_abc123"); for (const line of order.lines) { const subscriptionId = line.relatedResources?.subscriptionId; // string | null | undefined if (subscriptionId) { const subscription = await vatly.subscriptions.get(subscriptionId); } } ``` ## Retrieve an order `GET /v1/orders/{orderId}` ```ts const order = await vatly.orders.get("order_abc123"); console.log(order.total.value, order.total.currency); ``` ## List orders `GET /v1/orders` ```ts const page = await vatly.orders.list({ limit: 25 }); for await (const order of vatly.orders.listAll()) { // ... } ``` ## Invoice update link (hosted) `POST /v1/orders/{orderId}/invoice-update-link` Returns a hosted link where the customer can correct their invoice details (billing address, VAT number, company name). ```ts const link = await vatly.orders.createInvoiceUpdateLink("order_abc123"); redirect(link.href); ``` ## Refunds on an order Refunds are created against the order they belong to. ```ts // Partial refund of specific items: const refund = await vatly.orders.createRefund("order_abc123", { items: [ { itemId: "order_item_abc123", amount: { value: "15.00", currency: "EUR" } }, ], }); // Full refund of the entire order: const full = await vatly.orders.createFullRefund("order_abc123"); // List / get / cancel: const page = await vatly.orders.listRefunds("order_abc123", { limit: 10 }); for await (const r of vatly.orders.listAllRefunds("order_abc123")) { // ... } const one = await vatly.orders.getRefund("order_abc123", "refund_abc123"); await vatly.orders.cancelRefund("order_abc123", "refund_abc123"); // only while pending ``` See [Refunds](https://docs.vatly.com/packages/javascript/refunds) for the top-level refund endpoints. ## Chargebacks on an order ```ts const page = await vatly.orders.listChargebacks("order_abc123"); const chargeback = await vatly.orders.getChargeback("order_abc123", "chargeback_abc123"); ``` See [Chargebacks](https://docs.vatly.com/packages/javascript/chargebacks) for the top-level chargeback endpoints. # One-Off Products One-off products are single-purchase items (no recurring billing). They can be created, updated, archived, and unarchived through the API. For all fields and options, see the [One-off Products API reference](https://docs.vatly.com/api-reference/one-off-products){rel=""nofollow""}. The [OpenAPI spec](https://docs.vatly.com/openapi.yaml){rel=""nofollow""} is also available for tooling. ## The One-Off Product resource | Name | Type | Description | | ------------- | --------------- | ------------------------------------------------------------------------------ | | `id` | `string` | Unique identifier (`one_off_product_…`). | | `resource` | `string` | Always `one_off_product`. | | `name` | `string` | Display name. | | `description` | `string | null` | Optional description. | | `basePrice` | `Money` | Price, e.g. `{ value: "49.00", currency: "EUR" }`. | | `status` | `string` | `active`, `pending`, or `rejected`. Archive state is separate in `archivedAt`. | | `createdAt` | `string` | Creation timestamp (ISO 8601). | | `testmode` | `boolean` | Whether this is a test product. | ## Retrieve a one-off product `GET /v1/one-off-products/{oneOffProductId}` ```ts const product = await vatly.oneOffProducts.get("one_off_product_abc123"); ``` ## List one-off products `GET /v1/one-off-products` ```ts const page = await vatly.oneOffProducts.list({ limit: 25 }); for await (const product of vatly.oneOffProducts.listAll()) { // ... } ``` To sell a one-off product, pass its `id` in a [checkout](https://docs.vatly.com/packages/javascript/checkouts)'s `products`. ## Create, update and archive ```ts const product = await vatly.oneOffProducts.create({ name: "Premium License", description: "Lifetime access", productType: "saas", basePrice: { value: "99.00", currency: "EUR" }, taxBehavior: "exclusive", }); await vatly.oneOffProducts.update(product.id, { name: "Premium License v2" }); await vatly.oneOffProducts.archive(product.id); // 204: no return value const restored = await vatly.oneOffProducts.unarchive(product.id); const all = await vatly.oneOffProducts.list({ includeArchived: true }); ``` `productType` is `saas` or `ebook`. Creation and updates may require approval; inspect `status`, `pendingUpdates`, and `updateStatus` rather than assuming the requested values are already live. `taxBehavior` is immutable after creation. # Refunds A refund returns funds to a customer for an order. Refunds are **created** against an order (see [Orders](https://docs.vatly.com/packages/javascript/orders#refunds-on-an-order)); the top-level `refunds` resource lets you list and retrieve them across all orders. For all fields and options, see the [Refunds API reference](https://docs.vatly.com/api-reference/global-refunds){rel=""nofollow""} and [creating order refunds](https://docs.vatly.com/api-reference/refunds){rel=""nofollow""}. The [OpenAPI spec](https://docs.vatly.com/openapi.yaml){rel=""nofollow""} is also available for tooling. ## The Refund resource | Name | Type | Description | | ----------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Unique identifier (`refund_…`). | | `customerId` | `string` | The customer being refunded. | | `originalOrderId` | `string` | The order this refund is against. | | `status` | `string` | `pending`, `queued`, `processing`, `refunded`, `failed`, or `canceled`. The success event is `refund.completed`, but the status is `refunded`. | | `total` | `Money` | Gross amount refunded (incl. tax). | | `subtotal` | `Money` | Net amount refunded (excl. tax). | | `taxSummary` | `array` | Per-rate VAT breakdown of the refund. | | `testmode` | `boolean` | Whether this is a test refund. | ## Retrieve a refund `GET /v1/refunds/{refundId}` ```ts const refund = await vatly.refunds.get("refund_abc123"); ``` ## List refunds `GET /v1/refunds` ```ts const page = await vatly.refunds.list({ limit: 25 }); for await (const refund of vatly.refunds.listAll()) { // ... } ``` ## Creating refunds Create refunds against an order with `orders.createRefund` / `orders.createFullRefund`: ```ts await vatly.orders.createRefund("order_abc123", { items: [{ itemId: "order_item_abc123", amount: { value: "15.00", currency: "EUR" } }], }); await vatly.orders.createFullRefund("order_abc123"); ``` Listen for the `refund.completed` / `refund.failed` / `refund.canceled` webhooks to reconcile your local records — the webhook payload carries the full tax breakdown, so no follow-up call is needed. # Chargebacks A chargeback is a payment dispute raised by the cardholder's bank against an order. Vatly records it (and any later reversal) so you can suspend access and reconcile the reversed VAT. For all fields and options, see the [Chargebacks API reference](https://docs.vatly.com/api-reference/chargebacks){rel=""nofollow""}. The [OpenAPI spec](https://docs.vatly.com/openapi.yaml){rel=""nofollow""} is also available for tooling. ## The Chargeback resource | Name | Type | Description | | ----------------- | --------------- | ----------------------------------- | | `id` | `string` | Unique identifier (`chargeback_…`). | | `customerId` | `string` | The customer who disputed. | | `originalOrderId` | `string` | The order being disputed. | | `status` | `string` | Dispute status. | | `reason` | `string | null` | Reason given, if any. | | `total` | `Money` | Gross amount disputed (incl. tax). | | `subtotal` | `Money` | Net amount disputed (excl. tax). | | `taxSummary` | `array` | Per-rate VAT breakdown. | | `testmode` | `boolean` | Whether this is a test chargeback. | ## Retrieve a chargeback `GET /v1/chargebacks/{chargebackId}` ```ts const chargeback = await vatly.chargebacks.get("chargeback_abc123"); ``` ## List chargebacks `GET /v1/chargebacks` ```ts const page = await vatly.chargebacks.list({ limit: 25 }); for await (const chargeback of vatly.chargebacks.listAll()) { // ... } ``` Chargebacks for a specific order are also available via `vatly.orders.listChargebacks(orderId)` and `vatly.orders.getChargeback(orderId, chargebackId)` — see [Orders](https://docs.vatly.com/packages/javascript/orders#chargebacks-on-an-order). ## Reacting to disputes Listen for the `order.chargeback_received` and `order.chargeback_reversed` webhooks. The delivery's `entityId` is the order id and `object` is the full Chargeback (incl. the tax breakdown), so you can suspend access and reconcile the reversed VAT without a follow-up call. # Webhooks Vatly sends webhooks to notify your application when events happen — an order being paid, a refund completing, a subscription being canceled. Every delivery is HMAC-signed; the SDK verifies the signature and hands you a typed event. For event fields and endpoint options, see the [Webhook Events](https://docs.vatly.com/api-reference/webhook-events){rel=""nofollow""} and [Webhook Endpoints](https://docs.vatly.com/api-reference/webhook-endpoints){rel=""nofollow""} API references. The [OpenAPI spec](https://docs.vatly.com/openapi.yaml){rel=""nofollow""} is also available for tooling. ## Webhook events The `eventName` field identifies what happened. Names are available as constants on [`WebhookEventName`](https://github.com/vatly/vatly-api-js/blob/main/src/webhooks/events.ts){rel=""nofollow""}. | Event | `object` type | Description | | ---------------------------------------------------------------------------- | ---------------- | ------------------------------------------------------------------------- | | `order.paid` | Order | Order payment was successful. | | `order.canceled` | Order | Order was canceled. | | `order.payment_failed` | Order | A payment failed and dunning started. | | `order.chargeback_received` | Chargeback | A chargeback was received for an order. | | `order.chargeback_reversed` | Chargeback | A chargeback was reversed. | | `refund.completed` | Refund | Refund was processed successfully. | | `refund.failed` | Refund | Refund processing failed. | | `refund.canceled` | Refund | Refund was canceled. | | `subscription.started` | Subscription | Subscription was started. | | `subscription.billing_updated` | Subscription | Billing details (e.g. the mandate) changed. | | `subscription.canceled_immediately` | Subscription | Canceled immediately. | | `subscription.canceled_with_grace_period` | Subscription | Canceled; access until period end. | | `subscription.cancellation_grace_period_completed` | Subscription | Grace period ended. | | `subscription.resumed` | Subscription | A canceled subscription was resumed. | | `subscription.canceled_for_nonpayment` | Subscription | Payment recovery exhausted. | | `subscription.updated` | Subscription | Immediate/scheduled change or renewal; inspect `reason`. | | `subscription.update_scheduled` | Subscription | Change scheduled; inspect `scheduledUpdate`. | | `one_off_product.update_submitted` / `update_approved` / `update_rejected` | OneOffProduct | Product change review lifecycle (each suffix uses the same prefix). | | `one_off_product.archived` / `unarchived` | OneOffProduct | Product availability changed. | | `subscription_plan.update_submitted` / `update_approved` / `update_rejected` | SubscriptionPlan | Plan change review lifecycle. | | `subscription_plan.archived` / `unarchived` | SubscriptionPlan | Plan availability changed. | | `checkout.paid` | Checkout | Checkout was paid. | | `checkout.failed` | Checkout | Checkout payment failed. | | `checkout.canceled` | Checkout | Checkout was canceled. | | `checkout.expired` | Checkout | Checkout session expired. | | `webhook.setup` | Webhook | Verification call sent when an endpoint is registered or its URL changes. | ## Verify and process in one step `constructWebhookEventFromRequest` reads the raw body and `Vatly-Signature` header off a Fetch `Request`, verifies the HMAC, and returns a **discriminated** event. Check `event.known` first, then switch on `event.eventName` to narrow `event.object` to the exact resource — no casts, no follow-up API call (Vatly sends fat, signed payloads, so `object` is the full `GET /…/{id}` snapshot). ```ts import { constructWebhookEventFromRequest } from "@getvatly/sdk/webhooks"; export async function POST(request: Request): Promise { let event; try { event = await constructWebhookEventFromRequest(request, process.env.VATLY_WEBHOOK_SECRET!); } catch { return new Response("invalid signature", { status: 400 }); } if (!event.known) { // Retain the verified envelope durably for triage, then acknowledge it. // Until retention succeeds, retry rather than silently losing the delivery. return new Response("unsupported event requires triage", { status: 503 }); } switch (event.eventName) { case "order.paid": event.object.total; // Money — typed as Order break; case "subscription.billing_updated": event.object.mandate; // typed as Subscription break; case "webhook.setup": return new Response("ok"); // verification handshake — just acknowledge } return new Response("ok"); } ``` If you already have the raw bytes (e.g. a non-Fetch framework), use `constructWebhookEvent(rawBody, signatureHeader, secret)`. To verify only and get the raw `WebhookDelivery` envelope, use `constructEvent` / `constructEventFromRequest`, then narrow later with `toWebhookEvent(delivery)`. `VatlyWebhookEvent` includes `KnownWebhookEvent` (`known: true`) and `UnsupportedWebhookEvent` (`known: false`, `eventName: string`, `object: unknown`). The SDK adds this discriminator to a shallow copy after verification, overwriting any wire-supplied flag. It classifies the event name, not the resource schema. Both sides of `if (event.known)` narrow normally; no custom type guards are needed. Unknown event names can appear before an SDK upgrade. Keep them for triage and decide acknowledgement policy explicitly; a successful HMAC is not a reason to discard an event you cannot yet process. > **Always verify against the raw body bytes.** Re-serializing the JSON changes > the bytes (whitespace, key order, number formatting) and breaks the HMAC. ## The `webhook.setup` event When you register a webhook endpoint (or change its URL), Vatly sends a signed `webhook.setup` call to confirm the endpoint is reachable. It's delivered as a normal webhook — same envelope, same signature, same `Vatly-Event-Id` header — so there's nothing special to parse: verify it and return a `2xx`. Its `object` is the (secret-free) [webhook endpoint](https://docs.vatly.com/api-reference/webhook-endpoints){rel=""nofollow""} config and `links` is omitted (it's not a persisted event). ## Signature scheme ```text Vatly-Signature: t=1700000000,v1= Vatly-Event-Id: webhook_event_Qk8pRtSvWm2NjLhYcZaE ``` - `t` is unix seconds, captured fresh on each delivery attempt. - `v1` is `HMAC-SHA256("{t}.{rawBody}", webhookSecret)`, lowercase hex. - The SDK rejects signatures where `|now − t| > 300` seconds by default (5-minute clock-skew tolerance). Tune it with `{ toleranceSeconds }`. - Future algorithm rotation ships `v1=…,v2=…` simultaneously; the SDK verifies any version it recognizes and ignores the rest. ## Deduplication is your job The SDK is stateless — it can't remember which events it has verified. The clock-skew check bounds how long a leaked signature is replayable, but does not stop replays inside that window. For full replay defense, dedupe on the retry-stable, signed `event.id` in your own store after verification. The `Vatly-Event-Id` header is not signed and is for correlation only: ```ts const event = await constructWebhookEventFromRequest(request, secret); const eventId = event.id; if (await store.has(eventId)) return new Response("ok"); // already processed ``` Record successful processing and deduplication atomically; do not mark an event complete before its business effects succeed. Concurrent deliveries need a unique constraint or equivalent transactional claim in your store. ## Manage webhook endpoints ```ts const endpoint = await vatly.webhookEndpoints.create({ url: "https://yourapp.com/api/webhooks/vatly", secret: process.env.VATLY_WEBHOOK_SECRET!, enabledEvents: ["order.paid", "subscription.updated"], }); await vatly.webhookEndpoints.update(endpoint.id, { enabledEvents: [] }); // dormant const page = await vatly.webhookEndpoints.list(); await vatly.webhookEndpoints.delete(endpoint.id); // 204 ``` Secrets are write-only: store the one you supplied. HTTPS URLs must be unique within the storefront/mode, with up to five endpoints per mode. New event names are not automatically subscribed; update `enabledEvents` explicitly. ## Rotating secrets Every verification helper accepts a single secret or an array. During a rotation, pass both — the SDK accepts whichever signed the delivery: ```ts const event = await constructWebhookEventFromRequest(request, [ process.env.VATLY_WEBHOOK_SECRET_OLD!, process.env.VATLY_WEBHOOK_SECRET_NEW!, ]); ``` ## Fetching a persisted event Persisted events are available via the API. Note these are returned as the `WebhookEvent` shape (`GET /webhook-events/{id}`), which — unlike an inbound delivery — never includes the `webhook.setup` call and always carries `links`: ```ts const event = await vatly.webhookEvents.get("webhook_event_abc123"); ``` # SDK operation reference Import `VatlyClient` from `@getvatly/sdk`. All paths below are relative to `/v1`. Every method takes optional `RequestOptions` last. For field details, see the [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""}; the [OpenAPI spec](https://docs.vatly.com/openapi.yaml){rel=""nofollow""} is also available for tooling. Bodies and results use generated types; server-side validation still applies. Types, `components`, `paths`, and `operations` are exported from the package root. | SDK method | HTTP | Path | Result | | ------------------------------------------------- | ------ | ------------------------------------------------------- | ---------------------------------------------- | | `checkouts.list(params?)` | GET | `/checkouts` | Page of Checkout | | `checkouts.create(body)` | POST | `/checkouts` | Checkout | | `checkouts.get(id)` | GET | `/checkouts/{id}` | Checkout | | `customers.list(params?)` | GET | `/customers` | Page of Customer | | `customers.create(body)` | POST | `/customers` | Customer (new or existing) | | `customers.get(id)` | GET | `/customers/{id}` | Customer | | `customers.update(id, body)` | PATCH | `/customers/{id}` | Customer | | `customers.createPortalSession(id, body?)` | POST | `/customers/{id}/portal-sessions` | PortalSession | | `customers.listSubscriptions(id, params?)` | GET | `/customers/{id}/subscriptions` | Page of Subscription | | `customers.getSubscription(id, subId)` | GET | `/customers/{id}/subscriptions/{subId}` | Subscription | | `oneOffProducts.list(params?)` | GET | `/one-off-products` | Page of OneOffProduct | | `oneOffProducts.create(body)` | POST | `/one-off-products` | OneOffProduct | | `oneOffProducts.get(id)` | GET | `/one-off-products/{id}` | OneOffProduct | | `oneOffProducts.update(id, body)` | PATCH | `/one-off-products/{id}` | OneOffProduct | | `oneOffProducts.archive(id)` | POST | `/one-off-products/{id}/archive` | void (204) | | `oneOffProducts.unarchive(id)` | DELETE | `/one-off-products/{id}/archive` | OneOffProduct | | `subscriptionPlans.list(params?)` | GET | `/subscription-plans` | Page of SubscriptionPlan | | `subscriptionPlans.create(body)` | POST | `/subscription-plans` | SubscriptionPlan | | `subscriptionPlans.get(id)` | GET | `/subscription-plans/{id}` | SubscriptionPlan | | `subscriptionPlans.update(id, body)` | PATCH | `/subscription-plans/{id}` | SubscriptionPlan | | `subscriptionPlans.archive(id)` | POST | `/subscription-plans/{id}/archive` | void (204) | | `subscriptionPlans.unarchive(id)` | DELETE | `/subscription-plans/{id}/archive` | SubscriptionPlan | | `orders.list(params?)` | GET | `/orders` | Page of Order | | `orders.get(id)` | GET | `/orders/{id}` | Order | | `orders.createInvoiceUpdateLink(id)` | POST | `/orders/{id}/invoice-update-link` | InvoiceUpdateLink (`href`, `type`) | | `orders.listRefunds(id, params?)` | GET | `/orders/{id}/refunds` | Page of Refund | | `orders.createRefund(id, body)` | POST | `/orders/{id}/refunds` | Refund | | `orders.createFullRefund(id, body?)` | POST | `/orders/{id}/refunds/full` | Refund | | `orders.getRefund(id, refundId)` | GET | `/orders/{id}/refunds/{refundId}` | Refund | | `orders.cancelRefund(id, refundId)` | DELETE | `/orders/{id}/refunds/{refundId}` | void (204) | | `orders.listChargebacks(id, params?)` | GET | `/orders/{id}/chargebacks` | Page of Chargeback | | `orders.getChargeback(id, chargebackId)` | GET | `/orders/{id}/chargebacks/{chargebackId}` | Chargeback | | `refunds.list(params?)` | GET | `/refunds` | Page of Refund | | `refunds.get(id)` | GET | `/refunds/{id}` | Refund | | `chargebacks.list(params?)` | GET | `/chargebacks` | Page of Chargeback | | `chargebacks.get(id)` | GET | `/chargebacks/{id}` | Chargeback | | `webhookEvents.get(id)` | GET | `/webhook-events/{id}` | WebhookEvent | | `webhookEndpoints.list(params?)` | GET | `/webhook-endpoints` | Page of WebhookEndpoint | | `webhookEndpoints.create(body)` | POST | `/webhook-endpoints` | WebhookEndpoint | | `webhookEndpoints.get(id)` | GET | `/webhook-endpoints/{id}` | WebhookEndpoint | | `webhookEndpoints.update(id, body)` | PATCH | `/webhook-endpoints/{id}` | WebhookEndpoint | | `webhookEndpoints.delete(id)` | DELETE | `/webhook-endpoints/{id}` | void (204) | | `subscriptions.list(params?)` | GET | `/subscriptions` | Page of Subscription | | `subscriptions.get(id)` | GET | `/subscriptions/{id}` | Subscription | | `subscriptions.update(id, body)` | PATCH | `/subscriptions/{id}` | Subscription | | `subscriptions.cancel(id)` | DELETE | `/subscriptions/{id}` | void (204) | | `subscriptions.createBillingUpdateLink(id, body)` | POST | `/subscriptions/{id}/billing-update-link` | SubscriptionBillingUpdateLink (`href`, `type`) | | `subscriptions.resume(id)` | POST | `/subscriptions/{id}/resume` | Subscription | | `testHelpers.fastForwardRenewal(id, body?)` | POST | `/test-helpers/subscriptions/{id}/fast-forward-renewal` | Subscription | | `testHelpers.simulateOrderPayment(id, body)` | POST | `/test-helpers/orders/{id}/simulate-payment` | Order | All top-level lists have a `listAll(params?, opts?)` async iterator. Nested subscription/refund lists have `listAllSubscriptions` / `listAllRefunds`. Pagination params: `limit`, `startingAfter`, `endingBefore`. Product/plan lists also accept `includeArchived`. Immediate cancellation uses `subscriptions.cancel(id, { immediately: true, ...requestOptions })`. ## Alpha migration notes - Package scope changed to `@getvatly/sdk` (also `@getvatly/sdk/webhooks`). - Cancellation now accurately returns `Promise`, not a subscription. Fetch the subscription afterward if needed. - Billing-update methods now return a hosted link, not a subscription. Deprecated `updateBilling` / `requestAddressUpdateLink` aliases still work. - The obsolete `simulatePaymentFailure(transactionId)` endpoint is removed; use `simulateOrderPayment(orderId, { paymentStatus: "failed" })`. - `fastForwardRenewal` now takes an optional body second and options third. - Optional fields with server defaults no longer need to be supplied in requests. - Errors can expose `details`; only `in_progress` idempotency conflicts retry. - Subscription updates require at least one of `subscriptionPlanId`, `price`, or `quantity`; `trialUntil` cannot stand alone. This is validated by the API. ## Deterministic payment testing Only test-mode keys are allowed (guarded before sending a request): ```ts const subscription = await vatly.testHelpers.fastForwardRenewal("subscription_123", { paymentStatus: "failed", failureReason: "card_expired", }); const order = await vatly.testHelpers.simulateOrderPayment("order_123", { paymentStatus: "paid", }); ``` Omitting the renewal body advances the cycle and leaves its payment pending. `failureReason` only applies with `paymentStatus: "failed"`. These operations simulate payment outcomes; payment recovery remains managed by Vatly. See the [testing guide](https://docs.vatly.com/guides/testing){rel=""nofollow""} for recovery timelines and event semantics. # JavaScript Fluent > **Alpha — under active development. Every alpha release may include breaking changes. Lock the version you install and review the release notes before upgrading.** Create checkouts and manage billing with `@getvatly/fluent` on your server. Vatly is the European Merchant of Record for AI, software and digital products. Install the latest alpha of both packages: ```sh npm install --save-exact @getvatly/sdk @getvatly/fluent ``` ## Start a subscription Use a customer and plan from the key's storefront and mode. Check that the signed-in user owns the customer before calling this function: ```ts import { VatlyClient } from '@getvatly/sdk'; import { Vatly } from '@getvatly/fluent'; export async function startSubscription(apiKey: string, customerId: string, planId: string) { const vatly = new Vatly({ api: new VatlyClient({ apiKey }), redirectUrlSuccess: 'https://app.example.com/billing/return', redirectUrlCanceled: 'https://app.example.com/billing/canceled', }); const checkout = await vatly.subscribe({ vatlyId: customerId }) .toPlan(planId) .withQuantity(1) .create(); return checkout.getUrl(); // Redirect the customer's browser to this URL. } ``` Redirect to the returned URL. Use [webhooks](https://docs.vatly.com/packages/fluent-js/webhooks) to confirm payment, not the return page. For one-off purchases, use [`checkoutBuilder`](https://docs.vatly.com/packages/fluent-js/checkouts#one-off-or-mixed-purchases). ## Guides | Task | Guide | | ----------------------------------------- | ----------------------------------------------------------------------------------- | | Set keys, redirects, and error handling | [Configuration](https://docs.vatly.com/packages/fluent-js/configuration) | | Connect your database | [Core concepts and storage](https://docs.vatly.com/packages/fluent-js/coreconcepts) | | Link customers to your users | [Customers and bindings](https://docs.vatly.com/packages/fluent-js/customers) | | Sell products or start subscriptions | [Checkouts](https://docs.vatly.com/packages/fluent-js/checkouts) | | Swap, cancel, resume, or update billing | [Subscriptions](https://docs.vatly.com/packages/fluent-js/subscriptions) | | Open invoice history and billing controls | [Customer portal](https://docs.vatly.com/packages/fluent-js/customerportal) | | Verify and process events | [Webhooks](https://docs.vatly.com/packages/fluent-js/webhooks) | | Read invoices, lines, and reversals | [Orders](https://docs.vatly.com/packages/fluent-js/orders) | | Test your integration | [Testing](https://docs.vatly.com/packages/fluent-js/testing) | For field details, see the [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""}. The [OpenAPI spec](https://docs.vatly.com/openapi.yaml){rel=""nofollow""} is also available for tooling. # Installation and configuration Fluent requires `@getvatly/sdk` as a peer. Install the latest alpha of both; `--save-exact` pins the installed versions: ```sh npm install --save-exact @getvatly/sdk @getvatly/fluent ``` Use Node 20+ or a runtime with Fetch and Web Crypto. ESM, CommonJS, and TypeScript declarations are included. Keep keys and secrets on the server, never in browser code or `NEXT_PUBLIC_*` variables. ## Create the billing service Pass your server's `VATLY_API_KEY` to this factory: ```ts import { VatlyClient } from '@getvatly/sdk'; import { Vatly, type Wiring } from '@getvatly/fluent'; export function createBilling( apiKey: string, drivers: Omit = {}, ) { return new Vatly({ ...drivers, api: new VatlyClient({ apiKey, timeoutMs: 15_000, maxRetries: 2 }), redirectUrlSuccess: 'https://app.example.com/billing/return', redirectUrlCanceled: 'https://app.example.com/billing/canceled', }); } ``` `test_` keys select test mode; `live_` keys charge real money. Both use the same API URL. All IDs and bindings must match the key's storefront and mode. Checkout creation needs only `api` and redirect URLs. Add [storage drivers](https://docs.vatly.com/packages/fluent-js/coreconcepts) for bindings, local subscription updates, and webhook persistence. Missing drivers fail when used. For webhooks, also set `webhookSecret` from `VATLY_WEBHOOK_SECRET`, the endpoint's signing secret—not the API key. Use `vatly.api` for SDK operations without a Fluent helper, including catalogue management, pagination, and webhook endpoints. ## Handle errors and retries ```ts import { VatlyValidationError } from '@getvatly/sdk'; import { FluentError, type Vatly } from '@getvatly/fluent'; export async function renameCustomer(vatly: Vatly, customerId: string, name: string) { try { return await vatly.customer(customerId).update({ name }); } catch (error) { if (error instanceof VatlyValidationError) { return { validationErrors: error.errors }; } if (error instanceof FluentError) throw error; // Fix local input or wiring. throw error; // Preserve SDK status, details, and cause for your error handler. } } ``` SDK errors pass through unchanged. Most local input and wiring errors use `FluentError`; missing billing-update redirects throw a plain `Error` in this alpha. Reuse an `idempotencyKey` when retrying the same mutation: a timeout does not mean it failed. See [checkout retries](https://docs.vatly.com/packages/fluent-js/checkouts#payloads-and-retries). For HTTP options and field details, see the [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""} and [errors guide](https://docs.vatly.com/guides/errors){rel=""nofollow""}. # Core concepts and storage Connect Fluent to your existing tables through storage drivers. Your application owns the database, authentication, and jobs; Fluent supplies the contracts. ```ts import type { Order } from '@getvatly/sdk'; import type { LocalSubscription, Repository, Stored, Wiring } from '@getvatly/fluent'; export function storageDrivers( subscriptions: Repository, orders: Repository>, ): Pick { return { subscriptions, orders }; } ``` ## Repository behavior `Stored` adds `hostCustomerId` to the SDK resource. It is null for an unattributed customer. `LocalSubscription` also adds `endsAt`. | Method | Return value | | --------------------- | ---------------------------------------------------------------------------------------- | | `findByVatlyId(id)` | Record or null. | | `store(data)` | Saved record, or null to decline storage and skip the local-created event. | | `update(id, partial)` | Updated record. Omitted/`undefined` fields stay unchanged; null clears a nullable field. | Enforce unique Vatly IDs per tenant, storefront, and mode. Adapt existing tables rather than duplicating them. `store` can match a pending host record using checkout metadata and attach its Vatly ID. Metadata helps match records; it does not authorize access. `refunds` and `chargebacks` use `ReversalRepository`, which adds `listForOrder(id)` and `listForCustomer(id)`. Contracts accept sync or async implementations, except `webhookCalls.process`, which returns a promise. ## Billables and bindings Keep your user, team, or organization as the billable; there is no `Billable` mixin. `CustomerProfile` carries `vatlyId`, `email`, and optional `name`. Your application's ID (`hostId`) is separate from Vatly's customer ID (`vatlyId`). Authorize both. | `CustomerBindings` method | Behavior | | ---------------------------- | --------------------------------------------------------------------- | | `bind(vatlyId, hostId)` | Associate IDs atomically; enforce uniqueness on both sides. | | `record(vatlyId)` | Record an unattributed customer without clearing an existing binding. | | `vatlyCustomerIdFor(hostId)` | Return the Vatly ID or null. | | `hostCustomerIdFor(vatlyId)` | Return the host ID or null. | Do not silently reassign bindings. Keep test and live data separate. See [customers](https://docs.vatly.com/packages/fluent-js/customers) for creation and lookup examples. ## Webhook storage Wire `webhookCalls` for deduplication and audit retention, and `events` for outbox writes. They must share a transaction with repositories and bindings. Use your database's transaction context or request-scoped drivers, not a global variable shared by concurrent requests. The [webhook transaction steps](https://docs.vatly.com/packages/fluent-js/webhooks#idempotency-and-one-transaction) define what must commit or roll back together. For remote resource fields, use the [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""}. # Customers and bindings Find or create a Vatly customer for your signed-in user. Wire [binding storage](https://docs.vatly.com/packages/fluent-js/coreconcepts#billables-and-bindings) first. ## Create and bind ```ts import type { Vatly } from '@getvatly/fluent'; export async function customerFor(vatly: Vatly, hostId: string, email: string) { const existing = await vatly.customers.findByHostCustomerId(hostId); if (existing) return existing; return vatly.customers.createFor( hostId, { email, name: 'Example Customer' }, { metadata: { accountId: hostId } }, { idempotencyKey: `customer-for:${hostId}` }, ); } ``` `createFor` rejects an already-bound host. The API may return an existing customer for the email; Fluent checks the binding before attaching it. A binding failure cannot undo remote creation. Reconcile the customer before retrying. To link a verified existing customer, use `vatly.customers.attribute(vatlyId, hostId)`. To create without a host owner, use `createUnattributed(profile, extra?, requestOptions?)`; it still needs `bindings` to record the ID. ## Read and update identity ```ts import type { Vatly } from '@getvatly/fluent'; export async function updateIdentity(vatly: Vatly, customerId: string) { const customer = vatly.customer(customerId); await customer.update({ name: null }); // Explicitly clear the display name. await customer.sync(); // Refresh the cached API resource. return customer.identity(); // { name, email } } export async function matchingCustomers(vatly: Vatly, email: string) { const ids: string[] = []; for await (const customer of vatly.customers.findByEmail(email)) ids.push(customer.id); return ids; } ``` Handles fetch lazily and cache per handle. `model()`, `name()`, and `email()` read that cache; `sync()` refreshes it. Email lookup searches all cursor pages on the server. `findOneByEmail` returns the first match or null, not proof of ownership. Identity updates do not change invoice addresses; use the [billing-update flow](https://docs.vatly.com/packages/fluent-js/subscriptions#update-billing-details). ## Returning from checkout `customerIdFromCheckout(checkoutId)` returns an ID or null for a missing customer or 404; other API errors propagate. `claimCustomerFromCheckout(checkoutId, hostId)` binds that customer. Verify checkout ownership before calling it: an ID in a return URL is not proof. See [payment confirmation](https://docs.vatly.com/packages/fluent-js/webhooks). See [customer portal](https://docs.vatly.com/packages/fluent-js/customerportal) for portal links and the [Customers API reference](https://docs.vatly.com/api-reference/customers){rel=""nofollow""} for field details. # Checkouts Create a hosted payment page, then redirect the customer to `checkout.getUrl()`. ## One-off or mixed purchases ```ts import type { Vatly } from '@getvatly/fluent'; export async function buyProduct( vatly: Vatly, customerId: string, productId: string, purchaseId: string, ) { const checkout = await vatly.checkoutBuilder({ vatlyId: customerId }) .withItems([{ id: productId, quantity: 2 }]) .withMetadata({ purchaseId }) .withLocale('en_US') .create({}, { idempotencyKey: `checkout:${purchaseId}` }); return { id: checkout.id, url: checkout.getUrl() }; } ``` Set both redirect URLs in [configuration](https://docs.vatly.com/packages/fluent-js/configuration), or use `withRedirectUrlSuccess(url)` and `withRedirectUrlCanceled(url)` on the builder. `withItems` appends items and supports mixed carts. ## Subscription checkout ```ts import type { Vatly } from '@getvatly/fluent'; export async function startSubscription( vatly: Vatly, customerId: string, planId: string, purchaseId: string, ) { return vatly.subscribe({ vatlyId: customerId }) .toPlan(planId) .withQuantity(3) .withTrialDays(14) .create({}, { idempotencyKey: `subscribe:${purchaseId}` }); } ``` `subscribe` makes no request until `create()`, which creates a checkout, not a subscription. The subscription builder uses one plan; use `checkoutBuilder` for mixed carts. Quantity and trial days must be positive safe integers. Omit trial methods for no trial, or use `withTrialEndsAt(date)` to round up to whole days. ## Payloads and retries Use a new builder per purchase. `payload(overrides?)` returns a detached request snapshot without calling the API. `create(overrides?, requestOptions?)` returns the SDK checkout plus `getUrl()`. On plain SDK checkouts, read `links.checkoutUrl.href`. Persist the purchase ID before calling `create()`. Reuse its idempotency key on retries; use a new key for a new purchase. Validate customer, product, price, and redirect overrides on the server rather than passing browser input through. `inTestmode()` and `inLiveMode()` check the API key's mode; they do not change it. For a known customer, [create or bind them first](https://docs.vatly.com/packages/fluent-js/customers) and authorize their ID. An email-only profile does not create a customer. Omit the profile for an anonymous checkout where the API supports it. Save the checkout ID. Confirm payment through [webhooks](https://docs.vatly.com/packages/fluent-js/webhooks), not the return page. For product and checkout fields, see the [Checkouts API reference](https://docs.vatly.com/api-reference/checkouts){rel=""nofollow""} and [Subscription Plans](https://docs.vatly.com/api-reference/subscription-plans){rel=""nofollow""}. # Subscriptions Change an existing subscription with `vatly.subscription(localRecord)`. Load and authorize the record from your [repository](https://docs.vatly.com/packages/fluent-js/coreconcepts); wire that repository into `Vatly` so swap, resume, and sync can save changes. ## Change plan or quantity ```ts import type { LocalSubscription, Vatly } from '@getvatly/fluent'; export async function schedulePlan(vatly: Vatly, local: LocalSubscription, planId: string) { return vatly.subscription(local).swap(planId, { quantity: 2 }); } export async function changeAndInvoice(vatly: Vatly, local: LocalSubscription, planId: string) { return vatly.subscription(local).swapAndInvoice(planId, { quantity: 2 }); } export async function changeWithoutCharge(vatly: Vatly, local: LocalSubscription, planId: string) { return vatly.subscription(local).swapWithoutCharge(planId); } ``` Choose one action: | Method | Options sent to the API | | -------------------------------------- | ----------------------------------------------------------------------- | | `swap(planId, body?, requestOptions?)` | Your update options; without `applyImmediately`, changes are scheduled. | | `swapAndInvoice(...)` | Forces `applyImmediately: true`, `invoiceImmediately: true`. | | `swapWithoutCharge(...)` | Forces `applyImmediately: true`, `prorationCharge: false`. | `swapAndInvoice()` does not return the proration order. It is created and charged asynchronously, typically within 15 to 30 minutes: Vatly waits briefly so that other charges for the same customer made around the same time are combined into one order and one payment instead of several. Follow the `order.paid` webhook (or `order.payment_failed`); its order line has `relatedResources.subscriptionId` set to the subscription. In test mode, settle or decline its pending payment with `vatly.testHelpers().simulateOrderPayment()` (see [Testing](https://docs.vatly.com/packages/fluent-js/testing)). Local plan and quantity follow the API response. A scheduled swap leaves the current plan unchanged. `scheduledUpdate()` fetches the pending change; `hasScheduledUpdate()` checks whether one exists. See the API reference below for proration rules. ## Cancel and resume ```ts import type { LocalSubscription, Vatly } from '@getvatly/fluent'; export async function cancelNow(vatly: Vatly, local: LocalSubscription, operationId: string) { await vatly.subscription(local).cancel({ immediately: true, idempotencyKey: `cancel:${operationId}`, }); } export async function resume(vatly: Vatly, local: LocalSubscription) { const handle = await vatly.subscription(local).resume(); return handle.model(); } ``` `cancel()` uses the API's default timing; `{ immediately: true }` cancels now. Cancellation waits for [webhooks](https://docs.vatly.com/packages/fluent-js/webhooks) to set local `endsAt`. Resume clears it after the API succeeds. `cancellationReason()` fetches the remote reason. `model()` returns the local record. `sync()` fetches and saves the API resource. `state()` derives `active`, `valid`, `recurring`, `cancelled`, `onGracePeriod`, and `ended` from `endsAt`. Check Vatly's `status` separately for states such as paused. ### Grace-period limitation in this alpha This alpha's `sync()` and cancellation reactions set `endsAt` to `endedAt ?? canceledAt`. During a grace period, `endedAt` can be null and `canceledAt` is the cancellation request time, not the access deadline. The local flags can therefore report an ended subscription while access is still owed. Keep entitlement decisions separate from `state()` until this is corrected; confirm the grace deadline before changing access. Do not use `canceledAt` as an expiry. ## Update billing details ```ts import type { LocalSubscription, Vatly } from '@getvatly/fluent'; export async function billingUpdateUrl(vatly: Vatly, local: LocalSubscription) { return vatly.subscription(local).updateBilling({ redirectUrlSuccess: 'https://app.example.com/billing/updated', redirectUrlCanceled: 'https://app.example.com/billing/canceled', }); } ``` Redirect to the returned URL; do not log or persist it. This hosted flow updates billing details, rather than writing address fields directly. Both redirects are required here or in [configuration](https://docs.vatly.com/packages/fluent-js/configuration). Process `subscription.billing_updated` to update local payment details. For all options, eligibility, and fields, see the [Subscriptions API reference](https://docs.vatly.com/api-reference/subscriptions){rel=""nofollow""}. # Orders and invoices Fetch an order's invoice link, lines, and totals after checking the caller owns it. ## Read the order and invoice ```ts import type { Vatly } from '@getvatly/fluent'; export async function invoice(vatly: Vatly, orderId: string) { const order = vatly.order(orderId); const model = await order.model(); return { id: model.id, status: model.status, total: model.total, lines: await order.lines(), invoiceUrl: await order.invoiceUrl(), }; } ``` The handle fetches once and caches the API resource. `sync()` refreshes it. `invoiceUrl()` returns null if no link exists. These reads need no local order or line repository. Use [webhooks](https://docs.vatly.com/packages/fluent-js/webhooks) to persist payments and fulfill orders. ## Link order lines to subscriptions Each line's `relatedResources.subscriptionId` names the subscription it belongs to. Signup, renewal and immediate-update lines all use it. Signup lines keep `productType: 'subscription_plan'` with the plan in `productId`. Renewals use `'subscription'`. ```ts import type { Order } from '@getvatly/sdk'; export function subscriptionLinks(order: Order) { const linked = new Set(); const unresolved: string[] = []; for (const line of order.lines) { const id = line.relatedResources?.subscriptionId; if (id) linked.add(id); else if (line.productType === 'subscription_plan') unresolved.push(line.id); } return { subscriptionIds: [...linked], unresolvedLineIds: unresolved }; } ``` `relatedResources` is null on historical and unrelated lines, such as one-off products, and older payloads may omit it. `{ subscriptionId: null }` means a signup's subscription is not available yet. It does not mean creation failed. Fetch the order again later with `vatly.order(id).sync()`, because a stored `order.paid` snapshot keeps the value it was signed with. An ID does not prove the subscription is active or that access is owed. Check its status and owner first. `order.paid` handling stores the whole signed order, including these links, in your `orders` repository. Fluent does not query orders by subscription. Index the stored line IDs yourself if you need that. ## Money and reversals Use `toMinorUnits` for bigint arithmetic; keep the currency with the amount. ```ts import { toMinorUnits } from '@getvatly/sdk'; import type { Vatly } from '@getvatly/fluent'; export async function reversalSummary(vatly: Vatly, orderId: string) { const order = vatly.order(orderId); const model = await order.model(); return { totalMinor: toMinorUnits(model.total), reversedMinor: await order.reversedSubtotal(), refundableMinor: await order.refundableSubtotal(), fullyReversed: await order.isFullyReversed(), partiallyReversed: await order.isPartiallyReversed(), }; } ``` Money uses decimal strings, not floats. Convert bigints to strings before returning JSON. Reversal predicates read the cached API resource, not local reversal lists. `isReversed()` includes partial reversals. A paid order stays paid after a reversal. `order.refunds()` and `order.chargebacks()` read your wired reversal repositories. Without a driver they return an empty list. Use `vatly.api.orders` and `vatly.api.refunds` to create refunds or query remote reversals. Check API state before retrying a refund whose outcome is unknown. For fields and refund rules, see [Orders](https://docs.vatly.com/api-reference/orders){rel=""nofollow""}, [Order Refunds](https://docs.vatly.com/api-reference/refunds){rel=""nofollow""}, and [Chargebacks](https://docs.vatly.com/api-reference/chargebacks){rel=""nofollow""} in the API reference. # Customer portal Send a signed-in customer to their invoices and subscription controls: ```ts import type { Vatly } from '@getvatly/fluent'; export async function portalUrl(vatly: Vatly, authenticatedHostId: string) { const customer = await vatly.customers.findByHostCustomerId(authenticatedHostId); if (!customer) return null; const session = await vatly.customer(customer.id).portalSession({ returnUrl: 'https://app.example.com/account/billing', }); return session.url; } ``` Look up the customer through [bindings](https://docs.vatly.com/packages/fluent-js/customers); do not accept a customer ID from the browser. Redirect to the returned URL with `Cache-Control: no-store`. It is a short-lived, single-use credential: never log, cache, or persist it. If an idempotent retry returns a consumed link, request another with a fresh key. An eligible issued invoice is required; a subscription alone is not enough. One-off buyers can view invoice history too. On an eligibility 404, show your billing page instead of retrying. The portal stays in the key's storefront and mode, with no storefront picker. `returnUrl` is an HTTPS return link, not an automatic redirect. For a direct billing-details flow, see [subscriptions](https://docs.vatly.com/packages/fluent-js/subscriptions#update-billing-details). For eligibility and response fields, see [Create a customer portal session](https://docs.vatly.com/api-reference/customers#create-a-customer-portal-session){rel=""nofollow""}. # Webhooks Record payments and subscription changes from signed webhooks, not checkout redirects. Pass a configured `Vatly` to this Fetch handler, or export the returned function as a Next.js Route Handler's `POST`: ```ts import { VatlyInvalidSignatureError } from '@getvatly/sdk'; import { Vatly } from '@getvatly/fluent'; export function webhookRoute(vatly: Vatly) { return async function POST(request: Request): Promise { try { const processed = await vatly.webhookProcessor().handleRequest(request); return new Response(null, { status: processed ? 201 : 200 }); } catch (error) { if (error instanceof VatlyInvalidSignatureError) { return new Response('Invalid signature', { status: 400 }); } // Failed storage/reactions must be retried; do not acknowledge success. return new Response('Webhook processing failed', { status: 500 }); } }; } ``` Set `webhookSecret`, `webhookCalls`, and the repositories you want updated in [configuration](https://docs.vatly.com/packages/fluent-js/configuration). This route needs no browser session; signatures authenticate deliveries. Pass the original unread request, not reserialized JSON. For raw bytes, use `processor.handle(rawBody, signatureHeader)`. The SDK checks `Vatly-Signature` HMAC and timestamp before touching storage. Keep timestamp checks enabled. To rotate secrets, set `webhookSecret` to an array of accepted secrets. ## Idempotency and one transaction Implement `WebhookCalls.process(event, work)` in one transaction shared by all [storage drivers](https://docs.vatly.com/packages/fluent-js/coreconcepts#webhook-storage): 1. Lock or claim the signed `event.id`. If already committed, return false. 2. Retain the verified envelope, including unknown events. 3. Await `work()` to run reactions and dispatch. 4. Mark the ID processed and commit resource changes, bindings, audit, and outbox together. Return true. Roll back everything on failure. Never commit the deduplication row before the work; a failure would lose the retry. Use signed `event.id`, not the unsigned `Vatly-Event-Id` header. Scope keys and rows by tenant, storefront, and mode. Timestamp checks alone do not deduplicate. Write to an outbox in `events.dispatch`. Send email and make network calls from a worker after commit. Deliveries can arrive out of order; reconcile conflicting snapshots with the API. ## What Fluent persists | Event | Built-in action when the repository is wired | | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | `subscription.started` | Create or update a local subscription; a new saved row emits `local.subscription_created`. | | `subscription.updated`, `subscription.billing_updated` | Update plan, name, quantity, status, and non-null mandate on an existing row; otherwise skip. | | `subscription.resumed` | Update an existing row and clear `endsAt`. | | Cancellation events and grace-period completion | Update an existing row's `endsAt` and cancellation reason. | | `order.paid`, `order.payment_failed` | Create or update an order using the signed status; a newly stored paid order emits `local.order_created`. | | `order.canceled` | Update status and cancellation reason on an existing order; otherwise skip. | | `refund.completed`, `refund.failed`, `refund.canceled` | Upsert a refund if `refunds` is wired. | | `order.chargeback_received`, `order.chargeback_reversed` | Upsert a chargeback if `chargebacks` is wired. | | Scheduled subscription updates, catalogue, checkout, `webhook.setup` | Dispatch only; no built-in resource write. | Reactions use the signed snapshot without an API GET. Missing repositories skip writes, not dispatch. Null billing-event mandates leave the local mandate unchanged; subscription `sync()` reconciles removal. Before using subscription state to grant or revoke access, read the [grace-period limitation in this alpha](https://docs.vatly.com/packages/fluent-js/subscriptions#grace-period-limitation-in-this-alpha). ## Application events and extensions ```ts import type { DomainEvent, EventDispatcher } from '@getvatly/fluent'; export function billingEvents( enqueueInCurrentTransaction: (event: DomainEvent) => Promise, ): EventDispatcher { return { dispatch: event => enqueueInCurrentTransaction(event) }; } ``` Check `event.known` before switching on `eventName`. The union includes SDK deliveries and the two local-created events above. Unknown signed events have `known: false` and `object: unknown`; retain and dispatch them without built-in writes. Types do not validate resource fields at runtime. `additionalWebhookReactions` takes `{ supports(event), handle(event) }` objects. They run after built-ins and before dispatch, in the same transaction. Throw to roll back and allow retry. For event fields, see [Webhook Events](https://docs.vatly.com/api-reference/webhook-events){rel=""nofollow""}. Register endpoints using [Webhook Endpoints](https://docs.vatly.com/api-reference/webhook-endpoints){rel=""nofollow""}; the [webhooks guide](https://docs.vatly.com/guides/webhooks){rel=""nofollow""} describes delivery and signatures. # Testing Test API calls without a network by injecting the SDK's `fetch`: ```ts import { VatlyClient } from '@getvatly/sdk'; import { Vatly } from '@getvatly/fluent'; export async function testCheckoutLookup() { const vatly = new Vatly({ api: new VatlyClient({ apiKey: 'test_local_fixture_not_a_real_key', maxRetries: 0, fetch: async (input, init) => { if (new URL(String(input)).pathname !== '/v1/checkouts/checkout_fixture' || init?.method !== 'GET') throw new Error('Unexpected request'); return new Response(JSON.stringify({ customerId: 'customer_fixture' }), { headers: { 'content-type': 'application/json' }, }); }, }), }); const id = await vatly.customerIdFromCheckout('checkout_fixture'); if (id !== 'customer_fixture') throw new Error('Incorrect customer'); } ``` This fixture tests only customer lookup. Use full resource fixtures for other operations; SDK types do not validate them at runtime. ## Test your storage boundary Check the [storage contracts](https://docs.vatly.com/packages/fluent-js/coreconcepts): uniqueness under concurrency, test/live separation, omitted versus null updates, and a declined `store`. For [webhooks](https://docs.vatly.com/packages/fluent-js/webhooks), test valid, invalid, stale, and rotated signatures using an independent HMAC signer. Concurrent copies must commit once. A failed reaction must roll back rows, audit markers, and outbox work, then succeed on retry. Also test unknown events and out-of-order snapshots. Keep timestamp checks enabled. ## Live test-mode workflow 1. Set `VATLY_API_KEY` to a real `test_` key. Use customer and catalogue IDs from its storefront and mode. Test keys do not create real charges. 2. Expose your local webhook route through an HTTPS tunnel. Register the public URL and save its signing secret as `VATLY_WEBHOOK_SECRET`. 3. Pay through a [hosted checkout](https://docs.vatly.com/packages/fluent-js/checkouts). Save the checkout/order IDs and confirm signed `checkout.paid` and `order.paid` deliveries. 4. Check duplicate and failed deliveries. Delete or disable temporary endpoints before closing the tunnel; record any resources you create. `vatly.testHelpers()` exposes `advanceRenewal`, `forceRenewalPaid`, `forceRenewalFailed`, `forceOrderPaymentPaid`, `forceOrderPaymentFailed`, and the SDK-style `fastForwardRenewal`/`simulateOrderPayment`. These mutate account data. Use them only with permission and disposable test resources, not existing subscriptions or orders just because the key is in test mode. ## Test your edge runtime For edge hosts, also run your app in the local edge runtime with its storage adapter. Node tests alone do not check edge compatibility. See the [testing guide](https://docs.vatly.com/guides/testing){rel=""nofollow""} and [Test Helpers API reference](https://docs.vatly.com/api-reference/test-helpers){rel=""nofollow""}. # Python SDK Vatly is the European Merchant of Record for AI, software and digital products. Use this SDK for typed API calls from Python 3.10+. For a storage-backed billing integration, use Fluent Python or Vatly Django. **Alpha — under active development. Every alpha release may include breaking changes. Lock the version you install and review the release notes before upgrading.** ## Install and connect ```bash python -m pip install --pre vatly-api-python ``` The SDK is in alpha, so `--pre` is needed to install the latest alpha release. Set `VATLY_API_KEY` in your server environment. Test and live keys use the same API host; the key selects the mode. Never put credentials in client-side code. ```python from vatly import VatlyClient def example(): with VatlyClient() as client: return client.customers.list({"limit": 10}).data ``` Resource-page functions accept that configured client. Copy a function, then call `example(client)` inside the `with` block. Replace example resource IDs with your own. Creation, updates, cancellations and refunds mutate the selected account. ## Async applications ```python from vatly import AsyncVatlyClient async def example(): async with AsyncVatlyClient() as client: return [customer.id async for customer in client.customers.list_all({"limit": 25})] ``` Async resource methods use `await`; pagination uses `async for`. Both clients return Pydantic models. Python fields use snake\_case; dictionary inputs use Vatly's camelCase wire keys. Unknown response fields are preserved. ## Choose a guide | Guide | What you can do | | ------------------------------------------------------------------------------ | ----------------------------------------------- | | [Configuration](https://docs.vatly.com/packages/python/configuration) | Set timeouts, retries and handle errors | | [Customers](https://docs.vatly.com/packages/python/customers) | Create/find customers and open their portal | | [Checkouts](https://docs.vatly.com/packages/python/checkouts) | Build a hosted one-off or recurring payment | | [Subscriptions](https://docs.vatly.com/packages/python/subscriptions) | Change plans, cancel, resume and update billing | | [Subscription plans](https://docs.vatly.com/packages/python/subscriptionplans) | Manage recurring catalog products | | [One-off products](https://docs.vatly.com/packages/python/oneoffproducts) | Manage one-time catalog products | | [Orders](https://docs.vatly.com/packages/python/orders) | Read lines, totals and invoice links | | [Refunds](https://docs.vatly.com/packages/python/refunds) | Refund an order and track reversals | | [Chargebacks](https://docs.vatly.com/packages/python/chargebacks) | Read payment disputes | | [Webhooks](https://docs.vatly.com/packages/python/webhooks) | Verify raw signed deliveries | | [Webhook endpoints](https://docs.vatly.com/packages/python/webhookendpoints) | Register and manage receivers | | [API inventory](https://docs.vatly.com/packages/python/api) | Look up every method and endpoint | | [Development](https://docs.vatly.com/packages/python/development) | Contribute, regenerate models and run checks | [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""} contains the complete request and response contracts. Examples in these guides are executed against the published packages with local HTTP fixtures; tests make no Vatly account changes. # Configuration and errors Use one client per application task or worker lifetime and close it with `with` or `async with`. Both clients accept `VATLY_API_KEY` or an explicit server-side key. ```python from vatly import RequestOptions, VatlyClient def example(): with VatlyClient(timeout=20, max_retries=2) as client: return client.customers.get("customer_example", options=RequestOptions(timeout=5)) ``` | Option | Meaning | | -------------------------------- | ----------------------------------------------------------------------- | | `api_key` | Explicit key; otherwise read `VATLY_API_KEY` | | `timeout` | HTTP timeout in seconds; request options can override it | | `max_retries` | Automatic retry budget for eligible failures | | `base_url` | HTTP(S) endpoint without query/fragment; use HTTPS for real credentials | | `RequestOptions.idempotency_key` | Stable business key shared across caller retries | | `RequestOptions.headers` | Additional request headers | Retryable failures include connection/timeouts, rate limits and eligible server errors. Mutations receive an automatic key for internal retries; persist your own key when retrying across application calls. A timeout can leave the remote outcome unknown. Never assume it means a purchase or refund did not happen. ## Handle a missing resource ```python from vatly import VatlyClient, VatlyNotFoundError def example(client: VatlyClient): try: return client.customers.get("customer_missing") except VatlyNotFoundError: return None ``` Catch `VatlyError` for all SDK errors. API errors expose status, body, method, URL and request ID where supplied; connection and timeout errors retain their httpx cause and request context. Avoid logging credentials or full response bodies, which can contain personal data. Invalid resource responses raise `VatlyApiError` rather than silently returning None. [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""} · [Pagination examples](https://docs.vatly.com/packages/python/customers) # Customers Keep a Vatly customer ID alongside your own user or company. Customers hold billing identity; a shared email or customer ID is not proof that someone owns an order. Pass a configured `VatlyClient` to the functions below; see [setup](https://docs.vatly.com/packages/python/readme). ## Create, retrieve and update ```python from vatly import RequestOptions, VatlyClient from vatly.models import CreateCustomerRequest def example(client: VatlyClient): customer = client.customers.create( CreateCustomerRequest(email="buyer@example.com", name="Alex"), options=RequestOptions(idempotency_key="signup:user-42"), ) saved = client.customers.get(customer.id) updated = client.customers.update(saved.id, {"name": "Alex Morgan"}) return updated.id, updated.email ``` | Create/update parameter | Type | Purpose | | ----------------------- | -------------- | --------------------------------------------------- | | `email` | string | Required on create; optional on update | | `name` | string or null | Optional name; null clears it on update | | `metadata` | object | Optional custom data on create; not an update field | Update changes name/email, not invoice addresses. Use the hosted billing flows for address changes. Keep the same idempotency key when retrying the same signup. ## Find by email and read subscriptions ```python from vatly import VatlyClient def example(client: VatlyClient): customers = list(client.customers.list_all({"email": "buyer@example.com", "limit": 25})) subscriptions = list(client.customers.list_all_subscriptions("customer_example")) return customers, subscriptions ``` Email lookup returns zero or more customers within the API key's storefront and mode. General list filters are `limit` (1–100), `startingAfter`, or `endingBefore`; do not send both cursors. `list()` returns one page; `list_all()` yields resources. ## Open the hosted portal ```python from vatly import VatlyClient def example(client: VatlyClient): session = client.customers.create_portal_session( "customer_example", {"returnUrl": "https://app.example.com/billing"} ) return session.url ``` Authorize the customer before calling this. Redirect the browser to the returned single-use URL; never cache or log it. `returnUrl` is optional; use `{}` for no return link. It does not automatically redirect the customer back. | Response field | Python type | Meaning | | -------------------------- | -------------- | ------------------------------ | | `id`, `email` | str | Customer identity | | `name` | str or None | Display name | | `created_at`, `testmode` | datetime, bool | Creation time and mode | | `metadata`, `links` | model objects | Custom data and resource links | | Portal `url`, `expires_at` | str, datetime | Temporary entry URL and expiry | [Customer API reference](https://docs.vatly.com/api-reference/customers){rel=""nofollow""} · [All methods](https://docs.vatly.com/packages/python/api#customers) # Checkouts Create a hosted payment page and redirect your buyer to it. A checkout can contain one-off products, subscription plans, or both. Use IDs from your own product catalog. Examples accept the client from [setup](https://docs.vatly.com/packages/python/readme). ## Create a payment page ```python from vatly import RequestOptions, VatlyClient from vatly.models import CreateCheckoutRequest def example(client: VatlyClient): checkout = client.checkouts.create( CreateCheckoutRequest( products=[{"id": "one_off_product_example", "quantity": 1}], redirect_url_success="https://app.example.com/billing/success", redirect_url_canceled="https://app.example.com/billing/canceled", customer_id="customer_example", ), options=RequestOptions(idempotency_key="purchase:order-42"), ) return checkout.id, checkout.links.checkout_url.href ``` Persist the purchase key before calling Vatly and reuse it after a timeout. A new key can create a second purchase. The raw SDK Checkout has no `get_url()` method; that convenience belongs to Fluent. | Input model field | Wire key | Required? | | --------------------------------------- | -------------------------------------- | ------------------------------------------------------------------------- | | `products` | `products` | Yes: items with `id`, positive `quantity`; optional `trialDays` for plans | | `redirect_url_success` | `redirectUrlSuccess` | Yes | | `redirect_url_canceled` | `redirectUrlCanceled` | Yes | | `customer_id` | `customerId` | No: an authorized existing customer | | `locale`, `metadata`, `billing_address` | `locale`, `metadata`, `billingAddress` | No | Pydantic inputs accept Python names. Dictionary inputs use wire keys, including `trialDays` inside product dictionaries. Omit `customer_id` for a guest checkout. ## Read a checkout or traverse pages ```python from vatly import VatlyClient def example(client: VatlyClient): checkout = client.checkouts.get("checkout_example") page = client.checkouts.list({"limit": 10}) ids = [item.id for item in client.checkouts.list_all({"limit": 25})] return checkout.order_id, page.count, ids ``` | Response field | Meaning | | -------------------------- | --------------------------------------------------------------- | | `id`, `status`, `testmode` | Identifier, payment state and mode | | `customer_id` | Customer when assigned; may be None | | `order_id` | Read this Order for purchased lines; may be None before payment | | `links.checkout_url.href` | Hosted checkout destination | The success redirect is **not payment confirmation**. Use [signed webhooks](https://docs.vatly.com/packages/python/webhooks) and your own ownership records. Checkout responses do not contain a products array. [Checkout API reference](https://docs.vatly.com/api-reference/checkouts){rel=""nofollow""} · [All methods](https://docs.vatly.com/packages/python/api#checkouts) # Subscriptions A paid checkout containing a subscription plan starts recurring billing. There is no direct `subscriptions.create()`. Read and manage the resulting subscription ID after establishing who owns it. Examples use the client from [setup](https://docs.vatly.com/packages/python/readme). ## Read and change a subscription ```python from vatly import RequestOptions, VatlyClient def example(client: VatlyClient): subscription = client.subscriptions.get("subscription_example") changed = client.subscriptions.update( subscription.id, {"subscriptionPlanId": "subscription_plan_pro", "quantity": 2}, options=RequestOptions(idempotency_key="plan-change:42"), ) return changed.status, changed.scheduled_update ``` Changes are scheduled by default. Inspect `scheduled_update`; do not immediately replace the active plan in your application. | Update parameter (wire key) | Purpose | | -------------------------------------------------- | -------------------------------------------------- | | `subscriptionPlanId`, `quantity`, `price` | Send at least one to request a change | | `applyImmediately` | Apply now instead of scheduling | | `invoiceImmediately`, `prorate`, `prorationCharge` | Explicit invoicing/proration choices | | `trialUntil` | Optional aware datetime; cannot be the sole change | ## Cancel, resume and update billing details These are separate user actions. Only resume during a valid grace period. ```python from vatly import VatlyClient def example(client: VatlyClient): client.subscriptions.cancel("subscription_example", {"immediately": False}) ``` For a later, separate resume request: ```python from vatly import VatlyClient def example(client: VatlyClient): return client.subscriptions.resume("subscription_example") ``` ```python from vatly import VatlyClient def example(client: VatlyClient): link = client.subscriptions.create_billing_update_link( "subscription_example", { "redirectUrlSuccess": "https://app.example.com/billing/success", "redirectUrlCanceled": "https://app.example.com/billing/canceled", }, ) return link.href ``` Cancellation returns None; resume returns a Subscription. Set `immediately=True` only when the user intends immediate cancellation. Reuse business idempotency keys with `RequestOptions` when retrying mutations. | Response field | Meaning | | ------------------------------------------------- | ---------------------------------------------------------- | | `status` | Current lifecycle state; inspect it before granting access | | `customer_id`, `subscription_plan_id`, `quantity` | Billing identity and current purchase | | `canceled_at` | Cancellation **request** time, not grace expiry | | `ended_at` | Actual end when present | | `next_renewal_at`, `renewed_until`, `trial_until` | Period information; nullable | | `scheduled_update` | Pending changes or None | Do not infer a subscription ID from a plan ID. Initial order lines can still reference plans; this alpha does not consume the proposed related-resources subscription reference. [Fluent's guide](https://docs.vatly.com/packages/fluent-python/subscriptions){rel=""nofollow""} explains recovery and expiry limits. [Subscription API reference](https://docs.vatly.com/api-reference/subscriptions){rel=""nofollow""} · [All methods](https://docs.vatly.com/packages/python/api#subscriptions) # Subscription plans Plans define the recurring product, price and billing interval sold through a [checkout](https://docs.vatly.com/packages/python/checkouts). A plan is not a customer's subscription. Examples accept the client from [setup](https://docs.vatly.com/packages/python/readme). ## Create a monthly plan ```python from vatly import VatlyClient from vatly.models import CreateSubscriptionPlanRequest def example(client: VatlyClient): return client.subscription_plans.create( CreateSubscriptionPlanRequest( name="Pro", description="Monthly access to Pro", base_price={"value": "19.00", "currency": "EUR"}, product_type="saas", interval="month", interval_count=1, ) ) ``` | Input field | Type | Required? | | --------------------- | ------------------------------------------------------- | --------- | | `name`, `description` | string | Yes | | `base_price` | EUR money, e.g. `{"value": "19.00", "currency": "EUR"}` | Yes | | `product_type` | `"saas"` | Yes | | `interval` | `"month"` or `"year"` | Yes | | `interval_count` | `1` | Yes | | `tax_behavior` | `"exclusive"` or `"inclusive"` | No | Plans bill monthly (`"month"`, `1`) or yearly (`"year"`, `1`) in both live and test mode; any other combination returns `422`. Use decimal strings, never floats, for money. The current creation contract uses EUR. Model fields are snake\_case; dictionary inputs use `basePrice`, `productType`, `intervalCount` and `taxBehavior`. ## Find, update and archive ```python from vatly import VatlyClient def example(client: VatlyClient): plans = list(client.subscription_plans.list_all({"includeArchived": True, "limit": 25})) plan = client.subscription_plans.get("subscription_plan_example") updated = client.subscription_plans.update(plan.id, {"name": "Pro monthly"}) client.subscription_plans.archive(updated.id) restored = client.subscription_plans.unarchive(updated.id) return plans, restored ``` To change the billing interval, send `interval` and `intervalCount` together, set to `"month"` or `"year"` with `1`; anything else returns `422`. Other fields can be updated without sending the interval. Archiving prevents new sales, not existing renewals. `archive()` returns None; `unarchive()` returns the plan. Test changes are auto-approved; live changes may require approval. | Response field | Meaning | | ----------------------------------- | ---------------------------------------------------------------------------------------------- | | `id` | `subscription_plan_...` catalog ID | | `name`, `description`, `base_price` | Product and price | | `interval`, `interval_count` | Billing cadence; plans created earlier may still return `"day"`, `"week"` or a count above `1` | | `testmode`, `links` | Mode and resource links | [Plan API reference](https://docs.vatly.com/api-reference/subscription-plans){rel=""nofollow""} · [All methods](https://docs.vatly.com/packages/python/api#subscription_plans) # Orders Orders contain purchased lines, tax and financial totals. Read an order after its checkout has an `order_id`. Keep exact decimal amounts for accounting. Examples accept the client from [setup](https://docs.vatly.com/packages/python/readme). ## Read an order and its lines ```python from decimal import Decimal from vatly import VatlyClient def example(client: VatlyClient): order = client.orders.get("order_example") lines = [(line.product_type, line.product_id, line.quantity) for line in order.lines] subscription_ids = [ line.related_resources.subscription_id for line in order.lines if line.related_resources is not None ] refundable = Decimal(order.refundable_subtotal.root.value) return order.status, lines, subscription_ids, refundable ``` | Response field | Meaning | | ------------------------------------------ | ----------------------------------------------------------------------------------------- | | `id`, `status`, `customer_id` | Order identity and payment state | | `lines` | OrderLine models with `id`, `product_type`, `product_id`, `quantity`, `related_resources` | | `refundable_subtotal`, `reversed_subtotal` | Money wrappers; read `.root.value` and `.root.currency` | | `links.customer_invoice` | Optional customer invoice link | | `testmode`, `metadata` | Mode and custom data | `product_type="subscription_plan"` means `product_id` is a plan ID; `"subscription"` means a subscription ID. Never substitute one for the other. `line.related_resources.subscription_id` is the subscription associated with a signup, renewal or immediate-update line. `related_resources` is `None` on historical and unrelated lines. On a signup line, `subscription_id` is `None` until the subscription is available; read the order again later. An ID alone does not prove activation or entitlement: check the subscription's ownership and status before granting access. ## List orders and request an invoice-details link ```python from vatly import VatlyClient def example(client: VatlyClient): orders = list(client.orders.list_all({"limit": 25})) link = client.orders.create_invoice_update_link("order_example") return orders, link.href ``` The hosted link lets the customer update invoice details. Authorize the order before returning it. List filters include `limit`, `startingAfter`, `endingBefore`; see the API reference for resource-specific filters. Use [refunds](https://docs.vatly.com/packages/python/refunds) for reversals and [chargebacks](https://docs.vatly.com/packages/python/chargebacks) for disputes. Ownership comes from your checkout records, not a shared customer ID. [Order API reference](https://docs.vatly.com/api-reference/orders){rel=""nofollow""} · [All methods](https://docs.vatly.com/packages/python/api#orders) # One-off products Sell a digital product once rather than on a recurring schedule. Create it in the catalog, then pass its ID to a [checkout](https://docs.vatly.com/packages/python/checkouts). Examples accept the client from [setup](https://docs.vatly.com/packages/python/readme). ## Create a product ```python from vatly import VatlyClient from vatly.models import CreateOneOffProductRequest def example(client: VatlyClient): return client.one_off_products.create( CreateOneOffProductRequest( name="Python handbook", description="A downloadable programming book", product_type="ebook", base_price={"value": "29.00", "currency": "EUR"}, ) ) ``` | Input field | Type | Required? | | --------------------- | ----------------------------------- | --------- | | `name`, `description` | string | Yes | | `base_price` | EUR money with a two-decimal string | Yes | | `product_type` | `"saas"` or `"ebook"` | Yes | | `tax_behavior` | `"exclusive"` or `"inclusive"` | No | Dictionary inputs use `basePrice`, `productType` and `taxBehavior`. Responses may contain additional product-type strings; the SDK preserves them. That does not make those strings valid creation inputs. ## Read, update and archive ```python from vatly import VatlyClient def example(client: VatlyClient): products = list(client.one_off_products.list_all({"includeArchived": True})) product = client.one_off_products.get("one_off_product_example") client.one_off_products.update(product.id, {"name": "Revised handbook"}) client.one_off_products.archive(product.id) return products, client.one_off_products.unarchive(product.id) ``` Archiving stops new sales and returns None. Unarchiving returns the product. Live catalog changes may await approval; test-mode changes are auto-approved. | Response field | Meaning | | ---------------------------- | -------------------------------- | | `id` | `one_off_product_...` catalog ID | | `name`, `description` | Buyer-facing content | | `base_price`, `product_type` | Exact price and category | | `testmode`, `links` | Mode and resource links | [Product API reference](https://docs.vatly.com/api-reference/one-off-products){rel=""nofollow""} · [All methods](https://docs.vatly.com/packages/python/api#one_off_products) # Refunds Refunds reverse some or all of an order. Create them through `client.orders`, not `client.refunds`. The top-level refunds resource is for reads. Examples accept the client from [setup](https://docs.vatly.com/packages/python/readme). ## Issue a full refund ```python from vatly import RequestOptions, VatlyClient def example(client: VatlyClient): refund = client.orders.create_full_refund( "order_example", {}, options=RequestOptions(idempotency_key="refund:request-42"), ) return refund.id, refund.status ``` Keep the same key for retries of this refund. A timeout does not prove it failed; read the existing refund/order before deciding to issue another. | Operation | Inputs | Return | | --------------------------- | ----------------------------------------------- | ------ | | `orders.create_full_refund` | order ID, `{}` or optional metadata | Refund | | `orders.create_refund` | order ID, `{"items": [...]}`; optional metadata | Refund | | `orders.cancel_refund` | order ID, refund ID | None | | `refunds.get` | refund ID | Refund | ## Refund part of a line ```python from vatly import RequestOptions, VatlyClient def example(client: VatlyClient): return client.orders.create_refund( "order_example", { "items": [ {"itemId": "order_item_example", "amount": {"value": "5.00", "currency": "EUR"}} ], }, options=RequestOptions(idempotency_key="partial-refund:42"), ) ``` `itemId` must be an original order line ID. `amount` is before tax and must not exceed that line's remaining refundable amount. Preserve the order currency and use decimal strings, never rounded floats. Vatly calculates the tax reversal. ## Read and cancel a pending refund ```python from vatly import VatlyClient def example(client: VatlyClient): refunds = list(client.refunds.list_all({"limit": 25})) scoped = list(client.orders.list_all_refunds("order_example")) refund = client.orders.get_refund("order_example", "refund_example") client.orders.cancel_refund("order_example", refund.id) return refunds, scoped ``` Cancellation is only allowed while Vatly permits it; it is not a reversal of a completed refund. Signed refund events confirm completion, failure or cancellation. | Response field | Meaning | | ---------------------- | ------------------------------------ | | `id`, `status` | Refund identifier and state | | `original_order_id` | Order being reversed | | `lines` | Refunded lines and financial details | | `testmode`, `metadata` | Mode and custom data | [Refund API reference](https://docs.vatly.com/api-reference/refunds){rel=""nofollow""} · [All methods](https://docs.vatly.com/packages/python/api#refunds) # Chargebacks Read payment disputes and retain their financial snapshots for accounting. Chargeback methods are read-only. Examples accept the client from [setup](https://docs.vatly.com/packages/python/readme). ```python from vatly import VatlyClient def example(client: VatlyClient): chargeback = client.chargebacks.get("chargeback_example") all_disputes = list(client.chargebacks.list_all({"limit": 25})) order_disputes = list(client.orders.list_all_chargebacks("order_example")) scoped = client.orders.get_chargeback("order_example", "chargeback_example") return chargeback, all_disputes, order_disputes, scoped ``` | Input | Meaning | | ---------------------------------------- | ------------------------------------------ | | Chargeback ID | `chargeback_...` from Vatly | | Order ID | Required for the `orders`-scoped methods | | `limit`, `startingAfter`, `endingBefore` | List size and exclusive pagination cursors | | Response field | Meaning | | ------------------- | ------------------------------------ | | `id`, `resource` | Identifier; resource is `chargeback` | | `original_order_id` | Disputed order | | `lines` | Financial line snapshots | | `testmode`, `links` | Mode and resource links | `order.chargeback_received` and `order.chargeback_reversed` events contain a Chargeback object even though `entityType` is `order`. Inspect `event.object.resource`, not just the envelope's entity type. Verify the [signature](https://docs.vatly.com/packages/python/webhooks) first. [Chargeback API reference](https://docs.vatly.com/api-reference/chargebacks){rel=""nofollow""} · [All methods](https://docs.vatly.com/packages/python/api#chargebacks) # Webhooks Use signed webhooks to learn about payments and subscription changes. Verify the exact request bytes before parsing or changing anything. Register delivery URLs separately with [webhook endpoints](https://docs.vatly.com/packages/python/webhookendpoints). ## Verify and parse a delivery This function accepts the raw HTTP body, `Vatly-Signature` header and your endpoint secret. It returns a validated event; your route must persist it transactionally. ```python from vatly.webhooks import construct_webhook_event def example(raw_body: bytes, signature: str, secret: str): event = construct_webhook_event(raw_body, signature, secret) return event.id, event.event_name, event.known ``` | Input | Meaning | | ----------- | -------------------------------------------------------------------- | | `raw_body` | Original bytes, not re-serialized JSON | | `signature` | `Vatly-Signature` header: `t=,v1=` | | `secret` | Endpoint secret, or a sequence of secrets during rotation | | `tolerance` | Default 300 seconds of absolute clock skew; keep clocks synchronized | Invalid/missing signatures or invalid signed JSON raise `VatlyInvalidSignatureError`. `construct_event()` accepts only currently known event names; `construct_webhook_event()` also preserves future events with `known=False`. ## Check a signature without parsing ```python from vatly.webhooks import is_valid_webhook_signature def example(raw_body: bytes, signature: str, secret: str): return is_valid_webhook_signature(raw_body, signature, secret) ``` | Event field | Meaning | | ------------------------ | ------------------------------------------------------------ | | `id` | Signed deduplication authority | | `event_name` | For example `order.paid` or `subscription.started` | | `object` | Full resource snapshot; inspect its `resource` discriminator | | `testmode`, `created_at` | Mode and event creation time | Deduplicate signed `event.id` in the same transaction as business writes and an outbox. The unsigned `Vatly-Event-Id` header is only diagnostic. Return success after commit; let failures produce 5xx for retry. Freshness checks do not replace deduplication, and deduplication does not establish event ordering. The SDK supplies no database or route. Use Fluent or Django for storage integration. Do not grant access merely because a browser visited a checkout success URL. [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""} · [Endpoint API reference](https://docs.vatly.com/api-reference/webhook-endpoints){rel=""nofollow""} # Webhook endpoints Endpoints tell Vatly where to send events. Configure these from trusted server-side administration, not from a buyer's request. Examples accept the client from [setup](https://docs.vatly.com/packages/python/readme); running them changes your Vatly configuration. ## Register an HTTPS receiver ```python import secrets from vatly import VatlyClient def example(client: VatlyClient): secret = secrets.token_urlsafe(32) endpoint = client.webhook_endpoints.create( { "url": "https://app.example.com/billing/webhook/", "secret": secret, "enabledEvents": ["order.paid", "subscription.started"], } ) # Store secret in your secret manager; do not log it. return endpoint.id ``` | Input (wire key) | Required? | Purpose | | ---------------- | ------------- | ----------------------------------------------------------- | | `url` | Yes on create | Public HTTPS receiver | | `secret` | Yes on create | Secret used to verify deliveries | | `enabledEvents` | No | Event names to subscribe to; see API reference for defaults | Subscribe to every lifecycle event your integration needs, including cancellation, resume and refund events. The minimal example above is not a complete billing policy. ## List, update and remove an endpoint ```python from vatly import VatlyClient def example(client: VatlyClient): endpoints = list(client.webhook_endpoints.list_all({"limit": 25})) endpoint = client.webhook_endpoints.get("webhook_endpoint_example") updated = client.webhook_endpoints.update( endpoint.id, { "url": "https://app.example.com/billing/webhook/", }, ) client.webhook_endpoints.delete(updated.id) return endpoints ``` Deletion returns None. Coordinate secret rotation with your receiver, which can accept old and new secrets temporarily. Do not expose endpoint secrets to browsers. | Response field | Meaning | | ------------------- | --------------------------------- | | `id`, `url` | Endpoint identity and destination | | `enabled_events` | Event subscriptions | | `testmode`, `links` | Mode and resource links | [Endpoint API reference](https://docs.vatly.com/api-reference/webhook-endpoints){rel=""nofollow""} · [Verify deliveries](https://docs.vatly.com/packages/python/webhooks) # API reference Generated from `openapi.yaml`. Sync and async clients expose the same methods. Pass a Pydantic request/params model or a wire-format dictionary. All methods accept keyword-only `options=RequestOptions(...)`. ## `checkouts` | Method | HTTP endpoint | Returns | | ------------------- | ----------------------------- | ---------------- | | `list(params=None)` | `GET /checkouts` | `Page[Checkout]` | | `create(body)` | `POST /checkouts` | `Checkout` | | `get(checkout_id)` | `GET /checkouts/{checkoutId}` | `Checkout` | ## `customers` | Method | HTTP endpoint | Returns | | ------------------------------------------------ | ------------------------------------------------------------ | -------------------- | | `list(params=None)` | `GET /customers` | `Page[Customer]` | | `create(body)` | `POST /customers` | `Customer` | | `get(customer_id)` | `GET /customers/{customerId}` | `Customer` | | `update(customer_id, body)` | `PATCH /customers/{customerId}` | `Customer` | | `create_portal_session(customer_id, body)` | `POST /customers/{customerId}/portal-sessions` | `PortalSession` | | `list_subscriptions(customer_id, params=None)` | `GET /customers/{customerId}/subscriptions` | `Page[Subscription]` | | `get_subscription(customer_id, subscription_id)` | `GET /customers/{customerId}/subscriptions/{subscriptionId}` | `Subscription` | ## `one_off_products` | Method | HTTP endpoint | Returns | | ---------------------------------- | ---------------------------------------------------- | --------------------- | | `list(params=None)` | `GET /one-off-products` | `Page[OneOffProduct]` | | `create(body)` | `POST /one-off-products` | `OneOffProduct` | | `get(one_off_product_id)` | `GET /one-off-products/{oneOffProductId}` | `OneOffProduct` | | `update(one_off_product_id, body)` | `PATCH /one-off-products/{oneOffProductId}` | `OneOffProduct` | | `archive(one_off_product_id)` | `POST /one-off-products/{oneOffProductId}/archive` | `None` | | `unarchive(one_off_product_id)` | `DELETE /one-off-products/{oneOffProductId}/archive` | `OneOffProduct` | ## `subscription_plans` | Method | HTTP endpoint | Returns | | ------------------------------------ | --------------------------------------------------------- | ------------------------ | | `list(params=None)` | `GET /subscription-plans` | `Page[SubscriptionPlan]` | | `create(body)` | `POST /subscription-plans` | `SubscriptionPlan` | | `get(subscription_plan_id)` | `GET /subscription-plans/{subscriptionPlanId}` | `SubscriptionPlan` | | `update(subscription_plan_id, body)` | `PATCH /subscription-plans/{subscriptionPlanId}` | `SubscriptionPlan` | | `archive(subscription_plan_id)` | `POST /subscription-plans/{subscriptionPlanId}/archive` | `None` | | `unarchive(subscription_plan_id)` | `DELETE /subscription-plans/{subscriptionPlanId}/archive` | `SubscriptionPlan` | ## `orders` | Method | HTTP endpoint | Returns | | ----------------------------------------- | -------------------------------------------------- | ------------------- | | `list(params=None)` | `GET /orders` | `Page[Order]` | | `get(order_id)` | `GET /orders/{orderId}` | `Order` | | `create_invoice_update_link(order_id)` | `POST /orders/{orderId}/invoice-update-link` | `InvoiceUpdateLink` | | `list_refunds(order_id, params=None)` | `GET /orders/{orderId}/refunds` | `Page[Refund]` | | `create_refund(order_id, body)` | `POST /orders/{orderId}/refunds` | `Refund` | | `create_full_refund(order_id, body)` | `POST /orders/{orderId}/refunds/full` | `Refund` | | `get_refund(order_id, refund_id)` | `GET /orders/{orderId}/refunds/{refundId}` | `Refund` | | `cancel_refund(order_id, refund_id)` | `DELETE /orders/{orderId}/refunds/{refundId}` | `None` | | `list_chargebacks(order_id, params=None)` | `GET /orders/{orderId}/chargebacks` | `Page[Chargeback]` | | `get_chargeback(order_id, chargeback_id)` | `GET /orders/{orderId}/chargebacks/{chargebackId}` | `Chargeback` | ## `refunds` | Method | HTTP endpoint | Returns | | ------------------- | ------------------------- | -------------- | | `list(params=None)` | `GET /refunds` | `Page[Refund]` | | `get(refund_id)` | `GET /refunds/{refundId}` | `Refund` | ## `chargebacks` | Method | HTTP endpoint | Returns | | -------------------- | --------------------------------- | ------------------ | | `list(params=None)` | `GET /chargebacks` | `Page[Chargeback]` | | `get(chargeback_id)` | `GET /chargebacks/{chargebackId}` | `Chargeback` | ## `webhook_events` | Method | HTTP endpoint | Returns | | --------------- | ------------------------------- | -------------- | | `get(event_id)` | `GET /webhook-events/{eventId}` | `WebhookEvent` | ## `webhook_endpoints` | Method | HTTP endpoint | Returns | | ----------------------------------- | ----------------------------------------------- | ----------------------- | | `list(params=None)` | `GET /webhook-endpoints` | `Page[WebhookEndpoint]` | | `create(body)` | `POST /webhook-endpoints` | `WebhookEndpoint` | | `get(webhook_endpoint_id)` | `GET /webhook-endpoints/{webhookEndpointId}` | `WebhookEndpoint` | | `update(webhook_endpoint_id, body)` | `PATCH /webhook-endpoints/{webhookEndpointId}` | `WebhookEndpoint` | | `delete(webhook_endpoint_id)` | `DELETE /webhook-endpoints/{webhookEndpointId}` | `None` | ## `subscriptions` | Method | HTTP endpoint | Returns | | --------------------------------------------------- | ---------------------------------------------------------- | --------------------------------------------- | | `list(params=None)` | `GET /subscriptions` | `Page[Subscription]` | | `get(subscription_id)` | `GET /subscriptions/{subscriptionId}` | `Subscription` | | `update(subscription_id, body)` | `PATCH /subscriptions/{subscriptionId}` | `Subscription` | | `cancel(subscription_id, params=None)` | `DELETE /subscriptions/{subscriptionId}` | `None` | | `create_billing_update_link(subscription_id, body)` | `POST /subscriptions/{subscriptionId}/billing-update-link` | `CreateSubscriptionBillingUpdateLinkResponse` | | `resume(subscription_id)` | `POST /subscriptions/{subscriptionId}/resume` | `Subscription` | ## `test_helpers` | Method | HTTP endpoint | Returns | | --------------------------------------------- | ------------------------------------------------------------------------ | -------------- | | `fast_forward_renewal(subscription_id, body)` | `POST /test-helpers/subscriptions/{subscriptionId}/fast-forward-renewal` | `Subscription` | | `simulate_order_payment(order_id, body)` | `POST /test-helpers/orders/{orderId}/simulate-payment` | `Order` | # Development and release ## Set up the repository Run commands from the repository root. On Linux or in an Amp orb: ```bash .agents/setup ``` Setup installs uv 0.12.9 and Python 3.12, restores locked dependencies and checks imports. It needs no API credentials and makes no Vatly calls. ## Run tests ```bash uv run pytest --cov uv run python scripts/generate.py --check ``` Tests use local HTTP and signed webhook fixtures, not a Vatly account. The second command checks that generated models, resources, clients and the API inventory match the pinned specification. CI runs these checks on Python 3.10–3.14. ## Check formatting and types ```bash uv run ruff check . uv run ruff format --check . uv run mypy ``` ## Build and check the package ```bash uv build uv run twine check dist/* uv run python scripts/check_package.py ``` The last command installs the built wheel in a fresh environment and checks imports and `py.typed`. These commands build and validate; they do not publish. ## Update the API specification Replace `openapi.yaml` deliberately from the [production specification](https://docs.vatly.com/openapi.yaml){rel=""nofollow""}, update its provenance below, then regenerate: ```bash uv run python scripts/generate.py ``` Review the generated diff and rerun the checks above. Do not hand-edit generated models, resources, clients or `docs/API.md`. Output models preserve extra fields and keep URLs and emails as strings. The generator handles two observed API differences: metadata `[]` becomes `{}`, and response product types accept values such as `digital_download`. Request validation still follows the pinned schema. Invalid responses raise `VatlyApiError`; avoid logging response bodies that may contain personal data. ### Pinned source | Source | Revision | | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Production OpenAPI, retrieved 2026-11-21 | [vatly-docs specification](https://github.com/vatly/vatly-docs/blob/d5c09d94a52c4e7d884c2817b4b7834597294cb0/public/openapi.yaml){rel=""nofollow""} | | Original JS design reference | [SDK revision](https://github.com/vatly/vatly-api-js/commit/8b0b920c29f7e7b30bf71b9e379ec0a8a1a22028){rel=""nofollow""} | The checked-in specification is byte-identical to that source and to the bundle published by Vatly's production release. Its SHA-256 is: ```text be578c73c71c234262b6f5f21bd1f01e209fcc64464a1e81d7fd0675eb3c273c ``` The specification's generated-at date is not its retrieval date. ## Documentation sync Edit the flat Markdown guides in `docs/`; keep relative links portable. The API inventory is generated from `scripts/generate.py`, including its description. Pushes to `main` affecting `docs/**` notify `vatly/vatly-docs`. The notifier needs the Actions secret `VATLY_DOCS_DISPATCH_TOKEN` with Contents: write access to that repository. The sync uses an explicit frontmatter description when present, otherwise the page's introductory sentence. ## Prepare a release The published package is [vatly-api-python](https://pypi.org/project/vatly-api-python/){rel=""nofollow""}; the import name is `vatly`. Update the package version, `src/vatly/_version.py` and changelog, then run all checks. Publish the SDK before matching Fluent and Django versions, only after review and approval. | PyPI trusted publisher field | Value | | ---------------------------- | ------------------ | | Owner | `vatly` | | Repository | `vatly-api-python` | | Workflow | `release.yml` | | Environment | Leave blank | Publication starts only from a published GitHub release whose tag matches `v` plus the package version. Mark alphas as pre-releases. Never reuse a published version or move a release tag. Pushing `main` does not publish. Restrict release access: trusted publishing uses GitHub OIDC, with no environment approval gate or PyPI token. PyPI artifacts, including packaged source and docs, are public even if the GitHub repo is private. [Resource guides](https://docs.vatly.com/packages/python/readme) · [API inventory](https://docs.vatly.com/packages/python/api) # Python Fluent Build checkout, customer and subscription flows without tying billing to a web framework. Fluent composes the async SDK and your storage driver. Vatly is the European Merchant of Record for AI, software and digital products. **Alpha — under active development. Every alpha release may include breaking changes. Lock the version you install and review the release notes before upgrading.** ## Install and create a checkout ```bash python -m pip install --pre vatly-fluent-python ``` Python 3.10+ is required. `--pre` installs the latest alpha, including the matching `vatly-api-python` alpha. Set `VATLY_API_KEY` on the server, then run this async function with your event loop. ```python from vatly import AsyncVatlyClient, RequestOptions from vatly_fluent import Vatly, Wiring async def example(): async with AsyncVatlyClient() as api: vatly = Vatly( Wiring( api=api, redirect_url_success="https://app.example.com/billing/success", redirect_url_canceled="https://app.example.com/billing/canceled", ) ) checkout = ( await vatly.checkout_builder() .with_items( [ {"id": "one_off_product_example", "quantity": 1}, ] ) .create(options=RequestOptions(idempotency_key="purchase:42")) ) return checkout.get_url() ``` Replace the product ID and persist the purchase key before making the request. Redirect the buyer to the URL. This minimal example does not store ownership or process webhooks; add [storage](https://docs.vatly.com/packages/fluent-python/coreconcepts) before granting product access. ## Build your integration Functions in these guides accept the configured `vatly` instance from [Configuration](https://docs.vatly.com/packages/fluent-python/configuration). Await them inside your application's async lifespan. IDs and billable entities must be authorized by your application. | Guide | Task | | ------------------------------------------------------------------------------- | ------------------------------------------- | | [Configuration](https://docs.vatly.com/packages/fluent-python/configuration) | Wire the SDK, redirects and storage | | [Core concepts](https://docs.vatly.com/packages/fluent-python/coreconcepts) | Implement drivers and preserve ownership | | [Checkouts](https://docs.vatly.com/packages/fluent-python/checkouts) | Sell a cart or a subscription | | [Customers](https://docs.vatly.com/packages/fluent-python/customers) | Create, bind and look up billing identities | | [Customer portal](https://docs.vatly.com/packages/fluent-python/customerportal) | Send a buyer to hosted account management | | [Subscriptions](https://docs.vatly.com/packages/fluent-python/subscriptions) | Change plans, cancel, resume and reconcile | | [Orders](https://docs.vatly.com/packages/fluent-python/orders) | Read invoices, lines and reversals | | [Webhooks](https://docs.vatly.com/packages/fluent-python/webhooks) | Persist signed events once in a transaction | | [Testing](https://docs.vatly.com/packages/fluent-python/testing) | Run a checkout without network access | | [Porting](https://docs.vatly.com/packages/fluent-python/porting) | Map JS/PHP concepts to Python | | [Development](https://docs.vatly.com/packages/fluent-python/development) | Set up, test and build the package | [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""} documents the underlying requests. These examples are executed with the published packages and local fixtures; no real payments or account changes occur in documentation tests. # Configure Fluent Keep the SDK client open for your application or worker lifespan. Fluent reuses it; the caller remains responsible for closing it. See [installation](https://docs.vatly.com/packages/fluent-python/readme). ## Add your storage driver The `driver` below is your implementation of the [storage contracts](https://docs.vatly.com/packages/fluent-python/coreconcepts). Use one scope per tenant, storefront and test/live mode. Django users can use `vatly-django` instead of implementing this adapter. ```python from vatly import AsyncVatlyClient from vatly_fluent import Vatly, Wiring def example(api: AsyncVatlyClient, driver): return Vatly( Wiring( api=api, redirect_url_success="https://app.example.com/billing/success", redirect_url_canceled="https://app.example.com/billing/canceled", webhook_secret="replace-with-your-endpoint-secret", checkouts=driver.checkouts, bindings=driver.bindings, orders=driver.orders, subscriptions=driver.subscriptions, refunds=driver.refunds, chargebacks=driver.chargebacks, webhook_calls=driver, events=driver, ) ) ``` Load the endpoint secret from your secret manager rather than a source-code literal. The sample value is only a placeholder. | Wiring field | Required for | | ------------------------------------------- | ----------------------------------------------- | | `api`, both redirect URLs | Hosted checkout creation | | `checkouts` | `.for_entity(...)` and resource ownership links | | `bindings` | Customer-to-host identity mapping | | `orders`, `subscriptions` | Local signed snapshots and lifecycle helpers | | `refunds`, `chargebacks` | Optional local reversal records | | `webhook_secret`, `webhook_calls`, `events` | Verified, transactional delivery and outbox | Missing wiring fails when its feature is used. API-only checkout creation does not require repositories. A customer email in a profile does not create a remote customer. ## Retry the same business operation ```python from vatly import RequestOptions from vatly_fluent import Vatly async def example(vatly: Vatly): return ( await vatly.checkout_builder() .with_items( [ {"id": "one_off_product_example", "quantity": 1}, ] ) .create(options=RequestOptions(idempotency_key="purchase:42", timeout=10)) ) ``` Persist that key before calling. Reuse it after a network or local-save failure; do not generate a second purchase key on retry. SDK errors propagate unchanged. Live/test keys share a host; `.in_testmode()` checks the key, not switches it. [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""} # Store ownership safely Your application decides which user, team or organization owns a purchase. Fluent stores that decision as an `EntityRef` on your checkout record. A customer binding is billing identity only; it never grants access to another entity's resources. ## Attach an authorized entity ```python from vatly import RequestOptions from vatly_fluent import EntityRef, Vatly async def example(vatly: Vatly): # The host must authorize team 42 before running this function. return ( await vatly.subscribe() .to_plan("subscription_plan_example") .for_entity(EntityRef("team", "42")) .create(options=RequestOptions(idempotency_key="team-42:purchase-1")) ) ``` Save the checkout record durably. Signed checkout/order/subscription snapshots then follow those links; never infer ownership from email, customerId or metadata. ## Implement the storage contracts | Contract | Methods or responsibility | | -------------------- | --------------------------------------------------------------------------- | | `CheckoutRecords` | `record`, `find`, `link`, `find_for_resource`; reject conflicting ownership | | `CustomerBindings` | `bind`, `record`, lookups both ways; unique on both identities | | `Repository` | `find_by_vatly_id`, `store`, `update` complete wrapper records | | `ReversalRepository` | Repository plus `list_for_order`, `list_for_customer` | | `WebhookCalls` | `process(event, work)` claims signed ID, runs work and commits atomically | | `EventDispatcher` | `dispatch(event)` writes a transactional outbox entry | All methods are async. `Stored[T]` contains `resource` and optional `entity`; `LocalSubscription` also contains `ends_at`. Updates omit unchanged fields; None explicitly clears a field. A repository may decline a new save by returning None. Scope every unique key and lookup by tenant, storefront and mode. Use database constraints and locks, not an in-memory check followed by an insert. Webhook audit, deduplication, links, snapshots and outbox must share one transaction. The repository's `examples/sqlite_driver.py` is a runnable reference, not an installed production driver. It uses one connection and lock per instance. Use an async-native database driver or your framework's thread/transaction adapter for production. For Django, use its supplied ORMDriver. See [webhook processing](https://docs.vatly.com/packages/fluent-python/webhooks). [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""} # Create and find customers Bind a host user to a Vatly billing identity once, then reuse it. Bindings require the configured storage driver; examples accept `vatly` from [Configuration](https://docs.vatly.com/packages/fluent-python/configuration). ## Create a customer for a host user ```python from vatly import RequestOptions from vatly_fluent import CustomerProfile, Vatly async def example(vatly: Vatly): return await vatly.customers.create_for( "user-42", CustomerProfile(email="buyer@example.com", name="Alex"), options=RequestOptions(idempotency_key="signup:user-42"), ) ``` `create_for` rejects an already-bound host. To reuse an existing customer, authorize its ID then call `await vatly.customers.attribute(customer_id, host_id)` instead. Conflicting bindings fail rather than silently moving customers between users. | Profile field | Meaning | | ------------- | ------------------------------------------------------- | | `vatly_id` | Existing authorized customer, used by checkout builders | | `email` | Required when creating a new customer | | `name` | Optional communication name | An email-only checkout profile does not create a customer. Explicitly create it first if you need a durable binding. Bindings do not assign order ownership. ## Look up and refresh identity ```python from vatly_fluent import Vatly async def example(vatly: Vatly): found = await vatly.customers.find_one_by_email("buyer@example.com") handle = vatly.customer("customer_example") identity = await handle.identity() await handle.update({"name": "Alex Morgan"}) await handle.sync() return found, identity, await handle.email() ``` `model()`, `name()`, `email()` and `identity()` share a cached snapshot. `sync()` and `update()` refresh it. Name/email are not invoice address fields; use the [portal](https://docs.vatly.com/packages/fluent-python/customerportal) for hosted billing management. | Lookup | Return | | --------------------------- | ---------------------------------------------------- | | `find_by_host_customer_id` | Customer or None | | `find_by_vatly_customer_id` | Customer, or the SDK's not-found error | | `find_by_email` | Async iterator of matching customers | | `find_one_by_email` | First match or None, not a global identity assertion | `claim_customer_from_checkout` is only for an already host-authorized checkout; it binds billing identity, not entitlements. Never accept arbitrary buyer-supplied IDs. [Customer API reference](https://docs.vatly.com/api-reference/customers){rel=""nofollow""} # Create hosted checkouts Build a cart, then call `create()` to make the API request. The result is a full SDK Checkout with Fluent's `get_url()` convenience. Pass the configured `vatly` from [Configuration](https://docs.vatly.com/packages/fluent-python/configuration) to these functions. ## Sell a one-off or mixed cart ```python from vatly import RequestOptions from vatly_fluent import CustomerProfile, EntityRef, Vatly async def example(vatly: Vatly): checkout = ( await vatly.checkout_builder(CustomerProfile(vatly_id="customer_example")) .with_items( [ {"id": "one_off_product_example", "quantity": 2}, {"id": "subscription_plan_example", "quantity": 1}, ] ) .with_metadata({"purchaseId": "42"}) .for_entity(EntityRef("team", "42")) .create(options=RequestOptions(idempotency_key="purchase:42")) ) return checkout.id, checkout.get_url() ``` The customer and entity must already be authorized. Omit the profile for a guest checkout. `.for_entity()` needs the checkout-record driver. ## Start a subscription with a trial ```python from vatly import RequestOptions from vatly_fluent import Vatly async def example(vatly: Vatly): return ( await vatly.subscribe() .to_plan("subscription_plan_example") .with_quantity(3) .with_trial_days(14) .in_testmode() .create(options=RequestOptions(idempotency_key="trial:42")) ) ``` `subscribe().create()` creates a **checkout**, not an immediate subscription. Use the general builder for mixed carts. Reusing a subscription builder replaces its plan item rather than appending another. | Builder method | Purpose | | --------------------------------------------------------- | ----------------------------------------------------------- | | `with_items` | Append detached cart items | | `to_plan`, `with_quantity` | Select one plan and a positive integer quantity | | `with_trial_days`, `with_trial_ends_at` | Trial length or aware deadline, rounded up to whole days | | `with_redirect_url_success`, `with_redirect_url_canceled` | Override default redirects | | `with_locale`, `with_metadata`, `with_billing_address` | Add checkout details | | `payload` | Inspect a detached wire-format dictionary without a request | | `in_testmode`, `in_live_mode` | Assert the existing key's mode | Store the purchase key before the API call and reuse it after ambiguous failures, including a local-save failure after remote success. The redirect does not prove payment; use [webhooks](https://docs.vatly.com/packages/fluent-python/webhooks). Read lines through `checkout.order_id`'s Order. [Checkout API reference](https://docs.vatly.com/api-reference/checkouts){rel=""nofollow""} # Manage subscriptions Load a locally owned subscription, authorize its entity, then use a handle for plan changes or cancellation. Examples accept the configured `vatly` from [Configuration](https://docs.vatly.com/packages/fluent-python/configuration); its repositories must be wired. ## Load a handle and change a plan ```python from vatly import RequestOptions from vatly_fluent import EntityRef, FluentError, Vatly async def example(vatly: Vatly): record = await vatly.wiring.subscriptions.find_by_vatly_id("subscription_example") if record is None or record.entity != EntityRef("team", "42"): raise FluentError("Subscription is not owned by this team") handle = vatly.subscription(record) await handle.swap( "subscription_plan_pro", options=RequestOptions( idempotency_key="team-42:plan-change-1", ), ) return handle.model().resource ``` The host must authorize team 42 separately. A handle's `model()` is local; methods such as `sync()` make API calls. Scheduled changes do not prematurely replace the active plan. | Method | Behavior | | --------------------------- | ------------------------------------------------------------------ | | `swap` | Schedule a plan change by default | | `swap_and_invoice` | Apply and invoice immediately | | `swap_without_charge` | Apply now, disable proration charge | | `cancel(immediately=False)` | Request cancellation; wait for signed events to update local state | | `resume` | Resume through the API and save its returned snapshot | | `sync` | Refresh full resource and local expiry | | `update_billing` | Return hosted billing URL; requires both redirect URLs | ## Request cancellation ```python from vatly import RequestOptions from vatly_fluent import LocalSubscription, Vatly async def example(vatly: Vatly, local: LocalSubscription): # local has already been authorized by the caller. await vatly.subscription(local).cancel( immediately=False, options=RequestOptions(idempotency_key="cancel:42") ) ``` Only offer resume while Vatly permits it. `scheduled_update()`, `has_scheduled_update()` and `cancellation_reason()` read remotely. ## Use expiry without mistaking it for entitlement ```python from vatly_fluent import LocalSubscription, Vatly async def example(vatly: Vatly, local: LocalSubscription): handle = vatly.subscription(local) await handle.sync() return handle.model().resource.status, handle.state() ``` `state()` uses `ends_at` only. Check the resource status and your product's access rules too. `canceled_at` is the request time, not grace expiry. The shared mapper uses actual `ended_at`, otherwise usable future renewal/paid/trial information or a trusted prior end. Missing or conflicting trial/cycle deadlines raise `FluentError`, preserving committed state. Monitor and reconcile failures; stale state is not proof of continuing access. An active snapshot clears stale expiry. ## Recover an owned checkout ```python from vatly_fluent import Vatly async def example(vatly: Vatly): result = await vatly.reconcile_checkout("checkout_example", attempts=2) return result.subscriptions, result.pending_subscription_ids, result.legacy_plan_ids ``` Authorize the checkout and wrap local writes in your driver's transaction. Reads follow checkout → order → distinct subscription IDs from each line's `relatedResources.subscriptionId` and from `subscription` renewal lines; repeated 404s remain pending. A signup line whose `subscriptionId` is still null is reported in `unresolved_line_ids`: core has not resolved that subscription yet, so reconcile again later; it may never resolve. Plan lines on historical orders without `relatedResources` are reported as `legacy_plan_ids`. A plan/customer match is never an ownership fallback. Trial flows can lack `order.paid`, so reconciliation must be explicit. Unknown linkage must not grant access. [Subscription API reference](https://docs.vatly.com/api-reference/subscriptions){rel=""nofollow""} # Read orders and reversals Use an order handle to read purchased lines, an invoice link and exact reversal amounts. Authorize the order in your application first. Examples accept the configured `vatly` from [Configuration](https://docs.vatly.com/packages/fluent-python/configuration). ```python from vatly_fluent import Vatly async def example(vatly: Vatly): order = vatly.order("order_example") return { "invoice_url": await order.invoice_url(), "lines": await order.lines(), "refundable": await order.refundable_subtotal(), "partially_reversed": await order.is_partially_reversed(), "refunds": await order.refunds(), } ``` | Method | Return | | ----------------------------------------------------------- | ----------------------------------------------------------- | | `model`, `sync` | Cached SDK Order; refresh the handle | | `invoice_url` | Customer invoice URL or None | | `lines` | OrderLine models | | `reversed_subtotal`, `refundable_subtotal` | `Decimal` in currency units | | `is_reversed`, `is_fully_reversed`, `is_partially_reversed` | Predicates derived from both totals | | `refunds`, `chargebacks` | Local stored records, or an empty list without repositories | `model()` and the derived fields share one lazy read; `sync()` refreshes it. Do not convert financial values to floats. Preserve each amount's currency from the SDK resource when combining totals. ## Request a full refund ```python from vatly import RequestOptions from vatly_fluent import Vatly async def example(vatly: Vatly): return await vatly.api.orders.create_full_refund( "order_example", {}, options=RequestOptions(idempotency_key="refund:42"), ) ``` Fluent exposes the raw SDK as `vatly.api` for operations without a convenience handle. A timeout is ambiguous; reuse the same refund key instead of issuing a second refund. Signed reversal events update optional local repositories. [Order API reference](https://docs.vatly.com/api-reference/orders){rel=""nofollow""} · [Refund reference](https://docs.vatly.com/api-reference/refunds){rel=""nofollow""} # Open the customer portal Send an authenticated buyer to Vatly's hosted portal to manage subscriptions, invoices and billing details. Create a new session for each visit. ```python from vatly_fluent import FluentError, Vatly async def example(vatly: Vatly): # The host authorizes user-42 before this lookup. customer = await vatly.customers.find_by_host_customer_id("user-42") if customer is None: raise FluentError("No billing customer is bound to this user") session = await vatly.customer(customer.id).portal_session( { "returnUrl": "https://app.example.com/account/billing", } ) return session.url ``` Pass the configured `vatly` from [Configuration](https://docs.vatly.com/packages/fluent-python/configuration). The key selects the storefront and mode; the portal does not show a storefront picker. | Field | Meaning | | --------------------- | ---------------------------------------------------- | | Input `returnUrl` | Optional HTTPS return link; `{}` omits it | | Response `url` | Short-lived, single-use credential-bearing entry URL | | Response `expires_at` | Expiry of that entry link | Redirect the browser to `session.url`. Do not log, cache, email as a permanent link, or expose a portal session for an unverified customer ID. SDK errors propagate. For one subscription's invoice-address change, use its `update_billing()` helper in [Subscriptions](https://docs.vatly.com/packages/fluent-python/subscriptions). [Portal API reference](https://docs.vatly.com/api-reference/customers){rel=""nofollow""} # Process signed webhooks Fluent verifies a delivery, updates local snapshots and dispatches events through your storage driver. Your framework route supplies the raw bytes and signature. Use the `vatly` instance wired in [Configuration](https://docs.vatly.com/packages/fluent-python/configuration). ```python from vatly_fluent import Vatly async def example(vatly: Vatly, raw_body: bytes, signature: str): processed = await vatly.webhook_processor().handle(raw_body, signature) return "processed" if processed else "duplicate" ``` Respond 2xx after commit, including for a committed duplicate. Invalid signatures raise `VatlyInvalidSignatureError`; return 400. Let processing/storage failures return 5xx so Vatly retries. Do not parse and re-encode the body before verification. ## Make delivery atomic | Driver responsibility | Required behavior | | ------------------------------------ | --------------------------------------------------------------- | | `webhook_calls.process(event, work)` | Claim signed `event.id`; run `work`; commit all writes together | | Repositories and checkout links | Participate in that same transaction | | `events.dispatch(event)` | Write an outbox entry, not a network side effect | | Failure or concurrent duplicate | Roll back on failure; enforce DB uniqueness/locking | The signature's default clock tolerance is 300 seconds; secret sequences support rotation. Deduplicate the **signed** ID, not an unsigned event-ID header. Scope all claims by tenant/storefront/mode. Unknown signed events remain retained/dispatched. ## Know what the built-in reactions do | Event | Local effect | | ------------------------------------------------ | ------------------------------------------------------------------ | | `subscription.started` | Upsert; first save emits `local.subscription_created` | | Subscription update/billing/resume/cancel events | Update an existing snapshot and lifecycle expiry | | `order.paid`, `order.payment_failed` | Upsert order snapshot; first paid save emits `local.order_created` | | `order.canceled` | Update an existing order | | Refund/chargeback events | Upsert optional reversal repositories | | `checkout.paid` | Link through a host-owned checkout record | | Other/unknown events | Dispatch without an invented resource write | Reactions make no implicit API reads. Customer bindings never determine ownership. Created events can precede eventual ownership linkage; outbox consumers must read current persisted ownership before acting. Dispatch external effects after commit with idempotent consumer keys. Deduplication is not event ordering: reconcile stale or conflicting snapshots explicitly. See [subscription recovery](https://docs.vatly.com/packages/fluent-python/subscriptions). [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""} · [Endpoint API reference](https://docs.vatly.com/api-reference/webhook-endpoints){rel=""nofollow""} # Test without real payments Use httpx's MockTransport with the real published SDK and Fluent. The following example needs no API key or network connection and validates the outgoing cart. ```python import json import httpx from vatly import AsyncVatlyClient from vatly_fluent import Vatly, Wiring async def example(): def respond(request): assert request.method == "POST" assert request.url.path == "/v1/checkouts" assert json.loads(request.content)["products"] == [ {"id": "one_off_product_example", "quantity": 2} ] return httpx.Response( 200, json={ "id": "checkout_example", "resource": "checkout", "testmode": True, "status": "created", "customerId": None, "orderId": None, "redirectUrlSuccess": "https://app.example.com/ok", "redirectUrlCanceled": "https://app.example.com/no", "billingAddress": None, "metadata": {}, "locale": None, "createdAt": "2026-01-01T00:00:00Z", "expiresAt": None, "links": { "self": { "href": "https://api.vatly.com/v1/checkouts/checkout_example", "type": "application/json", }, "checkoutUrl": { "href": "https://checkout.example.com/example", "type": "text/html", }, }, }, ) async with AsyncVatlyClient("test_" + "x" * 20, transport=httpx.MockTransport(respond)) as api: vatly = Vatly(Wiring(api, "https://app.example.com/ok", "https://app.example.com/no")) checkout = ( await vatly.checkout_builder() .with_items( [ {"id": "one_off_product_example", "quantity": 2}, ] ) .create() ) assert checkout.get_url() == "https://checkout.example.com/example" return checkout.id ``` For storage tests, exercise duplicate signed deliveries, rollback after a reaction fails, conflicting checkout ownership and tenant/mode isolation. The source repository's SQLite example demonstrates those contracts; production concurrency needs your database's own integration tests. | Test mode helper | Remote effect | | -------------------------------------------------------- | ----------------------------------- | | `advance_renewal` | Fast-forward a subscription renewal | | `force_renewal_paid`, `force_renewal_failed` | Simulate renewal outcome | | `force_order_payment_paid`, `force_order_payment_failed` | Simulate payment outcome | These helpers live under `vatly.test_helpers()` and **mutate** the test account. They are not mocks. Use only with an intentional test key; never call them in ordinary unit tests or setup. The offline example above creates no Vatly data. [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""} # Move from JS or PHP Python Fluent keeps the same billing concepts, with snake\_case methods and async I/O. Compose an existing `AsyncVatlyClient`; no framework container is installed. | Concept | Python | | --------------------- | -------------------------------------------------------------------- | | Checkout builder | `vatly.checkout_builder().with_items(...).create()` | | Subscription checkout | `vatly.subscribe().to_plan(...).create()` | | Billable/entity | Host-authorized `EntityRef(kind, id)` | | Customer handle | `vatly.customer(id)`; await cache/network accessors | | Subscription handle | `vatly.subscription(LocalSubscription(...))` | | Resource fields | Pydantic snake\_case attributes; wire-key dictionaries for overrides | | Storage | Async Protocol implementations supplied by the host | ## Inspect a checkout before sending it ```python from vatly_fluent import Vatly def example(vatly: Vatly): builder = vatly.subscribe().to_plan("subscription_plan_example").with_quantity(2) return builder.payload() ``` `payload()` is a detached dictionary and makes no network request. Use the same builder with `await builder.create()` to send it. PHP/JS method names are not aliases in Python. Cancellation returns no resource; resume refreshes a handle. See [Core concepts](https://docs.vatly.com/packages/fluent-python/coreconcepts) before porting a storage driver and [Subscriptions](https://docs.vatly.com/packages/fluent-python/subscriptions) for the initial-linkage/expiry limitations. [PORTING.md](https://github.com/vatly/vatly-fluent-python/blob/main/PORTING.md){rel=""nofollow""} records upstream source revisions and deliberate API differences. [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""} defines wire fields. # Development and release ## Set up the repository Run commands from the repository root. On Linux or in an Amp orb: ```bash .agents/setup ``` Setup installs uv 0.12.9 and Python 3.12, restores locked dependencies and checks imports. It needs no API credentials and makes no Vatly calls. ## Run tests ```bash uv run pytest --cov ``` Tests use the real SDK with local HTTP and signed webhook fixtures. The SQLite driver tests cover storage, ownership, duplicate delivery, rollback and the outbox. No test changes a Vatly account. See [offline examples](https://docs.vatly.com/packages/fluent-python/testing) for host tests. ## Check formatting and types ```bash uv run ruff check . uv run ruff format --check . uv run mypy ``` CI runs tests and these checks on Python 3.10–3.14. Type checks also include the example storage driver. ## Build and check the package ```bash uv build uv run twine check dist/* uv run python scripts/check_package.py ``` The last command installs the built wheel in a fresh environment and checks imports and `py.typed`. These commands do not publish anything. ## Pinned SDK dependency Fluent pins one exact `vatly-api-python` version from PyPI in `pyproject.toml`; `uv.lock` records its hashes. To move to a new SDK version, change the pin, run `uv lock`, and run the full checks. Use a new Fluent alpha version when dependency behavior changes. ## Documentation sync Keep guides directly under `docs/` and link each page from [the overview](https://docs.vatly.com/packages/fluent-python/readme). Pushes to `main` affecting `docs/**` notify `vatly/vatly-docs`. The notifier needs `VATLY_DOCS_DISPATCH_TOKEN` with Contents: write access to that repository. The sync uses an explicit frontmatter description when present, otherwise the page's introductory sentence. ## Prepare a release The published package is [vatly-fluent-python](https://pypi.org/project/vatly-fluent-python/){rel=""nofollow""}; the import name is `vatly_fluent`. Publish the matching SDK version first, then Fluent, then Django, only after review and approval. | PyPI trusted publisher field | Value | | ---------------------------- | --------------------- | | Owner | `vatly` | | Repository | `vatly-fluent-python` | | Workflow | `release.yml` | | Environment | Leave blank | The workflow publishes only from a published GitHub release whose tag matches `v` plus the package version. Mark alphas as pre-releases. Pushing `main` does not publish. Restrict release access: trusted publishing needs no environment approval or PyPI token, and PyPI artifacts are public. [Storage contracts](https://docs.vatly.com/packages/fluent-python/coreconcepts) · [Porting notes](https://docs.vatly.com/packages/fluent-python/porting) # Django Add hosted checkout, customer billing and signed webhook persistence to Django. Vatly is the European Merchant of Record for AI, software and digital products. This package builds on Fluent Python and the Python SDK. **Alpha — under active development. Every alpha release may include breaking changes. Lock the version you install and review the release notes before upgrading.** ## Start here ```bash python -m pip install --pre vatly-django ``` Follow [Installation](https://docs.vatly.com/packages/django/installation) to add the app, URLs and database tables, then configure a server-owned product offer and add a checkout form. You do not need a custom user model: the `Billing` facade accepts any saved Django model. | Guide | Task | | ------------------------------------------------------------------------ | --------------------------------------------------------- | | [Installation](https://docs.vatly.com/packages/django/installation) | Install, connect URLs and run migrations | | [Configuration](https://docs.vatly.com/packages/django/configuration) | Set credentials, offers and tenant scope | | [Billable models](https://docs.vatly.com/packages/django/billablemodels) | Add billing helpers to your user or team model | | [Checkout](https://docs.vatly.com/packages/django/checkout) | Start a purchase with a durable retry key | | [Customer portal](https://docs.vatly.com/packages/django/customerportal) | Open hosted billing for an authorized customer | | [Subscriptions](https://docs.vatly.com/packages/django/billing) | Inspect, cancel, resume and reconcile owned subscriptions | | [Webhooks](https://docs.vatly.com/packages/django/webhooks) | Verify, deduplicate and persist deliveries atomically | | [Admin](https://docs.vatly.com/packages/django/admin) | Inspect billing records without editing them | | [Testing](https://docs.vatly.com/packages/django/testing) | Exercise checkout and signed webhooks offline | | [Development](https://docs.vatly.com/packages/django/development) | Run contributor checks and understand release tooling | Python 3.10+; Django 5.2 LTS, 6.0 and 6.1 within their supported Python ranges. Code samples are executed with the published packages and local fixtures. See the [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""} for Vatly's fields. # Install Vatly Django Start with a normal Django project, including its auth, sessions, messages and CSRF configuration. Install the latest alpha: ```bash python -m pip install --pre vatly-django ``` The package is in alpha, so `--pre` is needed. It also installs the matching `vatly-api-python` and `vatly-fluent-python` alphas. Add the billing app to your existing `settings.py` app list: ```python INSTALLED_APPS += ["vatly_django"] ``` Keep Django's generated authentication/session/CSRF middleware. If you use admin, keep its standard template context processors and messages middleware too. ## Mount the billing URLs Add this entry to your project URL configuration (preserve your other routes): ```python from django.urls import include, path urlpatterns = [path("billing/", include("vatly_django.urls"))] ``` | Route under `/billing/` | Method | Protection | | ----------------------- | ------ | ------------------------------------------- | | `checkout//` | POST | Login, CSRF and server-owned offer | | `portal/` | POST | Login, CSRF and authorized customer binding | | `webhook/` | POST | Raw-body Vatly signature; CSRF-exempt | Configure the required [settings](https://docs.vatly.com/packages/django/configuration), then create the tables: ```bash python manage.py migrate python manage.py check ``` No migration or setup command creates remote customers, products or webhook endpoints. Use HTTPS and your deployment's normal host/CSRF settings in production. PostgreSQL is recommended for concurrent workers; SQLite is suitable for local use. [Add a checkout](https://docs.vatly.com/packages/django/checkout) · [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""} # Configure billing Keep keys on the server. `test_` and `live_` select mode on the same API host. Add these values to your project's settings after [installation](https://docs.vatly.com/packages/django/installation). ```python import os VATLY_API_KEY = os.environ["VATLY_API_KEY"] VATLY_WEBHOOK_SECRET = os.environ["VATLY_WEBHOOK_SECRET"] VATLY_SCOPE = "my-tenant/my-storefront" VATLY_REDIRECT_URL_SUCCESS = "https://app.example.com/billing/success" VATLY_REDIRECT_URL_CANCELED = "https://app.example.com/billing/canceled" VATLY_PORTAL_REDIRECT_URL = "https://app.example.com/account/billing" VATLY_CHECKOUTS = { "book": {"products": [{"id": "one_off_product_example", "quantity": 1}]}, "pro": {"products": [{"id": "subscription_plan_example", "quantity": 1}]}, } ``` Replace catalog IDs with your own. Offers are an allowlist, not buyer-provided payloads. Products, quantity and redirect destinations stay under server control. | Setting | Required? | Meaning | | ----------------------------------------------------------- | ------------ | ---------------------------------------------------------------- | | `VATLY_API_KEY` | Yes | May fall back to the environment | | `VATLY_SCOPE` | Yes | Stable tenant/storefront identity, up to 200 characters | | `VATLY_WEBHOOK_SECRET` | For webhooks | Secret string or rotation sequence | | `VATLY_REDIRECT_URL_SUCCESS`, `VATLY_REDIRECT_URL_CANCELED` | For checkout | HTTPS return destinations | | `VATLY_PORTAL_REDIRECT_URL` | No | Optional return link in the portal | | `VATLY_CHECKOUTS` | For checkout | Offer slug → products; optional locale, metadata, billingAddress | | `VATLY_BILLABLE_RESOLVER` | No | Dotted callable taking request; defaults to request.user | | `VATLY_SCOPE_RESOLVER` | No | Dotted callable taking request; chooses a trusted scope | ## Bill an organization instead of the user A billable resolver must verify membership before returning a saved team/model. For the default user case, the equivalent resolver is: ```python from django.core.exceptions import PermissionDenied def example(request): if not request.user.is_authenticated: raise PermissionDenied("Login required") return request.user ``` Put your resolver in an importable module and set its dotted path in settings. Never trust a query-string tenant/customer ID as authorization. The facade uses one API key/secret configuration per deployment; scope resolvers alone do not switch credentials. For a multi-credential registry, compose ORMDriver and Fluent explicitly. Webhook routing must also select trusted credentials and scope. [Billable models](https://docs.vatly.com/packages/django/billablemodels) · [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""} # Choose a billable model A billable is the saved user, team or company your application has authorized to buy. Existing models can use `Billing()` without changing their inheritance. ```python from vatly_django.billing import Billing def example(billable): billing = Billing() return billing.resources(billable, "subscription") ``` Pass a saved, already-authorized model instance. Queries include its entity, scope and mode; no customer-ID ownership fallback is used. ## Add billing methods to your model Add helpers such as `checkout()`, `subscribed()` and `billing_portal()` to your user or team model without adding database columns. For a model in your `teams` app, inherit the abstract mixin: ```python from django.db import models from vatly_django.mixins import BillableMixin class Team(BillableMixin): name = models.CharField(max_length=200) class Meta: app_label = "teams" ``` Keep your model's normal fields and permissions. Run `makemigrations teams` and `migrate` as usual; the mixin itself adds no columns. Do not replace an existing auth user model just to integrate billing. | Mixin method | Purpose | | -------------------------------------------- | ----------------------------------------------------- | | `checkout(offer, idempotency_key=...)` | Create a hosted purchase | | `billing_portal()` | Open the bound customer's portal | | `subscriptions()`, `subscribed()` | Read owned subscriptions and convenience access state | | `cancel_subscription(id, immediately=False)` | Request cancellation | | `resume_subscription(id)` | Resume and refresh the snapshot | | `swap_subscription(id, plan_id)` | Request a plan change | | `billing(scope=...)` | Access the underlying facade | Entity identity is the Django model label plus primary key. Renaming models or changing keys needs a migration of your billing references. Deleting a user does not cascade through these generic billing references; apply your retention policy. [Checkout](https://docs.vatly.com/packages/django/checkout) · [Subscription access rules](https://docs.vatly.com/packages/django/billing) · [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""} # Start a checkout Configure a `book` offer in [settings](https://docs.vatly.com/packages/django/configuration), then POST to the built-in checkout route as an authenticated user. The view accepts an idempotency key, not buyer-controlled products or prices. ## Prepare one key per purchase ```python from uuid import uuid4 def example(): return {"purchase_key": str(uuid4())} ``` Persist the key with the host's purchase intent and pass it to your template. Re-render/retry with the same key after an ambiguous failure; do not generate a new UUID just because the API timed out. A genuinely new purchase needs a new key. ```html
{% csrf_token %}
``` ## Call from your own POST view Pass a saved, authorized billable and the key you persisted: ```python from vatly_django.billing import Billing def example(billable, purchase_key): return Billing().checkout(billable, "book", idempotency_key=purchase_key) ``` Redirect to the returned hosted URL. A durable CheckoutAttempt records the entity, payload fingerprint and key before network I/O. Reusing the key for a different entity or changed offer fails. Idempotency retention is finite; investigate stale attempts rather than blindly retrying forever. | Built-in view result | Meaning | | -------------------- | -------------------------------------------------------------------- | | 302 | Redirect to hosted checkout, or login for an unauthenticated request | | 400 | Invalid key or offer | | 403 | CSRF rejection | | 405 | Non-POST request | | 502 | SDK failure; retry/reconcile using the same purchase key | A return-page visit is not proof of payment. [Signed webhooks](https://docs.vatly.com/packages/django/webhooks) update local records; [reconciliation](https://docs.vatly.com/packages/django/billing) handles missing snapshots. Customer identity alone never assigns a purchase to a billable. [Checkout API reference](https://docs.vatly.com/api-reference/checkouts){rel=""nofollow""} # Manage owned subscriptions Use the facade with a saved, authorized billable. It checks local ownership before subscription mutations. A raw Vatly customer ID is never enough to authorize one. ## Read current local subscriptions ```python from vatly_django.billing import Billing def example(billable): return list( Billing().resources(billable, "subscription").values("vatly_id", "snapshot", "ends_at") ) ``` | Stored field | Meaning | | ----------------------------------- | ----------------------------------------------------- | | `vatly_id` | Subscription identifier | | `snapshot` | Full Vatly resource using wire keys, including status | | `ends_at` | Derived expiry, not cancellation request time | | `entity_kind`, `entity_id`, `scope` | Host ownership and tenant/storefront/mode | `BillableMixin.subscribed()` requires active/trial/on\_grace\_period status and no expired local end. It is a convenience policy, not your complete entitlement rule. Failed or stale synchronization must not be treated as proof of access. ## Cancel or resume from a user action These functions belong in authenticated, CSRF-protected POST handlers: ```python from vatly_django.billing import Billing def example(billable): Billing().subscription_action(billable, "subscription_example", "cancel", immediately=False) ``` ```python from vatly_django.billing import Billing def example(billable): Billing().subscription_action(billable, "subscription_example", "resume") ``` | Action | Behavior | | ------------------------------------------------- | ------------------------------------------------------ | | `cancel` | Request cancellation; signed events update local state | | `resume` | Resume during grace and persist the API response | | `sync` | Refresh a subscription snapshot | | `swap`, `swap_and_invoice`, `swap_without_charge` | Plan-change policies; pass `plan_id` | The facade's action helper returns None. Use Fluent/SDK RequestOptions directly when your mutation workflow needs an explicit stable idempotency key. ## Reconcile a known checkout ```python from vatly_django.billing import Billing def example(billable): result = Billing().reconcile(billable, "checkout_example") # Schedule a bounded later reconcile while either tuple is not empty. return result.unresolved_line_ids, result.pending_subscription_ids ``` The facade checks the checkout's host record, performs bounded API reads and persists snapshots/links transactionally. This may hold the scope lock during reads; run it in a worker for busy deployments. It emits no created outbox event. Signup lines reference their plan and name their subscription in `relatedResources.subscriptionId`; renewal lines reference the subscription as their product. Both link the subscription to the checkout's billable. | Result field | Meaning | What to do | | -------------------------- | ---------------------------------------------------------- | ------------------------------------------- | | `subscriptions` | Linked and stored subscriptions | Nothing | | `pending_subscription_ids` | Referenced, but not readable yet | Reconcile again later | | `unresolved_line_ids` | Signup lines whose `subscriptionId` is still null | Reconcile again later; it may never resolve | | `legacy_plan_ids` | Plan lines on historical orders without `relatedResources` | Resolve manually | A signed `order.paid` snapshot is frozen when it is sent and can carry a null `subscriptionId`, so the first order may still need an explicit reconcile. Schedule a bounded number of later reconciles while `unresolved_line_ids` is not empty. Never guess by customer/plan/quantity. Missing subscription IDs remain pending, not entitled. Trial flows may lack an order.paid event. Grace expiry uses Fluent's shared mapper. `canceledAt` is the request time. Missing or ambiguous period deadlines raise and retain the prior committed state; monitor and reconcile instead of inventing an expiry. Active snapshots clear stale ends after resume. [Fluent's guide](https://docs.vatly.com/packages/fluent-python/subscriptions){rel=""nofollow""} describes this policy and its limits. [Subscription API reference](https://docs.vatly.com/api-reference/subscriptions){rel=""nofollow""} # Open the customer portal The portal lets buyers manage billing, invoices and subscriptions in Vatly. Bind a known customer from trusted provisioning code before opening it. ```python from vatly_django.billing import Billing def example(billable): billing = Billing() # Verify customer_example belongs to this billable before binding. billing.bind_customer(billable, "customer_example") return billing.portal(billable) ``` The sample accepts a saved billable your application has authorized. There is no automatic remote customer creation or email lookup. Bindings are unique in both directions and do not grant order/subscription ownership. ## Add a portal button For a bound, logged-in billable, use the built-in CSRF-protected POST route: ```html
{% csrf_token %}
``` | Setting/result | Meaning | | --------------------------- | ------------------------------------------- | | `VATLY_PORTAL_REDIRECT_URL` | Optional `returnUrl` link inside the portal | | 302 | Redirect to a fresh single-use session | | 400 | No authorized customer binding | | 502 | Upstream SDK failure | Never log/cache the credential-bearing URL or accept a browser-supplied customer ID. Each visit creates a short-lived session for the API key's storefront and mode. [Customer API reference](https://docs.vatly.com/api-reference/customers){rel=""nofollow""} # Receive signed webhooks Mount the [billing URLs](https://docs.vatly.com/packages/django/installation) and register the public HTTPS `/billing/webhook/` URL in Vatly. Set `VATLY_WEBHOOK_SECRET` to that endpoint's secret. Installing the package does not register it automatically. ## Use the built-in receiver The built-in route verifies raw request bytes, checks the key's mode and stores the signed event ID. No custom view is required. If you need a separate adapter, the facade exposes the same processor: ```python from vatly_django.billing import Billing def example(raw_body: bytes, signature: str): return Billing().webhook(raw_body, signature) ``` Pass the unmodified request body and `Vatly-Signature` header. Do not reconstruct JSON or trust an unsigned Vatly-Event-Id header for deduplication. | Response | Meaning | | --------------- | ------------------------------------------------------------------ | | 200 `processed` | Signature accepted and transaction committed | | 200 `duplicate` | Same signed ID was already committed | | 400 | Invalid signature, JSON or envelope | | 405 | Non-POST request | | 500 | Processing failure; all writes roll back for a safe delivery retry | Signature freshness defaults to ±300 seconds. Keep server clocks synchronized; configure a sequence of secrets for rotation. Only this webhook route is CSRF-exempt. ## Know what is stored | Model | Purpose | | -------------------------- | --------------------------------------------------------------------------- | | `BillingScope` | Tenant/storefront and mode; serializes callbacks with a database write lock | | `WebhookCall` | Signed envelope and processed timestamp, unique per scope/event | | `Checkout`, `ResourceLink` | Immutable host-owned checkout/resource links | | `BillingResource` | Complete financial or subscription snapshot and optional owner | | `Outbox` | Durable events for your background worker | Audit, dedup, links, snapshots and outbox commit in one transaction. The ORM driver uses thread-sensitive async adapters so all nested work stays on that connection. It assumes Django's default database; custom routers need a purpose-built driver. PostgreSQL supports concurrent workers; SQLite delivery lock failures can be retried. Built-ins make no implicit API reads. Unknown events remain audited/dispatched. Customer bindings never fill missing ownership, and deduplication is not event ordering. Reconcile delayed/conflicting snapshots explicitly. ## Deliver your outbox ```python from vatly_django.models import Outbox def example(): return list( Outbox.objects.filter(delivered_at__isnull=True) .order_by("pk") .values("pk", "event_name", "payload")[:100] ) ``` This is an inspection query, not a safe concurrent worker. Your worker must claim rows with database locks, send using an idempotent key (scope + row primary key), and mark delivered\_at after success. External delivery is at least once. Created events can precede ownership linkage: read current ownership before side effects. No email sender or entitlement side effect is enabled by default. [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""} · [Admin](https://docs.vatly.com/packages/django/admin) # Inspect billing in admin When `django.contrib.admin` and `vatly_django` are installed, billing models register automatically. No separate `admin.py` setup is needed. Mount Django's standard admin: ```python from django.contrib import admin from django.urls import path urlpatterns = [path("admin/", admin.site.urls)] ``` Keep your other project URL patterns. Grant model **view** permissions to the staff who need them; do not give every support user superuser access. | Records | Useful for | | ------------------------ | ------------------------------------------------------------- | | Billing resources | Find Vatly IDs, entities, full snapshots and lifecycle expiry | | Webhook calls | Inspect signed event IDs and processing completion | | Outbox | Inspect queued and delivered events | | Checkouts/attempts/links | Diagnose ownership or idempotency failures | | Customer bindings/scopes | Inspect identity and tenant/mode separation | All billing admin registrations disable add/change/delete, even for superusers. Use hosted billing or authorized API actions to mutate subscriptions; editing a local snapshot would not change Vatly. Signed envelopes can contain personal data, so restrict access and apply your retention policy. [Webhook storage](https://docs.vatly.com/packages/django/webhooks) · [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""} # Test billing offline Use Django's test database and httpx fixtures. Do not use a real Vatly key in unit tests. The snippets below are helpers for your pytest-django tests. Call them from a test marked `@pytest.mark.django_db(transaction=True)` with your project configured. ## Read a customer with MockTransport ```python import httpx from asgiref.sync import async_to_sync from vatly import AsyncVatlyClient from vatly_fluent import Vatly, Wiring def example(): def respond(request): assert request.url.path == "/v1/customers/customer_example" return httpx.Response( 200, json={ "id": "customer_example", "resource": "customer", "testmode": True, "email": "buyer@example.com", "name": "Alex", "metadata": {}, "createdAt": "2026-01-01T00:00:00Z", "links": { "self": { "href": "https://api.vatly.com/v1/customers/customer_example", "type": "application/json", } }, }, ) async def read_customer(): async with AsyncVatlyClient( "test_" + "x" * 20, transport=httpx.MockTransport(respond) ) as api: vatly = Vatly(Wiring(api, "https://app.example.com/ok", "https://app.example.com/no")) return await vatly.customer("customer_example").email() assert async_to_sync(read_customer)() == "buyer@example.com" ``` This tests the async stack from synchronous Django code. To test your own checkout view, inject a MockTransport-backed AsyncVatlyClient into your billing test and assert its request products, idempotency key, redirect and local Checkout record. ## Send the same signed event twice ```python import hashlib import hmac import json import time from django.test import Client from django.test.utils import override_settings def example(): stamp = int(time.time()) secret = "offline-test-secret" raw = json.dumps( { "id": "event_docs", "resource": "webhook_event", "eventName": "future.event", "reason": None, "entityType": "future", "entityId": "future_1", "object": {"id": "future_1"}, "createdAt": "2026-01-01T00:00:00Z", "testmode": True, } ).encode() digest = hmac.new(secret.encode(), str(stamp).encode() + b"." + raw, hashlib.sha256).hexdigest() signature = f"t={stamp},v1={digest}" client = Client() with override_settings(VATLY_WEBHOOK_SECRET=secret): first = client.post( "/billing/webhook/", raw, content_type="application/json", HTTP_VATLY_SIGNATURE=signature, ) second = client.post( "/billing/webhook/", raw, content_type="application/json", HTTP_VATLY_SIGNATURE=signature, ) assert first.content == b"processed" assert second.content == b"duplicate" ``` Run with migrations applied in the test database and the billing URL prefix from [Installation](https://docs.vatly.com/packages/django/installation). Use a test API key and scope in test settings; this signed unknown event requires no remote API reads. Add tests for bad signatures, rollback, CSRF, unauthorized billables and concurrent duplicates on PostgreSQL. [Contributor checks](https://docs.vatly.com/packages/django/development) · [API reference](https://docs.vatly.com/api-reference){rel=""nofollow""} # Development and release ## Set up the repository Run commands from the repository root. On Linux or in an Amp orb: ```bash .agents/setup ``` Setup installs uv 0.12.9 and Python 3.12, restores locked dependencies and runs Django's system checks. It needs no API credentials and makes no Vatly calls. It does not migrate your application's database or create test data. ## Run tests ```bash uv run pytest --cov uv run python -m django makemigrations \ --check --dry-run --settings=tests.settings ``` Tests apply real migrations to a temporary database and use local HTTP and signed webhook fixtures. They check ownership, CSRF, duplicate delivery, rollback and subscription state without changing a Vatly account. SQLite is the default. The PostgreSQL-only concurrency test skips locally unless PostgreSQL is configured; CI runs it against PostgreSQL 17. ## Check formatting and types ```bash uv run ruff check . uv run ruff format --check . uv run mypy ``` ## Build and check the package ```bash uv build uv run twine check dist/* uv run python scripts/check_package.py ``` The last command installs the built wheel in a fresh environment, migrates an empty database and checks imports and the `py.typed` marker. None of these commands publishes a package. ## Supported versions | Component | Versions checked in CI | | ---------- | ------------------------------------------------------ | | Python | 3.10–3.14 | | Django | 5.2 LTS, 6.0 and 6.1 in compatible Python combinations | | PostgreSQL | 17, including concurrent webhook delivery | ## Pinned dependencies `pyproject.toml` pins one exact `vatly-api-python` and `vatly-fluent-python` version from PyPI; `uv.lock` records their hashes. To move to new versions, change the pins, run `uv lock`, and run the full checks. Use a new alpha version when dependency behavior changes. ## Prepare a release The published package is [vatly-django](https://pypi.org/project/vatly-django/){rel=""nofollow""}; the import name is `vatly_django`. Release matching versions in SDK → Fluent → Django order, only after review and approval. | PyPI trusted publisher field | Value | | ---------------------------- | -------------- | | Owner | `vatly` | | Repository | `vatly-django` | | Workflow | `release.yml` | | Environment | Leave blank | The workflow publishes only when a GitHub release is published with a tag matching `v` plus the package version. Pushing `main` or running a local build does not publish. Restrict release access: there is no environment approval gate or PyPI token, and all PyPI artifacts are public. [Offline testing examples](https://docs.vatly.com/packages/django/testing) · [Installation](https://docs.vatly.com/packages/django/installation) # SDKs & Packages > Official Vatly packages for your language or framework. Vatly is the European merchant of record for AI, software and digital products. These official packages connect billing, subscriptions, and tax compliance to your application. ## Available packages | Language / Framework | Package | Install | | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------- | | PHP SDK | [vatly/vatly-api-php](https://packagist.org/packages/vatly/vatly-api-php){rel=""nofollow""} · [Docs](https://docs.vatly.com/packages/php/readme) · [GitHub](https://github.com/vatly/vatly-api-php){rel=""nofollow""} | `composer require vatly/vatly-api-php` (after allowing alpha, see below) | | PHP Fluent | [vatly/vatly-fluent-php](https://packagist.org/packages/vatly/vatly-fluent-php){rel=""nofollow""} · [Docs](https://docs.vatly.com/packages/fluent-php/readme) · [GitHub](https://github.com/vatly/vatly-fluent-php){rel=""nofollow""} | `composer require vatly/vatly-fluent-php` (after allowing alpha, see below) | | Laravel | [vatly/vatly-laravel](https://packagist.org/packages/vatly/vatly-laravel){rel=""nofollow""} · [Docs](https://docs.vatly.com/packages/laravel/readme) · [GitHub](https://github.com/vatly/vatly-laravel){rel=""nofollow""} | `composer require vatly/vatly-laravel` (after allowing alpha, see below) | | JavaScript SDK | [@getvatly/sdk](https://www.npmjs.com/package/@getvatly/sdk){rel=""nofollow""} · [Docs](https://docs.vatly.com/packages/javascript/readme) · [GitHub](https://github.com/vatly/vatly-api-js){rel=""nofollow""} | `npm install --save-exact @getvatly/sdk` | | JavaScript Fluent | [@getvatly/fluent](https://www.npmjs.com/package/@getvatly/fluent){rel=""nofollow""} · [Docs](https://docs.vatly.com/packages/fluent-js/readme) · [GitHub](https://github.com/vatly/vatly-fluent-js){rel=""nofollow""} | `npm install --save-exact @getvatly/sdk @getvatly/fluent` | | Python SDK | [vatly-api-python](https://pypi.org/project/vatly-api-python/){rel=""nofollow""} · [Docs](https://docs.vatly.com/packages/python/readme) · [GitHub](https://github.com/vatly/vatly-api-python){rel=""nofollow""} | `pip install --pre vatly-api-python` | | Python Fluent | [vatly-fluent-python](https://pypi.org/project/vatly-fluent-python/){rel=""nofollow""} · [Docs](https://docs.vatly.com/packages/fluent-python/readme) · [GitHub](https://github.com/vatly/vatly-fluent-python){rel=""nofollow""} | `pip install --pre vatly-fluent-python` | | Django | [vatly-django](https://pypi.org/project/vatly-django/){rel=""nofollow""} · [Docs](https://docs.vatly.com/packages/django/readme) · [GitHub](https://github.com/vatly/vatly-django){rel=""nofollow""} | `pip install --pre vatly-django` | | FluentCart (WordPress) | [GitHub Releases](https://github.com/vatly/vatly-fluentcart-wp/releases/latest){rel=""nofollow""} · [Docs](https://docs.vatly.com/packages/fluentcart/readme) · [GitHub](https://github.com/vatly/vatly-fluentcart-wp){rel=""nofollow""} | Upload the release zip in WordPress | | Paid Memberships Pro (WordPress) | [GitHub Releases](https://github.com/vatly/vatly-pmpro/releases/latest){rel=""nofollow""} · [Docs](https://docs.vatly.com/packages/pmpro/readme) · [GitHub](https://github.com/vatly/vatly-pmpro){rel=""nofollow""} | Upload the release zip in WordPress | These packages are in alpha. Every alpha release may include breaking changes. Lock the version you install and review the release notes before upgrading. The install commands above get the latest alpha. For the PHP packages, first run `composer config minimum-stability alpha` and `composer config prefer-stable true`, because Composer installs only stable releases by default. For the Python packages, `--pre` selects the latest alpha. The Python packages require Python 3.10+; their import names are `vatly`, `vatly_fluent`, and `vatly_django`, respectively. The FluentCart plugin is in alpha and requires FluentCart 2.3 or newer. It is not on WordPress.org or Packagist: download the zip from [GitHub Releases](https://github.com/vatly/vatly-fluentcart-wp/releases/latest){rel=""nofollow""} and upload it under **Plugins → Add New → Upload Plugin**. The Paid Memberships Pro plugin is in alpha and requires Paid Memberships Pro 3.x. It is not on WordPress.org or Packagist: download the zip from [GitHub Releases](https://github.com/vatly/vatly-pmpro/releases/latest){rel=""nofollow""} and upload it under **Plugins → Add New → Upload Plugin**. Not using one of these languages? You can use the [REST API directly](https://docs.vatly.com/guides/authentication) with any HTTP client. # Lovable payments with Vatly Use Vatly as the **European merchant of record for your Lovable app** to sell software, digital products, or SaaS subscriptions without building your own tax and invoicing workflow. Vatly is the European merchant of record for AI, software and digital products: it becomes the legal seller, while you build and deliver the product. **[Get a test API key](https://my.vatly.com){rel=""nofollow""} · [Copy the Lovable agent prompt](https://docs.vatly.com/#prompt-lovable-to-build-the-integration)** This is a custom API integration using Vatly's existing JavaScript packages, not a native Lovable payment connector or an endorsement by Lovable. You do not need a Vatly-specific change to Lovable or Vatly to follow this approach. ## Why use a merchant of record instead of plain Stripe? Lovable can add a payment integration, but accepting a card payment is not the same as handing over the seller's responsibilities. With a standard payment-processing integration, your business remains the seller and must arrange tax compliance and invoicing. For a broader comparison, see [Vatly vs Stripe](https://vatly.com/vs/stripe){rel=""nofollow""}. With Vatly, the [tax and invoicing for Vatly sales are Vatly's responsibility](https://vatly.com/){rel=""nofollow""}: calculating and collecting EU VAT and applicable sales tax, handling registrations, filing and remitting tax, and issuing customer invoices. You still own your app, access control, and fulfillment. The difference is who takes on the legal seller's tax work, not just which checkout button you use. ## Why Vatly fits a Lovable app - **Europe-first.** Vatly is based in the Netherlands and built for European software and digital product businesses selling internationally, with [European payment methods through Mollie](https://vatly.com/mollie-merchant-of-record){rel=""nofollow""}. - **Software billing, including AI apps.** Sell an AI app's subscription or a one-off digital product through the same [checkout API](https://docs.vatly.com/api-reference/checkouts). You do not need a payment integration specific to the model or AI service your app uses. - **Multi-line orders.** A checkout can include multiple products and quantities, for example a subscription plan and a one-off digital download, with [order lines and tax information](https://docs.vatly.com/api-reference/orders) available to your backend. - **Hosted checkout and customer portal.** Redirect customers to checkout instead of building a payment form. The [hosted portal](https://docs.vatly.com/packages/fluent-js/customerportal) provides invoice history and subscription controls for eligible customers; portal access requires an issued invoice. ## Start with a test checkout **[Create your Vatly account](https://my.vatly.com){rel=""nofollow""}, get a test API key under Developers » API keys, and [copy the Lovable agent prompt](https://docs.vatly.com/#prompt-lovable-to-build-the-integration).** Create a test product under **Manage Products**, then let Lovable connect a checkout button to your existing backend using the prompt below. Enter the key only in Lovable's secure secret form, never in chat. Test mode works from the start. Your first milestone is a hosted test checkout followed by a verified webhook that updates access in your app, not a complete billing UI built from scratch. Live sales require [Vatly approval, product review, and Mollie verification](https://docs.vatly.com/introduction#going-live). Product review typically takes one to two business days; that is not a guarantee of your integration or go-live date. ## Choose the right server code for your Lovable project You keep your existing app, customer login, and database. Lovable adds a checkout action that sends customers to Vatly's hosted payment page, plus a background receiver for billing updates. After a verified payment, your app grants the purchased access. You do not need to build a card-entry form. For the responsibilities behind this flow, see [Build your own integration](https://docs.vatly.com/guides/build-your-own-integration). Lovable's [current stack documentation](https://docs.lovable.dev/introduction/faq){rel=""nofollow""} distinguishes two kinds of app: | Your project | Where Vatly code belongs | | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Newer TanStack Start app | A server function for authenticated checkout creation, and a public server route for signed webhooks. Keep SDK imports and secrets out of code shared with the browser. | | Older React + Vite app | An Edge Function in Lovable's built-in backend (Lovable Cloud), or your connected Supabase project. A React component or Vite development server is not a private backend. | Lovable says apps created from May 13, 2026 (June 22, 2026 for Enterprise workspaces) use TanStack Start. Inspect your actual project before choosing a route: an older project may have been upgraded. Its [direct API integration guide](https://docs.lovable.dev/integrations/any-api){rel=""nofollow""} explains this server-function versus Edge Function split. The [built-in backend](https://docs.lovable.dev/features/cloud){rel=""nofollow""} provides database, auth, storage, and Edge Functions using Supabase's open-source foundation. A [connected Supabase project](https://docs.lovable.dev/integrations/supabase){rel=""nofollow""} gives you ownership of the backend in your own Supabase account. Use the backend you already have; adding Vatly does not require migrating it. Store user-to-Vatly-customer mappings and processed webhook IDs in your database. ## Add Vatly rather than the default payments flow Lovable offers [built-in payments](https://docs.lovable.dev/features/payments){rel=""nofollow""} and other payment integrations. If you want **Vatly** to be the merchant of record, explicitly request a **direct Vatly API integration**. Do not ask only to "add payments": the agent could choose a different provider. Lovable also supports [custom API connectors](https://docs.lovable.dev/integrations/any-api){rel=""nofollow""}. This guide uses server-side Vatly packages so your app owns checkout authorization, webhook verification, and fulfillment. It does not use Lovable's built-in payments setup or ask you to connect a Stripe account for Vatly. The prompt below starts your agent with [`@getvatly/fluent`](https://docs.vatly.com/packages/fluent-js/readme), the higher-level JavaScript billing package. It provides building blocks for checkout, subscriptions, and webhook processing; your agent connects those to your database and access rules. The [general integration guide](https://docs.vatly.com/guides/build-your-own-integration#choose-your-tools) explains the alternatives, while the package docs own implementation examples. ## Set up the account and secrets Follow the [Quickstart](https://docs.vatly.com/guides/quickstart), starting with a test key and product. Both `@getvatly/fluent` and its underlying `@getvatly/sdk` are **alpha**; install them as shown in [fluent installation and configuration](https://docs.vatly.com/packages/fluent-js/configuration) and lock the installed versions, because alpha updates may break compatibility. When Lovable prompts for `VATLY_API_KEY`, use the secure **Add secret** form, not the chat. Manage project secrets under **More » Settings » Secrets**. If your app uses an external Supabase project, Lovable's **Manage secrets** opens the Supabase dashboard; store the secret in that project's Edge Function settings. See [Lovable secrets](https://docs.lovable.dev/features/secrets){rel=""nofollow""}. Add a separate `VATLY_WEBHOOK_SECRET` matching the signing secret configured for your Vatly webhook endpoint. Both values are **server-side only**. Never create `VITE_VATLY_API_KEY`, put the key in React code, or paste it into an agent prompt. Public Supabase connection values do not make a Vatly API key safe to expose. ## Prompt Lovable to build the integration Paste this into Lovable after choosing your product and return URLs. Provide IDs and URLs when asked, but enter secret values only in the secure secret form. ```text Use Vatly as the merchant of record for this app. Build a direct API integration, not Lovable built-in payments or a Stripe/Paddle integration. First inspect this project's framework and backend. If it uses TanStack Start, keep checkout creation in a server function and webhooks in a public server route. If it uses React + Vite, use an Edge Function in the existing Lovable Cloud or connected Supabase backend. Do not migrate the backend. Tell me which files and deployed routes will contain server-only code. Read these sources before writing code: https://docs.vatly.com/guides/build-your-own-integration https://docs.vatly.com/packages/fluent-js/readme https://docs.vatly.com/packages/fluent-js/configuration https://docs.vatly.com/packages/fluent-js/checkouts https://docs.vatly.com/packages/fluent-js/webhooks https://docs.vatly.com/packages/fluent-js/coreconcepts https://docs.vatly.com/guides/webhooks https://docs.vatly.com/api-reference https://docs.vatly.com/openapi.yaml Start with @getvatly/fluent and its required @getvatly/sdk dependency. Install both as documented in configuration, lock the installed versions, and check the deployed runtime; use pinned npm: imports for Deno. Use the underlying SDK when a fluent helper is missing or the deployed runtime requires a different approach, and explain the reason. Wire the documented storage drivers to our database; do not assume adapters are included. Ask me for a test-mode Vatly product ID and fixed success/canceled URLs. Ask for VATLY_API_KEY and VATLY_WEBHOOK_SECRET through the secret form, never chat. Never put either value in VITE_ variables or browser code. Authenticate checkout requests, load or create the signed-in user's Vatly customer on the server, and store the mapping in the database. Restrict products and quantities server-side. Use the documented fluent checkout or subscription builder and return only the hosted checkout URL to the browser. Redirect there. Do not unlock access on return. Make only the webhook route public without user JWT/session requirements. Follow fluent's webhook guide: verify the untouched request with the endpoint secret before writes, validate the envelope, and wire transactional webhook storage. Reject bad signatures and acknowledge verified webhook.setup. Use the verified event.id for deduplication; commit processing and database changes atomically, with retries on failure. Configure access policies so users cannot write their own billing/access state. Follow Vatly's actual event names and envelope, and handle subscription cancellation and renewals. Show me the deployed HTTPS webhook URL and which Vatly events to subscribe to under Developers > Webhooks. Test auth, cross-user customer access, CORS where needed, invalid signatures, duplicate events, and payment confirmation. Report what you tested and what still needs my setup; do not claim live payments work without a completed test-mode checkout and verified delivery. ``` Use the JavaScript packages in Lovable's managed server functions. A separately hosted backend can use [another package or the HTTP API](https://docs.vatly.com/guides/build-your-own-integration#choose-your-tools). If Lovable generates a Supabase function with JWT verification enabled for the webhook, ask it to allow external requests **only on that function**, while keeping Vatly signature verification mandatory. The checkout function must still require your user's authentication. ## Review the result in Lovable - Ask the agent to identify the server-only SDK imports and show that the browser calls your backend, not `api.vatly.com` with your API key. - In an older Vite app, confirm it deployed an Edge Function, not just a frontend helper. In a TanStack Start app, confirm the webhook is a deployed HTTP route, not a server function that only the UI can invoke. - Confirm the return page stays pending until the database reflects a verified payment event, and database policies prevent clients from granting themselves access. - Test unsigned, tampered, and stale webhooks, duplicate deliveries, and a database failure. Confirm retries cannot grant access twice. Follow [fluent testing](https://docs.vatly.com/packages/fluent-js/testing) and the [test-mode guide](https://docs.vatly.com/guides/testing). - Register the deployed webhook URL in Vatly, not the editor preview URL. Do not replace the test key with a live key until [onboarding](https://docs.vatly.com/introduction#going-live) is complete. Building in Bolt instead? See [Bolt payments with Vatly](https://docs.vatly.com/integrations/bolt). # Bolt payments with Vatly Add **Vatly payments to your Bolt.new app** without turning a generated checkout into a tax and invoicing project. Vatly is the European merchant of record for AI, software and digital products: it acts as the legal seller for your software, digital downloads, or subscriptions, while your Bolt app handles the product and customer access. **[Sign up and get a test key](https://my.vatly.com){rel=""nofollow""} · [Copy the Bolt integration prompt](https://docs.vatly.com/#prompt-bolt-to-add-checkout-and-webhooks)** This is a custom API integration, not a native Bolt connector or an endorsement by Bolt. It uses Vatly's existing API and JavaScript packages; no platform changes are required on Vatly's side. ## A payment integration is not a merchant of record Bolt's Stripe integration can generate checkout and webhook code. With a standard payment-processing integration, though, your business is still the seller: you must arrange tax compliance and customer invoicing alongside the integration. The distinction is between processing a payment and taking on the seller's responsibilities. See [Vatly vs Stripe](https://vatly.com/vs/stripe){rel=""nofollow""} for the broader comparison. Vatly takes on the latter for Vatly sales. It handles [EU VAT, applicable sales tax, registrations, returns, remittance, and customer invoices](https://vatly.com/){rel=""nofollow""}. That leaves Bolt's server functions responsible for a smaller integration: create checkout, verify billing events, and update your app's access state. Your product logic and fulfillment remain yours. ## What Vatly gives your Bolt app - **A European merchant of record.** Vatly is based in the Netherlands and focuses on European software and digital products, with [Mollie-powered European payment methods](https://vatly.com/mollie-merchant-of-record){rel=""nofollow""} for international sales. - **A fit for AI and software products.** Sell access to an AI tool or SaaS app as a subscription, or sell a one-off license or digital download. Use Vatly's existing API rather than building a billing system around your frontend framework. - **One checkout, multiple order lines.** Pass products and quantities to the [checkout API](https://docs.vatly.com/api-reference/checkouts), then use the resulting [order lines](https://docs.vatly.com/api-reference/orders) to fulfill a purchase containing more than one item. - **Hosted billing screens.** Vatly provides the checkout and a [customer portal](https://docs.vatly.com/packages/fluent-js/customerportal) for invoices and subscription management. Portal access requires an issued invoice; you still authenticate the user and create the portal session on your server. ## Get your first test payment working **[Sign up for Vatly](https://my.vatly.com){rel=""nofollow""}, get a test API key under Developers » API keys, and [copy the Bolt integration prompt](https://docs.vatly.com/#prompt-bolt-to-add-checkout-and-webhooks).** Add a test product in **Manage Products**. Bolt can then build the server functions and checkout button against your existing Bolt Database or Supabase backend; you do not need to switch database providers to use Vatly. Start in test mode as soon as your account is ready, with credentials stored in database **Secrets**. Verify a complete test checkout and webhook before considering the integration ready. Going live also depends on [Vatly approval, product review, and Mollie business verification](https://docs.vatly.com/introduction#going-live). Product review typically takes one to two business days, but neither that nor generated code guarantees a launch date. ## Identify your Bolt backend first Your customers keep using your Bolt app. A checkout button sends them to Vatly's hosted payment page, and a background billing update tells your app when to grant access. You keep the product UI, login, and database; Vatly handles checkout, tax, and invoicing. See [Build your own integration](https://docs.vatly.com/guides/build-your-own-integration) for the overall responsibilities before asking the agent to make changes. Bolt supports [JavaScript frontend frameworks and Node.js backends](https://support.bolt.new/reference/supported-technologies){rel=""nofollow""}, rather than requiring one frontend framework. Inspect `package.json` and the deployed backend instead of assuming every app is a React + Vite app or that a Node process in the editor is deployed as a production server. New projects use [Bolt Database by default](https://support.bolt.new/integrations/supabase){rel=""nofollow""}. Bolt Cloud [server functions](https://support.bolt.new/bolt-cloud/database/server-functions){rel=""nofollow""}, also called edge functions, handle external API calls, payments, and webhooks outside the browser. They belong to the connected database, and Bolt deploys them when it creates or updates them. You can also use an existing Supabase project with its database, authentication, and Edge Functions. Bolt's Supabase integration is available on Pro and Teams plans. Keep the database your app already uses: replacing its connection can risk existing data, and Vatly does not require a database migration to another provider. | Existing setup | Where to add Vatly | | --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | Bolt Cloud with Bolt Database | Server functions for authenticated checkout creation and a separate signed webhook endpoint. | | Connected Supabase project | Supabase Edge Functions and the existing auth/database integration. | | Separately hosted Node.js backend | Private server routes and that host's runtime secrets. Confirm the routes actually deploy; a browser-only static host cannot run them. | This guide focuses on Bolt Cloud and Supabase. For a separately hosted backend, choose a [package or direct HTTP integration](https://docs.vatly.com/guides/build-your-own-integration#choose-your-tools) that fits its runtime. ## Use Vatly, not Bolt's Stripe integration Bolt's [built-in Stripe integration](https://support.bolt.new/integrations/stripe){rel=""nofollow""} imports Stripe products and generates checkout and webhook code. Those conveniences apply to Stripe, **not to a custom Vatly integration**. Do not paste a Vatly key into the Stripe setup or reuse Stripe event names, signatures, or test cards. Tell the agent to use Vatly explicitly. Create your products in Vatly, create checkouts on your server, and register your webhook URL in Vatly yourself. Your app remains responsible for authorizing checkout requests and updating access from verified Vatly events. The prompt below starts your agent with [`@getvatly/fluent`](https://docs.vatly.com/packages/fluent-js/readme), the higher-level JavaScript billing package. Your agent connects its checkout and webhook building blocks to your existing database and access rules; it is not a ready-made Bolt Database or Supabase adapter. For other approaches, see [Choose your tools](https://docs.vatly.com/guides/build-your-own-integration#choose-your-tools). Implementation examples live in the package docs. ## Configure the database and secrets 1. Follow the [Quickstart](https://docs.vatly.com/guides/quickstart) to get a test key and product ID. 2. Ensure your Bolt project has a connected database. Bolt's server functions and secrets require one; if none exists, ask the agent to add it before building the payment functions. 3. Open the **database icon » Secrets** and add `VATLY_API_KEY` using your Vatly `test_` key. Add `VATLY_WEBHOOK_SECRET` with the signing secret configured for your Vatly webhook endpoint. Bolt can also prompt you to add these securely. See [Bolt secrets](https://support.bolt.new/bolt-cloud/database/secrets){rel=""nofollow""}. 4. Use **database icon » Server Functions** to inspect the generated functions and their logs. Never log the keys or full billing payloads while debugging. Secrets are available to server functions, not browser code. Do not put Vatly credentials in Bolt's project `.env`, `VITE_*` variables, frontend components, or agent chat. With a separately hosted backend, configure equivalent private runtime secrets on that host. Both `@getvatly/fluent` and its underlying `@getvatly/sdk` are **alpha**. Install them as shown in [fluent installation and configuration](https://docs.vatly.com/packages/fluent-js/configuration), lock the installed versions, and review breaking changes before upgrading. ## Prompt Bolt to add checkout and webhooks Use this prompt in your Bolt project. The agent should ask for product IDs and app URLs, not for secret values in chat. ```text Integrate Vatly as this app's merchant of record for payments and billing. Do not use Bolt's Stripe integration, Stripe products, or Stripe webhooks. Inspect package.json and identify the deployed backend. Keep the current Bolt Database or Supabase connection; do not replace it. If there is no database, explain that Bolt server functions and secrets need one and set it up before adding the functions. Use deployed server functions for checkout creation and a separate public Vatly webhook receiver, not a browser-only helper or a Node server that only runs in the editor. Read: https://docs.vatly.com/guides/build-your-own-integration https://docs.vatly.com/packages/fluent-js/readme https://docs.vatly.com/packages/fluent-js/configuration https://docs.vatly.com/packages/fluent-js/checkouts https://docs.vatly.com/packages/fluent-js/webhooks https://docs.vatly.com/packages/fluent-js/coreconcepts https://docs.vatly.com/guides/webhooks https://docs.vatly.com/api-reference https://docs.vatly.com/openapi.yaml Start with @getvatly/fluent and its required @getvatly/sdk dependency. Install both as documented in configuration, lock the installed versions, and check the deployed runtime; use pinned npm: imports for Deno. Use the underlying SDK when a fluent helper is missing or the deployed runtime requires a different approach, and explain the reason. Wire the documented storage drivers to our database; do not assume adapters are included. Ask me to add VATLY_API_KEY and VATLY_WEBHOOK_SECRET via database Secrets, never in chat or .env. Keep SDK imports and credentials exclusively in server functions. Ask me for a test-mode product ID and fixed success/canceled return URLs. Require authentication for checkout creation. Load or create the Vatly customer for the signed-in user and keep a server-owned database mapping. Never accept an arbitrary customer ID, price, or redirect URL from the UI. Allowlist products and validate quantities server-side. Use the documented fluent checkout or subscription builder; return only its hosted checkout URL so the browser can redirect. Add CORS handling restricted to my app's origins where functions are cross-origin. A return URL visit must never grant access. The webhook function must accept Vatly without a user JWT, while checkout creation stays authenticated. Follow fluent's webhook guide: verify the untouched request with the endpoint secret before writes, validate the envelope, and wire transactional webhook storage. Reject invalid signatures and acknowledge verified webhook.setup. Use the signed event.id for deduplication, commit processing and database changes atomically, and retry on failure. Protect billing tables from client writes. Implement Vatly event names and top-level object payloads, including the subscription lifecycle when selling subscriptions, not data.object. Show the deployed functions and HTTPS webhook URL, the Vatly events I need to subscribe to, and where to inspect function logs. Test login enforcement, cross-user isolation, invalid signatures, duplicate/concurrent deliveries, storage failure retries, and a completed test checkout. Distinguish tested behavior from configuration or deployment work I still need to do. ``` Use the JavaScript packages in Bolt's managed server functions. A separately hosted backend can use [another package or the HTTP API](https://docs.vatly.com/guides/build-your-own-integration#choose-your-tools). For Supabase Edge Functions, Vatly's webhook route needs JWT verification disabled for that function only: Vatly's signature, not a user's session, authenticates deliveries. ## Debug a deployed Bolt integration | Symptom | What to check | | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | No Secrets or Server Functions view | A database must be connected. Ask Bolt to confirm which backend it uses before creating another one. | | Checkout works in preview but not after publishing | Confirm the function deployed, the runtime has its secret, and CORS allows the published app's origin. The frontend preview alone does not prove a working backend. | | Vatly cannot register or deliver to the webhook | Use the deployed public HTTPS function URL. Remove user-JWT requirements from that endpoint only, verify Vatly signatures, and acknowledge signed `webhook.setup`. | | Webhook reports an invalid signature | Confirm the matching endpoint secret and verify the raw body before any JSON parsing. Use Vatly's verifier, not Stripe's. | | User pays but access stays pending | Inspect Server Functions logs and the durable inbox. Check event subscriptions, test/live mode, customer mapping, and failed database transactions. Do not bypass verification to make access appear. | Follow [fluent testing](https://docs.vatly.com/packages/fluent-js/testing) and the [test-mode guide](https://docs.vatly.com/guides/testing) before publishing for customers. Confirm unsigned, tampered, and stale webhooks are rejected, concurrent duplicates cannot fulfill twice, and storage failures can retry. Complete [Vatly onboarding](https://docs.vatly.com/introduction#going-live) before switching to live credentials. Building in Lovable instead? See [Lovable payments with Vatly](https://docs.vatly.com/integrations/lovable). # Integrations Connect Vatly to the tools and platforms you use to build your app. Vatly is the European merchant of record for AI, software and digital products, handling tax and customer invoicing while your app delivers the product. []{#choose-your-builder} ## Find your platform | Platform | How to get started | | ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- | | [Lovable](https://docs.vatly.com/integrations/lovable) | Understand how Vatly fits your Lovable app, prepare the account and secrets, and give Lovable's agent the integration brief. | | [Bolt.new](https://docs.vatly.com/integrations/bolt) | Connect Vatly to your existing Bolt app and backend, then have the agent build and test your checkout and billing flow. | The Lovable and Bolt guides describe custom integrations using Vatly's existing packages and API. They are not native payment connectors or endorsements by those platforms. []{#choose-your-integration-approach}[]{#create-a-checkout-with-the-javascript-sdk}[]{#create-a-checkout}[]{#prepare-your-vatly-account}[]{#keep-credentials-on-the-server}[]{#verify-webhooks-before-granting-access}[]{#before-you-connect}[]{#test-before-publishing}[]{#documentation-for-your-agent} ## Framework packages Using a framework rather than an app builder? Official [Laravel](https://docs.vatly.com/packages/laravel/readme) and [Django](https://docs.vatly.com/packages/django/readme) packages integrate Vatly with your application. Their installation, configuration and API guides live under [Packages](https://docs.vatly.com/packages), alongside the SDKs and fluent packages, rather than being duplicated here. These packages are in alpha. Every alpha release may include breaking changes. Lock the version you install and review the release notes before upgrading. Running a WordPress store on FluentCart? The [FluentCart plugin](https://docs.vatly.com/packages/fluentcart/readme) adds Vatly as a payment gateway. It is in alpha; try it in Vatly test mode before you take live payments. Selling memberships with Paid Memberships Pro? The [Paid Memberships Pro plugin](https://docs.vatly.com/packages/pmpro/readme) adds Vatly as a payment gateway. It is in alpha; try it in Vatly test mode before you take live payments. ## Connecting another app? Start with [Build your own integration](https://docs.vatly.com/guides/build-your-own-integration) to understand what Vatly handles, what your app needs, and what to ask your developer or agent to build. It also helps you choose a fluent package, SDK, or direct API approach. If you are ready for your first API request, follow the [Quickstart](https://docs.vatly.com/guides/quickstart). Implementation examples live in the [package docs](https://docs.vatly.com/packages), with exact endpoint and field details in the [API reference](https://docs.vatly.com/api-reference). # Start building with Vatly ::div{.guides-start} :::div ## Make your first API request Get a test key, choose a client and connect to the Vatly API. ::: [Open quickstart →](https://docs.vatly.com/guides/quickstart){.guides-primary} :: ## Build your integration ::div{.guides-paths} :::div ### Using Lovable or Bolt? Follow a guide for your builder, with the account setup and integration brief in one place. [Lovable](https://docs.vatly.com/integrations/lovable) · [Bolt](https://docs.vatly.com/integrations/bolt) ::: :::div ### Building your own app? See what Vatly handles, what your app needs to build, and how to choose your approach. [Build your own integration →](https://docs.vatly.com/guides/build-your-own-integration) ::: :: ## Understand the billing flow ::div{.guides-basics} :::div [Selling workflow](https://docs.vatly.com/guides/selling-workflow) From checkout to fulfillment. ::: :::div [Webhooks](https://docs.vatly.com/guides/webhooks) Keep your app in sync. ::: :::div [Testing](https://docs.vatly.com/guides/testing) Try the flow before going live. ::: :: ::div{.guides-crosslinks} Vatly is the European merchant of record for AI, software and digital products. Looking for implementation details? [SDKs & Packages](https://docs.vatly.com/packages) · [API Reference](https://docs.vatly.com/api-reference/customers) ::