# Collect payment for an invoice

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


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

Collects a specified amount of payment for an invoice, via a specified online payment method.

#### Offline payments[](#offline-payments)

When there is no payment method available, and if you wish to record an offline payment, use the [Record an offline payment API](/docs/api/invoices/record-an-invoice-payment) instead.

### Prerequisites & Constraints

-   The invoice `status` must be `payment_due`, `posted`, or `not_paid`.
-   The invoice `channel` must not be `app_store` or `play_store`.
-   The invoice's [`amount_to_collect`](/docs/api/invoices/invoice-object#amount_to_collect) must be greater than 0.
-   A valid `payment_source` must be associated with the customer.

### Impacts

**

Invoice

**

-   The invoice `status` changes to `paid` if the `amount_due` on the invoice becomes zero because of this payment. Otherwise, the `status` remains unchanged.

**

Payment Schedules

**

If a [`payment_schedule`](/docs/api/payment_schedules) exists for the invoice, then the `status` of the appropriate `schedule_entries[].status` is updated to `paid`.

#### Related APIs

Record an offline payment

## Sample Request

#### cURL

```bash
curl  https://{site}.chargebee.com/api/v2/invoices/__demo_inv__4/collect_payment \
     -u {site_api_key}:\
     -d payment_source_id="pm___test__8asyKSOcU2Zm5P"
```

#### .NET

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

ApiConfig.Configure("{site}","{site_api_key}");
EntityResult result = Invoice.CollectPayment("__demo_inv__4")
		.PaymentSourceId("pm___test__8asyKSOcU2Zm5P")
		.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"
)
func main() {
    chargebee.Configure("{site_api_key}","{site}");
    res,err := invoiceAction.CollectPayment("__demo_inv__4", &invoice.CollectPaymentRequestParams{
        PaymentSourceId : "pm___test__8asyKSOcU2Zm5P",
    }).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.InvoiceCollectPaymentRequest{
    PaymentSourceId : "pm___test__8asyKSOcU2Zm5P",
}
  res, err := client.Invoice.CollectPayment("__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;

public class Sample {

    public static void main(String args[]) throws IOException, Exception {
        Environment.configure("{site}", "{site_api_key}");
        Result result = Invoice.collectPayment("__demo_inv__4")
            .paymentSourceId("pm___test__8asyKSOcU2Zm5P")
            .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.InvoiceCollectPaymentParams;
import com.chargebee.v4.models.invoice.responses.InvoiceCollectPaymentResponse;
import com.chargebee.v4.models.transaction.Transaction;

public class InvoiceCollectPayment {

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

        InvoiceCollectPaymentParams params = InvoiceCollectPaymentParams.builder()
            .paymentSourceId("pm___test__8asyKSOcU2Zm5P")
            .build();

        InvoiceCollectPaymentResponse response = client
            .invoices()
            .collectPayment("__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.collectPayment("__demo_inv__4", {
        payment_source_id: "pm___test__8asyKSOcU2Zm5P"
    });

    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()->collectPayment("__demo_inv__4", [
    "payment_source_id" => "pm___test__8asyKSOcU2Zm5P"
]);
$invoice = $result->invoice;
$transaction = $result->transaction;
```

#### Python

```python
from chargebee import Chargebee

cb_client = Chargebee(api_key="{site_api_key}", site="{site}")
response = cb_client.Invoice.collect_payment("__demo_inv__4",
    cb_client.Invoice.CollectPaymentParams(
        payment_source_id="pm___test__8asyKSOcU2Zm5P"
    )
)
invoice = response.invoice
transaction = response.transaction
```

#### Ruby

```ruby
require 'chargebee'

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

result = ChargeBee::Invoice.collect_payment("__demo_inv__4",{
  :payment_source_id => "pm___test__8asyKSOcU2Zm5P"
})

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

## Sample Response

```json
{
  "invoice": {
    "adjustment_credit_notes": {},
    "amount_adjusted": 0,
    "amount_due": 0,
    "amount_paid": 1000,
    "amount_to_collect": 0,
    "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__8asxfSOcTzpo2s",
    "date": 1612796839,
    "deleted": false,
    "due_date": 1612796839,
    "dunning_attempts": [
      {
        "attempt": 0,
        "created_at": 1612796840,
        "dunning_type": "auto_collect",
        "retry_engine": "chargebee",
        "transaction_id": "txn___test__8asxfSOcU2Ku3v",
        "txn_amount": 1000,
        "txn_status": "failure"
      },
      {..}
    ],
    "dunning_status": "stopped",
    "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__8asxfSOcTzpo2s",
        "date_from": 1612796839,
        "date_to": 1612883239,
        "description": "Basic USD 2",
        "discount_amount": 0,
        "entity_id": "basic-USD2",
        "entity_type": "plan_item_price",
        "id": "li___test__8asxfSOcU2D83u",
        "is_taxed": false,
        "item_level_discount_amount": 0,
        "object": "line_item",
        "pricing_model": "per_unit",
        "quantity": 1,
        "subscription_id": "__test__8asxfSOcTzpo2s",
        "tax_amount": 0,
        "tax_exempt_reason": "tax_not_configured",
        "unit_amount": 1000
      },
      {..}
    ],
    "linked_orders": {},
    "linked_payments": [
      {
        "applied_amount": 1000,
        "applied_at": 1517490444,
        "txn_amount": 1000,
        "txn_date": 1517490444,
        "txn_id": "txn___test__8asyKSOcU2bm5W",
        "txn_status": "success"
      },
      {..}
    ],
    "net_term_days": 0,
    "object": "invoice",
    "paid_at": 1517490444,
    "price_type": "tax_exclusive",
    "recurring": true,
    "resource_version": 1517490444979,
    "round_off_amount": 0,
    "status": "paid",
    "sub_total": 1000,
    "subscription_id": "__test__8asxfSOcTzpo2s",
    "tax": 0,
    "term_finalized": true,
    "total": 1000,
    "updated_at": 1517490444,
    "write_off_amount": 0
  },
  "transaction": {
    "amount": 1000,
    "amount_unused": 0,
    "base_currency_code": "USD",
    "currency_code": "USD",
    "customer_id": "__test__8asxfSOcTzpo2s",
    "date": 1517490444,
    "deleted": false,
    "exchange_rate": 1,
    "gateway": "chargebee",
    "gateway_account_id": "gw___test__8asxfSOcTyhc1y",
    "id": "txn___test__8asyKSOcU2bm5W",
    "id_at_gateway": "cb___test__8asyKSOcU2bq5X",
    "linked_invoices": [
      {
        "applied_amount": 1000,
        "applied_at": 1517490444,
        "invoice_date": 1612796839,
        "invoice_id": "__demo_inv__4",
        "invoice_status": "paid",
        "invoice_total": 1000
      },
      {..}
    ],
    "linked_refunds": {},
    "masked_card_number": "***********0005",
    "object": "transaction",
    "payment_method": "card",
    "payment_source_id": "pm___test__8asyKSOcU2Zm5P",
    "resource_version": 1517490444979,
    "status": "success",
    "subscription_id": "__test__8asxfSOcTzpo2s",
    "type": "payment",
    "updated_at": 1517490444
  }
}
```

## URL Format

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

## Input Parameters

- `amount` (optional, in cents, min=1)
  Amount to be collected.
  
  **Constraints**
  
  -   Must be less than or equal to the `invoice.amount_to_collect` or the `transaction.amount` if `authorization_transaction_id` is passed, whichever is lesser.
  
  **Default value**
  
  -   When not passed, then `invoice.amount_to_collect` is assumed.

- `authorization_transaction_id` (optional, string, max chars=40)
  The `id` of the transaction that is used to authorize the payment. (The transaction's [`type`](/docs/api/transactions/transaction-object#type) must be `authorization`.)
  
  **Required if**
  
  -   `payment_source_id` is not passed.
  
  **Prerequisites**
  
  -   The `transaction.fraud_flag` must be `safe`.
  
  **Constraints**
  
  -   Applicable only for card payments via [Stripe](https://www.chargebee.com/docs/payments/2.0/payment-gateways-and-configuration/stripe).

- `payment_source_id` (optional, string, max chars=40)
  The `id` of a valid `payment_source` associated with the customer.
  
  **Required if**
  
  -   `authorization_transaction_id` is not passed.

- `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) .

- `payment_initiator` (optional, enumerated string)
  The initiator of this payment request. Sending this information can improve the success rate of the payment at the gateway.
  Possible enum values:
    - `customer`
      The payment was initiated by your customer.
    - `merchant`
      The payment was initiated by you (the merchant).

## Returns

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

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