|
| 1 | +# Part of Odoo. See LICENSE file for full copyright and licensing details. |
| 2 | + |
| 3 | +import base64 |
| 4 | +import binascii |
| 5 | +import hashlib |
| 6 | +import hmac |
| 7 | +import logging |
| 8 | +import pprint |
| 9 | + |
| 10 | +from werkzeug.exceptions import Forbidden |
| 11 | + |
| 12 | +from odoo.exceptions import ValidationError |
| 13 | +from odoo.http import request, route |
| 14 | + |
| 15 | +from odoo.addons.payment_adyen.controllers.main import AdyenController |
| 16 | + |
| 17 | +_logger = logging.getLogger(__name__) |
| 18 | + |
| 19 | + |
| 20 | +class AdyenPayByLinkController(AdyenController): |
| 21 | + |
| 22 | + @route() |
| 23 | + def adyen_notification(self, **post): |
| 24 | + """ Process the data sent by Adyen to the webhook based on the event code. |
| 25 | +
|
| 26 | + See https://docs.adyen.com/development-resources/webhooks/understand-notifications for the |
| 27 | + exhaustive list of event codes. |
| 28 | +
|
| 29 | + :return: The '[accepted]' string to acknowledge the notification |
| 30 | + :rtype: str |
| 31 | + """ |
| 32 | + _logger.info( |
| 33 | + "notification received from Adyen with data:\n%s", pprint.pformat(post) |
| 34 | + ) |
| 35 | + try: |
| 36 | + # Check the integrity of the notification |
| 37 | + tx_sudo = request.env['payment.transaction'].sudo()._adyen_form_get_tx_from_data(post) |
| 38 | + self._verify_notification_signature(post, tx_sudo) |
| 39 | + |
| 40 | + # Check whether the event of the notification succeeded and reshape the notification |
| 41 | + # data for parsing |
| 42 | + event_code = post['eventCode'] |
| 43 | + if event_code == 'AUTHORISATION' and post['success'] == 'true': |
| 44 | + post['authResult'] = 'AUTHORISED' |
| 45 | + |
| 46 | + # Handle the notification data |
| 47 | + request.env['payment.transaction'].sudo().form_feedback(post, 'adyen') |
| 48 | + except ValidationError: # Acknowledge the notification to avoid getting spammed |
| 49 | + _logger.exception("unable to handle the notification data; skipping to acknowledge") |
| 50 | + |
| 51 | + return '[accepted]' # Acknowledge the notification |
| 52 | + |
| 53 | + @staticmethod |
| 54 | + def _verify_notification_signature(notification_data, tx_sudo): |
| 55 | + """ Check that the received signature matches the expected one. |
| 56 | +
|
| 57 | + :param dict notification_data: The notification payload containing the received signature |
| 58 | + :param recordset tx_sudo: The sudoed transaction referenced by the notification data, as a |
| 59 | + `payment.transaction` record |
| 60 | + :return: None |
| 61 | + :raise: :class:`werkzeug.exceptions.Forbidden` if the signatures don't match |
| 62 | + """ |
| 63 | + # Retrieve the received signature from the payload |
| 64 | + received_signature = notification_data.get('additionalData.hmacSignature') |
| 65 | + if not received_signature: |
| 66 | + _logger.warning("received notification with missing signature") |
| 67 | + raise Forbidden() |
| 68 | + |
| 69 | + # Compare the received signature with the expected signature computed from the payload |
| 70 | + hmac_key = tx_sudo.acquirer_id.adyen_hmac_key |
| 71 | + expected_signature = AdyenPayByLinkController._compute_signature( |
| 72 | + notification_data, hmac_key |
| 73 | + ) |
| 74 | + if not hmac.compare_digest(received_signature, expected_signature): |
| 75 | + _logger.warning("received notification with invalid signature") |
| 76 | + raise Forbidden() |
| 77 | + |
| 78 | + @staticmethod |
| 79 | + def _compute_signature(payload, hmac_key): |
| 80 | + """ Compute the signature from the payload. |
| 81 | +
|
| 82 | + See https://docs.adyen.com/development-resources/webhooks/verify-hmac-signatures |
| 83 | +
|
| 84 | + :param dict payload: The notification payload |
| 85 | + :param str hmac_key: The HMAC key of the acquirer handling the transaction |
| 86 | + :return: The computed signature |
| 87 | + :rtype: str |
| 88 | + """ |
| 89 | + def _flatten_dict(_value, _path_base='', _separator='.'): |
| 90 | + """ Recursively generate a flat representation of a dict. |
| 91 | +
|
| 92 | + :param Object _value: The value to flatten. A dict or an already flat value |
| 93 | + :param str _path_base: They base path for keys of _value, including preceding separators |
| 94 | + :param str _separator: The string to use as a separator in the key path |
| 95 | + """ |
| 96 | + if isinstance(_value, dict): # The inner value is a dict, flatten it |
| 97 | + _path_base = _path_base if not _path_base else _path_base + _separator |
| 98 | + for _key in _value: |
| 99 | + yield from _flatten_dict(_value[_key], _path_base + str(_key)) |
| 100 | + else: # The inner value cannot be flattened, yield it |
| 101 | + yield _path_base, _value |
| 102 | + |
| 103 | + def _to_escaped_string(_value): |
| 104 | + """ Escape payload values that are using illegal symbols and cast them to string. |
| 105 | +
|
| 106 | + String values containing `\\` or `:` are prefixed with `\\`. |
| 107 | + Empty values (`None`) are replaced by an empty string. |
| 108 | +
|
| 109 | + :param Object _value: The value to escape |
| 110 | + :return: The escaped value |
| 111 | + :rtype: string |
| 112 | + """ |
| 113 | + if isinstance(_value, str): |
| 114 | + return _value.replace('\\', '\\\\').replace(':', '\\:') |
| 115 | + elif _value is None: |
| 116 | + return '' |
| 117 | + else: |
| 118 | + return str(_value) |
| 119 | + |
| 120 | + signature_keys = [ |
| 121 | + 'pspReference', 'originalReference', 'merchantAccountCode', 'merchantReference', |
| 122 | + 'value', 'currency', 'eventCode', 'success' |
| 123 | + ] |
| 124 | + # Build the list of signature values as per the list of required signature keys |
| 125 | + signature_values = [payload.get(key) for key in signature_keys] |
| 126 | + # Escape values using forbidden symbols |
| 127 | + escaped_values = [_to_escaped_string(value) for value in signature_values] |
| 128 | + # Concatenate values together with ':' as delimiter |
| 129 | + signing_string = ':'.join(escaped_values) |
| 130 | + # Convert the HMAC key to the binary representation |
| 131 | + binary_hmac_key = binascii.a2b_hex(hmac_key.encode('ascii')) |
| 132 | + # Calculate the HMAC with the binary representation of the signing string with SHA-256 |
| 133 | + binary_hmac = hmac.new(binary_hmac_key, signing_string.encode('utf-8'), hashlib.sha256) |
| 134 | + # Calculate the signature by encoding the result with Base64 |
| 135 | + return base64.b64encode(binary_hmac.digest()).decode() |
0 commit comments