Skip to content

Commit

Permalink
[12.0][FIX] payment_garanti ported to Odoo 12.0 workflow
Browse files Browse the repository at this point in the history
  • Loading branch information
yibudak committed Aug 14, 2023
1 parent 76cdcea commit 8c056fc
Show file tree
Hide file tree
Showing 13 changed files with 376 additions and 376 deletions.
15 changes: 5 additions & 10 deletions payment_garanti/__init__.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
# Copyright 2022 Yiğit Budak (https://github.com/yibudak)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

from . import controllers
from . import models

# from odoo.addons.payment import setup_provider, reset_payment_provider
from . import controllers
from odoo.addons.payment.models.payment_acquirer import (
create_missing_journal_for_acquirers,
)
from odoo.addons.payment import reset_payment_provider
from odoo.addons.payment.models.payment_acquirer import create_missing_journal_for_acquirers

#
#
# def post_init_hook(cr, registry):
# setup_provider(cr, registry, 'garanti')


def uninstall_hook(cr, registry):
reset_payment_provider(cr, registry, 'garanti')
reset_payment_provider(cr, registry, "garanti")
7 changes: 1 addition & 6 deletions payment_garanti/__manifest__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
"website": "https://github.com/odoo-turkey",
"author": "Yigit Budak",
"sequence": 350,
# TODO: Summary ingilizceye çevrilebilir
"summary": "Garanti BBVA Sanal POS, internet üzerinden yapılan satışlarda"
" kredi kartı ile ödeme alınabilmesi için oluşturulan güvenli"
" bir ödeme çözümüdür.",
Expand All @@ -17,13 +16,9 @@
"data": [
"views/payment_garanti_templates.xml",
"views/payment_views.xml",
"templates/result_page.xml",
"data/payment_acquirer_data.xml",
],
# 'assets': {
# 'web.assets_frontend': [
# 'payment_garanti/static/src/js/payment_form.js',
# ],
# },
"application": True,
"post_init_hook": "create_missing_journal_for_acquirers",
"uninstall_hook": "uninstall_hook",
Expand Down
146 changes: 86 additions & 60 deletions payment_garanti/controllers/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,75 +2,89 @@
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
import pprint
from odoo import _, http
from odoo import _, http, fields
from odoo.exceptions import ValidationError
from odoo.addons.payment.controllers.portal import PaymentProcessing
from odoo.tools import float_compare
from odoo.http import request
from datetime import datetime

# from odoo.addons.payment import utils as payment_utils

_logger = logging.getLogger(__name__)


class GarantiController(http.Controller):
_payment_url = "/payment/garanti/s2s/create_json_3ds"
_return_url = "/payment/garanti/return"

@http.route("/payment/garanti/s2s/create_json_3ds", type="json", auth="public")
def garanti_s2s_create_json_3ds(self, verify_validity=False, **kwargs):
token = False
acquirer = request.env["payment.acquirer"].browse(
int(kwargs.get("acquirer_id"))
@http.route(_payment_url, type="json", auth="public")
def garanti_s2s_create_json_3ds(self, **kwargs):
# !!! Printing the card data for debugging purposes is a security risk !!!
# _logger.debug(
# "Garanti payment request received: s2s_create_json_3ds: kwargs=%s",
# pprint.pformat(kwargs),
# )
acq = (
request.env["payment.acquirer"]
.sudo()
.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}

# Validate the card data
card_args = dict()
card_args["card_number"] = kwargs.get("cardNumber")
card_args["card_cvv"] = kwargs.get("cardCVV")
card_args["card_name"] = kwargs.get("cardName")
card_args["card_number"] = kwargs.get("cc_number")
card_args["card_cvv"] = kwargs.get("cc_cvc")
card_args["card_name"] = kwargs.get("cc_holder_name")
card_args["card_valid_month"] = kwargs.get("cc_expiry")[0:2]
card_args["card_valid_year"] = kwargs.get("cc_expiry")[6:]
card_args["card_valid_year"] = kwargs.get("cc_expiry")[5:]

card_error = acquirer_sudo._garanti_validate_card_args(card_args)
card_error = acq._garanti_validate_card_args(card_args)
if card_error:
raise ValidationError(card_error)

# tx_sudo = (
# request.env["payment.transaction"]
# .sudo()
# .search([("reference", "=", reference)])
# )
# Get the order
order_sudo = (
request.env["sale.order"].sudo().browse(int(kwargs.get("order_id")))
)
if not order_sudo:
raise ValidationError(_("Sale order not found"))

# Validate the amount
try:
amount = float(kwargs.get("amount_total"))
except (ValueError, TypeError):
raise ValidationError(_("Invalid amount"))

precision = request.env["decimal.precision"].precision_get("account")
if float_compare(amount, order_sudo.amount_total, precision) != 0:
raise ValidationError(_("Invalid amount"))

# Create the transaction
tx_sudo = (
request.env["payment.transaction"]
.sudo()
.create(
{
"amount": order_sudo.amount_total,
"acquirer_id": acq.id,
"acquirer_reference": order_sudo.name,
"partner_id": order_sudo.partner_id.id,
"sale_order_ids": [(4, order_sudo.id, False)],
"currency_id": order_sudo.currency_id.id,
"date": datetime.now(),
"state": "draft",
}
)
)

# Get client IP
client_ip = request.httprequest.environ.get("REMOTE_ADDR")

response_content = acquirer_sudo._garanti_make_payment_request(
amount, currency_id, card_args, client_ip
# Get the payment response, it can be a redirect or a form
response_content = acq.sudo()._garanti_make_payment_request(
tx_sudo, amount, order_sudo.currency_id.id, card_args, client_ip
)
# Save the transaction in the session
PaymentProcessing.add_payment_transaction(tx_sudo)
return response_content

@http.route(
Expand All @@ -79,25 +93,37 @@ def garanti_s2s_create_json_3ds(self, verify_validity=False, **kwargs):
auth="public",
csrf=False,
save_session=False,
methods=["POST"],
methods=["GET"],
)
def garanti_return_from_3ds_auth(self, **kwargs):
"""
Handle the return from the 3DS authentication.
notification_data is a dict coming from Garanti.
"""
tx_sudo = (
request.env["payment.transaction"]
.sudo()
._handle_notification_data("garanti", kwargs)
)

_logger.info(
"handling redirection from Garanti for transaction with"
" reference %s with data:\n%s",
tx_sudo.reference,
# handle the response
# Careful about the log here, it can contain sensitive information
_logger.debug(
"Garanti 3DS auth return received: return_from_3ds_auth: kwargs=%s",
pprint.pformat(kwargs),
)
try:
tx = (
request.env["payment.transaction"]
.sudo()
.form_feedback(data=kwargs, acquirer_name="garanti")
)
if tx.state != "done":
raise ValidationError(_("Transaction not completed"))
except:
return _(
"An error occurred while processing your payment. Please contact us."
)

# Redirect the user to the status page
return request.redirect("/payment/status")
return request.render(
"payment_garanti.garanti_payment_result",
qcontext={
"tx_id": tx,
"order_id": fields.first(tx.sale_order_ids[0]),
},
)
6 changes: 2 additions & 4 deletions payment_garanti/data/payment_acquirer_data.xml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<odoo noupdate="1">

<record id="payment_acquirer_garanti" model="payment.acquirer">
<field name="name">Garanti</field>
Expand All @@ -9,6 +9,7 @@
<field name="view_template_id" ref="payment_garanti.garanti_form"/>
<field name="registration_view_template_id" ref="payment_garanti.garanti_s2s_form"/>
<field name="environment">test</field>
<field name="payment_flow">s2s</field>
<field name="pre_msg"><![CDATA[
<p><br></p>]]></field>

Expand All @@ -22,9 +23,6 @@
<field name="garanti_prov_user">dummy</field>
<field name="garanti_prov_password">dummy</field>
<field name="garanti_store_key">dummy</field>


<!-- <field name="inline_form_view_id" ref="inline_form"/>-->
</record>

</odoo>
Loading

0 comments on commit 8c056fc

Please sign in to comment.