# Regenerate an invoice

> For the complete machine-readable documentation index, see [llms.txt](https://apidocs.chargebee.com/llms.txt).


[Idempotency Supported](/docs/api/idempotency)

Use this API to regenerate the current-term [invoice](/docs/api/invoices) for a subscription. The new invoice will contain non-metered charges from the current term and [metered](/docs/api/items/item-object#metered) charges from the previous term. If a customer was billed incorrectly, because of a wrong plan, price, or tax configuration, you can first [void](/docs/api/invoices/void-an-invoice) or [delete](/docs/api/invoices/delete-an-invoice) the erroneous invoice, update the [subscription](/docs/api/subscriptions/update-subscription-for-items) or [usage](/docs/api/usages/create-a-usage) records, and then run this operation to issue the corrected invoice.

### Prerequisites & Constraints

Before regenerating an invoice, ensure the following conditions are met:

-   The subscription's current-term invoice must be voided or deleted.
-   The subscription [`status`](/docs/api/subscriptions/subscription-object#status) must be `active` or `non_renewing`.
-   There should be no [unbilled charges](/docs/api/unbilled_charges) for non-`metered` subscribed items for the current term.
-   There should be no unbilled charges for `metered` items for the previous term.
-   The subscription must not have any [advance invoices](https://www.chargebee.com/docs/2.0/advance-invoices.html#generating-an-advance-invoice)

### Impacts

**

Current-Term Invoice

**

Chargebee does not modify the voided or deleted invoice for the current term. Instead, it creates a new invoice.

The new invoice includes:

-   Subscription-item charges for the current term.
-   Usage charges from the previous term.

The new invoice **does not** include:

-   One-time addon charges, including mandatory addons.
-   Ad hoc or other one-time charges from the voided or deleted invoice.
-   Unbilled charges.
-   Usage charges for the current term.

If every charge for the current-term has a value of zero, and your site is configured to [hide zero-value line items](https://www.chargebee.com/docs/billing/2.0/kb/billing/how-to-hide-zero-value-line-items-from-my-customers), the invoice is not generated.

If you delete the original invoice, the associated usage data is also deleted. To ensure accurate billing for metered items, [add](/docs/api/usages/create-a-usage) or [bulk import](https://www.chargebee.com/docs/2.0/bulk-operations.html#overview_available-bulk-operations) usage records before regenerating the invoice.

**

Payment Collection

**

If [`auto-collection`](/docs/api/customers/customer-object#auto_collection) is `on`, Chargebee attempts to collect payment for the regenerated invoice. If the payment collection **fails**, the invoice regeneration also **fails**.

**Note**: Chargebee applies any [customer balances](/docs/api/customers/customer-object#balances), such as unapplied payment from the voided invoice, before attempting to collect the remaining amount.

**

Order

**

Any [orders](/docs/api/orders) associated with the invoice are regenerated automatically when the invoice is regenerated.

### Implementation Notes

Before calling this API, perform the following checks:

-   Confirm that the subscription `status` is `active` or `non_renewing`.
-   The invoice regeneration is supported for the current term only. If you're using the `date_from` and `date_to` parameters, ensure that their values fall within the range defined by [`subscription.current_term_start`](/docs/api/subscriptions/subscription-object#current_term_start) and [`subscription.current_term_end`](/docs/api/subscriptions/subscription-object#current_term_end).

## Sample Request

### Default

#### cURL

```bash
curl  https://{site}.chargebee.com/api/v2/subscriptions/__test__KyVnOuSHufd0ih/regenerate_invoice \
     -u {site_api_key}:\
     -d invoice_immediately="true"
```

#### .NET

```dotnet
using ChargeBee.Api;
using ChargeBee.Models;

ApiConfig.Configure("{site}","{site_api_key}");
EntityResult result = Subscription.RegenerateInvoice("__test__KyVnOuSHufd0ih")
		.InvoiceImmediately(true)
		.Request();

Invoice invoice = result.Invoice;
List<UnbilledCharge> unbilledCharges = result.UnbilledCharges;
```

#### Go

```go
package main
import (
    "fmt"
    "github.com/chargebee/chargebee-go/v3"
    subscriptionAction "github.com/chargebee/chargebee-go/v3/actions/subscription"
    "github.com/chargebee/chargebee-go/v3/models/subscription"
)
func main() {
    chargebee.Configure("{site_api_key}","{site}");
    res,err := subscriptionAction.RegenerateInvoice("__test__KyVnOuSHufd0ih", &subscription.RegenerateInvoiceRequestParams{
        InvoiceImmediately : chargebee.Bool(true),
    }).Request()
    if err != nil {
        fmt.Println(err)
    } else {
        Invoice := res.Invoice
        UnbilledCharges := res.UnbilledCharges
    }
}
```

#### Go

```go
package main

import (
  "fmt"
  "github.com/chargebee/chargebee-go/v4"
)

func main() {
  config := &chargebee.ClientConfig{
    SiteName: "{site}",
    ApiKey: "{site_api_key}",
  }    
  client := chargebee.NewClient(config)
  req := &chargebee.SubscriptionRegenerateInvoiceRequest{
    InvoiceImmediately : chargebee.Bool(true),
}
  res, err := client.Subscription.RegenerateInvoice("__test__KyVnOuSHufd0ih", req)
      if err != nil {
        fmt.Println(err)
    } else {
        Invoice := res.Invoice
        UnbilledCharges := res.UnbilledCharges
    }
}
```

#### Java

```java
import com.chargebee.*;
import com.chargebee.ListResult;
import com.chargebee.models.*;
import com.chargebee.models.enums.*;
import java.io.IOException;
import java.util.List;

public class Sample {

    public static void main(String args[]) throws IOException, Exception {
        Environment.configure("{site}", "{site_api_key}");
        Result result = Subscription.regenerateInvoice("__test__KyVnOuSHufd0ih")
            .invoiceImmediately(true)
            .request();

        Invoice invoice = result.invoice();
        List<UnbilledCharge> unbilledCharges = result.unbilledCharges();
    }
}
```

#### Java

```java
import com.chargebee.v4.client.ChargebeeClient;
import com.chargebee.v4.models.invoice.Invoice;
import com.chargebee.v4.models.subscription.params.SubscriptionRegenerateInvoiceParams;
import com.chargebee.v4.models.subscription.responses.SubscriptionRegenerateInvoiceResponse;
import com.chargebee.v4.models.unbilledCharge.UnbilledCharge;
import java.util.List;

public class SubscriptionRegenerateInvoice {

    public static void main(String[] args) {
        ChargebeeClient client = ChargebeeClient.builder()
            .apiKey("{site_api_key}")
            .siteName("{site}")
            .build();

        SubscriptionRegenerateInvoiceParams params = SubscriptionRegenerateInvoiceParams.builder()
            .invoiceImmediately(true)
            .build();

        SubscriptionRegenerateInvoiceResponse response = client
            .subscriptions()
            .regenerateInvoice("__test__KyVnOuSHufd0ih", params);

        Invoice invoice = response.getInvoice();
        List<UnbilledCharge> unbilledCharges = response.getUnbilledCharges();
    }
}
```

#### Node.js

```node
import Chargebee from "chargebee";

const chargebee = new Chargebee({
    site: "{site}",
    apiKey: "{site_api_key}",
});

try {
    const result = await chargebee.subscription.regenerateInvoice("__test__KyVnOuSHufd0ih", {
        invoice_immediately: true
    });

    console.log(result);
    const invoice = result.invoice;
    const unbilledCharges = result.unbilled_charges;
} catch (err) {
    console.log(err);
}
```

#### PHP

```php
<?php

require __DIR__ . '/vendor/autoload.php';

use Chargebee\ChargebeeClient;

$chargebee = new ChargebeeClient(options: [
    "site" => "{site}",
    "apiKey" => "{site_api_key}",
]);
$result = $chargebee->subscription()->regenerateInvoice("__test__KyVnOuSHufd0ih", [
    "invoice_immediately" => true
]);
$invoice = $result->invoice;
$unbilledCharges = $result->unbilled_charges;
```

#### Python

```python
from chargebee import Chargebee

cb_client = Chargebee(api_key="{site_api_key}", site="{site}")
response = cb_client.Subscription.regenerate_invoice("__test__KyVnOuSHufd0ih",
    cb_client.Subscription.RegenerateInvoiceParams(
        invoice_immediately=True
    )
)
invoice = response.invoice
unbilled_charges = response.unbilled_charges
```

#### Ruby

```ruby
require 'chargebee'

ChargeBee.configure(:site => "{site}",
  :api_key => "{site_api_key}")

result = ChargeBee::Subscription.regenerate_invoice("__test__KyVnOuSHufd0ih",{
  :invoice_immediately => "true"
})

invoice = result.invoice
unbilled_charges = result.unbilled_charges
```

### Regenerate For Custom Term

#### cURL

```bash
curl  https://{site}.chargebee.com/api/v2/subscriptions/__test__KyVnOuSHufVfXT/regenerate_invoice \
     -u {site_api_key}:\
     -d invoice_immediately="false" \
     -d date_from=1517826222 \
     -d date_to=1519208622 \
     -d prorate="true"
```

#### .NET

```dotnet
using ChargeBee.Api;
using ChargeBee.Models;

ApiConfig.Configure("{site}","{site_api_key}");
EntityResult result = Subscription.RegenerateInvoice("__test__KyVnOuSHufVfXT")
		.InvoiceImmediately(false)
		.DateFrom(1517826222)
		.DateTo(1519208622)
		.Prorate(true)
		.Request();

Invoice invoice = result.Invoice;
List<UnbilledCharge> unbilledCharges = result.UnbilledCharges;
```

#### Go

```go
package main
import (
    "fmt"
    "github.com/chargebee/chargebee-go/v3"
    subscriptionAction "github.com/chargebee/chargebee-go/v3/actions/subscription"
    "github.com/chargebee/chargebee-go/v3/models/subscription"
)
func main() {
    chargebee.Configure("{site_api_key}","{site}");
    res,err := subscriptionAction.RegenerateInvoice("__test__KyVnOuSHufVfXT", &subscription.RegenerateInvoiceRequestParams{
        InvoiceImmediately : chargebee.Bool(false),
        DateFrom : chargebee.Int64(1517826222),
        DateTo : chargebee.Int64(1519208622),
        Prorate : chargebee.Bool(true),
    }).Request()
    if err != nil {
        fmt.Println(err)
    } else {
        Invoice := res.Invoice
        UnbilledCharges := res.UnbilledCharges
    }
}
```

#### Go

```go
package main

import (
  "fmt"
  "github.com/chargebee/chargebee-go/v4"
)

func main() {
  config := &chargebee.ClientConfig{
    SiteName: "{site}",
    ApiKey: "{site_api_key}",
  }    
  client := chargebee.NewClient(config)
  req := &chargebee.SubscriptionRegenerateInvoiceRequest{
    InvoiceImmediately : chargebee.Bool(false),
    DateFrom : chargebee.Int64(1517826222),
    DateTo : chargebee.Int64(1519208622),
    Prorate : chargebee.Bool(true),
}
  res, err := client.Subscription.RegenerateInvoice("__test__KyVnOuSHufVfXT", req)
      if err != nil {
        fmt.Println(err)
    } else {
        Invoice := res.Invoice
        UnbilledCharges := res.UnbilledCharges
    }
}
```

#### Java

```java
import com.chargebee.*;
import com.chargebee.ListResult;
import com.chargebee.models.*;
import com.chargebee.models.enums.*;
import java.io.IOException;
import java.util.List;
import java.sql.Timestamp;

public class Sample {

    public static void main(String args[]) throws IOException, Exception {
        Environment.configure("{site}", "{site_api_key}");
        Result result = Subscription.regenerateInvoice("__test__KyVnOuSHufVfXT")
            .invoiceImmediately(false)
            .dateFrom(new Timestamp(1517826222L * 1000))
            .dateTo(new Timestamp(1519208622L * 1000))
            .prorate(true)
            .request();

        Invoice invoice = result.invoice();
        List<UnbilledCharge> unbilledCharges = result.unbilledCharges();
    }
}
```

#### Java

```java
import com.chargebee.v4.client.ChargebeeClient;
import com.chargebee.v4.models.invoice.Invoice;
import com.chargebee.v4.models.subscription.params.SubscriptionRegenerateInvoiceParams;
import com.chargebee.v4.models.subscription.responses.SubscriptionRegenerateInvoiceResponse;
import com.chargebee.v4.models.unbilledCharge.UnbilledCharge;
import java.sql.Timestamp;
import java.util.List;

public class SubscriptionRegenerateInvoice {

    public static void main(String[] args) {
        ChargebeeClient client = ChargebeeClient.builder()
            .apiKey("{site_api_key}")
            .siteName("{site}")
            .build();

        SubscriptionRegenerateInvoiceParams params = SubscriptionRegenerateInvoiceParams.builder()
            .invoiceImmediately(false)
            .dateFrom(new Timestamp(1517826222L * 1000))
            .dateTo(new Timestamp(1519208622L * 1000))
            .prorate(true)
            .build();

        SubscriptionRegenerateInvoiceResponse response = client
            .subscriptions()
            .regenerateInvoice("__test__KyVnOuSHufVfXT", params);

        Invoice invoice = response.getInvoice();
        List<UnbilledCharge> unbilledCharges = response.getUnbilledCharges();
    }
}
```

#### Node.js

```node
import Chargebee from "chargebee";

const chargebee = new Chargebee({
    site: "{site}",
    apiKey: "{site_api_key}",
});

try {
    const result = await chargebee.subscription.regenerateInvoice("__test__KyVnOuSHufVfXT", {
        invoice_immediately: false,
        date_from: 1517826222,
        date_to: 1519208622,
        prorate: true
    });

    console.log(result);
    const invoice = result.invoice;
    const unbilledCharges = result.unbilled_charges;
} catch (err) {
    console.log(err);
}
```

#### PHP

```php
<?php

require __DIR__ . '/vendor/autoload.php';

use Chargebee\ChargebeeClient;

$chargebee = new ChargebeeClient(options: [
    "site" => "{site}",
    "apiKey" => "{site_api_key}",
]);
$result = $chargebee->subscription()->regenerateInvoice("__test__KyVnOuSHufVfXT", [
    "invoice_immediately" => false,
    "date_from" => 1517826222,
    "date_to" => 1519208622,
    "prorate" => true
]);
$invoice = $result->invoice;
$unbilledCharges = $result->unbilled_charges;
```

#### Python

```python
from chargebee import Chargebee

cb_client = Chargebee(api_key="{site_api_key}", site="{site}")
response = cb_client.Subscription.regenerate_invoice("__test__KyVnOuSHufVfXT",
    cb_client.Subscription.RegenerateInvoiceParams(
        invoice_immediately=False,
        date_from=1517826222,
        date_to=1519208622,
        prorate=True
    )
)
invoice = response.invoice
unbilled_charges = response.unbilled_charges
```

#### Ruby

```ruby
require 'chargebee'

ChargeBee.configure(:site => "{site}",
  :api_key => "{site_api_key}")

result = ChargeBee::Subscription.regenerate_invoice("__test__KyVnOuSHufVfXT",{
  :invoice_immediately => "false",
  :date_from => 1517826222,
  :date_to => 1519208622,
  :prorate => "true"
})

invoice = result.invoice
unbilled_charges = result.unbilled_charges
```

## Sample Response

```json
{
  "invoice": {
    "adjustment_credit_notes": {},
    "amount_adjusted": 0,
    "amount_due": 895,
    "amount_paid": 0,
    "amount_to_collect": 895,
    "applied_credits": {},
    "base_currency_code": "USD",
    "credits_applied": 0,
    "currency_code": "USD",
    "customer_id": "__test__KyVnOuSHufd0ih",
    "date": 1517480651,
    "deleted": false,
    "due_date": 1517480651,
    "dunning_attempts": {},
    "exchange_rate": 1,
    "first_invoice": true,
    "has_advance_charges": false,
    "id": "__demo_inv__2",
    "is_gifted": false,
    "issued_credit_notes": {},
    "line_items": [
      {
        "amount": 895,
        "customer_id": "__test__KyVnOuSHufd0ih",
        "date_from": 1517480650,
        "date_to": 1519899850,
        "description": "No Trial",
        "discount_amount": 0,
        "entity_id": "no_trial",
        "entity_type": "plan",
        "id": "li___test__KyVnOuSHufd80s",
        "is_taxed": false,
        "item_level_discount_amount": 0,
        "object": "line_item",
        "pricing_model": "per_unit",
        "quantity": 1,
        "subscription_id": "__test__KyVnOuSHufd0ih",
        "tax_amount": 0,
        "tax_exempt_reason": "tax_not_configured",
        "unit_amount": 895
      },
      {..}
    ],
    "linked_orders": {},
    "linked_payments": {},
    "net_term_days": 0,
    "new_sales_amount": 895,
    "object": "invoice",
    "price_type": "tax_exclusive",
    "recurring": true,
    "resource_version": 1517480651257,
    "round_off_amount": 0,
    "status": "payment_due",
    "sub_total": 895,
    "subscription_id": "__test__KyVnOuSHufd0ih",
    "tax": 0,
    "term_finalized": true,
    "total": 895,
    "updated_at": 1517480651,
    "write_off_amount": 0
  }
}
```

## URL Format

**POST** https://[site].chargebee.com/api/v2/subscriptions/{subscription-id}/regenerate_invoice

## Input Parameters

- `date_from` (optional, timestamp(UTC) in seconds)
  The start date of the period being invoiced. The default value is [current\_term\_start](/docs/api/subscriptions/subscription-object#current_term_start) .

- `date_to` (optional, timestamp(UTC) in seconds)
  The end date of the period being invoiced. The default value is [current\_term\_end](/docs/api/subscriptions/subscription-object#current_term_end) .

- `prorate` (optional, boolean)
  Whether the charges should be prorated according to the term specified by `date_from` and `date_to`. Should not be passed without `date_from` and `date_to` .

- `invoice_immediately` (optional, boolean)
  Only applicable when [Consolidated Invoicing](https://www.chargebee.com/docs/consolidated-invoicing.html ) is enabled for the customer. Set to `false` to leave the current term charge for the subscription as [unbilled](https://www.chargebee.com/docs/unbilled-charges.html ). Once you have done this for all suitable subscriptions of the customer, call [Create an invoice for unbilled charges](/docs/api/unbilled_charges/create-an-invoice-for-unbilled-charges) to invoice them.

## Returns

- `invoice` (Invoice object)
  Resource object representing invoice

- `unbilled_charges` (optional)
  Resource object representing unbilled\_charge
