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

# CWM Pay API Error Codes: Reference and Handling Guide

> Reference for all CWM Pay API error codes, HTTP status codes, and recommended handling strategies for authentication, payment, and validation errors.

When a request to the CWM Pay API fails, the response body contains a JSON error object with a `code`, `message`, and `type` that describe exactly what went wrong. Use this page to look up any error you encounter, understand its cause, and apply the right fix or retry strategy in your integration.

## Error Response Format

Every failed request returns the same error envelope, regardless of the error type:

```json theme={null}
{
  "error": {
    "type": "card_error",
    "code": "card_declined",
    "message": "Your card was declined.",
    "param": null,
    "request_id": "req_abc123"
  }
}
```

| Field        | Description                                                                   |
| ------------ | ----------------------------------------------------------------------------- |
| `type`       | The broad category of the error (see [Error Types](#error-types) below).      |
| `code`       | A machine-readable string identifying the specific error.                     |
| `message`    | A human-readable description of what went wrong.                              |
| `param`      | The request parameter that caused the error, if applicable; otherwise `null`. |
| `request_id` | A unique identifier for this request. Include this when contacting support.   |

## Error Types

Use the `type` field to determine the correct handling strategy at a high level before inspecting the specific `code`.

| Type                    | Description                                                                 |
| ----------------------- | --------------------------------------------------------------------------- |
| `api_error`             | Something went wrong on CWM Pay's end. Retry with exponential backoff.      |
| `authentication_error`  | Invalid or missing API key. Check your `Authorization` header.              |
| `card_error`            | The customer's card was declined or is invalid.                             |
| `invalid_request_error` | Bad request parameters — check your request body against the API reference. |
| `rate_limit_error`      | Too many requests. Slow down and retry after a delay.                       |

## HTTP Status Codes

CWM Pay uses standard HTTP status codes alongside the JSON error body.

| Status                      | Description                                                                                                                           |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `200 OK`                    | Request succeeded.                                                                                                                    |
| `400 Bad Request`           | Invalid parameters. Check the `error.param` field for the offending field name.                                                       |
| `401 Unauthorized`          | Missing or invalid API key. Verify your `Authorization: Bearer` header.                                                               |
| `402 Payment Required`      | The card was declined. Surface the `error.message` to the customer.                                                                   |
| `404 Not Found`             | The requested resource does not exist. Check the ID in your request path.                                                             |
| `409 Conflict`              | Duplicate request detected. Use idempotency keys to prevent unintended double charges.                                                |
| `422 Unprocessable Entity`  | The request was valid but could not be processed in its current state.                                                                |
| `429 Too Many Requests`     | Rate limit exceeded. Retry after the value in the `Retry-After` response header.                                                      |
| `500 Internal Server Error` | CWM Pay server error. Retry with exponential backoff. If the issue persists, contact [support@cwmpay.com](mailto:support@cwmpay.com). |

## Card Error Codes

When `error.type` is `card_error`, use the `code` field to decide how to respond to your customer.

| Code                 | Recommended Action                                                               |
| -------------------- | -------------------------------------------------------------------------------- |
| `card_declined`      | Generic decline. Ask the customer to try a different card.                       |
| `insufficient_funds` | Card has insufficient funds. Ask the customer to use a different payment method. |
| `expired_card`       | Card is expired. Ask the customer to update their card details.                  |
| `incorrect_cvc`      | CVC is incorrect. Ask the customer to re-enter their security code.              |
| `incorrect_zip`      | Billing ZIP doesn't match. Ask the customer to verify their billing address.     |
| `do_not_honor`       | Card issuer declined. Ask the customer to contact their bank.                    |
| `lost_card`          | Card reported lost. Do not retry — ask the customer to use a different card.     |
| `stolen_card`        | Card reported stolen. Do not retry — ask the customer to use a different card.   |
| `fraudulent`         | Payment flagged as fraudulent. Do not retry this charge.                         |

## Authentication Error Codes

When `error.type` is `authentication_error`, your API key is missing, malformed, or invalid. These errors always return HTTP `401`.

| Code                 | Recommended Action                                                                                                                                |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `api_key_missing`    | No `Authorization` header was sent. Add `Authorization: Bearer YOUR_SECRET_KEY` to every request.                                                 |
| `api_key_invalid`    | The key was provided but is not recognized. Verify the key in your [dashboard](https://dashboard.cwmpay.com) under **Settings → API Keys**.       |
| `api_key_revoked`    | The key has been revoked. Generate a new key in **Settings → API Keys** and update your configuration.                                            |
| `api_key_wrong_mode` | You used a live key against a test resource, or vice versa. Match your key prefix (`sk_live_` or `sk_test_`) to the environment you're targeting. |

## Invalid Request Error Codes

When `error.type` is `invalid_request_error`, one or more fields in your request body or URL are incorrect. Check `error.param` for the name of the offending field.

| Code                      | Recommended Action                                                                                                                                      |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `parameter_missing`       | A required field was omitted. Add the field named in `error.param` to your request.                                                                     |
| `parameter_invalid`       | A field was present but its value is not valid (wrong type, out of range, etc.). Check the [API reference](/api-reference/overview) for allowed values. |
| `resource_not_found`      | The ID in your request path does not match any existing object. Confirm the ID is correct.                                                              |
| `resource_already_exists` | You tried to create a resource that already exists (for example, a duplicate customer email). Use the existing resource or provide different values.    |
| `amount_too_small`        | The `amount` is below the minimum allowed for the currency. Check the minimum charge amount for your currency.                                          |
| `currency_not_supported`  | The `currency` value is not supported for your account or region. Check your dashboard for enabled currencies.                                          |

## Handling Errors in Code

Wrap every API call in error handling logic that inspects `error.type` and `error.code` to decide whether to surface a message to the customer, retry the request, or escalate to your team.

<CodeGroup>
  ```javascript JavaScript theme={null}
  try {
    const response = await fetch('https://api.cwmpay.com/v1/payments', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.CWM_SECRET_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ amount: 1000, currency: 'usd' })
    });

    if (!response.ok) {
      const { error } = await response.json();
      console.error(error.code, error.message);

      switch (error.type) {
        case 'card_error':
          // Surface error.message to the customer
          break;
        case 'authentication_error':
          // Check your API key configuration
          break;
        case 'invalid_request_error':
          // Fix your request parameters — check error.param
          break;
        case 'rate_limit_error':
        case 'api_error':
          // Retry with exponential backoff
          break;
        default:
          // Log and investigate
      }
    }
  } catch (err) {
    // Network error — retry with backoff
    console.error('Network error:', err.message);
  }
  ```

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

  try:
      response = requests.post(
          'https://api.cwmpay.com/v1/payments',
          headers={
              'Authorization': f"Bearer {os.environ['CWM_SECRET_KEY']}",
              'Content-Type': 'application/json'
          },
          json={'amount': 1000, 'currency': 'usd'}
      )

      if not response.ok:
          error = response.json().get('error', {})
          print(error.get('code'), error.get('message'))

          error_type = error.get('type')
          if error_type == 'card_error':
              # Surface error['message'] to the customer
              pass
          elif error_type == 'authentication_error':
              # Check your API key configuration
              pass
          elif error_type == 'invalid_request_error':
              # Fix your request parameters — check error['param']
              pass
          elif error_type in ('rate_limit_error', 'api_error'):
              # Retry with exponential backoff
              pass
          else:
              # Log and investigate
              pass

  except requests.exceptions.ConnectionError as err:
      # Network error — retry with backoff
      print(f"Network error: {err}")
  ```
</CodeGroup>

## Rate Limits

CWM Pay enforces the following request limits per API key:

* **Live mode:** 100 requests per second
* **Test mode:** 20 requests per second

When you exceed the limit, the API returns a `429 Too Many Requests` response. Check the `Retry-After` header in the response for the number of seconds to wait before retrying. Implement exponential backoff with jitter in your retry logic to avoid thundering-herd issues during traffic spikes.

<Tip>
  Every API error response includes a `request_id` field (for example, `req_abc123`). Always include this value when you contact [support@cwmpay.com](mailto:support@cwmpay.com) — it allows the CWM Pay support team to locate your exact request and diagnose the issue faster.
</Tip>
