# Record an invoice payment

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


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

Records an [offline payment](https://www.chargebee.com/docs/payments/2.0/offline-checkout/offline_payments) for an [invoice](/docs/api/invoices).

Use this API to record payments that you receive outside Chargebee, such as bank transfers or checks, so that you can reconcile them against invoices.

### Prerequisites & Constraints

-   The invoice [`status`](/docs/api/invoices/invoice-object#status) must be `payment_due`, `posted`, or `not_paid`.

### Impacts

**

Invoice

**

-   The `amount_due` on the invoice decreases by `transaction[amount]` when the `transaction[status]` is `success`.
-   The invoice `status` changes to `paid` if the `amount_due` on the invoice becomes zero because of this payment. Otherwise, the `status` remains unchanged.

**

Customer

**

If the recorded payment exceeds the invoice's `amount_due`, the excess is added to the customer's [`excess_payments`](/docs/api/customers/customer-object#excess_payments) balance.

### Implementation Notes

Before calling this API, ensure the following:

-   The invoice `status` must be `payment_due`, `posted`, or `not_paid`.

## Sample Request

#### cURL

```bash
curl  https://{site}.chargebee.com/api/v2/invoices/__demo_inv__4/record_payment \
     -u {site_api_key}:\
     -d comment="Payment received" \
     -d "transaction[amount]"=200 \
     -d "transaction[payment_method]"="BANK_TRANSFER" \
     -d "transaction[date]"=1612800517
```

#### .NET

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

ApiConfig.Configure("{site}","{site_api_key}");
EntityResult result = Invoice.RecordPayment("__demo_inv__4")
		.Comment("Payment received")
		.TransactionAmount(200)
		.TransactionPaymentMethod(PaymentMethodEnum.BankTransfer)
		.TransactionDate(1612800517)
		.Request();

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

#### 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"
    enum "github.com/chargebee/chargebee-go/v3/enum"
)
func main() {
    chargebee.Configure("{site_api_key}","{site}");
    res,err := invoiceAction.RecordPayment("__demo_inv__4", &invoice.RecordPaymentRequestParams{
        Comment : "Payment received",
        Transaction : &invoice.RecordPaymentTransactionParams{
            Amount : chargebee.Int64(200),
            PaymentMethod : enum.PaymentMethodBankTransfer,
            Date : chargebee.Int64(1612800517),
        },
    }).Request()
    if err != nil {
        fmt.Println(err)
    } else {
        Invoice := res.Invoice
        Transaction := res.Transaction
    }
}
```

#### 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.InvoiceRecordPaymentRequest{
    Comment : "Payment received",
    Transaction : &chargebee.InvoiceRecordPaymentTransaction{
        Amount : chargebee.Int64(200),
        PaymentMethod : chargebee.PaymentMethodBankTransfer,
        Date : chargebee.Int64(1612800517),
    },
}
  res, err := client.Invoice.RecordPayment("__demo_inv__4", req)
      if err != nil {
        fmt.Println(err)
    } else {
        Invoice := res.Invoice
        Transaction := res.Transaction
    }
}
```

#### Java

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

public class Sample {

    public static void main(String args[]) throws IOException, Exception {
        Environment.configure("{site}", "{site_api_key}");
        Result result = Invoice.recordPayment("__demo_inv__4")
            .comment("Payment received")
            .transactionAmount(200L)
            .transactionPaymentMethod(PaymentMethod.BANK_TRANSFER)
            .transactionDate(new Timestamp(1612800517L * 1000))
            .request();

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

#### Java

```java
import com.chargebee.v4.client.ChargebeeClient;
import com.chargebee.v4.models.invoice.Invoice;
import com.chargebee.v4.models.invoice.params.InvoiceRecordPaymentParams;
import com.chargebee.v4.models.invoice.responses.InvoiceRecordPaymentResponse;
import com.chargebee.v4.models.transaction.Transaction;
import java.sql.Timestamp;

public class InvoiceRecordPayment {

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

        InvoiceRecordPaymentParams.TransactionParams transactionParams =
            InvoiceRecordPaymentParams.TransactionParams.builder()
                .amount(200L)
                .paymentMethod(InvoiceRecordPaymentParams.TransactionParams.PaymentMethod.BANK_TRANSFER)
                .date(new Timestamp(1612800517L * 1000))
                .build();

        InvoiceRecordPaymentParams params = InvoiceRecordPaymentParams.builder()
            .comment("Payment received")
            .transaction(transactionParams)
            .build();

        InvoiceRecordPaymentResponse response = client
            .invoices()
            .recordPayment("__demo_inv__4", params);

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

#### Node.js

```node
import Chargebee from "chargebee";

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

try {
    const result = await chargebee.invoice.recordPayment("__demo_inv__4", {
        comment: "Payment received",
        transaction: {
            amount: 200,
            payment_method: "bank_transfer",
            date: 1612800517
        }
    });

    console.log(result);
    const invoice = result.invoice;
    const transaction = result.transaction;
} 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()->recordPayment("__demo_inv__4", [
    "comment" => "Payment received",
    "transaction" => [
        "amount" => 200,
        "payment_method" => "bank_transfer",
        "date" => 1612800517
    ]
]);
$invoice = $result->invoice;
$transaction = $result->transaction;
```

#### Python

```python
import chargebee
from chargebee import Chargebee

cb_client = Chargebee(api_key="{site_api_key}", site="{site}")
response = cb_client.Invoice.record_payment("__demo_inv__4",
    cb_client.Invoice.RecordPaymentParams(
        comment="Payment received",
        transaction=cb_client.Invoice.RecordPaymentTransactionParams(
            amount=200,
            payment_method=chargebee.PaymentMethod.BANK_TRANSFER,
            date=1612800517
        )
    )
)
invoice = response.invoice
transaction = response.transaction
```

#### Ruby

```ruby
require 'chargebee'

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

result = ChargeBee::Invoice.record_payment("__demo_inv__4",{
  :comment => "Payment received",
  :transaction => {
    :amount => 200,
    :payment_method => "BANK_TRANSFER",
    :date => 1612800517
  }
})

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

## Sample Response

```json
{
  "invoice": {
    "adjustment_credit_notes": {},
    "amount_adjusted": 0,
    "amount_due": 800,
    "amount_paid": 200,
    "amount_to_collect": 800,
    "applied_credits": {},
    "base_currency_code": "USD",
    "billing_address": {
      "first_name": "Rachel",
      "last_name": "Green",
      "object": "billing_address",
      "validation_status": "not_validated"
    },
    "credits_applied": 0,
    "currency_code": "USD",
    "customer_id": "__test__8aswoSOcUJgJ2s",
    "date": 1612796914,
    "deleted": false,
    "due_date": 1612796914,
    "dunning_attempts": [
      {
        "attempt": 0,
        "created_at": 1612796915,
        "dunning_type": "auto_collect",
        "retry_engine": "chargebee",
        "transaction_id": "txn___test__8aswoSOcUM0M3v",
        "txn_amount": 1000,
        "txn_status": "failure"
      },
      {..}
    ],
    "dunning_status": "in_progress",
    "exchange_rate": 1,
    "first_invoice": false,
    "has_advance_charges": false,
    "id": "__demo_inv__4",
    "is_gifted": false,
    "issued_credit_notes": {},
    "line_items": [
      {
        "amount": 1000,
        "customer_id": "__test__8aswoSOcUJgJ2s",
        "date_from": 1612796914,
        "date_to": 1612883314,
        "description": "Basic USD 2",
        "discount_amount": 0,
        "entity_id": "basic-USD2",
        "entity_type": "plan_item_price",
        "id": "li___test__8aswoSOcULwP3u",
        "is_taxed": false,
        "item_level_discount_amount": 0,
        "object": "line_item",
        "pricing_model": "per_unit",
        "quantity": 1,
        "subscription_id": "__test__8aswoSOcUJgJ2s",
        "tax_amount": 0,
        "tax_exempt_reason": "tax_not_configured",
        "unit_amount": 1000
      },
      {..}
    ],
    "linked_orders": {},
    "linked_payments": [
      {
        "applied_amount": 1000,
        "applied_at": 1612796915,
        "txn_amount": 1000,
        "txn_date": 1612796915,
        "txn_id": "txn___test__8aswoSOcUM0M3v",
        "txn_status": "failure"
      },
      {..}
    ],
    "net_term_days": 0,
    "next_retry_at": 1612883315,
    "object": "invoice",
    "price_type": "tax_exclusive",
    "recurring": true,
    "resource_version": 1517490520418,
    "round_off_amount": 0,
    "status": "payment_due",
    "sub_total": 1000,
    "subscription_id": "__test__8aswoSOcUJgJ2s",
    "tax": 0,
    "term_finalized": true,
    "total": 1000,
    "updated_at": 1517490520,
    "write_off_amount": 0
  },
  "transaction": {
    "amount": 200,
    "amount_unused": 0,
    "base_currency_code": "USD",
    "currency_code": "USD",
    "customer_id": "__test__8aswoSOcUJgJ2s",
    "date": 1612800517,
    "deleted": false,
    "exchange_rate": 1,
    "gateway": "not_applicable",
    "id": "txn___test__8asyKSOcUMEY6O",
    "linked_invoices": [
      {
        "applied_amount": 200,
        "applied_at": 1517490520,
        "invoice_date": 1612796914,
        "invoice_id": "__demo_inv__4",
        "invoice_status": "payment_due",
        "invoice_total": 1000
      },
      {..}
    ],
    "linked_refunds": {},
    "object": "transaction",
    "payment_method": "bank_transfer",
    "resource_version": 1517490520417,
    "status": "success",
    "subscription_id": "__test__8aswoSOcUJgJ2s",
    "type": "payment",
    "updated_at": 1517490520
  }
}
```

## URL Format

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

## Input Parameters

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

- `transaction` (optional, in cents)
  Parameters for transaction
  - `amount` (optional, in cents, min=0)
    The payment transaction amount.
    
    **Default value**
    
    -   If not specified, the [`amount_due`](/docs/api/invoices/invoice-object#amount_due) on the invoice is considered as the payment amount.
  - `payment_method` (required, enumerated string)
    The payment method of this transaction
    Possible enum values:
      - `cash`
        Cash
      - `check`
        Check
      - `bank_transfer`
        Bank Transfer
      - `other`
        Payment Methods other than the above types
      - `custom`
        Custom payment method.
        
        **Prerequisite**
        
        -   [Custom payment methods](https://app.chargebee.com/login?forward=https://app.chargebee.com/request_access/custom-payment-methods&ref=feature) must be enabled in Chargebee Billing.
      - `dana`
      - `touch_n_go`
      - `tamara`
      - `qpay`
      - `ovo`
      - `momo`
      - `mercado_pago`
      - `nequi`
      - `nupay`
      - `picpay`
      - `thai_qr`
      - `blik`
      - `fpx`
      - `wero`
      - `p24`
      - `affirm_pay`
      - `rakuten_pay`
  - `reference_number` (optional, string, max chars=100)
    The reference number for this transaction. e.g check number in case of 'check' payments.
  - `custom_payment_method_id` (optional, string, max chars=50)
    A unique identifier for the custom payment method of this transaction.
    
    **Prerequisite**
    
    -   The `transaction[payment_method]` is `custom`.
  - `id_at_gateway` (optional, string, max chars=100)
    The id with which this transaction is referred in gateway.
  - `status` (optional, enumerated string)
    The status of this transaction.
    Possible enum values:
      - `success`
        The transaction was successful.
        
        **Impacts**
        
        -   The `amount_due` on the invoice is decreased by the `transaction[amount]`.
        -   If the `transaction[amount]` is greater than the `amount_due`, the excess amount is added to the customer's [`excess_payments`](/docs/api/customers/customer-object#excess_payments) balance.
      - `failure`
        Transaction failed. Pass the `transaction[error_code]` and `transaction[error_text]` to identify the reason for failure. The `amount_due` on the invoice or the customer's `excess_payments` balance is not affected when this status is set.
      - `late_failure`
        Indicates that a previously successful payment transaction has failed due to a late failure notification from the payment gateway. Common reasons include insufficient funds or a closed bank account. Pass the `transaction[error_code]` and `transaction[error_text]` to identify the reason for failure. The `amount_due` on the invoice or the customer's `excess_payments` balance is not affected when this status is set.
  - `date` (optional, timestamp(UTC) in seconds)
    Indicates when this transaction occurred.
  - `error_code` (optional, string, max chars=100)
    Error code for the transaction failure. This is typically set by the payment gateway when a transaction fails.
    
    **Prerequisite**
    
    -   The `transaction[status]` is `failure` or `late_failure`.
  - `error_text` (optional, string, max chars=65k)
    Error message for transaction failure. This is typically set by the payment gateway when a transaction fails.
    
    **Prerequisite**
    
    -   The `transaction[status]` is `failure` or `late_failure`.

## Returns

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

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