# Apply credits for an invoice

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


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

Applies a customer's [refundable credits](/docs/api/customers/customer-object#refundable_credits) to a specified invoice.

You can either specify the credit notes to be applied, or let Chargebee apply the available credit notes automatically.

### Prerequisites & Constraints

-   The customer must have refundable credits available.
-   The invoice `status` must be `not_paid`, `payment_due`, or `posted`.

### Impacts

**

Invoice

**

-   The `amount_due` decreases by the amount of credits applied.
-   The invoice `status`:
    -   changes to `paid` if the applied credits fully cover the amount due.
    -   remains unchanged if the applied credits only partially cover the amount due.

**

Credit Notes

**

The credit note `status`:

-   changes to `refunded` if the entire `credit_note.amount_available` is applied to the invoice.
-   remains `refund_due` if only part of the `credit_note.amount_available` is applied.

### Implementation Notes

Before calling this API, make sure the following conditions are met:

-   `customer.refundable_credits` is non-zero.
-   The invoice `status` is `not_paid`, `payment_due`, or `posted`.
-   The `credit_note.customer_id` matches the `invoice.customer_id`.

#### Related APIs

Apply payments for an invoice

Collect payment for an invoice

Record an invoice payment

## Sample Request

#### cURL

```bash
curl  https://{site}.chargebee.com/api/v2/invoices/__demo_inv__2/apply_credits \
     -X POST  \
     -u {site_api_key}:
```

#### .NET

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

ApiConfig.Configure("{site}","{site_api_key}");
EntityResult result = Invoice.ApplyCredits("__demo_inv__2").Request();

Invoice invoice = result.Invoice;
```

#### Go

```go
package main
import (
    "fmt"
    "github.com/chargebee/chargebee-go/v3"
    invoiceAction "github.com/chargebee/chargebee-go/v3/actions/invoice"
)
func main() {
    chargebee.Configure("{site_api_key}","{site}");
    res,err := invoiceAction.ApplyCredits("__demo_inv__2", nil).Request()
    if err != nil {
        fmt.Println(err)
    } else {
        Invoice := res.Invoice
    }
}
```

#### 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.InvoiceApplyCreditsRequest{}
  res, err := client.Invoice.ApplyCredits("__demo_inv__2", req)
      if err != nil {
        fmt.Println(err)
    } else {
        Invoice := res.Invoice
    }
}
```

#### Java

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

public class Sample {

    public static void main(String args[]) throws IOException, Exception {
        Environment.configure("{site}", "{site_api_key}");
        Result result = Invoice.applyCredits("__demo_inv__2").request();

        Invoice invoice = result.invoice();
    }
}
```

#### Java

```java
import com.chargebee.v4.client.ChargebeeClient;
import com.chargebee.v4.models.invoice.Invoice;
import com.chargebee.v4.models.invoice.params.InvoiceApplyCreditsParams;
import com.chargebee.v4.models.invoice.responses.InvoiceApplyCreditsResponse;

public class InvoiceApplyCredits {

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

        InvoiceApplyCreditsResponse response = client.invoices().applyCredits("__demo_inv__2");

        Invoice invoice = response.getInvoice();
    }
}
```

#### Node.js

```node
import Chargebee from "chargebee";

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

try {
    const result = await chargebee.invoice.applyCredits("__demo_inv__2");

    console.log(result);
    const invoice = result.invoice;
} 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->invoice()->applyCredits("__demo_inv__2");
$invoice = $result->invoice;
```

#### Python

```python
from chargebee import Chargebee

cb_client = Chargebee(api_key="{site_api_key}", site="{site}")
response = cb_client.Invoice.apply_credits("__demo_inv__2")
invoice = response.invoice
```

#### Ruby

```ruby
require 'chargebee'

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

result = ChargeBee::Invoice.apply_credits("__demo_inv__2")

invoice = result.invoice
```

## Sample Response

```json
{
  "invoice": {
    "adjustment_credit_notes": {},
    "amount_adjusted": 0,
    "amount_due": 0,
    "amount_paid": 0,
    "amount_to_collect": 0,
    "applied_credits": [
      {
        "applied_amount": 2000,
        "applied_at": 1612962254,
        "cn_create_reason_code": "Service Unsatisfactory",
        "cn_date": 1612962254,
        "cn_id": "__demo_cn__1",
        "cn_reason_code": "service_unsatisfactory",
        "cn_status": "refund_due"
      },
      {..}
    ],
    "base_currency_code": "USD",
    "billing_address": {
      "first_name": "John",
      "last_name": "Mathew",
      "object": "billing_address",
      "validation_status": "not_validated"
    },
    "credits_applied": 2000,
    "currency_code": "USD",
    "customer_id": "__test__8asyKSOcTDt4N",
    "date": 1612962253,
    "deleted": false,
    "due_date": 1612962253,
    "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": 1000,
        "customer_id": "__test__8asyKSOcTDt4N",
        "date_from": 1612962253,
        "date_to": 1615381453,
        "description": "basic USD",
        "discount_amount": 0,
        "entity_id": "basic-USD",
        "entity_type": "plan_item_price",
        "id": "li___test__8asyKSOcTErGh",
        "is_taxed": false,
        "item_level_discount_amount": 0,
        "object": "line_item",
        "pricing_model": "per_unit",
        "quantity": 1,
        "subscription_id": "__test__8asyKSOcTEo4f",
        "tax_amount": 0,
        "tax_exempt_reason": "tax_not_configured",
        "unit_amount": 1000
      },
      {..}
    ],
    "linked_orders": {},
    "linked_payments": {},
    "net_term_days": 0,
    "new_sales_amount": 2000,
    "object": "invoice",
    "paid_at": 1612962254,
    "price_type": "tax_exclusive",
    "recurring": true,
    "resource_version": 1612962254000,
    "round_off_amount": 0,
    "status": "paid",
    "sub_total": 2000,
    "subscription_id": "__test__8asyKSOcTEo4f",
    "tax": 0,
    "term_finalized": true,
    "total": 2000,
    "updated_at": 1612962254,
    "write_off_amount": 0
  }
}
```

## URL Format

**POST** https://[site].chargebee.com/api/v2/invoices/{invoice-id}/apply_credits

## Input Parameters

- `comment` (optional, string, max chars=300)
  An internal [comment](/docs/api/comments) to be added for this operation, to the invoice. This comment is displayed on the Chargebee UI. It is not displayed on any customer-facing [Hosted Page](/docs/api/hosted_pages) or any document such as the [Invoice PDF](/docs/api/invoices/retrieve-invoice-as-pdf) .

- `credit_notes` (optional, array)
  Parameters for credit\_notes
  - `id` (optional, string, max chars=50)
    The ID of the credit note to be applied to the invoice.
    
    **Constraints**
    
    -   `credit_note.type` must be `refundable`.
    -   The `credit_note.customer_id` must always be the same as `invoice.customer_id` even if `invoice.payment_owner` is different.
    
    **Default behavior**
    
    When the parameter is not passed, [available refundable credits](/docs/api/customers/customer-object#refundable_credits) with the customer are applied to the invoice.

## Returns

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