Files
odoo_source/addons/payment_authorize/controllers/main.py
T
nie be2ce0522e [FIX] payment_authorize: Show UserError to user
Steps:
- Install website_sale and payment_authorize
- Set up a tunnel (e.g. ngrok)
- Log in to Authorize.Net backend
- Go to Account > Response/Receipt URLs > Add Url
- Enter the tunnel URL
- In Odoo, go to Website > Configuration > eCommerce > Payment Acquirers
- Edit "Authorize.Net"
  - Credentials tab:
    - State: Test Mode
    - API Login Id, Transaction and Signature key
    - Save, then Generate Client Key
  - Configuration tab:
    - Payment Flow: Payment from Odoo
- Stop the server
- Replace https://github.com/odoo/odoo/blob/1b9b99dc2643910c1412b564affccf02ba1e55d9/addons/payment_authorize/models/authorize_request.py#L46 with `resp = {'messages': {'resultCode': 'Error', 'message': [{'code': 'E00027', 'text': 'An error occurred during processing. Call Merchant Service Provider.'}]}}`
- Restart the server
- Go to "Website" > "Go to Website" > Shop
- Add a product to the basket
- Check out the basket
- Choose "Credit Card (powered by Authorize) Test Mode"
- Pay Now
- Enter any card data (e.g. 4111 1111 1111 1111 - 01/22 - 900)

Bug:
When the Pay Now process is done, the customer is redirected to
`/shop?error=invalid_token_id`. No errors are shown.

Explanation:
The patch simulates an error from Authorize.Net happening during their
process. Using the special card numbers won't trigger the wanted
behavior.

When getting an error from Authorize.net, a `UserError` is raised. This
error is then caught in the controller to return a formatted message.
However, returning a dict in this part of the code embeds it inside
`{'result': [...]}`. The error message is, thus, not blocking the form's
redirection and the user gets redirected to the form action, i.e.
`/shop/payment/token`. This route requires `pm_id`, but, in this
scenario, it's an empty string. This leads to another redirection to
`/shop/?error=invalid_token_id` as seen here:
https://github.com/odoo/odoo/blob/1b9b99dc2643910c1412b564affccf02ba1e55d9/addons/website_sale/controllers/main.py#L938-L941

Letting the error bubble up forces the backend to return a blocking
error response. This makes the fronted display the Authorize.Net error
underneath the provider selection, and prevents it from redirecting.

opw:2419260

closes odoo/odoo#64482

X-original-commit: 2636b9f5059808b443be67b06fca129cf9d3a913
Signed-off-by: backspac <backspac@users.noreply.github.com>
2021-01-13 13:44:00 +00:00

86 lines
3.9 KiB
Python

# -*- coding: utf-8 -*-
import pprint
import logging
from werkzeug import urls, utils
from odoo import http, _
from odoo.http import request
from odoo.exceptions import ValidationError, UserError
_logger = logging.getLogger(__name__)
class AuthorizeController(http.Controller):
_return_url = '/payment/authorize/return/'
_cancel_url = '/payment/authorize/cancel/'
@http.route([
'/payment/authorize/return/',
'/payment/authorize/cancel/',
], type='http', auth='public', csrf=False)
def authorize_form_feedback(self, **post):
_logger.info('Authorize: entering form_feedback with post data %s', pprint.pformat(post))
if post:
request.env['payment.transaction'].sudo().form_feedback(post, 'authorize')
base_url = request.env['ir.config_parameter'].sudo().get_param('web.base.url')
# Authorize.Net is expecting a response to the POST sent by their server.
# This response is in the form of a URL that Authorize.Net will pass on to the
# client's browser to redirect them to the desired location need javascript.
return request.render('payment_authorize.payment_authorize_redirect', {
'return_url': urls.url_join(base_url, "/payment/process")
})
@http.route(['/payment/authorize/s2s/create_json_3ds'], type='json', auth='public', csrf=False)
def authorize_s2s_create_json_3ds(self, verify_validity=False, **kwargs):
token = False
acquirer = request.env['payment.acquirer'].browse(int(kwargs.get('acquirer_id')))
try:
if not kwargs.get('partner_id'):
kwargs = dict(kwargs, partner_id=request.env.user.partner_id.id)
token = acquirer.s2s_process(kwargs)
except ValidationError as e:
message = e.args[0]
if isinstance(message, dict) and 'missing_fields' in message:
if request.env.user._is_public():
message = _("Please sign in to complete the payment.")
# update message if portal mode = b2b
if request.env['ir.config_parameter'].sudo().get_param('auth_signup.allow_uninvited', 'False').lower() == 'false':
message += _(" If you don't have any account, ask your salesperson to grant you a portal access. ")
else:
msg = _("The transaction cannot be processed because some contact details are missing or invalid: ")
message = msg + ', '.join(message['missing_fields']) + '. '
message += _("Please complete your profile. ")
return {
'error': message
}
if not token:
res = {
'result': False,
}
return res
res = {
'result': True,
'id': token.id,
'short_name': token.short_name,
'3d_secure': False,
'verified': True, #Authorize.net does a transaction type of Authorization Only
#As Authorize.net already verify this card, we do not verify this card again.
}
#token.validate() don't work with Authorize.net.
#Payments made via Authorize.net are settled and allowed to be refunded only on the next day.
#https://account.authorize.net/help/Miscellaneous/FAQ/Frequently_Asked_Questions.htm#Refund
#<quote>The original transaction that you wish to refund must have a status of Settled Successfully.
#You cannot issue refunds against unsettled, voided, declined or errored transactions.</quote>
return res
@http.route(['/payment/authorize/s2s/create'], type='http', auth='public')
def authorize_s2s_create(self, **post):
acquirer_id = int(post.get('acquirer_id'))
acquirer = request.env['payment.acquirer'].browse(acquirer_id)
acquirer.s2s_process(post)
return utils.redirect("/payment/process")