> ## Documentation Index
> Fetch the complete documentation index at: https://docs.wepayout.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Cancel Charge

> Request the cancellation of Payins of type boleto or pix

# Cancel Charge

Request the cancellation of Payins of type `boleto` or `pix`.

## Eligibility

<Warning>
  **Cancellation Restrictions**:

  * Only Payins with `status = created` can be canceled
  * Payin in any other status cannot be canceled
</Warning>

## Minimum Time Before Cancellation

* **pix**: at least 5 minutes after creation
* **boleto**: at least 30 minutes after creation

## Behavior After Cancellation Request

* **pix**: canceled instantly
* **boleto**: requires at least 1 day to move from `drop_requested` to `canceled`, since the process depends on confirmation from the payment processor

## Path Parameters

<ParamField path="cashInId" type="string" required>
  The ID of the payin (charge) to cancel.

  Example: `32458`
</ParamField>

## Request Body

<ParamField body="cashInId" type="string" required>
  The ID of the payin to cancel (must match the path parameter).
</ParamField>

## Response

<ResponseField name="status" type="boolean">
  Indicates if the cancellation request was successful.
</ResponseField>

<ResponseField name="data" type="object">
  Response data object.

  <Expandable title="Data">
    <ResponseField name="message" type="string">
      Confirmation message about the cancellation request.
    </ResponseField>
  </Expandable>
</ResponseField>

## Request Example

<CodeGroup>
  ```bash cURL theme={null}
  curl --request DELETE \
    --url https://api.sandbox.wepayout.com.br/v1/payin/payments/32457/request-cancel \
    --header 'Accept: application/json' \
    --header 'Authorization: Bearer 123' \
    --header 'Content-Type: application/json' \
    --data '{
      "cashInId": "32457"
    }'
  ```

  ```javascript JavaScript theme={null}
  async function cancelCharge(cashInId) {
    const response = await fetch(
      `https://api.sandbox.wepayout.com.br/v1/payin/payments/${cashInId}/request-cancel`,
      {
        method: 'DELETE',
        headers: {
          'Accept': 'application/json',
          'Authorization': 'Bearer 123',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          cashInId: cashInId.toString()
        })
      }
    );
    
    return await response.json();
  }

  // Usage
  const result = await cancelCharge(32457);
  console.log('Cancellation result:', result);
  ```

  ```python Python theme={null}
  import requests

  def cancel_charge(cash_in_id):
      url = f'https://api.sandbox.wepayout.com.br/v1/payin/payments/{cash_in_id}/request-cancel'
      headers = {
          'Accept': 'application/json',
          'Authorization': 'Bearer 123',
          'Content-Type': 'application/json'
      }
      data = {
          'cashInId': str(cash_in_id)
      }
      
      response = requests.delete(url, headers=headers, json=data)
      return response.json()

  # Usage
  result = cancel_charge(32457)
  print('Cancellation result:', result)
  ```
</CodeGroup>

<ResponseExample>
  ```json 200 OK theme={null}
  {
    "status": true,
    "data": {
      "message": "Cancellation request submitted successfully"
    }
  }
  ```

  ```json 422 Unprocessable Entity theme={null}
  {
    "status": false,
    "message": "Cannot cancel charge. Status must be 'created'"
  }
  ```
</ResponseExample>

## Use Cases

<AccordionGroup>
  <Accordion title="Cancel Pix Charge">
    Cancel a Pix charge that hasn't been paid yet:

    ```javascript theme={null}
    async function cancelPixCharge(chargeId) {
      // First, check if the charge is eligible for cancellation
      const charge = await getChargeById(chargeId);
      
      if (charge.payment_method !== 'pix') {
        throw new Error('Not a Pix charge');
      }
      
      if (charge.status.id !== 1) {
        throw new Error('Charge status must be "created" to cancel');
      }
      
      // Check if 5 minutes have passed since creation
      const createdAt = new Date(charge.created_at);
      const now = new Date();
      const minutesPassed = (now - createdAt) / 1000 / 60;
      
      if (minutesPassed < 5) {
        throw new Error('Must wait at least 5 minutes before canceling Pix');
      }
      
      // Cancel the charge
      const result = await cancelCharge(chargeId);
      return result;
    }
    ```
  </Accordion>

  <Accordion title="Cancel Boleto Charge">
    Cancel a Boleto charge that hasn't been paid:

    ```javascript theme={null}
    async function cancelBoletoCharge(chargeId) {
      const charge = await getChargeById(chargeId);
      
      if (charge.payment_method !== 'boleto') {
        throw new Error('Not a Boleto charge');
      }
      
      if (charge.status.id !== 1) {
        throw new Error('Charge status must be "created" to cancel');
      }
      
      // Check if 30 minutes have passed since creation
      const createdAt = new Date(charge.created_at);
      const now = new Date();
      const minutesPassed = (now - createdAt) / 1000 / 60;
      
      if (minutesPassed < 30) {
        throw new Error('Must wait at least 30 minutes before canceling Boleto');
      }
      
      // Cancel the charge
      const result = await cancelCharge(chargeId);
      
      console.log('Boleto cancellation requested.');
      console.log('Note: It may take at least 1 day for the status to change to "canceled"');
      
      return result;
    }
    ```
  </Accordion>

  <Accordion title="Batch Cancel Charges">
    Cancel multiple charges at once:

    ```javascript theme={null}
    async function batchCancelCharges(chargeIds) {
      const results = [];
      
      for (const chargeId of chargeIds) {
        try {
          const result = await cancelCharge(chargeId);
          results.push({
            chargeId,
            success: true,
            result
          });
        } catch (error) {
          results.push({
            chargeId,
            success: false,
            error: error.message
          });
        }
        
        // Add delay to avoid rate limiting
        await new Promise(resolve => setTimeout(resolve, 100));
      }
      
      return results;
    }

    // Usage
    const chargesToCancel = [32457, 32458, 32459];
    const results = await batchCancelCharges(chargesToCancel);
    console.log('Cancellation results:', results);
    ```
  </Accordion>

  <Accordion title="Auto-Cancel Expired Charges">
    Automatically cancel charges that have expired:

    ```javascript theme={null}
    async function autoCancelExpiredCharges() {
      // Get all charges with status "created"
      const charges = await fetch(
        'https://api.sandbox.wepayout.com.br/v2/payin/payments?status_id=1',
        {
          headers: {
            'Authorization': 'Bearer 123',
            'Accept': 'application/json'
          }
        }
      ).then(r => r.json());
      
      const now = new Date();
      const canceledCharges = [];
      
      for (const charge of charges.data) {
        const createdAt = new Date(charge.created_at);
        const minutesPassed = (now - createdAt) / 1000 / 60;
        
        // Check if charge is eligible for cancellation
        const minMinutes = charge.payment_method === 'pix' ? 5 : 30;
        
        if (minutesPassed >= minMinutes) {
          try {
            await cancelCharge(charge.id);
            canceledCharges.push(charge.id);
          } catch (error) {
            console.error(`Failed to cancel charge ${charge.id}:`, error);
          }
        }
      }
      
      return canceledCharges;
    }
    ```
  </Accordion>

  <Accordion title="Cancel with Validation">
    Cancel a charge with full validation:

    ```javascript theme={null}
    async function cancelChargeWithValidation(chargeId) {
      // Get charge details
      const charge = await getChargeById(chargeId);
      
      // Validation checks
      const validations = {
        statusCheck: charge.status.id === 1,
        paymentMethodCheck: ['pix', 'boleto'].includes(charge.payment_method),
        timeCheck: false
      };
      
      // Check minimum time
      const createdAt = new Date(charge.created_at);
      const now = new Date();
      const minutesPassed = (now - createdAt) / 1000 / 60;
      
      if (charge.payment_method === 'pix') {
        validations.timeCheck = minutesPassed >= 5;
      } else if (charge.payment_method === 'boleto') {
        validations.timeCheck = minutesPassed >= 30;
      }
      
      // Check all validations
      if (!validations.statusCheck) {
        throw new Error('Charge status must be "created"');
      }
      
      if (!validations.paymentMethodCheck) {
        throw new Error('Only pix and boleto charges can be canceled');
      }
      
      if (!validations.timeCheck) {
        const minTime = charge.payment_method === 'pix' ? 5 : 30;
        throw new Error(`Must wait at least ${minTime} minutes before canceling`);
      }
      
      // All validations passed, cancel the charge
      const result = await cancelCharge(chargeId);
      
      return {
        success: true,
        chargeId,
        paymentMethod: charge.payment_method,
        result
      };
    }
    ```
  </Accordion>
</AccordionGroup>

## Important Notes

<Note>
  **Pix Cancellation**: Pix charges are canceled instantly once the request is made.
</Note>

<Warning>
  **Boleto Cancellation**: Boleto charges require at least 1 day to move from `drop_requested` to `canceled` status, as the process depends on confirmation from the payment processor.
</Warning>

<Tip>
  **Time Requirements**: Always check that the minimum time has passed before attempting to cancel:

  * Pix: 5 minutes
  * Boleto: 30 minutes
</Tip>

## Status Flow

### Pix Cancellation Flow

```
Created → (cancel request) → Canceled (instant)
```

### Boleto Cancellation Flow

```
Created → (cancel request) → Drop Requested → (1+ day) → Canceled
```

## Error Handling

Common errors when canceling charges:

| Error                        | Cause                                     | Solution                            |
| ---------------------------- | ----------------------------------------- | ----------------------------------- |
| Status not "created"         | Charge has already been paid or canceled  | Cannot cancel                       |
| Time requirement not met     | Tried to cancel too soon after creation   | Wait for minimum time               |
| Invalid charge ID            | Charge doesn't exist                      | Verify the charge ID                |
| Payment method not supported | Trying to cancel unsupported payment type | Only pix and boleto can be canceled |
