| 1 |
# Part of Odoo. See LICENSE file for full copyright and licensing details. |
| 2 |
|
| 3 |
import json |
| 4 |
from datetime import timedelta |
| 5 |
from urllib.parse import urlencode |
| 6 |
|
| 7 |
from odoo import _, api, fields, models |
| 8 |
from odoo.exceptions import RedirectWarning, ValidationError |
| 9 |
from odoo.fields import Command |
| 10 |
from odoo.http import request |
| 11 |
from odoo.tools.urls import urljoin |
| 12 |
|
| 13 |
from odoo.addons.payment import utils as payment_utils |
| 14 |
from odoo.addons.payment.const import REPORT_REASONS_MAPPING |
| 15 |
from odoo.addons.payment.logging import get_payment_logger |
| 16 |
from odoo.addons.payment_mercado_pago import const |
| 17 |
|
| 18 |
|
| 19 |
_logger = get_payment_logger(__name__) |
| 20 |
|
| 21 |
|
| 22 |
class PaymentProvider(models.Model): |
| 23 |
_inherit = 'payment.provider' |
| 24 |
|
| 25 |
code = fields.Selection( |
| 26 |
selection_add=[('mercado_pago', "Mercado Pago")], ondelete={'mercado_pago': 'set default'} |
| 27 |
) |
| 28 |
mercado_pago_account_country_id = fields.Many2one( |
| 29 |
string="Mercado Pago Account Country", |
| 30 |
help="The country of the Mercado Pago account. The currency will be updated to match the" |
| 31 |
" country of the Mercado Pago account.", |
| 32 |
comodel_name='res.country', |
| 33 |
inverse='_inverse_mercado_pago_account_country_id', |
| 34 |
domain=[('code', 'in', list(const.SUPPORTED_COUNTRIES))], |
| 35 |
required_if_provider='mercado_pago', |
| 36 |
copy=False, |
| 37 |
) |
| 38 |
# TODO anko remove in 19.1 |
| 39 |
mercado_pago_is_oauth_supported = fields.Boolean(compute='_compute_mercado_pago_is_oauth_supported') |
| 40 |
|
| 41 |
# OAuth fields |
| 42 |
mercado_pago_access_token = fields.Char( |
| 43 |
string="Mercado Pago Access Token", |
| 44 |
copy=False, |
| 45 |
groups='base.group_system', |
| 46 |
) |
| 47 |
mercado_pago_access_token_expiry = fields.Datetime( |
| 48 |
string="Mercado Pago Access Token Expiry", |
| 49 |
copy=False, |
| 50 |
groups='base.group_system', |
| 51 |
) |
| 52 |
mercado_pago_refresh_token = fields.Char( |
| 53 |
string="Mercado Pago Refresh Token", |
| 54 |
copy=False, |
| 55 |
groups='base.group_system', |
| 56 |
) |
| 57 |
mercado_pago_public_key = fields.Char( |
| 58 |
string="Mercado Pago Public Key", |
| 59 |
copy=False, |
| 60 |
groups='base.group_system', |
| 61 |
) |
| 62 |
|
| 63 |
# === COMPUTE METHODS === # |
| 64 |
|
| 65 |
def _compute_feature_support_fields(self): |
| 66 |
"""Override of `payment` to enable additional features.""" |
| 67 |
super()._compute_feature_support_fields() |
| 68 |
self.filtered(lambda p: p.code == 'mercado_pago').update({ |
| 69 |
'support_tokenization': True, |
| 70 |
}) |
| 71 |
|
| 72 |
def _inverse_mercado_pago_account_country_id(self): |
| 73 |
for provider in self.filtered( |
| 74 |
lambda p: p.code == 'mercado_pago' and p.mercado_pago_account_country_id |
| 75 |
): |
| 76 |
currency_code = const.CURRENCY_MAPPING.get(self.mercado_pago_account_country_id.code) |
| 77 |
currency = self.env['res.currency'].with_context( |
| 78 |
active_test=False, |
| 79 |
).search([('name', '=', currency_code)], limit=1) |
| 80 |
provider.available_currency_ids = [Command.set(currency.ids)] |
| 81 |
|
| 82 |
def _compute_mercado_pago_is_oauth_supported(self): |
| 83 |
"""Return current state of OAuth support by Odoo. To be removed in future versions.""" |
| 84 |
self.mercado_pago_is_oauth_supported = False |
| 85 |
|
| 86 |
# === CONSTRAINT METHODS === # |
| 87 |
|
| 88 |
@api.constrains('state', 'mercado_pago_access_token') |
| 89 |
def _check_mercado_pago_credentials_are_set_before_enabling(self): |
| 90 |
"""Check that the Mercado Pago credentials are valid when the provider is enabled. |
| 91 |
|
| 92 |
:raise ValidationError: If the Mercado Pago credentials are not set. |
| 93 |
""" |
| 94 |
for provider in self.filtered(lambda p: p.code == 'mercado_pago' and p.state != 'disabled'): |
| 95 |
if not provider.mercado_pago_access_token: |
| 96 |
raise ValidationError(_( |
| 97 |
"Mercado Pago credentials are missing. Click the \"Connect\" button to set up" |
| 98 |
" your account." |
| 99 |
)) |
| 100 |
|
| 101 |
@api.constrains('allow_tokenization', 'mercado_pago_public_key') |
| 102 |
def _check_mercado_pago_credentials_are_set_before_allowing_tokenization(self): |
| 103 |
"""Check that the OAuth credentials are valid when the tokenization is enabled. |
| 104 |
|
| 105 |
:raise ValidationError: If the Mercado Pago credentials are not valid. |
| 106 |
""" |
| 107 |
if any( |
| 108 |
p.code == 'mercado_pago' |
| 109 |
and p.allow_tokenization |
| 110 |
and not p.mercado_pago_public_key |
| 111 |
for p in self |
| 112 |
): |
| 113 |
raise ValidationError(_("Connect your account before enabling tokenization.")) |
| 114 |
|
| 115 |
# === CRUD METHODS === # |
| 116 |
|
| 117 |
def _get_default_payment_method_codes(self): |
| 118 |
""" Override of `payment` to return the default payment method codes. """ |
| 119 |
self.ensure_one() |
| 120 |
if self.code != 'mercado_pago': |
| 121 |
return super()._get_default_payment_method_codes() |
| 122 |
return const.DEFAULT_PAYMENT_METHOD_CODES |
| 123 |
|
| 124 |
# === ACTIONS METHODS === # |
| 125 |
|
| 126 |
def action_start_onboarding(self, menu_id=None): |
| 127 |
"""Override of `payment` to redirect to the Mercado Pago OAuth URL. |
| 128 |
|
| 129 |
Note: `self.ensure_one()` |
| 130 |
|
| 131 |
:param int menu_id: The menu from which the onboarding is started, as an `ir.ui.menu` id. |
| 132 |
:return: An URL action to redirect to the Mercado Pago OAuth URL. |
| 133 |
:rtype: dict |
| 134 |
:raise RedirectWarning: If the company's currency is not supported. |
| 135 |
""" |
| 136 |
self.ensure_one() |
| 137 |
|
| 138 |
if self.code != 'mercado_pago': |
| 139 |
return super().action_start_onboarding(menu_id=menu_id) |
| 140 |
|
| 141 |
if self.company_id.country_id.code not in const.SUPPORTED_COUNTRIES: |
| 142 |
raise RedirectWarning( |
| 143 |
_( |
| 144 |
"Mercado Pago is not available in your country; please use another payment" |
| 145 |
" provider." |
| 146 |
), |
| 147 |
self.env.ref('payment.action_payment_provider').id, |
| 148 |
_("Other Payment Providers"), |
| 149 |
) |
| 150 |
|
| 151 |
if not self.mercado_pago_account_country_id: |
| 152 |
raise ValidationError(_("Set the account country before connecting the account.")) |
| 153 |
|
| 154 |
# Encode the return URL parameters here rather than passing them in the 'state' parameter |
| 155 |
# from IAP, because Mercado Pago doesn't JSON dumps in that parameter. |
| 156 |
return_url_params = { |
| 157 |
'provider_id': self.id, |
| 158 |
'csrf_token': request.csrf_token(), |
| 159 |
} |
| 160 |
return_url = urljoin(self.get_base_url(), const.OAUTH_RETURN_ROUTE) |
| 161 |
proxy_url_params = { |
| 162 |
'return_url': f'{return_url}?{urlencode(return_url_params)}', |
| 163 |
'account_country_code': self.mercado_pago_account_country_id.code.lower(), |
| 164 |
} |
| 165 |
proxy_url = self._build_request_url('/authorize', is_proxy_request=True) |
| 166 |
return { |
| 167 |
'type': 'ir.actions.act_url', |
| 168 |
'url': f'{proxy_url}?{urlencode(proxy_url_params)}', |
| 169 |
'target': 'self', |
| 170 |
} |
| 171 |
|
| 172 |
def _get_reset_values(self): |
| 173 |
"""Override of `payment` to supply the provider-specific credential values to reset.""" |
| 174 |
if self.code != 'mercado_pago': |
| 175 |
return super()._get_reset_values() |
| 176 |
|
| 177 |
return { |
| 178 |
'mercado_pago_access_token': None, |
| 179 |
'mercado_pago_access_token_expiry': None, |
| 180 |
'mercado_pago_public_key': None, |
| 181 |
'mercado_pago_refresh_token': None, |
| 182 |
'allow_tokenization': False, # The account must be connected to allow tokenization. |
| 183 |
} |
| 184 |
|
| 185 |
# === BUSINESS METHODS === # |
| 186 |
|
| 187 |
@api.model |
| 188 |
def _get_compatible_providers(self, *args, is_validation=False, report=None, **kwargs): |
| 189 |
""" Override of `payment` to filter out Mercado Pago providers for validation operations. |
| 190 |
""" |
| 191 |
providers = super()._get_compatible_providers( |
| 192 |
*args, is_validation=is_validation, report=report, **kwargs |
| 193 |
) |
| 194 |
|
| 195 |
if is_validation: |
| 196 |
unfiltered_providers = providers |
| 197 |
providers = providers.filtered(lambda p: p.code != 'mercado_pago') |
| 198 |
payment_utils.add_to_report( |
| 199 |
report, |
| 200 |
unfiltered_providers - providers, |
| 201 |
available=False, |
| 202 |
reason=REPORT_REASONS_MAPPING['validation_not_supported'], |
| 203 |
) |
| 204 |
|
| 205 |
return providers |
| 206 |
|
| 207 |
def _mercado_pago_get_inline_form_values(self, partner_id): |
| 208 |
"""Return a serialized JSON of the values required to render the inline form. |
| 209 |
|
| 210 |
Note: `self.ensure_one()` |
| 211 |
|
| 212 |
:param int partner_id: The partner of the transaction, as a `res.partner` id. |
| 213 |
:return: The JSON serial of the inline form values. |
| 214 |
:rtype: str |
| 215 |
""" |
| 216 |
self.ensure_one() |
| 217 |
|
| 218 |
partner = self.env['res.partner'].browse(partner_id).exists() |
| 219 |
inline_form_values = { |
| 220 |
'email': partner.email, |
| 221 |
'public_key': self.mercado_pago_public_key, |
| 222 |
} |
| 223 |
return json.dumps(inline_form_values) |
| 224 |
|
| 225 |
# === REQUEST HELPERS === # |
| 226 |
|
| 227 |
def _build_request_url(self, endpoint, *, is_proxy_request=False, **kwargs): |
| 228 |
"""Override of `payment` to build the request URL.""" |
| 229 |
if self.code != 'mercado_pago': |
| 230 |
return super()._build_request_url(endpoint, is_proxy_request=is_proxy_request, **kwargs) |
| 231 |
|
| 232 |
if is_proxy_request: |
| 233 |
return urljoin(f'{const.PROXY_URL}/1', endpoint) |
| 234 |
|
| 235 |
return urljoin('https://api.mercadopago.com', endpoint) |
| 236 |
|
| 237 |
def _build_request_headers( |
| 238 |
self, |
| 239 |
method, |
| 240 |
*args, |
| 241 |
idempotency_key=None, |
| 242 |
is_proxy_request=False, |
| 243 |
is_refresh_token_request=False, |
| 244 |
**kwargs, |
| 245 |
): |
| 246 |
"""Override of `payment` to build the request headers.""" |
| 247 |
if self.code != 'mercado_pago': |
| 248 |
return super()._build_request_headers( |
| 249 |
method, |
| 250 |
*args, |
| 251 |
idempotency_key=idempotency_key, |
| 252 |
is_proxy_request=is_proxy_request, |
| 253 |
**kwargs, |
| 254 |
) |
| 255 |
|
| 256 |
headers = { |
| 257 |
'X-Platform-Id': 'dev_cdf1cfac242111ef9fdebe8d845d0987', |
| 258 |
} |
| 259 |
if method == 'POST' and idempotency_key: |
| 260 |
headers['X-Idempotency-Key'] = idempotency_key |
| 261 |
if not is_proxy_request and not is_refresh_token_request: |
| 262 |
access_token = self._mercado_pago_fetch_access_token() |
| 263 |
headers['Authorization'] = f'Bearer {access_token}' |
| 264 |
return headers |
| 265 |
|
| 266 |
def _mercado_pago_fetch_access_token(self): |
| 267 |
"""Generate a new access token if it's expired, otherwise return the existing access token. |
| 268 |
|
| 269 |
Note: `self.ensure_one()` |
| 270 |
|
| 271 |
:return: A valid access token. |
| 272 |
:rtype: str |
| 273 |
:raise ValidationError: If the access token can not be fetched. |
| 274 |
""" |
| 275 |
self.ensure_one() |
| 276 |
|
| 277 |
if ( |
| 278 |
self.mercado_pago_access_token |
| 279 |
and ( |
| 280 |
not self.mercado_pago_access_token_expiry # Legacy access token |
| 281 |
or self.mercado_pago_access_token_expiry >= fields.Datetime.now() |
| 282 |
) |
| 283 |
): |
| 284 |
return self.mercado_pago_access_token |
| 285 |
else: |
| 286 |
proxy_payload = self._prepare_json_rpc_payload( |
| 287 |
{ |
| 288 |
'refresh_token': self.mercado_pago_refresh_token, |
| 289 |
'account_country_code': self.mercado_pago_account_country_id.code.lower(), |
| 290 |
} |
| 291 |
) |
| 292 |
response_content = self._send_api_request( |
| 293 |
'POST', |
| 294 |
'/refresh_access_token', |
| 295 |
json=proxy_payload, |
| 296 |
is_proxy_request=True, |
| 297 |
is_refresh_token_request=True, |
| 298 |
) |
| 299 |
expires_in = ( |
| 300 |
fields.Datetime.now() |
| 301 |
+ timedelta(seconds=int(response_content['expires_in'])) |
| 302 |
- timedelta(days=31) |
| 303 |
) |
| 304 |
self.write({ |
| 305 |
'mercado_pago_access_token': response_content['access_token'], |
| 306 |
'mercado_pago_access_token_expiry': expires_in, |
| 307 |
'mercado_pago_refresh_token': response_content['refresh_token'], |
| 308 |
}) |
| 309 |
return self.mercado_pago_access_token |
| 310 |
|
| 311 |
def _parse_response_content(self, response, *, is_proxy_request=False, **kwargs): |
| 312 |
"""Override of `payment` to parse the response content.""" |
| 313 |
if self.code != 'mercado_pago' or not is_proxy_request: |
| 314 |
return super()._parse_response_content( |
| 315 |
response, is_proxy_request=is_proxy_request, **kwargs |
| 316 |
) |
| 317 |
return self._parse_proxy_response(response) |
| 318 |
|
| 319 |
def _parse_response_error(self, response): |
| 320 |
"""Override of `payment` to parse the error message.""" |
| 321 |
if self.code != 'mercado_pago': |
| 322 |
return super()._parse_response_error(response) |
| 323 |
return response.json().get('message', '') |