Debian Codegraph @

addons/payment_mercado_pago/models/payment_transaction.py

raw
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 from urllib.parse import quote as url_quote
4
5 from werkzeug.urls import url_decode, url_parse
6
7 from odoo import _, api, models
8 from odoo.exceptions import ValidationError
9 from odoo.tools import float_round
10 from odoo.tools.urls import urljoin
11
12 from odoo.addons.payment import utils as payment_utils
13 from odoo.addons.payment.logging import get_payment_logger
14 from odoo.addons.payment_mercado_pago import const
15
16
17 _logger = get_payment_logger(__name__)
18
19
20 class PaymentTransaction(models.Model):
21 _inherit = 'payment.transaction'
22
23 def _get_specific_rendering_values(self, processing_values):
24 """ Override of `payment` to return Mercado Pago-specific rendering values.
25
26 Note: self.ensure_one() from `_get_rendering_values`.
27
28 :param dict processing_values: The generic and specific processing values of the transaction
29 :return: The dict of provider-specific processing values.
30 :rtype: dict
31 """
32 if self.provider_code != 'mercado_pago':
33 return super()._get_specific_rendering_values(processing_values)
34
35 # Initiate the payment and retrieve the payment link data.
36 payload = self._mercado_pago_prepare_preference_request_payload()
37 try:
38 response_content = self._send_api_request('POST', '/checkout/preferences', json=payload)
39 except ValidationError as error:
40 self._set_error(str(error))
41 return {}
42
43 api_url = response_content[
44 'init_point' if self.provider_id.state == 'enabled' else 'sandbox_init_point'
45 ]
46
47 # Extract the payment link URL and params and embed them in the redirect form.
48 parsed_url = url_parse(api_url)
49 url_params = url_decode(parsed_url.query)
50 rendering_values = {
51 'api_url': api_url,
52 'url_params': url_params, # Encore the params as inputs to preserve them.
53 }
54 return rendering_values
55
56 def _mercado_pago_prepare_preference_request_payload(self):
57 """Create the payload for the preference request based on the transaction values.
58
59 :return: The preference request payload.
60 :rtype: dict
61 """
62 payload = self._mercado_pago_prepare_base_request_payload()
63
64 base_url = self.provider_id.get_base_url()
65 return_url = urljoin(base_url, const.PAYMENT_RETURN_ROUTE)
66 payload.update({
67 'auto_return': 'all',
68 'back_urls': {
69 'success': return_url,
70 'pending': return_url,
71 'failure': return_url,
72 },
73 'items': [{
74 'title': self.reference,
75 'quantity': 1,
76 'currency_id': self.currency_id.name,
77 'unit_price': self._mercado_pago_convert_amount(),
78 }],
79 'payer': {
80 'name': self.partner_name,
81 'email': self.partner_email,
82 'phone': {
83 'number': self.partner_phone,
84 },
85 'address': {
86 'zip_code': self.partner_zip,
87 'street_name': self.partner_address,
88 },
89 },
90 })
91 return payload
92
93 def _mercado_pago_prepare_payment_request_payload(self):
94 """Create the payload for the direct payment request based on the transaction values.
95
96 :return: The payment request payload.
97 :rtype: dict
98 """
99 payload = self._mercado_pago_prepare_base_request_payload()
100 first_name, last_name = payment_utils.split_partner_name(self.partner_name)
101 payload.update({
102 'additional_info': {
103 'items': [{
104 'title': self.reference,
105 'quantity': 1,
106 'unit_price': self._mercado_pago_convert_amount(),
107 }],
108 },
109 'payer': {
110 'first_name': first_name,
111 'last_name': last_name,
112 'email': self.partner_email,
113 },
114 })
115 return payload
116
117 def _mercado_pago_prepare_base_request_payload(self):
118 """ Create the base payload for requests based on the transaction values.
119
120 :return: The base request payload.
121 :rtype: dict
122 """
123 base_url = self.provider_id.get_base_url()
124 sanitized_reference = url_quote(self.reference)
125 # Append the reference to identify the transaction from the webhook payment data.
126 webhook_url = urljoin(base_url, f'{const.WEBHOOK_ROUTE}/{sanitized_reference}')
127 return {
128 'external_reference': self.reference,
129 'notification_url': webhook_url,
130 }
131
132 def _send_payment_request(self):
133 """Override of `payment` to send a payment request to Mercado Pago.
134
135 Note: `self.ensure_one()` from :meth:`_charge_with_token`
136
137 :rtype: None
138 """
139 if self.provider_code != 'mercado_pago':
140 super()._send_payment_request()
141 return
142
143 # A new token has to be generated based on 'card_id' for every payment.
144 response_content = self._send_api_request(
145 'POST', '/v1/card_tokens', data={'card_id': self.token_id.provider_ref}
146 )
147
148 # Send the payment request to Mercado Pago.
149 data = {
150 'transaction_amount': self._mercado_pago_convert_amount(),
151 'token': response_content['id'],
152 'installments': 1,
153 'payer': {
154 'type': 'customer',
155 'id': self.token_id.mercado_pago_customer_id,
156 },
157 }
158 response_content = self._send_api_request(
159 'POST',
160 endpoint='/v1/payments',
161 json=data,
162 idempotency_key=payment_utils.generate_idempotency_key(
163 self, scope='token_payment'
164 ),
165 )
166 self._process('mercado_pago', response_content)
167
168 def _mercado_pago_convert_amount(self):
169 """Convert the transaction amount according to Mercado Pago's currency requirements.
170
171 Mercado Pago requires certain currencies (COP, HNL, NIO) to be expressed as integers rather
172 than following the standard ISO 4217 decimal places. This method rounds down the amount to
173 the appropriate decimal places to ensure API compatibility.
174
175 :return: The transaction amount rounded to Mercado Pago's required decimal precision.
176 :rtype: float
177 """
178 unit_price = self.amount
179 decimal_places = const.CURRENCY_DECIMALS.get(self.currency_id.name)
180 if decimal_places is not None:
181 unit_price = float_round(unit_price, decimal_places, rounding_method='DOWN')
182 return unit_price
183
184 @api.model
185 def _extract_reference(self, provider_code, payment_data):
186 """Override of `payment` to extract the reference from the payment data."""
187 if provider_code != 'mercado_pago':
188 return super()._extract_reference(provider_code, payment_data)
189 return payment_data.get('external_reference')
190
191 def _extract_amount_data(self, payment_data):
192 """Override of payment to extract the amount and currency from the payment data."""
193 if self.provider_code != 'mercado_pago':
194 return super()._extract_amount_data(payment_data)
195
196 if self.operation in ('online_redirect', 'online_direct'):
197 amount = payment_data.get('additional_info', {}).get('items', [{}])[0].get('unit_price')
198 else: # 'online_token', 'offline'
199 amount = payment_data.get('transaction_amount')
200 currency_code = payment_data.get('currency_id')
201 return {
202 'amount': float(amount),
203 'currency_code': currency_code,
204 'precision_digits': const.CURRENCY_DECIMALS.get(currency_code),
205 }
206
207 def _apply_updates(self, payment_data):
208 """Override of `payment` to update the transaction based on the payment data."""
209 if self.provider_code != 'mercado_pago':
210 return super()._apply_updates(payment_data)
211
212 # Update the provider reference.
213 payment_id = payment_data.get('id')
214 if not payment_id:
215 self._set_error(_("Received data with missing payment id."))
216 return
217 self.provider_reference = payment_id
218
219 # Update the payment method.
220 payment_method_type = payment_data.get('payment_type_id', '')
221 for odoo_code, mp_codes in const.PAYMENT_METHODS_MAPPING.items():
222 if any(payment_method_type == mp_code for mp_code in mp_codes.split(',')):
223 payment_method_type = odoo_code
224 break
225 if payment_method_type == 'card':
226 payment_method_code = payment_data.get('payment_method_id')
227 else:
228 payment_method_code = payment_method_type
229 payment_method = self.env['payment.method']._get_from_code(
230 payment_method_code, mapping=const.PAYMENT_METHODS_MAPPING
231 )
232 # Fall back to "unknown" if the payment method is not found (and if "unknown" is found), as
233 # the user might have picked a different payment method than on Odoo's payment form.
234 if not payment_method:
235 payment_method = self.env['payment.method'].search([('code', '=', 'unknown')], limit=1)
236 self.payment_method_id = payment_method or self.payment_method_id
237
238 # Update the payment state.
239 payment_status = payment_data.get('status')
240 if not payment_status:
241 self._set_error(_("Received data with missing status."))
242 return
243
244 if payment_status in const.TRANSACTION_STATUS_MAPPING['pending']:
245 self._set_pending()
246 elif payment_status in const.TRANSACTION_STATUS_MAPPING['done']:
247 self._set_done()
248 elif payment_status in const.TRANSACTION_STATUS_MAPPING['canceled']:
249 self._set_canceled()
250 elif payment_status in const.TRANSACTION_STATUS_MAPPING['error']:
251 status_detail = payment_data.get('status_detail')
252 _logger.warning(
253 "Received data for transaction %s with status %s and error code: %s.",
254 self.reference, payment_status, status_detail
255 )
256 error_message = self._mercado_pago_get_error_msg(status_detail)
257 self._set_error(error_message)
258 else: # Classify unsupported payment status as the `error` tx state.
259 _logger.warning(
260 "Received data for transaction %s with invalid payment status: %s.",
261 self.reference, payment_status
262 )
263 self._set_error(_("Received data with invalid status: %s.", payment_status))
264
265 def _extract_token_values(self, payment_data):
266 """Override of `payment` to return token data based on payment data."""
267 if self.provider_code != 'mercado_pago':
268 return super()._extract_token_values(payment_data)
269
270 # Fetch the customer id or create a new one.
271 email_data = {'email': payment_data['payer']['email']}
272 response_content = self._send_api_request('GET', '/v1/customers/search', params=email_data)
273 if customers_data := response_content['results']:
274 customer_id = customers_data[0]['id']
275 else: # No customer found.
276 # Create a new customer.
277 response_content = self._send_api_request('POST', '/v1/customers', json=email_data)
278 customer_id = response_content['id']
279
280 # Fetch the card data.
281 payload = {
282 'token': payment_data['token'],
283 'issuer_id': int(payment_data['issuer_id']),
284 'payment_method_id': payment_data['payment_method_id']
285 }
286 response_content = self._send_api_request(
287 'POST', f'/v1/customers/{customer_id}/cards', json=payload
288 )
289 card_id = response_content['id']
290 last_four_digits = response_content['last_four_digits']
291
292 return {
293 'mercado_pago_customer_id': customer_id,
294 'payment_details': last_four_digits,
295 'provider_ref': card_id,
296 }
297
298 @api.model
299 def _mercado_pago_get_error_msg(self, status_detail):
300 """ Return the error message corresponding to the payment status.
301
302 :param str status_detail: The status details sent by the provider.
303 :return: The error message.
304 :rtype: str
305 """
306 return const.ERROR_MESSAGE_MAPPING.get(
307 status_detail, const.ERROR_MESSAGE_MAPPING['cc_rejected_other_reason']
308 )