I have developed a payment gateway module called instapago, but I am trying to use it in the odoo 15 web portal to execute a payment and it just loads and the button does nothing, it just loads and loads and does not show me the form to validate entering the data and validating payment.
These are part of the codes I have
`
anexo manifest ->
'depends': [
'base','payment', 'account',
],
'data':[
'views/pago_movil_insta_c2p.xml',
'security/ir.model.access.csv',
'views/payment_templates.xml',
'data/payment_method_data.xml',
'views/payment_pago_movil_templates.xml',
],
'assets': {
'web.assets_frontend':[
'instapagos_conexion/static/src/js/payment_movil.js',
'instapagos_conexion/static/src/js/instapago_payment.js',
'instapagos_conexion/static/src/js/payment_validation.js',
],
},
`
from odoo import models, fields, api
from odoo.exceptions import ValidationError
import requests
import json
class InstapagoTransaction(models.Model):
_name = 'instapago.transaction'
_description = 'Instapago Transaction'
phone_number = fields.Char('N° Telefono')
docs = fields.Selection([('V', 'V'), ('J','J'), ('G', 'G')], default='V', string='Documento')
client_id = fields.Char('C.I o Rif')
#bank = fields.Char('Banco')
amount = fields.Float('Monto')
order_number = fields.Char('Número de orden')
referencia = fields.Char('Referencia cliente')
reference_dest = fields.Char('referencia banco')
phonenumber_client = fields.Char('N° Telefono cliente')
#receipt_bank = fields.Char('Banco del Recibo')
date = fields.Date('Fecha')
transaction_status = fields.Selection(
[('pending', 'Pending'), ('completed', 'Completed'), ('failed', 'Failed')],
default='pending', string='Status'
)
start_date = fields.Date('Fecha inicial')
end_date = fields.Date('Fecha final')
formatted_start_date = fields.Char(string='Formatted Start Date', compute='_compute_formatted_dates')
formatted_end_date = fields.Char(string='Formatted End Date', compute='_compute_formatted_dates')
bank = fields.Selection([
('0601', '0601 Instituto Municipal de Crédito Popular')
], string='Banco')
receipt_bank = fields.Selection([
('0601', '0601 Instituto Municipal de Crédito Popular')
], string='Banco del Recibo')
ful_client_id = fields.Char(string='CI o Rif', compute='_compute_ful_client_id')
@api.model
def create(self, vals):
if 'amount' in vals:
vals['amount'] = float('{:.2f}'.format(float(vals['amount'])))
return super(InstapagoTransaction, self).create(vals)
def write(self, vals):
if 'amount' in vals:
vals['amount'] = float('{:.2f}'.format(float(vals['amount'])))
return super(InstapagoTransaction, self).write(vals)
@api.depends('docs', 'client_id')
def _compute_ful_client_id(self):
for record in self:
record.ful_client_id = f"{record.docs}{record.client_id}" if record.docs and record.client_id else ''
@api.depends('start_date', 'end_date')
def _compute_formatted_dates(self):
for record in self:
record.formatted_start_date = record.start_date.strftime('%Y-%m-%d') if record.start_date else ''
record.formatted_end_date = record.end_date.strftime('%Y-%m-%d') if record.end_date else ''
def _get_full_phone_number(self):
self.ensure_one()
if self.phone_number:
return '0058' + self.phone_number
if self.phonenumber_client:
return '0058' + self.phonenumber_client
return ''
def _send_notification(self, message, title='Notification'):
return {
'type': 'ir.actions.client',
'tag': 'display_notification',
'params': {
'title': title,
'message': message,
'sticky': False,
}
}
def action_validacion_pago(self):
acquirer = self.env['payment.acquirer'].search([('provider', '=', 'pago_movil')], limit=1)
if not acquirer:
raise ValidationError('No payment acquirer configured for Pago Movil.')
full_phone_number = self._get_full_phone_number()
response = acquirer.validacion_pago(
phonenumber_client=full_phone_number,
client_id=self.ful_client_id,
bank=self.bank,
date=self.date,
reference=self.referencia,
receipt_bank=self.receipt_bank,
amount=self.amount,
)
if response.get('success'):
# Si el pago se valida correctamente, establece el estado como completado
self.write({'transaction_status': 'completed'})
payments = response.get('payments', [])
if payments:
for payment in payments:
amount_float = float(payment['amount'].replace(',', '.')) if isinstance(payment['amount'], str) else payment['amount']
self.env['instapago.transaction'].create({
'date': payment.get('date', ''),
'phone_number': payment.get('phonenumber', ''),
'client_id': payment.get('rif', ''),
'referencia': payment.get('reference', ''),
'reference_dest': payment.get('referencedest', ''),
'bank': payment.get('bank', ''),
'phonenumber_client': payment.get('phonenumberclient', ''),
'amount': amount_float,
'receipt_bank': payment.get('receiptbank', ''),
'transaction_status': 'completed',
})
else:
# Si el pago no se valida correctamente, establece el estado como fallido y retorna el mensaje de error
self.write({'transaction_status': 'failed'})
return {'error': True, 'message': response.get('message', 'Unknown error')}
`
`import requests
from odoo import models, fields, api
from odoo.exceptions import ValidationError
import json
#from odoo.http import Response
class PaymentAcquirerPagoMovil(models.Model):
_inherit = 'payment.acquirer'
provider = fields.Selection(
selection_add=[('pago_movil', 'Pago Movil')],
ondelete={'pago_movil': 'set default'}
)
instapago_key_id_p2p = fields.Char('Key ID P2P')
instapago_key_id_c2p = fields.Char('Key ID C2P')
instapago_public_key_id = fields.Char('Public Key ID')
journal_id = fields.Many2one('account.journal', string='Payment Journal', domain=[('type', '=', 'bank')])
start_date = fields.Date('Fecha inicial')
end_date = fields.Date('Fecha final')
formatted_start_date = fields.Char(string='Formatted Start Date', compute='_compute_formatted_dates')
formatted_end_date = fields.Char(string='Formatted End Date', compute='_compute_formatted_dates')
@api.depends('start_date', 'end_date')
def _compute_formatted_dates(self):
for record in self:
record.formatted_start_date = record.start_date.strftime('%Y-%m-%d') if record.start_date else ''
record.formatted_end_date = record.end_date.strftime('%Y-%m-%d') if record.end_date else ''
def _get_headers(self):
return {
'Content-Type': 'application/x-www-form-urlencoded',
}
def _get_base_url(self):
return 'https://merchant.instapago.com/services/api'
def validacion_pago(self, phonenumber_client, client_id, bank, date, reference, receipt_bank, amount):
url = f"{self._get_base_url()}/v2/payments/p2p/validatepayment"
params = {
'keyId': self.instapago_key_id_p2p,
'publickeyid': self.instapago_public_key_id,
'phonenumberclient': phonenumber_client,
#'idclient': client_id,
'clientid': client_id,
'bank': bank,
'date': date.strftime('%Y-%m-%d'),
'reference': reference,
'receiptbank': receipt_bank,
'amount': '{:.2f}'.format(amount).replace(',', '.'),
}
response = requests.get(url, params=params, headers=self._get_headers())
return response.json()
`
`from odoo import http
from odoo.http import request
import requests
class PagoMovilController(http.Controller):
@http.route('/payment/pago_movil/validate', type='json', auth='public')
def validate_payment(self, **post):
phonenumber_client = post.get('phonenumber_client')
client_id = post.get('client_id')
bank = post.get('bank')
date = post.get('date')
reference = post.get('referencia')
receipt_bank = post.get('receipt_bank')
amount = post.get('amount')
acquirer = request.env['payment.acquirer'].search([('provider', '=', 'pago_movil')], limit=1)
if not acquirer:
return {'success': False, 'message': 'Acquirer not found'}
url = f"{acquirer._get_base_url()}/v2/payments/p2p/validatepayment"
params = {
'keyId': acquirer.instapago_key_id_p2p,
'publickeyid': acquirer.instapago_public_key_id,
'phonenumberclient': phonenumber_client,
'clientid': client_id,
'bank': bank,
'date': date,
'reference': reference,
'receiptbank': receipt_bank,
'amount': amount
}
response = requests.get(url, params=params, headers={'Content-Type': 'application/json'})
result = response.json()
if result.get('success'):
return {'success': True, 'message': 'Payment validated successfully'}
else:
return {'success': False, 'message': result.get('message')}
class InstapagoController(http.Controller):
@http.route('/instapago/validate', type='json', auth='public', methods=['POST'])
def validate_payment(self, **post):
try:
transaction = request.env['instapago.transaction'].create(post)
transaction.action_validacion_pago()
return json.dumps({'success': True, 'message': 'Payment validated successfully.'})
except Exception as e:
return json.dumps({'success': False, 'message': str(e)})
`
` <!-- Payment Validation View -->
<record id="view_instapago_transaction_form_validacion_pago" model="ir.ui.view">
<field name="name">instapago.transaction.form.validacion_pago</field>
<field name="model">instapago.transaction</field>
<field name="arch" type="xml">
<form string="Validación de Pago">
<sheet>
<group>
<field name="phonenumber_client" required="1"/>
<field name="docs"/>
<field name="client_id" required="1"/>
<field name="bank" required="1"/>
<field name="amount" required="1"/>
<field name="referencia" required="1"/>
<field name="receipt_bank" required="1"/>
<field name="date" required="1"/>
</group>
</sheet>
<footer>
<button name="action_validacion_pago" string="Validar Pago" type="object" class="btn-primary"/>
</footer>
</form>
</field>
</record>
template -> <?xml version='1.0' encoding='utf-8'?>
<odoo>
<data>
<template id="payment_form_pago_movil" name="Payment Form Pago Movil" inherit_id="payment.payment_acquirer_form">
<xpath expr="//group[@name='acquirer']" position="inside">
<t t-if="acquirer.provider == 'pago_movil'">
<div class="form-group">
<label for="phone_number">Número de Teléfono</label>
<input type="text" name="phone_number" id="phone_number" required="required" />
</div>
<div class="form-group">
<label for="docs">Documento</label>
<select name="docs" id="docs" required="required">
<option value="V">V</option>
<option value="J">J</option>
<option value="G">G</option>
</select>
</div>
<div class="form-group">
<label for="client_id">C.I o Rif</label>
<input type="text" name="client_id" id="client_id" required="required" />
</div>
<div class="form-group">
<label for="bank">Banco</label>
<select name="bank" id="bank" required="required">
<option value="0191">0191 Banco Nacional de Crédito C.A. Banco Universal</option>
<option value="0601">0601 Instituto Municipal de Crédito Popular</option>
</select>
</div>
<div class="form-group">
<label for="date">Fecha</label>
<input type="date" name="date" id="date" required="required" />
</div>
<div class="form-group">
<label for="referencia">Referencia</label>
<input type="text" name="referencia" id="referencia" required="required" />
</div>
<div class="form-group">
<label for="receipt_bank">Banco del Recibo</label>
<select name="receipt_bank" id="receipt_bank" required="required">
<option value="0191">0191 Banco Nacional de Crédito C.A. Banco Universal</option>
<option value="0601">0601 Instituto Municipal de Crédito Popular</option>
</select>
</div>
<button type="button" id="submit_payment">Pagar</button>
</t>
</xpath>
</template>
<template id="portal_payment_movil_response" name="Pago Movil Response">
<div t-if="response.get('success')">
<div class="alert alert-success">Su pago ha sido validado</div>
</div>
<div t-else="">
<div class="alert alert-danger">Pago no encontrado: <t t-esc="response.get('message')"/>
</div>
</div>
</template>
</data>
</odoo>
``