# Agreement Webhooks

Agreement webhooks provide real-time notifications about agreement lifecycle events that occur when agreements are created, changed, or cancelled by payment system providers (card vendors, NETS, MobilePay, etc.).

## Overview

Agreement webhooks are triggered by events in the FarPay core system when agreements are processed by payment providers. These webhooks enable you to:

* **Track agreement creation** - Know when new payment agreements are established
* **Monitor agreement changes** - Get notified when account numbers or cards are updated
* **Handle agreement cancellations** - Respond when agreements are cancelled or deleted
* **Maintain agreement status** - Keep your system in sync with FarPay's agreement state

## Agreement Events

| Event    | Numeric Value | Description                                                | MobilePay | BS | LS | Card |
| -------- | ------------- | ---------------------------------------------------------- | --------- | -- | -- | ---- |
| `Create` | 100           | Agreement received from provider as valid                  | ✅         | ✅  | ✅  | ✅    |
| `Change` | 110           | Changes to account number, card, or provider result        | ⛔         | ✅  | ✅  | ⛔    |
| `Cancel` | 120           | Agreement cancelled instantly, cannot be used for payments | ✅         | ✅  | ✅  | ✅    |
| `Delete` | 130           | Agreement deleted (only if never used)                     | ✅         | ✅  | ✅  | ✅    |

### BS Agreement Cancellation Behavior

When a BS (Betalingsservice) agreement is cancelled, pending payments transition according to the BS configuration:

| BS Type      | Transition Behavior                                                                                         |
| ------------ | ----------------------------------------------------------------------------------------------------------- |
| **BS Total** | Payment transitions to payment slip with new +71 key. When paid, FarPay can associate payment with customer |
| **BS Basic** | Payment is parked, no further processing occurs                                                             |

## Webhook Payload Structure

### JSON Format (POST)

```json
{
  "Agreement": {
    "CustomerNumber": "ABC123",
    "AgreementId": "12345",
    "AgreementType": "Card",
    "CardMask": "1234 XXXXX XXXXX 4321",
    "CardExpire": "202009",
    "Event": "Create"
  }
}
```

### XML Format (POST)

```xml
<Agreement>
  <CustomerNumber>2</CustomerNumber>
  <AgreementId>12345</AgreementId>
  <ExternalId>REF99102933C</ExternalId>
  <AgreementType>Card</AgreementType>
  <CardMask>1234 XXXX XXXX 4321</CardMask>
  <CardExpire>202009</CardExpire>
  <Event>Create</Event>
</Agreement>
```

### URL Parameters (GET)

```
https://yourdomain.com/webhook?CustomerNumber=2&AgreementId=12345&AgreementType=Card&CardMask=1234%20XXXX%20XXXX%204321&CardExpire=202009&Event=Create
```

## Payload Properties

| Property         | Type   | Description           | Format                             |
| ---------------- | ------ | --------------------- | ---------------------------------- |
| `CustomerNumber` | string | Customer identifier   | Alphanumeric                       |
| `AgreementId`    | string | Agreement identifier  | Numeric                            |
| `ExternalId`     | string | External reference ID | Alphanumeric (optional)            |
| `AgreementType`  | string | Type of agreement     | "Card", "BS", "LS", "MobilePay"    |
| `CardMask`       | string | Masked card number    | "1234 XXXX XXXX 4321" (cards only) |
| `CardExpire`     | string | Card expiration date  | "YYYYMM" format (cards only)       |
| `Event`          | string | Agreement event type  | See Event table above              |

## Security Considerations

For security reasons, agreement webhooks provide only partial information:

* **Card information** is distributed with expiration date and partially masked card number
* **Bank account information** is not distributed in webhooks
* **Sensitive data** is protected and not exposed

## Best Practices

### 1. Event Handling

* **Handle all event types** - Don't ignore events you don't expect
* **Log all events** - Keep detailed logs for debugging and audit
* **Process asynchronously** - Use queues for heavy processing
* **Implement idempotency** - Handle duplicate webhooks gracefully

### 2. Data Validation

* **Validate required fields** - Check all required properties
* **Verify agreement types** - Ensure agreement type is supported
* **Check customer references** - Validate customer number format
* **Handle missing data** - Account for optional fields

### 3. Business Logic

* **Update customer records** - Keep customer payment methods current
* **Handle pending payments** - Process BS/LS pending payments appropriately
* **Notify customers** - Inform customers of agreement changes
* **Update billing systems** - Sync with your billing infrastructure

### 4. Security

* **Verify webhook origin** - Use checksums when available
* **Validate data integrity** - Check for tampering
* **Use HTTPS** - Secure all webhook endpoints
* **Rate limiting** - Prevent abuse of your endpoints

## Testing

### Test Scenarios

1. **Agreement creation** - Test handling of new agreements
2. **Agreement changes** - Test handling of agreement modifications
3. **Agreement cancellation** - Test cancellation scenarios
4. **Agreement deletion** - Test deletion handling
5. **Different agreement types** - Test card, BS, LS, MobilePay
6. **Invalid data** - Test error handling with malformed data
7. **Duplicate webhooks** - Test idempotency

### Test Data Examples

```json
// Card agreement created
{
  "Agreement": {
    "CustomerNumber": "CUST-001",
    "AgreementId": "12345",
    "AgreementType": "Card",
    "CardMask": "1234 XXXX XXXX 4321",
    "CardExpire": "202512",
    "Event": "Create"
  }
}

// BS agreement cancelled
{
  "Agreement": {
    "CustomerNumber": "CUST-002",
    "AgreementId": "67890",
    "AgreementType": "BS",
    "Event": "Cancel"
  }
}

// LS agreement changed
{
  "Agreement": {
    "CustomerNumber": "CUST-003",
    "AgreementId": "11111",
    "AgreementType": "LS",
    "Event": "Change"
  }
}
```

## Related Documentation

* [Webhooks Overview](webhooks.md) - General webhook information
* [Payment Webhooks](payment-webhooks.md) - Payment event notifications
* [Order Webhooks](order-webhooks.md) - Order status tracking
* [API Documentation](../README.md) - Main API documentation