handleWebhook method

  1. @override
Future<DVBillingWebhookResult> handleWebhook(
  1. String payload,
  2. String signatureHeader
)
override

Verifies signatureHeader against payload and applies the event.

Throws when the signature is missing, wrong, or outside the accepted time window; nothing is changed in that case.

Implementation

@override
Future<DVBillingWebhookResult> handleWebhook(
    String payload, String signatureHeader) async {
  if (!_sameText(sign(payload, _secretKey), signatureHeader.trim())) {
    throw const DVBillingError('The webhook signature does not match.');
  }
  final Object? decoded;
  try {
    decoded = jsonDecode(payload);
  } on FormatException {
    throw const DVBillingError('The webhook payload is not JSON.');
  }
  if (decoded is! Map) {
    throw const DVBillingError('The webhook payload is not an event.');
  }
  final String type = '${decoded['event'] ?? ''}';
  final Object? data = decoded['data'];
  if (data is! Map) return DVBillingWebhookResult(type: type, handled: false);
  final Object? customerObject = data['customer'];
  final String? email = customerObject is Map && customerObject['email'] is String
      ? customerObject['email'] as String
      : null;
  final Object? plan = data['plan'];
  final String? code = plan is Map && plan['plan_code'] is String
      ? plan['plan_code'] as String
      : null;
  switch (type) {
    case 'charge.success':
    case 'subscription.create':
      final Set<Entitlement> granted = <Entitlement>{};
      if (code != null && email != null) {
        final Set<String> held = _grants.putIfAbsent(email, () => <String>{});
        for (final Entitlement entitlement
            in entitlements[code] ?? const <Entitlement>{}) {
          if (held.add(entitlement.id)) granted.add(entitlement);
        }
      }
      final String reference = '${data['reference'] ?? ''}';
      return DVBillingWebhookResult(
        type: type,
        handled: true,
        customer: email,
        granted: granted,
        reference: reference.isEmpty ? null : reference,
        checkoutId: reference.isEmpty ? null : reference,
        eventId: data['id'] == null ? null : '${data['id']}',
      );
    case 'subscription.disable':
      final Set<Entitlement> revoked = <Entitlement>{};
      if (code != null && email != null) {
        final Set<String>? held = _grants[email];
        for (final Entitlement entitlement
            in entitlements[code] ?? const <Entitlement>{}) {
          if (held?.remove(entitlement.id) ?? false) revoked.add(entitlement);
        }
      }
      return DVBillingWebhookResult(
          type: type, handled: true, customer: email, revoked: revoked);
    default:
      return DVBillingWebhookResult(type: type, handled: false);
  }
}