# Refund an invoice

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


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

[Asynchronous](/docs/api/async_response/async-response-object)

Refunds online payments or online refundable credit notes applied to an invoice.

If multiple [transactions](/docs/api/invoices/invoice-object#linked_payments) or [credit note allocations](/docs/api/invoices/invoice-object#applied_credits) are associated with the invoice, the refund can be processed only for one transaction or allocation at a time. The refund amount is returned to the customer through the [`payment_source`](/docs/api/payment_sources) associated with the transaction.

For recording offline refunds, including those for [`linked_taxes_withheld`](/docs/api/invoices/invoice-object#linked_taxes_withheld), use the [Record refund for an invoice](/docs/api/invoices/record-refund-for-an-invoice) API.

### Prerequisites & Constraints

-   The invoice must have a [refundable amount](/docs/api/invoices/invoice-object#refundable-amount) derived from online transactions.
-   There must be no `linked_payments` with a status of `in-progress`.
-   Partial refunds can be processed only if the associated payment gateway supports partial refund operations.
-   Ensure that all parameter-level requirements are met.

### Impacts

**Invoice**

-   The invoice status does **not** change after this operation.

**Credit note**

-   A refundable [credit note](/docs/api/credit_notes) is created for the invoice to capture the refund details.

### Implementation Notes

Before calling this API, ensure the following:

-   The invoice must have a refundable amount derived from online transactions.  
    The refundable amount is calculated as:  
    `linked_payments[].amount` for online payments + `applied_credits[].applied_amount` - `issued_credit_notes[].cn_total`
-   There must be no `linked_payments` with a status of `in-progress`.
-   All parameter-level requirements are met.

#### Related APIs

Record refund for an invoice

## Sample Request

#### cURL

```bash
curl  https://{site}.chargebee.com/api/v2/invoices/__demo_inv__14/refund \
     -u {site_api_key}:\
     -d refund_amount=500 \
     -d "credit_note[reason_code]"="SERVICE_UNSATISFACTORY"
```

#### .NET

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

ApiConfig.Configure("{site}","{site_api_key}");
EntityResult result = Invoice.Refund("__demo_inv__14")
		.RefundAmount(500)
		.CreditNoteReasonCode(CreditNote.ReasonCodeEnum.ServiceUnsatisfactory)
		.Request();

Invoice invoice = result.Invoice;
Transaction transaction = result.Transaction;
CreditNote creditNote = result.CreditNote;
```

#### Go

```go
package main
import (
    "fmt"
    "github.com/chargebee/chargebee-go/v3"
    invoiceAction "github.com/chargebee/chargebee-go/v3/actions/invoice"
    "github.com/chargebee/chargebee-go/v3/models/invoice"
    creditNoteEnum "github.com/chargebee/chargebee-go/v3/models/creditnote/enum"
)
func main() {
    chargebee.Configure("{site_api_key}","{site}");
    res,err := invoiceAction.Refund("__demo_inv__14", &invoice.RefundRequestParams{
        RefundAmount : chargebee.Int64(500),
        CreditNote : &invoice.RefundCreditNoteParams{
            ReasonCode : creditNoteEnum.ReasonCodeServiceUnsatisfactory,
        },
    }).Request()
    if err != nil {
        fmt.Println(err)
    } else {
        Invoice := res.Invoice
        Transaction := res.Transaction
        CreditNote := res.CreditNote
    }
}
```

#### 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.InvoiceRefundRequest{
    RefundAmount : chargebee.Int64(500),
    CreditNote : &chargebee.InvoiceRefundCreditNote{
        ReasonCode : chargebee.CreditNoteReasonCodeServiceUnsatisfactory,
    },
}
  res, err := client.Invoice.Refund("__demo_inv__14", req)
      if err != nil {
        fmt.Println(err)
    } else {
        Invoice := res.Invoice
        Transaction := res.Transaction
        CreditNote := res.CreditNote
    }
}
```

#### 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.refund("__demo_inv__14")
            .refundAmount(500L)
            .creditNoteReasonCode(CreditNote.ReasonCode.SERVICE_UNSATISFACTORY)
            .request();

        Invoice invoice = result.invoice();
        Transaction transaction = result.transaction();
        CreditNote creditNote = result.creditNote();
    }
}
```

#### Java

```java
import com.chargebee.v4.client.ChargebeeClient;
import com.chargebee.v4.models.creditNote.CreditNote;
import com.chargebee.v4.models.invoice.Invoice;
import com.chargebee.v4.models.invoice.params.InvoiceRefundParams;
import com.chargebee.v4.models.invoice.responses.InvoiceRefundResponse;
import com.chargebee.v4.models.transaction.Transaction;

public class InvoiceRefund {

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

        InvoiceRefundParams.CreditNoteParams creditNoteParams =
            InvoiceRefundParams.CreditNoteParams.builder()
                .reasonCode(InvoiceRefundParams.CreditNoteParams.ReasonCode.SERVICE_UNSATISFACTORY)
                .build();

        InvoiceRefundParams params = InvoiceRefundParams.builder()
            .refundAmount(500L)
            .creditNote(creditNoteParams)
            .build();

        InvoiceRefundResponse response = client
            .invoices()
            .refund("__demo_inv__14", params);

        Invoice invoice = response.getInvoice();
        Transaction transaction = response.getTransaction();
        CreditNote creditNote = response.getCreditNote();
    }
}
```

#### Node.js

```node
import Chargebee from "chargebee";

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

try {
    const result = await chargebee.invoice.refund("__demo_inv__14", {
        refund_amount: 500,
        credit_note: {
            reason_code: "service_unsatisfactory"
        }
    });

    console.log(result);
    const invoice = result.invoice;
    const transaction = result.transaction;
    const creditNote = result.credit_note;
} 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()->refund("__demo_inv__14", [
    "refund_amount" => 500,
    "credit_note" => [
        "reason_code" => "service_unsatisfactory"
    ]
]);
$invoice = $result->invoice;
$transaction = $result->transaction;
$creditNote = $result->credit_note;
```

#### Python

```python
import chargebee
from chargebee import Chargebee

cb_client = Chargebee(api_key="{site_api_key}", site="{site}")
response = cb_client.Invoice.refund("__demo_inv__14",
    cb_client.Invoice.RefundParams(
        refund_amount=500,
        credit_note=cb_client.Invoice.RefundCreditNoteParams(
            reason_code=chargebee.CreditNote.ReasonCode.SERVICE_UNSATISFACTORY
        )
    )
)
invoice = response.invoice
transaction = response.transaction
credit_note = response.credit_note
```

#### Ruby

```ruby
require 'chargebee'

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

result = ChargeBee::Invoice.refund("__demo_inv__14",{
  :refund_amount => 500,
  :credit_note => {
    :reason_code => "SERVICE_UNSATISFACTORY"
  }
})

invoice = result.invoice
transaction = result.transaction
credit_note = result.credit_note
```

## Sample Response

```json
{
  "credit_note": {
    "allocations": {},
    "amount_allocated": 0,
    "amount_available": 0,
    "amount_refunded": 500,
    "base_currency_code": "USD",
    "create_reason_code": "Service Unsatisfactory",
    "currency_code": "USD",
    "customer_id": "__test__8asyKSOcTKEe3L",
    "date": 1517490275,
    "deleted": false,
    "exchange_rate": 1,
    "fractional_correction": 0,
    "id": "__demo_cn__4",
    "line_item_discounts": {},
    "line_item_taxes": {},
    "line_items": [
      {
        "amount": 500,
        "customer_id": "__test__8asyKSOcTKEe3L",
        "date_from": 1517490275,
        "date_to": 1517490275,
        "description": "SSL Charge USD Monthly",
        "discount_amount": 0,
        "entity_id": "ssl-charge-USD",
        "entity_type": "charge_item_price",
        "id": "li___test__8asyKSOcTKQc3b",
        "is_taxed": false,
        "item_level_discount_amount": 0,
        "object": "line_item",
        "pricing_model": "flat_fee",
        "quantity": 1,
        "tax_amount": 0,
        "tax_exempt_reason": "tax_not_configured",
        "unit_amount": 500
      },
      {..}
    ],
    "linked_refunds": [
      {
        "applied_amount": 500,
        "applied_at": 1517490275,
        "txn_amount": 500,
        "txn_date": 1517490275,
        "txn_id": "txn___test__8asyKSOcTKQE3Z",
        "txn_status": "success"
      },
      {..}
    ],
    "object": "credit_note",
    "price_type": "tax_exclusive",
    "reason_code": "service_unsatisfactory",
    "reference_invoice_id": "__demo_inv__14",
    "refunded_at": 1517490275,
    "resource_version": 1517490275164,
    "round_off_amount": 0,
    "status": "refunded",
    "sub_total": 500,
    "taxes": {},
    "total": 500,
    "type": "refundable",
    "updated_at": 1517490275
  },
  "invoice": {
    "adjustment_credit_notes": {},
    "amount_adjusted": 0,
    "amount_due": 0,
    "amount_paid": 500,
    "amount_to_collect": 0,
    "applied_credits": {},
    "base_currency_code": "USD",
    "billing_address": {
      "first_name": "John",
      "last_name": "Mathew",
      "object": "billing_address",
      "validation_status": "not_validated"
    },
    "credits_applied": 0,
    "currency_code": "USD",
    "customer_id": "__test__8asyKSOcTKEe3L",
    "date": 1517490274,
    "deleted": false,
    "due_date": 1517490274,
    "dunning_attempts": {},
    "exchange_rate": 1,
    "first_invoice": true,
    "has_advance_charges": false,
    "id": "__demo_inv__14",
    "is_gifted": false,
    "issued_credit_notes": [
      {
        "cn_create_reason_code": "Service Unsatisfactory",
        "cn_date": 1517490275,
        "cn_id": "__demo_cn__4",
        "cn_reason_code": "service_unsatisfactory",
        "cn_status": "refunded",
        "cn_total": 500
      },
      {..}
    ],
    "line_items": [
      {
        "amount": 500,
        "customer_id": "__test__8asyKSOcTKEe3L",
        "date_from": 1517490274,
        "date_to": 1517490274,
        "description": "SSL Charge USD Monthly",
        "discount_amount": 0,
        "entity_id": "ssl-charge-USD",
        "entity_type": "charge_item_price",
        "id": "li___test__8asyKSOcTKKc3T",
        "is_taxed": false,
        "item_level_discount_amount": 0,
        "object": "line_item",
        "pricing_model": "flat_fee",
        "quantity": 1,
        "tax_amount": 0,
        "tax_exempt_reason": "tax_not_configured",
        "unit_amount": 500
      },
      {..}
    ],
    "linked_orders": {},
    "linked_payments": [
      {
        "applied_amount": 500,
        "applied_at": 1517490274,
        "txn_amount": 500,
        "txn_date": 1517490274,
        "txn_id": "txn___test__8asyKSOcTKOR3U",
        "txn_status": "success"
      },
      {..}
    ],
    "net_term_days": 0,
    "new_sales_amount": 500,
    "object": "invoice",
    "paid_at": 1517490274,
    "price_type": "tax_exclusive",
    "recurring": false,
    "resource_version": 1517490275163,
    "round_off_amount": 0,
    "status": "paid",
    "sub_total": 500,
    "tax": 0,
    "term_finalized": true,
    "total": 500,
    "updated_at": 1517490275,
    "write_off_amount": 0
  },
  "transaction": {
    "amount": 500,
    "base_currency_code": "USD",
    "currency_code": "USD",
    "customer_id": "__test__8asyKSOcTKEe3L",
    "date": 1517490275,
    "deleted": false,
    "exchange_rate": 1,
    "gateway": "chargebee",
    "gateway_account_id": "gw___test__8aspaSOcTCvD1y",
    "id": "txn___test__8asyKSOcTKQE3Z",
    "id_at_gateway": "cb___test__8asyKSOcTKOV3V",
    "linked_credit_notes": [
      {
        "applied_amount": 500,
        "applied_at": 1517490275,
        "cn_create_reason_code": "Service Unsatisfactory",
        "cn_date": 1517490275,
        "cn_id": "__demo_cn__4",
        "cn_reason_code": "service_unsatisfactory",
        "cn_reference_invoice_id": "__demo_inv__14",
        "cn_status": "refunded",
        "cn_total": 500
      },
      {..}
    ],
    "masked_card_number": "***********0005",
    "object": "transaction",
    "payment_method": "card",
    "payment_source_id": "pm___test__8asyKSOcTKF63N",
    "refunded_txn_id": "txn___test__8asyKSOcTKOR3U",
    "resource_version": 1517490275165,
    "status": "success",
    "type": "refund",
    "updated_at": 1517490275
  }
}
```

## URL Format

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

## Input Parameters

- `refund_amount` (optional, in cents, min=1)
  The amount to be refunded.
  
  **Constraints**
  
  -   If multiple [transactions](/docs/api/invoices/invoice-object#linked_payments) or [credit note allocations](/docs/api/invoices/invoice-object#applied_credits) are associated with the invoice, the refund can be processed only for one transaction or allocation at a time.
  -   Offline refunds, including those for [`linked_taxes_withheld`](/docs/api/invoices/invoice-object#linked_taxes_withheld), cannot be refunded via this operation. Use the [Record refund for an invoice](/docs/api/invoices/record-refund-for-an-invoice) API instead.
  
  **Default behavior**
  
  -   If not specified, the total refundable amount for this invoice derived from online transactions is implied. The refundable amount is calculated as: (the total amount paid on the invoice via online payments) + (allocations on the invoice from refundable credit notes that were created from online payments) - (any amount already refunded from the invoice).

- `comment` (optional, string, max chars=300)
  Comment, if any, on the refund.

- `customer_notes` (optional, string, max chars=2000)
  The Customer Notes to be filled in the Credit Notes created to capture this refund detail.

- `credit_note` (optional, enumerated string)
  Parameters for credit\_note
  - `reason_code` (optional, enumerated string)
    The reason for issuing this Credit Note. The following reason codes are supported now\[Deprecated; use the [create\_reason\_code](/docs/api/credit_notes/credit_note-object#create_reason_code) parameter instead\]
    Possible enum values:
      - `product_unsatisfactory`
        Product Unsatisfactory
      - `service_unsatisfactory`
        Service Unsatisfactory
      - `order_change`
        Order Change
      - `order_cancellation`
        Order Cancellation
      - `waiver`
        Waiver
      - `other`
        Can be set when none of the above reason codes are applicable
  - `create_reason_code` (optional, string, max chars=100)
    Reason code for creating the credit note. Must be one from a list of reason codes set in the Chargebee app in Settings > Configure Chargebee > Reason Codes > Credit Notes > Create Credit Note. The codes are case-sensitive

## Returns

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

- `transaction` (Transaction object)
  Resource object representing transaction

- `credit_note` (Credit note object)
  Resource object representing credit\_note
