Создание вложенного JSON необязательно - PullRequest
0 голосов
/ 18 января 2020

Мой webhook успешно получает информацию о платежах из моего банка. Ниже приведены мои JSON сериализаторы, которые проверяют JSON полученный от банка.

Платежи проходят успешно и регистрируются. Но банковские переводы не проходят проверку, поскольку они не содержат вложенной информации о продавце. Я попытался установить Required = False в сериализаторах, но все равно получаю сообщение об ошибке: {'data': {'merchant': [ErrorDetail(string='This field may not be null.', code='null')]}}

Как настроить сериализаторы для проверки с или без информации о продавце?

Serializers.py:

class MerchantSerializer(serializers.Serializer):
    id = serializers.CharField(required=True, max_length=50)
    name = serializers.CharField(required=True, max_length=100)
    logo = serializers.URLField(max_length=250, required=False)

class DataSerializer(serializers.Serializer):
    account_id = serializers.CharField(required=True, max_length=50)
    amount = serializers.IntegerField(required=True)
    created = serializers.DateTimeField()
    currency = serializers.CharField(required=True, max_length=3)
    description = serializers.CharField(required=True, max_length=250)
    id = serializers.CharField(required=True, max_length=50)
    category = serializers.CharField(required=True, max_length=100)
    is_load = serializers.BooleanField()
    merchant = MerchantSerializer(required=False) # Have set this to false but still not working

class TransactionSerializer(serializers.Serializer):
    type = serializers.CharField(required=True, max_length=50)
    data = DataSerializer()

JSON для банковского перевода (который не проходит проверку) - хэшированная конфиденциальная информация:

{
    'type': 'transaction.created',
    'data': {
        'id': '##########',
        'created': '2020-01-18T14:36:52.337Z',
        'description': 'MONZO',
        'amount': 1000,
        'fees': {},
        'currency': 'GBP',
        'merchant': None,
        'notes': 'MONZO',
        'metadata': {
            'faster_payment': 'true',
            'fps_fpid': '#####',
            'fps_payment_id': '####',
            'insertion': '###',
            'notes': 'MONZO',
            'trn': '#######'
        },
        'labels': None,
        'account_balance': 0,
        'attachments': None,
        'international': None,
        'category': 'general',
        'categories': None,
        'is_load': False,
        'settled': '2020-01-20T07:00:00Z',
        'local_amount': 1000,
        'local_currency': 'GBP',
        'updated': '2020-01-18T14:36:52.444Z',
        'account_id': 'acc_#############',
        'user_id': '',
        'counterparty': {
            'account_number': '########',
            'name': '######',
            'sort_code': '#####',
            'user_id': 'anonuser_########'
        },
        'scheme': 'payport_faster_payments',
        'dedupe_id': '#######',
        'originator': False,
        'include_in_spending': False,
        'can_be_excluded_from_breakdown': False,
        'can_be_made_subscription': False,
        'can_split_the_bill': False,
        'can_add_to_tab': False,
        'amount_is_pending': False
    }
}

JSON для платежа (проходит проверку - хэшированная конфиденциальная информация):

{
    'type': 'transaction.created',
    'data': {
        'id': 'tx_######',
        'created': '2020-01-18T13:26:25.036Z',
        'description': '#####',
        'amount': -7054,
        'fees': {},
        'currency': 'GBP',
        'merchant': {
            'id': 'merch_###',
            'group_id': '#####',
            'created': '2016-05-14T20:17:49.743Z',
            'name': 'BP',
            'logo': 'https://mondo-logo-cache.appspot.com/twitter/BP_UK/?size=large',
            'emoji': '⛽️',
            'category': 'transport',
            'online': False,
            'atm': False,
            'address': {
                'short_formatted': '#####',
                'formatted': '####',
                'address': '######',
                'city': '###',
                'region': '',
                'country': 'GBR',
                'postcode': '###',
                'latitude': 51.25906,
                'longitude': -0.5446080000000001,
                'zoom_level': 17,
                'approximate': False
            },
            'updated': '2016-11-18T19:18:41.23Z',
            'metadata': {
                'created_for_merchant': 'merch_###',
                'created_for_transaction': 'tx_#####',
                'enriched_from_settlement': 'tx_####',
                'foursquare_category': 'Gas Station / Garage',
                'foursquare_category_icon': 'https://ss3.4sqi.net/img/categories_v2/shops/gas_88.png',
                'foursquare_id': '######',
                'foursquare_website': 'http://www.bp.com',
                'google_places_icon': '###',
                'google_places_id': '####',
                'google_places_name': 'BP',
                'suggested_name': 'BP',
                'suggested_tags': '#garage #transport #petrol #station',
                'twitter_id': 'BP_UK',
                'website': 'https://www.bp.com/en_gb/united-kingdom.html'
            },
            'disable_feedback': False
        },
        'notes': '',
        'metadata': {
            'mastercard_auth_message_id': '####',
            'mastercard_lifecycle_id': '####',
            'mcc': '5541'
        },
        'labels': None,
        'account_balance': 0,
        'attachments': None,
        'international': None,
        'category': 'transport',
        'categories': {
            'transport': -7054
        },
        'is_load': False,
        'settled': '',
        'decline_reason': 'INSUFFICIENT_FUNDS',
        'local_amount': -7054,
        'local_currency': 'GBP',
        'updated': '2020-01-18T13:26:25.624Z',
        'account_id': 'acc_#####',
        'user_id': 'user_####',
        'counterparty': {},
        'scheme': 'mastercard',
        'dedupe_id': '####',
        'originator': False,
        'include_in_spending': False,
        'can_be_excluded_from_breakdown': True,
        'can_be_made_subscription': False,
        'can_split_the_bill': False,
        'can_add_to_tab': False,
        'amount_is_pending': False
    }
}
...