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

# Conciliation Webhook

> This webhook is used to send the conciliation data to your system

## Webhook Endpoint

You should configure your webhook endpoint to receive POST requests from Propaga. The webhook will send the conciliation data in JSON format.
Please contact us to set up the webhook.

## Payload Structure

Here's an example of the webhook payload you'll receive:

```json theme={null}
{
  "transferedAmount": 5000.00,
  "refundsAmountUsed": 0.00,
  "startDate": "2024-01-01T00:00:00Z",
  "cutoffDate": "2024-01-31T23:59:59Z",
  "transferedDate": "2024-02-01T10:00:00Z",
  "referenceNumber": "REF123456789",
  "transactions": [
    {
      "transactionId": "e83bd5ca-7742-42e5-97c2-b7a0fbaa68cf",
      "cornerStoreId": "57b9d911-1c6e-45c0-be98-bfaeec8d9cf8",
      "wholesalerExternalId": "WH-123456",
      "transactionStatus": "COMPLETED",
      "movementDate": "2024-01-15T14:30:00Z",
      "totalAmount": 2000.00,
      "interests": 100.00,
      "totalAmountWithInterests": 2100.00,
      "products": [
        {
          "externalSKU": "7501018310103",
          "name": "Pasta Spaghetti La Moderna - Moderna - Paquete 200 g",
          "quantity": 5
        }
      ]
    }
  ]
}
```

### Payload Fields

| Field               | Type   | Description                                                  |
| ------------------- | ------ | ------------------------------------------------------------ |
| `transferedAmount`  | Number | The total amount transferred in this conciliation.           |
| `refundsAmountUsed` | Number | The amount of refunds or credit notes applied.               |
| `startDate`         | String | The start date of the conciliation period (ISO 8601 format). |
| `cutoffDate`        | String | The end date of the conciliation period (ISO 8601 format).   |
| `transferedDate`    | String | The date when the transfer was executed (ISO 8601 format).   |
| `referenceNumber`   | String | A unique reference number for the transfer.                  |
| `transactions`      | Array  | List of transactions included in this conciliation.          |

### Transaction Object Fields

| Field                      | Type   | Description                                                 |
| -------------------------- | ------ | ----------------------------------------------------------- |
| `transactionId`            | String | Propaga's unique identifier for the transaction.            |
| `cornerStoreId`            | String | The ID of the corner store associated with the transaction. |
| `wholesalerExternalId`     | String | The ID of the transaction in the wholesaler's system.       |
| `transactionStatus`        | String | The current status of the transaction.                      |
| `movementDate`             | String | The date when the transaction occurred (ISO 8601 format).   |
| `totalAmount`              | Number | The original amount of the transaction.                     |
| `interests`                | Number | The interest amount applied to the transaction.             |
| `totalAmountWithInterests` | Number | The total amount including interests.                       |
| `products`                 | Array  | List of products in the transaction.                        |

### Product Object Fields

| Field         | Type   | Description                  |
| ------------- | ------ | ---------------------------- |
| `externalSKU` | String | The SKU of the product.      |
| `name`        | String | The name of the product.     |
| `quantity`    | Number | The quantity of the product. |

## Handling the Webhook

Here's an example of how to handle the webhook in different programming languages:

<CodeGroup>
  ```javascript JavaScript theme={null}
  app.post('/webhook/conciliation', async (req, res) => {
    try {
      const conciliation = req.body;
      
      // Process the conciliation data
      await processConciliation(conciliation);
      
      // Respond with success
      res.status(200).json({ status: 'success' });
    } catch (error) {
      console.error('Error processing conciliation:', error);
      res.status(500).json({ status: 'error', message: error.message });
    }
  });

  async function processConciliation(conciliation) {
    // Validate the transfer amount
    console.log(`Processing transfer: ${conciliation.referenceNumber}`);
    console.log(`Total amount: ${conciliation.transferedAmount}`);
    
    // Process each transaction
    for (const transaction of conciliation.transactions) {
      console.log(`Processing transaction: ${transaction.transactionId}`);
      // Your transaction processing logic here
    }
  }
  ```

  ```python Python theme={null}
  from flask import Flask, request, jsonify

  app = Flask(__name__)

  @app.route('/webhook/conciliation', methods=['POST'])
  def handle_conciliation():
      try:
          conciliation = request.json
          
          # Process the conciliation data
          process_conciliation(conciliation)
          
          return jsonify({'status': 'success'}), 200
      except Exception as e:
          print(f'Error processing conciliation: {str(e)}')
          return jsonify({'status': 'error', 'message': str(e)}), 500

  def process_conciliation(conciliation):
      # Validate the transfer amount
      print(f"Processing transfer: {conciliation['referenceNumber']}")
      print(f"Total amount: {conciliation['transferedAmount']}")
      
      # Process each transaction
      for transaction in conciliation['transactions']:
          print(f"Processing transaction: {transaction['transactionId']}")
          # Your transaction processing logic here
  ```
</CodeGroup>

## Best Practices

1. **Verify the Webhook Source**: Implement security measures to verify that the webhook is coming from Propaga.

2. **Implement Idempotency**: Store the `referenceNumber` to avoid processing the same conciliation multiple times.

3. **Handle Errors Gracefully**: Implement proper error handling and logging to track any issues with webhook processing.

4. **Respond Quickly**: Your webhook endpoint should respond as quickly as possible. If processing takes time, handle it asynchronously.

5. **Validate Data**: Always validate the incoming data before processing it.
