Merge pull request #2759 from expsa/ENS-3085
[MIG][IMP][ADD] payment_applepay, p_donation_theme, ensan_sale_management: migrate applypay to v14
This commit is contained in:
commit
5b5714fa00
|
|
@ -0,0 +1 @@
|
|||
from . import models
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
'name': 'Ensan Sale Management',
|
||||
'version': '14.0',
|
||||
'description': '',
|
||||
'summary': '',
|
||||
'author': 'Ensan',
|
||||
'website': 'https://ensan.com',
|
||||
'license': 'LGPL-3',
|
||||
'category': 'Sales',
|
||||
'depends': ['base', 'website_sale'],
|
||||
'data': [
|
||||
'security/ir.model.access.csv',
|
||||
'data/sms_data.xml',
|
||||
'views/sale_order_views.xml',
|
||||
'views/product_views.xml'
|
||||
],
|
||||
}
|
||||
|
|
@ -9,10 +9,9 @@
|
|||
|
||||
<record id="sms_template_donors_data_donation" model="sms.template">
|
||||
<field name="name">Donation on Behalf Confirmed</field>
|
||||
<field name="model_id" ref="p_donation_theme.model_sale_order_extra_donators"/>
|
||||
<field name="model_id" ref="ensan_sale_management.model_sale_order_extra_donators"/>
|
||||
<field name="lang">ar</field>
|
||||
<field name="body">بكل الود أهديك تبرع عبر منصة إنسان لمشروع: {{object.product_id.name}} من : {{object.sale_id.order_name}}</field>
|
||||
<!-- <field name="body" type="html"><p>Hello {{object.donator_name}},</p><p>{{object.sale_id.order_name}} has donated for you on {{object.product_id.name}} with amount {{ object.sale_id.currency_id.symbol if object.sale_id.currency_id.position == 'before' else '' }}{{ object.donated_amount }}{{ object.sale_id.currency_id.symbol if object.sale_id.currency_id.position == 'after' else '' }} On Ensan Donation Platform.</p></field> -->
|
||||
</record>
|
||||
</data>
|
||||
</odoo>
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
from . import sale_order
|
||||
from . import product
|
||||
|
|
@ -4,6 +4,7 @@ from odoo.tools.json import scriptsafe as json_scriptsafe
|
|||
|
||||
class SaleOrder_Inherit(models.Model):
|
||||
_inherit = 'sale.order'
|
||||
|
||||
done_with_quick_donation = fields.Boolean(default=False)
|
||||
order_mobile_number = fields.Char("Donor Number")
|
||||
order_name = fields.Char("Donor Name")
|
||||
|
|
@ -12,8 +13,7 @@ class SaleOrder_Inherit(models.Model):
|
|||
|
||||
def get_sale_order_portal_url(self):
|
||||
for sale in self:
|
||||
sale.sale_order_portal_url = self.env['ir.config_parameter'].sudo().get_param(
|
||||
'web.base.url') + sale.get_portal_url()
|
||||
sale.sale_order_portal_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') + sale.get_portal_url()
|
||||
|
||||
def _cart_update(self, *args, **kwargs):
|
||||
res = super(SaleOrder_Inherit, self)._cart_update(*args, **kwargs)
|
||||
|
|
@ -48,13 +48,13 @@ class SaleOrder_Inherit(models.Model):
|
|||
if call_super == True:
|
||||
for rec in self:
|
||||
if rec.order_mobile_number:
|
||||
sms_template_id = self.env.ref('p_donation_theme.sms_template_data_donation')
|
||||
sms_template_id = self.env.ref('ensan_sale_management.sms_template_data_donation')
|
||||
rec._message_sms_with_template(
|
||||
template=sms_template_id,
|
||||
put_in_queue=False,
|
||||
sms_numbers=[rec.order_mobile_number]
|
||||
)
|
||||
donar_sms_template_id = self.env.ref('p_donation_theme.sms_template_donors_data_donation')
|
||||
donar_sms_template_id = self.env.ref('ensan_sale_management.sms_template_donors_data_donation')
|
||||
for donator in rec.donators_ids:
|
||||
donator._message_sms_with_template(
|
||||
template=donar_sms_template_id,
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
|
||||
access_sale_order_extra_donators,access.sale.order.extra_donators,model_sale_order_extra_donators,,1,1,1,1
|
||||
|
|
|
@ -0,0 +1,42 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
|
||||
<record model="ir.ui.view" id="product_template_inherit_form">
|
||||
<field name="name">product.template.form.inherit</field>
|
||||
<field name="model">product.template</field>
|
||||
<field name="inherit_id" ref="product.product_template_only_form_view"/>
|
||||
<field name="arch" type="xml">
|
||||
<field name="sale_ok" position="before">
|
||||
<div>
|
||||
<field name="is_donation"/>
|
||||
<label for="is_donation"/>
|
||||
</div>
|
||||
</field>
|
||||
<xpath expr="//page[@name='general_information']" position="after">
|
||||
<page name="bbb" string="Donation" attrs= "{'invisible':[('is_donation','=', False)]}">
|
||||
<group>
|
||||
<group>
|
||||
<field name="is_quick_donation"/>
|
||||
<field name="donation_type"/>
|
||||
<field name="target_amount"/>
|
||||
<field name="donated_amount"/>
|
||||
<field name="remaining_amount"/>
|
||||
<field name="done_percentage" widget="percentpie"/>
|
||||
</group>
|
||||
<group>
|
||||
<field name="number_of_donations"/>
|
||||
<field name="beneficiaries"/>
|
||||
<field name="beneficiaries_been_supported"/>
|
||||
<field name="beneficiaries_residual"/>
|
||||
<field name="done_beneficiaries_percentage" widget="percentpie"/>
|
||||
</group>
|
||||
</group>
|
||||
|
||||
</page>
|
||||
</xpath>
|
||||
|
||||
|
||||
</field>
|
||||
</record>
|
||||
|
||||
</odoo>
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
|
||||
<record id="view_order_form" model="ir.ui.view">
|
||||
<field name="name">extrafield.sale.order.form.view</field>
|
||||
<field name="model">sale.order</field>
|
||||
<field name="inherit_id" ref="sale.view_order_form"/>
|
||||
<field name="arch" type="xml">
|
||||
<xpath expr="//field[@name='partner_id']" position="before">
|
||||
<field name="order_name"/>
|
||||
<field name="order_mobile_number"/>
|
||||
<field name="done_with_quick_donation" readonly="1"/>
|
||||
</xpath>
|
||||
<xpath expr="//notebook" position="inside">
|
||||
<page name="extra_donators" string="Donators">
|
||||
<field name="donators_ids">
|
||||
<tree string="Donators">
|
||||
<field name="product_id"/>
|
||||
<field name="donator_name"/>
|
||||
<field name="donated_amount"/>
|
||||
<field name="donator_mobile_number"/>
|
||||
</tree>
|
||||
</field>
|
||||
</page>
|
||||
</xpath>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
</odoo>
|
||||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from . import controllers
|
||||
from . import models
|
||||
from . import controllers
|
||||
|
|
@ -12,13 +12,17 @@
|
|||
'license': 'LGPL-3',
|
||||
'category': 'Uncategorized',
|
||||
'version': '14.0.1',
|
||||
'depends': ['base', 'website_sale', 'theme_prime', 'droggol_theme_common', 'payment_hyperpay', 'payment_applepay'],
|
||||
'depends': ['base',
|
||||
'website_sale',
|
||||
'theme_prime',
|
||||
'droggol_theme_common',
|
||||
'payment_hyperpay',
|
||||
'payment_applepay',
|
||||
'ensan_sale_management'],
|
||||
|
||||
'data': [
|
||||
'security/ir.model.access.csv',
|
||||
'views/templates.xml',
|
||||
'views/views.xml',
|
||||
'data/sms_data.xml'
|
||||
],
|
||||
'images': ['static/description/banner.png'],
|
||||
}
|
||||
|
|
|
|||
|
|
@ -122,10 +122,10 @@ class WebsiteSaleExtended(WebsiteSale):
|
|||
try:
|
||||
if acquire_id:
|
||||
payment_acquire_id = request.env['payment.acquirer'].sudo().search(
|
||||
[('code', 'in', ['hyperpay', 'applepay']), ('company_id', 'in', (False, order.company_id.id)), ('id', '=', int(acquire_id))], limit=1)
|
||||
[('provider', '=', 'hyperpay'), ('company_id', 'in', (False, order.company_id.id)), ('id', '=', int(acquire_id))], limit=1)
|
||||
else:
|
||||
payment_acquire_id = request.env['payment.acquirer'].sudo().search(
|
||||
[('code', '=', 'hyperpay'), ('company_id', 'in', (False, order.company_id.id))], limit=1)
|
||||
[('provider', '=', 'hyperpay'), ('company_id', 'in', (False, order.company_id.id))], limit=1)
|
||||
|
||||
# Create transaction
|
||||
vals = {'acquirer_id': payment_acquire_id,
|
||||
|
|
|
|||
|
|
@ -1,3 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from . import sale, product
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
id,name,model_id/id,group_id/id,perm_read,perm_write,perm_create,perm_unlink
|
||||
access_sale_order_extra_donators,access.sale.order.extra_donators,model_sale_order_extra_donators,,1,1,1,1
|
||||
|
|
|
@ -1,70 +1,6 @@
|
|||
<odoo>
|
||||
<data>
|
||||
|
||||
<record model="ir.ui.view" id="product_template_inherit_form">
|
||||
<field name="name">product.template.form.inherit</field>
|
||||
<field name="model">product.template</field>
|
||||
<field name="inherit_id" ref="product.product_template_only_form_view"/>
|
||||
<field name="arch" type="xml">
|
||||
<field name="sale_ok" position="before">
|
||||
<div>
|
||||
<field name="is_donation"/>
|
||||
<label for="is_donation"/>
|
||||
</div>
|
||||
</field>
|
||||
<xpath expr="//page[@name='general_information']" position="after">
|
||||
<page name="bbb" string="Donation" attrs= "{'invisible':[('is_donation','=', False)]}">
|
||||
<group>
|
||||
<group>
|
||||
<field name="is_quick_donation"/>
|
||||
<field name="donation_type"/>
|
||||
<field name="target_amount"/>
|
||||
<field name="donated_amount"/>
|
||||
<field name="remaining_amount"/>
|
||||
<field name="done_percentage" widget="percentpie"/>
|
||||
</group>
|
||||
<group>
|
||||
<field name="number_of_donations"/>
|
||||
<field name="beneficiaries"/>
|
||||
<field name="beneficiaries_been_supported"/>
|
||||
<field name="beneficiaries_residual"/>
|
||||
<field name="done_beneficiaries_percentage" widget="percentpie"/>
|
||||
</group>
|
||||
</group>
|
||||
|
||||
</page>
|
||||
</xpath>
|
||||
|
||||
|
||||
</field>
|
||||
|
||||
|
||||
</record>
|
||||
<record id="view_order_form" model="ir.ui.view">
|
||||
<field name="name">extrafield.sale.order.form.view</field>
|
||||
<field name="model">sale.order</field>
|
||||
<field name="inherit_id" ref="sale.view_order_form"/>
|
||||
<field name="arch" type="xml">
|
||||
<xpath expr="//field[@name='partner_id']" position="before">
|
||||
<field name="order_name"/>
|
||||
<field name="order_mobile_number"/>
|
||||
<field name="done_with_quick_donation" readonly="1"/>
|
||||
</xpath>
|
||||
<xpath expr="//notebook" position="inside">
|
||||
<page name="extra_donators" string="Donators">
|
||||
<field name="donators_ids">
|
||||
<tree string="Donators">
|
||||
<field name="product_id"/>
|
||||
<field name="donator_name"/>
|
||||
<field name="donated_amount"/>
|
||||
<field name="donator_mobile_number"/>
|
||||
</tree>
|
||||
</field>
|
||||
</page>
|
||||
</xpath>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<template id="assets_frontend" name="Frontend Assets" inherit_id="web.assets_frontend">
|
||||
<xpath expr="." position="inside">
|
||||
<link rel="stylesheet" type="text/scss" href="/p_donation_theme/static/src/scss/hyperpay_quick_donation.scss"/>
|
||||
|
|
|
|||
|
|
@ -14,12 +14,13 @@
|
|||
'price': 79.99,
|
||||
'currency': 'EUR',
|
||||
'license': 'Other proprietary',
|
||||
'depends': ['payment'],
|
||||
'depends': ['payment', 'website_sale', 'ensan_sale_management'],
|
||||
'data': [
|
||||
'views/payment_views.xml',
|
||||
'views/payment_popup_template.xml',
|
||||
'views/payment_applepay_templates.xml',
|
||||
'data/payment_acquirer_data.xml',
|
||||
'views/applepay_iframe.xml',
|
||||
],
|
||||
'images': ['images/main_screenshot.gif'],
|
||||
'installable': True,
|
||||
|
|
|
|||
|
|
@ -1,77 +1,172 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# This module and its content is copyright of Technaureus Info Solutions Pvt. Ltd.
|
||||
# - © Technaureus Info Solutions Pvt. Ltd 2020. All rights reserved.
|
||||
|
||||
import json
|
||||
import logging
|
||||
import pprint
|
||||
|
||||
import requests
|
||||
import werkzeug
|
||||
from werkzeug import urls
|
||||
|
||||
from odoo import http, _
|
||||
from odoo.addons.payment.models.payment_provider import ValidationError
|
||||
from odoo.http import request
|
||||
from odoo.exceptions import UserError, Warning
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ApplepayController(http.Controller):
|
||||
|
||||
@http.route('/payment/applepay/return', type='http', auth='public', csrf=False)
|
||||
def applepay_return(self, **post):
|
||||
""" applepay."""
|
||||
acquirer = request.env['payment.provider'].sudo().search([('code', '=', 'applepay')], limit=1)
|
||||
_logger.info("acquirer......applepay%s" % (acquirer.state))
|
||||
_logger.info("Post Return = %s" % (post))
|
||||
if post.get('resourcePath'):
|
||||
if acquirer.state == 'test':
|
||||
url = "https://eu-test.oppwa.com"
|
||||
else:
|
||||
url = "https://eu-prod.oppwa.com"
|
||||
url += post.get('resourcePath')
|
||||
url += '?entityId=' + acquirer.applepay_entity_id
|
||||
authorization_bearer = "Bearer " + acquirer.applepay_authorization_bearer
|
||||
_logger.info("Url = %s",url)
|
||||
_logger.info("Headers = %s",authorization_bearer)
|
||||
try:
|
||||
headers = {'Authorization': authorization_bearer}
|
||||
|
||||
response = requests.get(
|
||||
url,
|
||||
headers=headers,
|
||||
)
|
||||
response = json.loads(response.text)
|
||||
except Exception as e:
|
||||
raise UserError(_(e))
|
||||
_logger.info(
|
||||
'applepay: entering form_feedback with post data %s', pprint.pformat(post))
|
||||
_logger.info("Response = %s",response)
|
||||
payment = request.env['payment.transaction'].sudo()
|
||||
tx_id = payment.search([('applepay_checkout_id', '=', post.get('id',''))])
|
||||
#tx_sudo = request.env['payment.transaction'].sudo().
|
||||
#response.update({'tx_id': tx})
|
||||
_logger.info("Tx Sudo = %s",tx_id)
|
||||
tx = response.get('customParameters',{}).get('SHOPPER_tx_id') or tx_id or ''
|
||||
response.update({'tx_id': tx})
|
||||
#tx = response.get('customParameters',{}).get('SHOPPER_tx_id') or tx_sudo and tx_sudo.id or ''
|
||||
#response.update({'tx_id': tx})
|
||||
|
||||
tx._handle_notification_data('applepay', response)
|
||||
return werkzeug.utils.redirect(f'/payment/status')
|
||||
|
||||
@http.route('/shop/applepay/payment/', type='http', auth="none", methods=['POST'], csrf=False)
|
||||
def _payment_applepay_card(self, **kw):
|
||||
acquirer = request.env['payment.provider'].sudo().search([('code', '=', 'applepay')], limit=1)
|
||||
|
||||
kw['currency'] = 'SAR'
|
||||
_logger.info("Post Values From Apple Payment = %s",kw)
|
||||
|
||||
if acquirer.state == 'test':
|
||||
return request.render("payment_applepay.payment_applepay_card",
|
||||
{'check_out_id': kw.get('check_out_id'), 'return_url': kw.get('applepay_return')})
|
||||
else:
|
||||
return request.render("payment_applepay.payment_applepay_card_live",
|
||||
{'check_out_id': kw.get('check_out_id'), 'return_url': kw.get('applepay_return')})
|
||||
# -*- coding: utf-8 -*-
|
||||
# This module and its content is copyright of Technaureus Info Solutions Pvt. Ltd.
|
||||
# - © Technaureus Info Solutions Pvt. Ltd 2020. All rights reserved.
|
||||
|
||||
import json
|
||||
import logging
|
||||
import pprint
|
||||
|
||||
import requests
|
||||
from odoo import http, _
|
||||
from odoo.addons.payment.controllers.portal import PaymentProcessing
|
||||
from odoo.http import request
|
||||
from odoo.exceptions import UserError
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ApplepayController(http.Controller):
|
||||
|
||||
def check_mobile_number_validation(self, phone):
|
||||
if phone[0] == '+' and phone[1] != '0':
|
||||
if phone[1:4] == '966':
|
||||
if len(phone[4:]) >= 8:
|
||||
return phone.replace('+', '')
|
||||
else:
|
||||
phone = phone[0] + '966' + phone[1:]
|
||||
elif phone[0] == '+' and phone[1] == '0':
|
||||
phone = phone[0] + '966' + phone[2:]
|
||||
elif phone[0] == '0' and phone[1] == '5':
|
||||
phone = '+966' + phone[1:]
|
||||
elif phone[0:2] == '00': # 00966555555555
|
||||
if phone[2:5] == '966':
|
||||
phone = '+' + '966' + phone[5:]
|
||||
elif phone[0] == '0': # 0966555555555
|
||||
if phone[1:4] == '966':
|
||||
phone = '+' + '966' + phone[4:]
|
||||
else:
|
||||
if phone[0:3] == '966':
|
||||
phone = '+' + phone
|
||||
else:
|
||||
phone = '+' + '966' + phone
|
||||
return phone.replace('+', '')
|
||||
|
||||
@http.route('/payment/applepay/return', type='http', auth='public', csrf=False)
|
||||
def applepay_return(self, **post):
|
||||
""" applepay."""
|
||||
acquirer = request.env['payment.acquirer'].sudo().search([('provider', '=', 'applepay')], limit=1)
|
||||
_logger.info("Post Return = %s" % (post))
|
||||
if post.get('resourcePath'):
|
||||
if acquirer.state == 'test':
|
||||
url = "https://eu-test.oppwa.com"
|
||||
else:
|
||||
url = "https://oppwa.com"
|
||||
url += post.get('resourcePath')
|
||||
url += '?entityId=' + acquirer.applepay_entity_id
|
||||
authorization_bearer = "Bearer " + acquirer.applepay_authorization_bearer
|
||||
_logger.info("Url = %s", url)
|
||||
_logger.info("Headers = %s", authorization_bearer)
|
||||
try:
|
||||
headers = {'Authorization': authorization_bearer}
|
||||
response = requests.get(url, headers=headers)
|
||||
response = json.loads(response.text)
|
||||
except Exception as e:
|
||||
raise UserError(_(e))
|
||||
_logger.info('applepay: entering form_feedback with post data %s', pprint.pformat(post))
|
||||
_logger.info("Response = %s", response)
|
||||
phone = response.get('customer', {}).get('phone', '')
|
||||
phone = self.check_mobile_number_validation(phone)
|
||||
payment = request.env['payment.transaction'].sudo()
|
||||
tx_id = payment.search([('applepay_checkout_id', '=', post.get('id', ''))])
|
||||
tx_id.sale_order_ids.sudo().write({'order_mobile_number': phone})
|
||||
_logger.info("Tx Sudo = %s", tx_id)
|
||||
tx = response.get('customParameters', {}).get('SHOPPER_tx_id') or tx_id or ''
|
||||
response.update({'tx_id': tx})
|
||||
ids = tx_id.sale_order_ids.sudo().ids
|
||||
request.session['sale_last_order_id'] = ids[0] if len(ids) else None
|
||||
request.env['payment.transaction'].sudo().form_feedback(response, "applepay")
|
||||
return request.redirect('/payment/process')
|
||||
|
||||
@http.route('/shop/applepay/payment/', type='http', auth="none", methods=['POST'], csrf=False)
|
||||
def _payment_applepay_card(self, **kw):
|
||||
acquirer = request.env['payment.acquirer'].sudo().search([('provider', '=', 'applepay')], limit=1)
|
||||
|
||||
kw['currency'] = 'SAR'
|
||||
_logger.info("Post Values From Apple Payment = %s", kw)
|
||||
|
||||
if acquirer.state == 'test':
|
||||
return request.render("payment_applepay.payment_applepay_card",
|
||||
{'check_out_id': kw.get('check_out_id'), 'return_url': kw.get('applepay_return')})
|
||||
else:
|
||||
return request.render("payment_applepay.payment_applepay_card_live",
|
||||
{'check_out_id': kw.get('check_out_id'), 'return_url': kw.get('applepay_return')})
|
||||
|
||||
|
||||
@http.route('/applepay', type='http', auth='public', website=True, csrf=False)
|
||||
def apple_pay_iframe(self, **kwargs):
|
||||
response = request.render("payment_applepay.apple_pay_iframe")
|
||||
response.headers['Content-Security-Policy'] = "script-src blob: 'self' 'unsafe-inline' 'unsafe-eval' https://*; worker-src blob: 'self' 'unsafe-inline' 'unsafe-eval' https://*;connect-src 'self' https://* wss://*;frame-src 'self' blob: https://*;"
|
||||
return response
|
||||
|
||||
@http.route('/applepay/checkout', type='json', auth='public', website=True)
|
||||
def apple_pay_create_checkout(self, **post):
|
||||
data = json.loads(request.httprequest.data.decode('utf-8'))
|
||||
checkout_id = self._apple_pay_create_checkout(data)
|
||||
return {'checkout_id': checkout_id}
|
||||
|
||||
def _apple_pay_create_checkout(self, data):
|
||||
try:
|
||||
order = request.website.sale_get_order(force_create=True)
|
||||
product_ids = data.get('product_ids', [])
|
||||
gifts = data.get('gifts', [])
|
||||
use_current_order = data.get('use_current_order', False)
|
||||
|
||||
if not order:
|
||||
return ''
|
||||
|
||||
if not use_current_order:
|
||||
|
||||
order_mobile_number = data.get('mobile', '')
|
||||
order_name = data.get('name', '')
|
||||
|
||||
extra_donators_ids = [(0, 0, {
|
||||
'sale_id': order.id,
|
||||
'product_id': gift.get('product_id'),
|
||||
'donated_amount': gift.get('amount'),
|
||||
'donator_name': gift.get('receiver_name'),
|
||||
'donator_mobile_number': gift.get('receiver_mobile')
|
||||
}) for gift in gifts if gift.get('product_id')]
|
||||
|
||||
order_line = [(0, 0, {
|
||||
'product_id': product.get('id'),
|
||||
'extra_donators_ids': extra_donators_ids,
|
||||
'product_uom_qty': product.get('quantity', 1),
|
||||
'price_unit': product.get('price_unit', 0) + sum(gift.get('amount', 0) for gift in gifts if gift.get('product_id') == product.get('id'))}) for product in product_ids if product.get('id')]
|
||||
|
||||
if order_line:
|
||||
order.order_line.sudo().unlink()
|
||||
order.write({
|
||||
'order_line': order_line,
|
||||
'order_mobile_number': order_mobile_number,
|
||||
'order_name': order_name
|
||||
})
|
||||
|
||||
payment_acquire_id = request.env['payment.acquirer'].sudo().search([('provider', '=', 'applepay'),
|
||||
('company_id', 'in', (False, order.company_id.id))], limit=1)
|
||||
|
||||
# Create transaction
|
||||
vals = {'acquirer_id': payment_acquire_id.id,
|
||||
'return_url': '/payment/applepay/return'}
|
||||
|
||||
tx = order._create_payment_transaction(vals)
|
||||
|
||||
# store the new transaction into the transaction list and if there's an old one, we remove it
|
||||
# until the day the ecommerce supports multiple orders at the same time
|
||||
last_tx_id = request.session.get('__website_sale_last_tx_id')
|
||||
last_tx = request.env['payment.transaction'].browse(last_tx_id).sudo().exists()
|
||||
if last_tx:
|
||||
PaymentProcessing.remove_payment_transaction(last_tx)
|
||||
PaymentProcessing.add_payment_transaction(tx)
|
||||
request.session['__website_sale_last_tx_id'] = tx.id
|
||||
|
||||
vals = {'partner_id': tx.partner_id.id,
|
||||
'reference': tx.reference,
|
||||
'amount': tx.amount}
|
||||
|
||||
checkout_id = payment_acquire_id._get_authenticate_apple_pay(vals)
|
||||
tx.sale_order_ids.sudo().write({'done_with_quick_donation': data.get('done_with_quick_donation', False)})
|
||||
|
||||
return checkout_id
|
||||
except Exception as e:
|
||||
_logger.error("Error in Apple pay Payment: %s" % (e))
|
||||
return ''
|
||||
|
|
|
|||
|
|
@ -1,22 +1,16 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<data noupdate="1">
|
||||
|
||||
<record id="payment_acquirer_applepay" model="payment.provider">
|
||||
<data noupdate="1">
|
||||
<record id="payment_acquirer_applepay" model="payment.acquirer">
|
||||
<field name="name">Applepay</field>
|
||||
<field name="image_128" type="base64"
|
||||
file="payment_applepay/static/src/img/applepay_icon.png"/>
|
||||
<field name="code">applepay</field>
|
||||
<field name="company_id" ref="base.main_company"/>
|
||||
<field name="redirect_form_view_id" ref="applepay_form"/>
|
||||
<field name="image_128" type="base64" file="payment_applepay/static/src/img/applepay_icon.png"/>
|
||||
<field name="provider">applepay</field>
|
||||
<field name="view_template_id" ref="applepay_form"/>
|
||||
<field name="pre_msg"><![CDATA[<p>You will be redirected to the applepay payment form after clicking on the payment button.</p>]]></field>
|
||||
<field name="applepay_entity_id">dummy</field>
|
||||
<field name="applepay_authorization_bearer">dummy</field>
|
||||
</record>
|
||||
<record id="payment_method_applepay" model="account.payment.method">
|
||||
<field name="name">Applepay</field>
|
||||
<field name="code">applepay</field>
|
||||
<field name="payment_type">inbound</field>
|
||||
</record>
|
||||
</data>
|
||||
|
||||
</odoo>
|
||||
|
|
|
|||
|
|
@ -4,4 +4,3 @@
|
|||
|
||||
from . import payment
|
||||
from . import payment_transaction
|
||||
from . import account_payment_method
|
||||
|
|
|
|||
|
|
@ -1,14 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, models
|
||||
|
||||
|
||||
class AccountPaymentMethod(models.Model):
|
||||
_inherit = 'account.payment.method'
|
||||
|
||||
@api.model
|
||||
def _get_payment_method_information(self):
|
||||
res = super()._get_payment_method_information()
|
||||
res['applepay'] = {'mode': 'unique', 'domain': [('type', '=', 'bank')]}
|
||||
return res
|
||||
|
|
@ -1,126 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# This module and its content is copyright of Technaureus Info Solutions Pvt. Ltd.
|
||||
# - © Technaureus Info Solutions Pvt. Ltd 2020. All rights reserved.
|
||||
|
||||
import json
|
||||
import re
|
||||
import logging
|
||||
from odoo.exceptions import UserError
|
||||
|
||||
from urllib.parse import urljoin
|
||||
from odoo import api, fields, models, _
|
||||
from odoo.addons.payment.models.payment_provider import ValidationError
|
||||
import requests
|
||||
|
||||
from odoo.http import request
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AcquirerApplepay(models.Model):
|
||||
_inherit = 'payment.provider'
|
||||
|
||||
code = fields.Selection(selection_add=[('applepay', 'applepay')], ondelete={'applepay': 'set default'})
|
||||
|
||||
applepay_entity_id = fields.Char(string='Merchant ID/Entity Id', required_if_provider='applepay',
|
||||
groups='base.group_user')
|
||||
applepay_authorization_bearer = fields.Char(
|
||||
string='Authorization Bearer', required_if_provider='applepay', groups='base.group_user')
|
||||
|
||||
@api.model
|
||||
def _get_authorize_urls(self):
|
||||
base_url = self.get_base_url()
|
||||
""" ApplePay URLS """
|
||||
return base_url + 'shop/applepay/payment/'
|
||||
|
||||
def _partner_split_name(self, partner_name):
|
||||
return [' '.join(partner_name.split()[:-1]), ' '.join(partner_name.split()[-1:])]
|
||||
|
||||
def _get_authenticate_apple_pay(self, values):
|
||||
url = "https://eu-test.oppwa.com/v1/checkouts" if self.state == 'test' else "https://eu-prod.oppwa.com/v1/checkouts"
|
||||
authorization_bearer = "Bearer " + self.applepay_authorization_bearer
|
||||
currency = self.env['res.currency'].browse(values['currency_id'])
|
||||
partner = self.env['res.partner'].browse(values['partner_id'])
|
||||
last_name = self._partner_split_name(partner.name)[1]
|
||||
_logger.info(">>%s" % (authorization_bearer))
|
||||
data = {
|
||||
'entityId': self.applepay_entity_id,
|
||||
'amount': str(format(values['amount'], '.2f')),
|
||||
'currency': 'SAR',
|
||||
'paymentType': 'DB',
|
||||
'merchantTransactionId': values.get('reference'),
|
||||
'customer.email': partner.email,
|
||||
'customer.givenName': partner.name,
|
||||
'customer.companyName': partner.company_id.name,
|
||||
'customer.phone': partner.phone,
|
||||
'billing.street1': partner.street,
|
||||
'billing.state': partner.state_id.name,
|
||||
'billing.country': partner.country_id.code,
|
||||
'billing.postcode': partner.zip,
|
||||
'customer.surname': last_name
|
||||
|
||||
}
|
||||
try:
|
||||
headers = {'Authorization': authorization_bearer}
|
||||
response = requests.post(
|
||||
url,
|
||||
headers=headers,
|
||||
data=data
|
||||
)
|
||||
response = json.loads(response.text)
|
||||
_logger.info("Info From Authorization = %s " % (response))
|
||||
return response.get('id')
|
||||
except Exception as e:
|
||||
raise UserError(_(e))
|
||||
|
||||
def applepay_form_generate_values(self, values):
|
||||
currency = self.env['res.currency'].browse(values['currency_id'])
|
||||
base_url = self.get_base_url()
|
||||
check_out_id = self._get_authenticate_apple_pay(values)
|
||||
_logger.info(">>%s" % (self.applepay_authorization_bearer))
|
||||
authorization_bearer = "Bearer " + self.applepay_authorization_bearer
|
||||
applepay_tx_values = dict(values)
|
||||
applepay_tx_values.update({
|
||||
'entityId': self.applepay_entity_id,
|
||||
'check_out_id': check_out_id,
|
||||
'Authorization': authorization_bearer,
|
||||
'amount': str(format(values['amount'], '.2f')),
|
||||
'currency': currency.id and currency.name or '',
|
||||
'paymentBrand': 'APPLEPAY',
|
||||
'paymentType': 'DB',
|
||||
'merchantTransactionId': values.get('reference'),
|
||||
'shopperResultUrl': '%s' % urljoin(base_url, '/shop/applepay/payment/'),
|
||||
'applepay_return': '%s' % urljoin(base_url, '/payment/applepay/return'),
|
||||
'custom': json.dumps({'return_url': '%s' % applepay_tx_values.pop('return_url')}) if applepay_tx_values.get(
|
||||
'return_url') else False,
|
||||
})
|
||||
return applepay_tx_values
|
||||
#New method added to core
|
||||
def _get_default_payment_method_id(self,code):
|
||||
provider_method_id = self._get_provider_payment_method(code)
|
||||
if provider_method_id:
|
||||
return provider_method_id.id
|
||||
return self.env.ref('payment_applepay.payment_method_applepay').id
|
||||
|
||||
#def _get_default_payment_method_id(self):
|
||||
# self.ensure_one()
|
||||
# if self.provider != 'applepay':
|
||||
# return super()._get_default_payment_method_id()
|
||||
# return self.env.ref('payment_applepay.payment_method_applepay').id
|
||||
|
||||
def applepay_get_form_action_url(self):
|
||||
self.ensure_one()
|
||||
environment = 'prod' if self.state == 'enabled' else 'test'
|
||||
return self._get_authorize_urls_apple_pay(environment)['url']
|
||||
|
||||
@api.model
|
||||
def _get_compatible_providers(self, *args, currency_id=None, **kwargs):
|
||||
""" Override of payment to unlist PayPal providers when the currency is not supported. """
|
||||
providers = super()._get_compatible_providers(*args, currency_id=currency_id, **kwargs)
|
||||
|
||||
currency = self.env['res.currency'].browse(currency_id).exists()
|
||||
#if currency and currency.name:
|
||||
|
||||
# providers = providers.filtered(lambda p: p.code != 'applepay')
|
||||
|
||||
return providers
|
||||
|
|
@ -1,139 +1,109 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# This module and its content is copyright of Technaureus Info Solutions Pvt. Ltd.
|
||||
# - © Technaureus Info Solutions Pvt. Ltd 2020. All rights reserved.
|
||||
|
||||
import json
|
||||
import re
|
||||
import logging
|
||||
import random
|
||||
from odoo.exceptions import UserError
|
||||
|
||||
from urllib.parse import urljoin
|
||||
from odoo import api, fields, models, _
|
||||
from odoo.addons.payment.models.payment_provider import ValidationError
|
||||
import requests
|
||||
|
||||
from odoo.http import request
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AcquirerApplepay(models.Model):
|
||||
_inherit = 'payment.provider'
|
||||
|
||||
code = fields.Selection(selection_add=[('applepay', 'applepay')], ondelete={'applepay': 'set default'})
|
||||
|
||||
applepay_entity_id = fields.Char(string='Merchant ID/Entity Id', required_if_provider='applepay',
|
||||
groups='base.group_user')
|
||||
applepay_authorization_bearer = fields.Char(
|
||||
string='Authorization Bearer', required_if_provider='applepay', groups='base.group_user')
|
||||
|
||||
@api.model
|
||||
def _get_authorize_urls(self):
|
||||
base_url = self.get_base_url()
|
||||
""" ApplePay URLS """
|
||||
return base_url + 'shop/applepay/payment/'
|
||||
|
||||
def _partner_split_name(self, partner_name):
|
||||
if partner_name:
|
||||
return [' '.join(partner_name.split()[:-1]), ' '.join(partner_name.split()[-1:])]
|
||||
else:
|
||||
return ['', '']
|
||||
|
||||
def _get_authenticate_apple_pay(self, values):
|
||||
url = "https://eu-test.oppwa.com/v1/checkouts" if self.state == 'test' else "https://eu-prod.oppwa.com/v1/checkouts"
|
||||
authorization_bearer = "Bearer " + self.applepay_authorization_bearer
|
||||
# currency = self.env['res.currency'].browse(values['currency_id'])
|
||||
partner = self.env['res.partner'].sudo().browse(values['partner_id']).sudo()
|
||||
order_no = values.get('reference', '').split('-', 1)
|
||||
partner_name = partner.name or ''
|
||||
partner_mobile = partner.mobile or ''
|
||||
if order_no:
|
||||
order_id = request.env['sale.order'].sudo().search([('name', '=', order_no[0])], limit=1).sudo()
|
||||
if order_id:
|
||||
partner_mobile = order_id.order_mobile_number
|
||||
partner_name = order_id.order_name
|
||||
last_name = self._partner_split_name(partner_name)[-1] if partner_name else ''
|
||||
_logger.info(">>%s" % (authorization_bearer))
|
||||
|
||||
data = {
|
||||
'entityId': self.applepay_entity_id,
|
||||
'amount': str(format(values['amount'], '.2f')),
|
||||
'currency': 'SAR',
|
||||
'paymentType': 'DB',
|
||||
'merchantTransactionId': values.get('reference'),
|
||||
'customer.email': '{seq}@ensan.sa'.format(seq=random.randint(0,10000)),
|
||||
'customer.givenName': partner_name or 'guest',
|
||||
'customer.companyName': partner.company_id.name,
|
||||
'customer.phone': partner_mobile,
|
||||
'billing.street1': partner.street or 'Riyadh',
|
||||
'billing.state': partner.state_id.name or 'Riyadh',
|
||||
'billing.country': partner.country_id.code or 'SA',
|
||||
'billing.postcode': partner.zip,
|
||||
'customer.surname': last_name or 'guest'
|
||||
|
||||
}
|
||||
try:
|
||||
headers = {'Authorization': authorization_bearer}
|
||||
response = requests.post(
|
||||
url,
|
||||
headers=headers,
|
||||
data=data
|
||||
)
|
||||
response = json.loads(response.text)
|
||||
_logger.info("Info From Authorization = %s ",response)
|
||||
return response.get('id')
|
||||
except Exception as e:
|
||||
raise UserError(_(e))
|
||||
|
||||
def applepay_form_generate_values(self, values):
|
||||
currency = self.env['res.currency'].browse(values['currency_id'])
|
||||
base_url = self.get_base_url()
|
||||
check_out_id = self._get_authenticate_apple_pay(values)
|
||||
_logger.info(">>%s" % (self.applepay_authorization_bearer))
|
||||
authorization_bearer = "Bearer " + self.applepay_authorization_bearer
|
||||
applepay_tx_values = dict(values)
|
||||
applepay_tx_values.update({
|
||||
'entityId': self.applepay_entity_id,
|
||||
'check_out_id': check_out_id,
|
||||
'Authorization': authorization_bearer,
|
||||
'amount': str(format(values['amount'], '.2f')),
|
||||
'currency': currency.id and currency.name or '',
|
||||
'paymentBrand': 'APPLEPAY',
|
||||
'paymentType': 'DB',
|
||||
'merchantTransactionId': values.get('reference'),
|
||||
'shopperResultUrl': '%s' % urljoin(base_url, '/shop/applepay/payment/'),
|
||||
'applepay_return': '%s' % urljoin(base_url, '/payment/applepay/return'),
|
||||
'custom': json.dumps({'return_url': '%s' % applepay_tx_values.pop('return_url')}) if applepay_tx_values.get(
|
||||
'return_url') else False,
|
||||
})
|
||||
return applepay_tx_values
|
||||
#New method added to core
|
||||
def _get_default_payment_method_id(self,code):
|
||||
provider_method_id = self._get_provider_payment_method(code)
|
||||
if provider_method_id:
|
||||
return provider_method_id.id
|
||||
return self.env.ref('payment_applepay.payment_method_applepay').id
|
||||
|
||||
#def _get_default_payment_method_id(self):
|
||||
# self.ensure_one()
|
||||
# if self.provider != 'applepay':
|
||||
# return super()._get_default_payment_method_id()
|
||||
# return self.env.ref('payment_applepay.payment_method_applepay').id
|
||||
|
||||
def applepay_get_form_action_url(self):
|
||||
self.ensure_one()
|
||||
environment = 'prod' if self.state == 'enabled' else 'test'
|
||||
return self._get_authorize_urls_apple_pay(environment)['url']
|
||||
|
||||
@api.model
|
||||
def _get_compatible_providers(self, *args, currency_id=None, **kwargs):
|
||||
""" Override of payment to unlist PayPal providers when the currency is not supported. """
|
||||
providers = super()._get_compatible_providers(*args, currency_id=currency_id, **kwargs)
|
||||
|
||||
currency = self.env['res.currency'].browse(currency_id).exists()
|
||||
#if currency and currency.name:
|
||||
|
||||
# providers = providers.filtered(lambda p: p.code != 'applepay')
|
||||
|
||||
return providers
|
||||
# -*- coding: utf-8 -*-
|
||||
# This module and its content is copyright of Technaureus Info Solutions Pvt. Ltd.
|
||||
# - © Technaureus Info Solutions Pvt. Ltd 2020. All rights reserved.
|
||||
|
||||
import json
|
||||
import logging
|
||||
import random
|
||||
from urllib.parse import urljoin
|
||||
import requests
|
||||
|
||||
from odoo.exceptions import UserError
|
||||
from odoo import api, fields, models, _
|
||||
from odoo.http import request
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AcquirerApplepay(models.Model):
|
||||
_inherit = 'payment.acquirer'
|
||||
|
||||
provider = fields.Selection(selection_add=[('applepay', 'applepay')], ondelete={'applepay': 'set default'})
|
||||
applepay_entity_id = fields.Char(string='Merchant ID/Entity Id', required_if_provider='applepay', groups='base.group_user')
|
||||
applepay_authorization_bearer = fields.Char(string='Authorization Bearer', required_if_provider='applepay', groups='base.group_user')
|
||||
|
||||
def _partner_split_name(self, partner_name):
|
||||
if partner_name:
|
||||
return [' '.join(partner_name.split()[:-1]), ' '.join(partner_name.split()[-1:])]
|
||||
else:
|
||||
return ['', '']
|
||||
|
||||
def _get_authenticate_apple_pay(self, values):
|
||||
url = "https://eu-test.oppwa.com/v1/checkouts" if self.state == 'test' else "https://oppwa.com/v1/checkouts"
|
||||
authorization_bearer = "Bearer " + self.applepay_authorization_bearer
|
||||
partner = self.env['res.partner'].sudo().browse(values['partner_id']).sudo()
|
||||
order_no = values.get('reference', '').split('-', 1)
|
||||
partner_name = partner.name or ''
|
||||
partner_mobile = partner.mobile or ''
|
||||
if order_no:
|
||||
order_id = request.env['sale.order'].sudo().search([('name', '=', order_no[0])], limit=1).sudo()
|
||||
if order_id:
|
||||
partner_mobile = order_id.order_mobile_number
|
||||
partner_name = order_id.order_name
|
||||
last_name = self._partner_split_name(partner_name)[-1] if partner_name else ''
|
||||
_logger.info(">>%s" % (authorization_bearer))
|
||||
|
||||
data = {
|
||||
'entityId': self.applepay_entity_id,
|
||||
'amount': str(format(values['amount'], '.2f')),
|
||||
'currency': 'SAR',
|
||||
'paymentType': 'DB',
|
||||
'merchantTransactionId': values.get('reference'),
|
||||
'customer.email': '{seq}@ensan.sa'.format(seq=random.randint(0, 10000)),
|
||||
'customer.givenName': partner_name or 'guest',
|
||||
'customer.companyName': partner.company_id.name,
|
||||
'billing.street1': partner.street or 'Riyadh',
|
||||
'billing.state': partner.state_id.name or 'Riyadh',
|
||||
'billing.country': partner.country_id.code or 'SA',
|
||||
'billing.postcode': partner.zip,
|
||||
'customer.surname': last_name or 'guest'
|
||||
|
||||
}
|
||||
try:
|
||||
headers = {'Authorization': authorization_bearer}
|
||||
response = requests.post(
|
||||
url,
|
||||
headers=headers,
|
||||
data=data
|
||||
)
|
||||
response = json.loads(response.text)
|
||||
_logger.info("Info From Authorization = %s ", response)
|
||||
return response.get('id')
|
||||
except Exception as e:
|
||||
raise UserError(_(e))
|
||||
|
||||
def applepay_form_generate_values(self, values):
|
||||
currency = self.env['res.currency'].browse(values['currency_id'])
|
||||
base_url = self.get_base_url()
|
||||
check_out_id = self._get_authenticate_apple_pay(values)
|
||||
_logger.info(">>%s" % (self.applepay_authorization_bearer))
|
||||
authorization_bearer = "Bearer " + self.applepay_authorization_bearer
|
||||
applepay_tx_values = dict(values)
|
||||
applepay_tx_values.update({
|
||||
'entityId': self.applepay_entity_id,
|
||||
'check_out_id': check_out_id,
|
||||
'Authorization': authorization_bearer,
|
||||
'amount': str(format(values['amount'], '.2f')),
|
||||
'currency': currency.id and currency.name or '',
|
||||
'paymentBrand': 'APPLEPAY',
|
||||
'paymentType': 'DB',
|
||||
'merchantTransactionId': values.get('reference'),
|
||||
'shopperResultUrl': '%s' % urljoin(base_url, '/shop/applepay/payment/'),
|
||||
'applepay_return': '%s' % urljoin(base_url, '/payment/applepay/return'),
|
||||
'custom': json.dumps({'return_url': '%s' % applepay_tx_values.pop('return_url')}) if applepay_tx_values.get(
|
||||
'return_url') else False,
|
||||
})
|
||||
return applepay_tx_values
|
||||
|
||||
@api.model
|
||||
def _get_authorize_urls_apple_pay(self, environment):
|
||||
""" applepay URLS """
|
||||
if environment == 'prod':
|
||||
return {'applepay_form_url': 'https://oppwa.com/v1/checkouts'}
|
||||
else:
|
||||
return {'applepay_form_url': 'https://test.oppwa.com/v1/checkouts'}
|
||||
|
||||
def applepay_get_form_action_url(self):
|
||||
self.ensure_one()
|
||||
environment = 'prod' if self.state == 'enabled' else 'test'
|
||||
return self._get_authorize_urls_apple_pay(environment)['applepay_form_url']
|
||||
|
|
|
|||
|
|
@ -1,138 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# This module and its content is copyright of Technaureus Info Solutions Pvt. Ltd.
|
||||
# - © Technaureus Info Solutions Pvt. Ltd 2020. All rights reserved.
|
||||
|
||||
import json
|
||||
import re
|
||||
import logging
|
||||
from odoo.exceptions import UserError
|
||||
|
||||
from urllib.parse import urljoin
|
||||
from odoo import api, fields, models, _
|
||||
from odoo.addons.payment.models.payment_provider import ValidationError
|
||||
import requests
|
||||
|
||||
from odoo.http import request
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AcquirerApplepay(models.Model):
|
||||
_inherit = 'payment.provider'
|
||||
|
||||
code = fields.Selection(selection_add=[('applepay', 'applepay')], ondelete={'applepay': 'set default'})
|
||||
|
||||
applepay_entity_id = fields.Char(string='Merchant ID/Entity Id', required_if_provider='applepay',
|
||||
groups='base.group_user')
|
||||
applepay_authorization_bearer = fields.Char(
|
||||
string='Authorization Bearer', required_if_provider='applepay', groups='base.group_user')
|
||||
|
||||
@api.model
|
||||
def _get_authorize_urls(self):
|
||||
base_url = self.get_base_url()
|
||||
""" ApplePay URLS """
|
||||
return base_url + 'shop/applepay/payment/'
|
||||
|
||||
def _partner_split_name(self, partner_name):
|
||||
if partner_name:
|
||||
return [' '.join(partner_name.split()[:-1]), ' '.join(partner_name.split()[-1:])]
|
||||
else:
|
||||
return ['', '']
|
||||
|
||||
def _get_authenticate_apple_pay(self, values):
|
||||
url = "https://eu-test.oppwa.com/v1/checkouts" if self.state == 'test' else "https://eu-prod.oppwa.com/v1/checkouts"
|
||||
authorization_bearer = "Bearer " + self.applepay_authorization_bearer
|
||||
# currency = self.env['res.currency'].browse(values['currency_id'])
|
||||
partner = self.env['res.partner'].sudo().browse(values['partner_id']).sudo()
|
||||
order_no = values.get('reference', '').split('-', 1)
|
||||
partner_name = partner.name or ''
|
||||
partner_mobile = partner.mobile or ''
|
||||
if order_no:
|
||||
order_id = request.env['sale.order'].sudo().search([('name', '=', order_no[0])], limit=1).sudo()
|
||||
if order_id:
|
||||
partner_mobile = order_id.order_mobile_number
|
||||
partner_name = order_id.order_name
|
||||
last_name = self._partner_split_name(partner_name)[-1] if partner_name else ''
|
||||
_logger.info(">>%s" % (authorization_bearer))
|
||||
|
||||
data = {
|
||||
'entityId': self.applepay_entity_id,
|
||||
'amount': str(format(values['amount'], '.2f')),
|
||||
'currency': 'SAR',
|
||||
'paymentType': 'DB',
|
||||
'merchantTransactionId': values.get('reference'),
|
||||
'customer.email': partner.email,
|
||||
'customer.givenName': partner_name or 'guest',
|
||||
'customer.companyName': partner.company_id.name,
|
||||
'customer.phone': partner_mobile,
|
||||
'billing.street1': partner.street or 'Riyadh',
|
||||
'billing.state': partner.state_id.name or 'Riyadh',
|
||||
'billing.country': partner.country_id.code or 'SA',
|
||||
'billing.postcode': partner.zip,
|
||||
'customer.surname': last_name or 'guest'
|
||||
|
||||
}
|
||||
try:
|
||||
headers = {'Authorization': authorization_bearer}
|
||||
response = requests.post(
|
||||
url,
|
||||
headers=headers,
|
||||
data=data
|
||||
)
|
||||
response = json.loads(response.text)
|
||||
_logger.info("Info From Authorization = %s ",response)
|
||||
return response.get('id')
|
||||
except Exception as e:
|
||||
raise UserError(_(e))
|
||||
|
||||
def applepay_form_generate_values(self, values):
|
||||
currency = self.env['res.currency'].browse(values['currency_id'])
|
||||
base_url = self.get_base_url()
|
||||
check_out_id = self._get_authenticate_apple_pay(values)
|
||||
_logger.info(">>%s" % (self.applepay_authorization_bearer))
|
||||
authorization_bearer = "Bearer " + self.applepay_authorization_bearer
|
||||
applepay_tx_values = dict(values)
|
||||
applepay_tx_values.update({
|
||||
'entityId': self.applepay_entity_id,
|
||||
'check_out_id': check_out_id,
|
||||
'Authorization': authorization_bearer,
|
||||
'amount': str(format(values['amount'], '.2f')),
|
||||
'currency': currency.id and currency.name or '',
|
||||
'paymentBrand': 'APPLEPAY',
|
||||
'paymentType': 'DB',
|
||||
'merchantTransactionId': values.get('reference'),
|
||||
'shopperResultUrl': '%s' % urljoin(base_url, '/shop/applepay/payment/'),
|
||||
'applepay_return': '%s' % urljoin(base_url, '/payment/applepay/return'),
|
||||
'custom': json.dumps({'return_url': '%s' % applepay_tx_values.pop('return_url')}) if applepay_tx_values.get(
|
||||
'return_url') else False,
|
||||
})
|
||||
return applepay_tx_values
|
||||
#New method added to core
|
||||
def _get_default_payment_method_id(self,code):
|
||||
provider_method_id = self._get_provider_payment_method(code)
|
||||
if provider_method_id:
|
||||
return provider_method_id.id
|
||||
return self.env.ref('payment_applepay.payment_method_applepay').id
|
||||
|
||||
#def _get_default_payment_method_id(self):
|
||||
# self.ensure_one()
|
||||
# if self.provider != 'applepay':
|
||||
# return super()._get_default_payment_method_id()
|
||||
# return self.env.ref('payment_applepay.payment_method_applepay').id
|
||||
|
||||
def applepay_get_form_action_url(self):
|
||||
self.ensure_one()
|
||||
environment = 'prod' if self.state == 'enabled' else 'test'
|
||||
return self._get_authorize_urls_apple_pay(environment)['url']
|
||||
|
||||
@api.model
|
||||
def _get_compatible_providers(self, *args, currency_id=None, **kwargs):
|
||||
""" Override of payment to unlist PayPal providers when the currency is not supported. """
|
||||
providers = super()._get_compatible_providers(*args, currency_id=currency_id, **kwargs)
|
||||
|
||||
currency = self.env['res.currency'].browse(currency_id).exists()
|
||||
#if currency and currency.name:
|
||||
|
||||
# providers = providers.filtered(lambda p: p.code != 'applepay')
|
||||
|
||||
return providers
|
||||
|
|
@ -1,14 +1,9 @@
|
|||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
import logging
|
||||
|
||||
from werkzeug import urls
|
||||
import dateutil.parser
|
||||
import re
|
||||
from odoo import _, api, models,fields
|
||||
import pytz
|
||||
from odoo import _, models,fields, api
|
||||
from odoo.exceptions import ValidationError
|
||||
from odoo.tools.float_utils import float_compare
|
||||
|
||||
from odoo.addons.payment_applepay.controllers.main import ApplepayController
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
|
@ -18,78 +13,54 @@ class PaymentTransaction(models.Model):
|
|||
|
||||
applepay_checkout_id = fields.Char('Checkout Id', groups='base.group_user', help='Unique checkout id for every applepay transasction')
|
||||
|
||||
def _get_specific_rendering_values(self, processing_values):
|
||||
res = super()._get_specific_rendering_values(processing_values)
|
||||
if self.provider_code != 'applepay':
|
||||
return res
|
||||
|
||||
base_url = self.provider_id.get_base_url()
|
||||
rendering_values = self.provider_id.applepay_form_generate_values(processing_values)
|
||||
tx = self.env['payment.transaction'].sudo().search([('reference', '=', self.reference)])
|
||||
tx.applepay_checkout_id = rendering_values.get('check_out_id')
|
||||
rendering_values.update({
|
||||
'api_url': self.provider_id._get_authorize_urls(),
|
||||
"txId": tx.id,
|
||||
'reference':self.reference
|
||||
})
|
||||
return rendering_values
|
||||
|
||||
|
||||
def _get_tx_from_notification_data(self, provider_code, notification_data):
|
||||
if provider_code != 'applepay':
|
||||
return tx
|
||||
_logger.info("Notification Data = %s",notification_data)
|
||||
reference = notification_data.get('ndc')
|
||||
tx_id = notification_data.get('tx_id')
|
||||
tx = tx_id and self.sudo().browse(int(tx_id))
|
||||
if not tx or len(tx) > 1:
|
||||
error_msg = _('received data for reference %s') % (pprint.pformat(reference))
|
||||
if not tx:
|
||||
error_msg += _('; no order found')
|
||||
else:
|
||||
error_msg += _('; multiple order found')
|
||||
@api.model
|
||||
def _applepay_form_get_tx_from_data(self, data):
|
||||
reference, txn_id = data.get('ndc'), data.get('tx_id')
|
||||
if not reference or not txn_id:
|
||||
error_msg = _('ApplePay: received data with missing reference (%s) or txn_id (%s)') % (reference, txn_id)
|
||||
_logger.info(error_msg)
|
||||
raise ValidationError(error_msg)
|
||||
return tx
|
||||
|
||||
def _process_notification_data(self, data):
|
||||
super()._process_notification_data(data)
|
||||
if self.provider_code != 'applepay':
|
||||
return
|
||||
txs = self.env['payment.transaction'].search([('id', '=', int(txn_id))])
|
||||
if not txs or len(txs) > 1:
|
||||
error_msg = 'ApplePay: received data for reference %s' % (reference)
|
||||
if not txs:
|
||||
error_msg += '; no order found'
|
||||
else:
|
||||
error_msg += '; multiple order found'
|
||||
_logger.info(error_msg)
|
||||
raise ValidationError(error_msg)
|
||||
return txs[0]
|
||||
|
||||
def _applepay_form_validate(self, data):
|
||||
_logger.info('Validated ApplePay payment for tx %s: set as pending' % (self.reference))
|
||||
|
||||
result = data.get('result')
|
||||
status_code = data.get('result').get('code')
|
||||
res = {
|
||||
'acquirer_reference': data.get('id'),
|
||||
'state_message': result.get('description', '')
|
||||
}
|
||||
|
||||
success_regex_1 = re.compile(r'000\.000\.|000\.100\.1|000\.[36]').search(status_code)
|
||||
success_regex_2 = re.compile(r'000\.400\.0[^3]|000\.400\.100').search(status_code)
|
||||
pending_regex_1 = re.compile(r'000\.200').search(status_code)
|
||||
pending_regex_2 = re.compile(r'800\.400\.5|100\.400\.500').search(status_code)
|
||||
error_regex_1 = re.compile(r'000\.100\.2').search(status_code)
|
||||
|
||||
_logger.info("Apple Pay Status Code = %s",status_code)
|
||||
|
||||
if success_regex_1 or success_regex_2:
|
||||
success_message = data.get('result').get('description') or 'success'
|
||||
logger_msg = _('applepay:' + success_message)
|
||||
_logger.info(logger_msg)
|
||||
self.write({
|
||||
'provider_reference': data.get('id'),
|
||||
})
|
||||
self._set_done()
|
||||
return True
|
||||
date_validate = dateutil.parser.parse(data.get('timestamp')).astimezone(pytz.utc).replace(tzinfo=None)
|
||||
res.update(provider_reference=data.get('id'), date=date_validate)
|
||||
self._set_transaction_done()
|
||||
elif pending_regex_1 or pending_regex_2:
|
||||
pending_message = data.get('result').get('description') or 'pending'
|
||||
logger_msg = _('applepay:' + pending_message)
|
||||
_logger.info(logger_msg)
|
||||
self.write({'provider_reference': data.get('id')})
|
||||
self._set_pending()
|
||||
return True
|
||||
self._set_transaction_pending()
|
||||
elif error_regex_1:
|
||||
error_message = data.get('result').get('description') or 'error'
|
||||
error = _('applepay:' + error_message)
|
||||
_logger.info(error)
|
||||
self.write({'state_message': error})
|
||||
self._set_canceled()
|
||||
return False
|
||||
self._set_transaction_error()
|
||||
else:
|
||||
cancel_message = data.get('result').get('description') or 'cancel'
|
||||
logger_msg = _('applepay:' + cancel_message)
|
||||
_logger.info(logger_msg)
|
||||
self.write({'provider_reference': data.get('id')})
|
||||
self._set_canceled()
|
||||
return True
|
||||
error = 'Received unrecognized status for ApplePay payment %s: %s, set as error' % (self.reference, status_code)
|
||||
_logger.info(error)
|
||||
self._set_transaction_cancel()
|
||||
return self.write(res)
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,131 @@
|
|||
var wpwlOptions = {
|
||||
applePay: {
|
||||
version: 3,
|
||||
displayName: "ENSAN",
|
||||
total: { label: "ENSAN", amount: "10" },
|
||||
checkAvailability: "applePayCapabilities",
|
||||
currencyCode: "SAR",
|
||||
supportedNetworks: ["mada","masterCard", "visa"],
|
||||
merchantCapabilities: ["supports3DS", "supportsCredit", "supportsDebit"],
|
||||
merchantIdentifier: "8ac9a4ca811e7d6f018132e7a3654ddf",
|
||||
supportedCountries: ["SA"],
|
||||
buttonSource: "css",
|
||||
buttonStyle: "black",
|
||||
buttonType: "pay",
|
||||
countryCode: "SA",
|
||||
submitOnPaymentAuthorized: ["customer"],
|
||||
requiredShippingContactFields: ["phone"],
|
||||
onCancel: function() {
|
||||
if (window.wpwl && window.wpwl.checkout && window.wpwl.checkout.id) {
|
||||
window.wpwl.checkout.id = "";
|
||||
}
|
||||
},
|
||||
|
||||
},
|
||||
locale: "ar-AB",
|
||||
onReady: function(){
|
||||
const amounts = $('.donation-product-detail-layout .single-amount', window.parent.document);
|
||||
const fixedQty = $('#fixedqtyinput-1', window.parent.document);
|
||||
if (amounts.length > 0) {
|
||||
window.wpwlOptions.applePay.total.amount = amounts.get(0).dataset.amount;
|
||||
console.log("Apple Pay Amount updated to:", window.wpwlOptions.applePay.total.amount);
|
||||
} else if(fixedQty.length > 0){
|
||||
window.wpwlOptions.applePay.total.amount = fixedQty.data('price');
|
||||
console.log("Apple Pay Amount updated to:", window.wpwlOptions.applePay.total.amount);
|
||||
}
|
||||
window.parent.document.addEventListener('applePayAmountUpdate', function(e) {
|
||||
window.wpwlOptions.applePay.total.amount = e.detail.amount;
|
||||
console.log("Apple Pay Amount updated to:", window.wpwlOptions.applePay.total.amount);
|
||||
});
|
||||
let isCheckoutPage = $("#oe_structure_website_sale_payment_1", window.parent.document).length;
|
||||
if (isCheckoutPage) {
|
||||
let applepayButton = $('apple-pay-button');
|
||||
let totalAmount = $("tr#order_total", window.parent.document).find("span.oe_currency_value").text().replaceAll(",", "");
|
||||
window.wpwlOptions.applePay.total.amount = totalAmount;
|
||||
console.log("Apple Pay Amount updated to:", window.wpwlOptions.applePay.total.amount);
|
||||
applepayButton.css({
|
||||
'--apple-pay-button-height': '60px',
|
||||
'--apple-pay-button-border-radius': '4px',
|
||||
'--apple-pay-button-padding': '15px 5px',
|
||||
'--apple-pay-button-box-sizing': 'border-box'
|
||||
});
|
||||
}
|
||||
},
|
||||
createCheckout: function() {
|
||||
let name = "";
|
||||
let product_ids = gifts = [];
|
||||
let done_with_quick_donation = false;
|
||||
let use_current_order = false;
|
||||
|
||||
// product details screen
|
||||
if ($(".js_product", window.parent.document).length) {
|
||||
let hasGifts = $("#sendAsGiftCheckbox", window.parent.document).is(":checked");
|
||||
let product_id = parseInt($('.js_product', window.parent.document).find('.product_id').val());
|
||||
let amount = parseFloat($("input.personal-donation-amount", window.parent.document).val()) || 0;
|
||||
let quantity = parseInt($($('#fixedqtyinput-1', window.parent.document).get(0)).val()) || 1;
|
||||
|
||||
product_ids = [{
|
||||
id: product_id,
|
||||
quantity: hasGifts ? 1 : quantity,
|
||||
price_unit: hasGifts ? 0 : amount
|
||||
}];
|
||||
|
||||
if (hasGifts) {
|
||||
let $giftBoxElements = $(".gifteeBoxDetails", window.parent.document);
|
||||
gifts = $giftBoxElements.map(function() {
|
||||
let result = {};
|
||||
result.product_id = product_id;
|
||||
result.amount = parseFloat($(this).find('input.gift-donation-amount').val(), 10) || 0;
|
||||
result.receiver_name = $(this).find('.input-gifteeName').val();
|
||||
result.receiver_mobile = $(this).find('.input-gifteeNumber').val();
|
||||
return result;
|
||||
}).get();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
// checkout page
|
||||
else if ($("#oe_structure_website_sale_payment_1", window.parent.document).length) {
|
||||
name = $("#order_name", window.parent.document).val();
|
||||
let $productRows = $("table#cart_products tbody tr", window.parent.document);
|
||||
product_ids = $productRows.map(function() {
|
||||
let result = {};
|
||||
result.id = parseInt($(this).data('product-id'));
|
||||
result.quantity = parseInt($(this).find('td.td-qty').text().replaceAll(",", ""));
|
||||
result.price_unit = parseFloat($(this).find('td.td-price span.oe_currency_value').text().replaceAll(",", ""));
|
||||
return result;
|
||||
}).get();
|
||||
use_current_order = true;
|
||||
}
|
||||
// quick donation page
|
||||
else {
|
||||
done_with_quick_donation = true;
|
||||
let amount = parseFloat($("#qd_amount", window.parent.document).val());
|
||||
product_ids = [{
|
||||
id: parseInt($("#qd-options li.active", window.parent.document).data('product_id')),
|
||||
quantity: 1,
|
||||
price_unit: amount
|
||||
}];
|
||||
}
|
||||
|
||||
let requestData = { product_ids: product_ids,
|
||||
gifts: gifts,
|
||||
name: name,
|
||||
done_with_quick_donation: done_with_quick_donation,
|
||||
use_current_order: use_current_order};
|
||||
|
||||
console.log(requestData);
|
||||
const rootUrl = `${window.location.protocol}//${window.location.host}/`;
|
||||
return $.ajax({
|
||||
url: `${rootUrl}applepay/checkout`,
|
||||
type: "POST",
|
||||
contentType: "application/json",
|
||||
data: JSON.stringify(requestData),
|
||||
dataType: "json",
|
||||
})
|
||||
.then(function(response) {
|
||||
console.log(response);
|
||||
return response.result.checkout_id;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
body {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.wpwl-form {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.wpwl-container {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.wpwl-clearfix:after {
|
||||
clear: none;
|
||||
}
|
||||
.wpwl-group {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
apple-pay-button {
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
|
||||
<template id="apple_pay_iframe" name="Apple Pay Iframe">
|
||||
<html>
|
||||
<head>
|
||||
<script src="https://oppwa.com/v1/paymentWidgets.js" />
|
||||
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" />
|
||||
<script src="/payment_applepay/static/src/js/applepay_iframe.js" />
|
||||
<link rel="stylesheet" href="/payment_applepay/static/src/scss/applepay_iframe_content.scss" />
|
||||
</head>
|
||||
<body>
|
||||
<form t-attf-action="{{request.httprequest.url_root}}payment/applepay/return"
|
||||
class="paymentWidgets" data-brands="APPLEPAY"></form>
|
||||
</body>
|
||||
</html>
|
||||
</template>
|
||||
|
||||
</odoo>
|
||||
|
|
@ -49,7 +49,7 @@
|
|||
<!-- }-->
|
||||
|
||||
</style>
|
||||
<script src="https://eu-prod.oppwa.com/v1/paymentWidgets.js?checkoutId={check_out_id}"></script>
|
||||
<script src="https://oppwa.com/v1/paymentWidgets.js?checkoutId={check_out_id}"></script>
|
||||
<input type="hidden" name="data_set" t-att-data-action-url="shopperResultUrl" data-remove-me=""/>
|
||||
<input type="hidden" name="entityId" t-att-value="entityId"/>
|
||||
<input type="hidden" name="merchantTransactionId" t-att-value="merchantTransactionId"/>
|
||||
|
|
|
|||
|
|
@ -65,7 +65,7 @@
|
|||
APPLEPAY
|
||||
</form>
|
||||
</body>
|
||||
<script t-att-src="'https://eu-prod.oppwa.com/v1/paymentWidgets.js?checkoutId=%s' %(check_out_id)"></script>
|
||||
<script t-att-src="'https://oppwa.com/v1/paymentWidgets.js?checkoutId=%s' %(check_out_id)"></script>
|
||||
<script>
|
||||
var wpwlOptions = {
|
||||
applePay: {
|
||||
|
|
|
|||
|
|
@ -4,16 +4,17 @@
|
|||
|
||||
<record id="acquirer_form_applepay" model="ir.ui.view">
|
||||
<field name="name">acquirer.form.applepay</field>
|
||||
<field name="model">payment.provider</field>
|
||||
<field name="inherit_id" ref="payment.payment_provider_form"/>
|
||||
<field name="model">payment.acquirer</field>
|
||||
<field name="inherit_id" ref="payment.acquirer_form"/>
|
||||
<field name="arch" type="xml">
|
||||
<group name='provider_credentials' position='inside'>
|
||||
<group attrs="{'invisible': [('code', '!=', 'applepay')]}">
|
||||
<xpath expr='//group[@name="acquirer"]' position='inside'>
|
||||
<group attrs="{'invisible': [('provider', '!=', 'applepay')]}">
|
||||
<field name="applepay_entity_id"/>
|
||||
<field name="applepay_authorization_bearer"/>
|
||||
</group>
|
||||
</group>
|
||||
</xpath>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
</data>
|
||||
</odoo>
|
||||
|
|
|
|||
|
|
@ -41,7 +41,8 @@
|
|||
"live_test_url": "http://odoodemo.webkul.com/?module=payment_hyperpay",
|
||||
"depends": ['account',
|
||||
'payment',
|
||||
'website_sale'],
|
||||
'website_sale',
|
||||
'ensan_sale_management'],
|
||||
"data": [
|
||||
'views/payment_views.xml',
|
||||
'views/payment_hyperpay_templates.xml',
|
||||
|
|
|
|||
Loading…
Reference in New Issue