Debian Codegraph @

addons/pos_mercado_pago/controllers/main.py

raw
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2 import hashlib
3 import hmac
4 import logging
5 import re
6
7 from odoo import http
8 from odoo.http import request
9
10 _logger = logging.getLogger(__name__)
11
12
13 class PosMercadoPagoWebhook(http.Controller):
14 @http.route('/pos_mercado_pago/notification', methods=['POST'], type="http", auth="none", csrf=False)
15 def notification(self):
16 """ Process the notification sent by Mercado Pago
17
18 Notification format is always json
19 """
20 # Check for mandatory keys in header
21 x_request_id = request.httprequest.headers.get('X-Request-Id')
22 if not x_request_id:
23 _logger.warning('POST message received with no X-Request-Id in header')
24 return http.Response(status=400)
25
26 x_signature = request.httprequest.headers.get('X-Signature')
27 if not x_signature:
28 _logger.warning('POST message received with no X-Signature in header')
29 return http.Response(status=400)
30
31 ts_m = re.search(r"ts=(\d+)", x_signature)
32 v1_m = re.search(r"v1=([a-f0-9]+)", x_signature)
33 ts = ts_m.group(1) if ts_m else None
34 v1 = v1_m.group(1) if v1_m else None
35 if not ts or not v1:
36 _logger.warning('Webhook bad X-Signature, ts: %s, v1: %s', ts, v1)
37 return http.Response(status=400)
38
39 # Check for payload
40 data = request.httprequest.get_json(silent=True)
41 if not data:
42 _logger.warning('POST message received with no data')
43 return http.Response(status=400)
44
45 # If and only if this webhook is related with a payment intend (see payment_mercado_pago.js)
46 # then the field data['additional_info']['external_reference'] contains a string
47 # formated like `XXX_YYY_ZZZ` where:
48 # - `XXX` is the session_id
49 # - `YYY` is the payment_method_id
50 # - `ZZZ` is the pos order uuid for customer identification (Format xxxx-xxxx-xxx) where x is a hexadecimal digit
51 external_reference = data.get('additional_info', {}).get('external_reference')
52
53 mercado_pago_pattern = r'(\d+)_(\d+)_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})'
54
55 if not external_reference or not (match := re.fullmatch(mercado_pago_pattern, external_reference)):
56 _logger.warning('POST message received with no or malformed "external_reference" key: %s', external_reference)
57 return http.Response(status=400)
58
59 session_id, payment_method_id, _ = match.groups()
60
61 pos_session_sudo = request.env['pos.session'].sudo().browse(int(session_id))
62 if not pos_session_sudo or pos_session_sudo.state != 'opened':
63 _logger.error("Invalid session id: %s", session_id)
64 # This error is not related with Mercado Pago, simply acknowledge Mercado Pago message
65 return http.Response('OK', status=200)
66
67 payment_method_sudo = pos_session_sudo.config_id.payment_method_ids.filtered(lambda p: p.id == int(payment_method_id))
68 if not payment_method_sudo or payment_method_sudo.use_payment_terminal != 'mercado_pago':
69 _logger.error("Invalid payment method id: %s", payment_method_id)
70 # This error is not related with Mercado Pago, simply acknowledge Mercado Pago message
71 return http.Response('OK', status=200)
72
73 # We have to check if this comes from Mercado Pago with the secret key
74 secret_key = payment_method_sudo.mp_webhook_secret_key
75 signed_template = f"id:{data['id']};request-id:{x_request_id};ts:{ts};"
76 cyphed_signature = hmac.new(secret_key.encode(), signed_template.encode(), hashlib.sha256).hexdigest()
77 if not hmac.compare_digest(cyphed_signature, v1):
78 _logger.error('Webhook authenticating failure, ts: %s, v1: %s', ts, v1)
79 return http.Response(status=401)
80
81 _logger.debug('Webhook authenticated, POST message: %s', data)
82
83 # Notify the frontend that we received a message from Mercado Pago
84 pos_session_sudo.config_id._notify('MERCADO_PAGO_LATEST_MESSAGE', {
85 'config_id': pos_session_sudo.config_id.id
86 })
87
88 # Acknowledge Mercado Pago message
89 return http.Response('OK', status=200)