Skip to content

Commit

Permalink
[IMP]v 9.0.5.0 , Recepción de datos Desde Webpay
Browse files Browse the repository at this point in the history
- Proceso Solamente estado aceptado
- @todo estados de Rehazo
  • Loading branch information
dansanti committed Jun 12, 2017
1 parent 66c3e3b commit 8fdeafb
Show file tree
Hide file tree
Showing 5 changed files with 172 additions and 27 deletions.
3 changes: 2 additions & 1 deletion __openerp__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
'author': 'Daniel Santibáñez Polanco',
'summary': 'Payment Acquirer: Webpay Implementation',
'website': 'https://odoocoop.cl',
'version': "9.0.2.0",
'version': "9.0.5.0",
'description': """Webpay Payment Acquirer""",
'depends': ['payment'],
'python-depends':[
Expand All @@ -20,6 +20,7 @@
'data': [
'views/webpay.xml',
'views/payment_acquirer.xml',
'views/payment_transaction.xml',
'data/webpay.xml',
],
'installable': True,
Expand Down
81 changes: 73 additions & 8 deletions controllers/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,83 @@ class WebpayController(http.Controller):
_exception_url = '/payment/webpay/test/exception'
_cancel_url = '/payment/webpay/test/cancel'

def _webpay_form_get_tx_from_data(self, cr, uid, data, context=None):
reference, txn_id = data.get('item_number'), data.get('txn_id')
if not reference or not txn_id:
error_msg = _('Paypal: received data with missing reference (%s) or txn_id (%s)') % (reference, txn_id)
_logger.info(error_msg)
raise ValidationError(error_msg)

# find tx -> @TDENOTE use txn_id ?
tx_ids = self.pool['payment.transaction'].search(cr, uid, [('reference', '=', reference)], context=context)
if not tx_ids or len(tx_ids) > 1:
error_msg = 'Paypal: received data for reference %s' % (reference)
if not tx_ids:
error_msg += '; no order found'
else:
error_msg += '; multiple order found'
_logger.info(error_msg)
raise ValidationError(error_msg)
return self.browse(cr, uid, tx_ids[0], context=context)

def _webpay_form_validate(self, cr, uid, tx, data, context=None):
status = data.get('payment_status')
res = {
'acquirer_reference': data.get('txn_id'),
'paypal_txn_type': data.get('payment_type'),
}
if status in ['Completed', 'Processed']:
_logger.info('Validated Paypal payment for tx %s: set as done' % (tx.reference))
res.update(state='done', date_validate=data.get('payment_date', fields.datetime.now()))
return tx.write(res)
elif status in ['Pending', 'Expired']:
_logger.info('Received notification for Paypal payment %s: set as pending' % (tx.reference))
res.update(state='pending', state_message=data.get('pending_reason', ''))
return tx.write(res)
else:
error = 'Received unrecognized status for Paypal payment %s: %s, set as error' % (tx.reference, status)
_logger.info(error)
res.update(state='error', state_message=error)
return tx.write(res)

@http.route([
'/payment/webpay/accept', '/payment/webpay/test/accept',
'/payment/webpay/decline', '/payment/webpay/test/decline',
'/payment/webpay/exception', '/payment/webpay/test/exception',
'/payment/webpay/cancel', '/payment/webpay/test/cancel',
], type='http', auth='none')
def webpay_form_feedback(self, **post):
'/payment/webpay/return/<model("payment.acquirer"):acquirer_id>',
'/payment/webpay/test/return',
], type='http', auth='public', csrf=False, website=True)
def webpay_form_feedback(self, acquirer_id=None, **post):
""" Webpay contacts using GET, at least for accept """
_logger.info('Webpay: entering form_feedback with post data %s', pprint.pformat(post)) # debug
cr, uid, context = request.cr, SUPERUSER_ID, request.context
request.registry['payment.transaction'].form_feedback(cr, uid, post, 'webpay', context=context)
return werkzeug.utils.redirect(post.pop('return_url', '/'))
resp = request.registry['payment.transaction'].getTransaction(cr, uid, [], acquirer_id, post['token_ws'], context=context)
_logger.info(resp)
'''
TSY: Autenticación exitosa
TSN: Autenticación fallida.
TO6: Tiempo máximo excedido para autenticación.
ABO: Autenticación abortada por tarjetahabiente.
U3: Error interno en la autenticación.
Puede ser vacío si la transacción no se autenticó.
'''
if resp.VCI in ['TSY']:
request.registry['payment.transaction'].form_feedback(cr, uid, resp, 'webpay', context=context)
urequest = urllib2.Request(resp.urlRedirection, werkzeug.url_encode({'token_ws': post['token_ws'], }))
uopen = urllib2.urlopen(urequest)
resp = uopen.read()
values={
'webpay_redirect': resp,
}
return request.website.render('payment_webpay.webpay_redirect', values)


@http.route([
'/payment/webpay/final',
'/payment/webpay/test/final',
], type='http', auth='public', csrf=False, website=True)
def final(self, **post):
""" Webpay contacts using GET, at least for accept """
_logger.info('Webpay: entering End with post data %s', pprint.pformat(post)) # debug
cr, uid, context = request.cr, SUPERUSER_ID, request.context
return werkzeug.utils.redirect('/shop/payment/validate')


@http.route(['/payment/webpay/s2s/create_json'], type='json', auth='public', csrf=False)
Expand Down
94 changes: 77 additions & 17 deletions models/webpay.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,9 @@ def _get_webpay_urls(self):

@api.multi
def webpay_form_generate_values(self, values):
_logger.info(values)
base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
values.update({
'cmd': '_xclick',
'business': self.company_id.name,
'item_name': '%s: %s' % (self.company_id.name, values['reference']),
'item_number': values['reference'],
Expand All @@ -84,7 +84,7 @@ def webpay_form_generate_values(self, values):
'zip_code': values.get('partner_zip'),
'first_name': values.get('partner_first_name'),
'last_name': values.get('partner_last_name'),
'return_url': base_url + "/my/transaction/" + str(self.id)
'return_url': base_url + '/payment/webpay/final'
})
return values

Expand Down Expand Up @@ -125,8 +125,9 @@ def get_client(self,):
Permite inicializar una transaccion en Webpay.
Como respuesta a la invocacion se genera un token que representa en forma unica una transaccion.
"""
def initTransaction(self, post, buyOrder=1123, sessionId=2):

def initTransaction(self, post):
_logger.info(post)
base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
client = self.get_client()
client.options.cache.clear()
init = client.factory.create('wsInitTransactionInput')
Expand All @@ -135,16 +136,16 @@ def initTransaction(self, post, buyOrder=1123, sessionId=2):

init.commerceId = self.webpay_commer_code

init.buyOrder = buyOrder
init.sessionId = sessionId
init.returnURL = post['return_url']
init.finalURL = post['return_url']
init.buyOrder = post['item_number']
init.sessionId = self.company_id.id
init.returnURL = base_url + '/payment/webpay/return/'+str(self.id)
init.finalURL = post['return_url']

detail = client.factory.create('wsTransactionDetail')
detail.amount = post['amount']

detail.commerceCode = self.webpay_commer_code
detail.buyOrder = buyOrder
detail.buyOrder = post['item_number']

init.transactionDetails.append(detail)
init.wPMDetail=client.factory.create('wpmDetailInput')
Expand All @@ -158,19 +159,29 @@ def initTransaction(self, post, buyOrder=1123, sessionId=2):
class PaymentTxWebpay(models.Model):
_inherit = 'payment.transaction'

webpay_txn_type = fields.Selection([
('VD','Venta Debito'),
('VN','Venta Normal'),
('VC','Venta en cuotas'),
('SI','3 cuotas sin interés'),
('S2','cuotas sin interés'),
('NC','N Cuotas sin interés'),
],
string="Webpay Tipo Transacción")

"""
getTransaction
Permite obtener el resultado de la transaccion una vez que
Webpay ha resuelto su autorizacion financiera.
"""
def getTransaction(self, token):

client = WebpayNormal.get_client(url, config.getPrivateKey(), config.getPublicCert(), config.getWebPayCert())
@api.multi
def getTransaction(self, acquirer_id, token):
client = acquirer_id.get_client()
client.options.cache.clear()

transactionResultOutput = client.service.getTransactionResult(token)
acknowledge = WebpayNormal.acknowledgeTransaction(token)
acknowledge = self.acknowledgeTransaction(acquirer_id, token)

return transactionResultOutput

Expand All @@ -179,13 +190,62 @@ def getTransaction(self, token):
acknowledgeTransaction
Indica a Webpay que se ha recibido conforme el resultado de la transaccion
"""
def acknowledgeTransaction(self, token):
client = WebpayNormal.get_client(url, config.getPrivateKey(), config.getPublicCert(), config.getWebPayCert())
def acknowledgeTransaction(self, acquirer_id, token):
client = acquirer_id.get_client()
client.options.cache.clear()

acknowledge = client.service.acknowledgeTransaction(token)

return acknowledge

def _webpay_form_get_tx_from_data(self, cr, uid, data, context=None):
reference, txn_id = data.buyOrder, data.sessionId
if not reference or not txn_id:
error_msg = _('Webpay: received data with missing reference (%s) or txn_id (%s)') % (reference, txn_id)
_logger.info(error_msg)
raise ValidationError(error_msg)

# find tx -> @TDENOTE use txn_id ?
tx_ids = self.pool['payment.transaction'].search(cr, uid, [('reference', '=', reference)], context=context)
if not tx_ids or len(tx_ids) > 1:
error_msg = 'Webpay: received data for reference %s' % (reference)
if not tx_ids:
error_msg += '; no order found'
else:
error_msg += '; multiple order found'
_logger.info(error_msg)
raise ValidationError(error_msg)
return self.browse(cr, uid, tx_ids[0], context=context)

def _webpay_form_validate(self, cr, uid, tx, data, context=None):
'''
codes = 0 Transacción aprobada.
-1 Rechazo de transacción.
-2 Transacción debe reintentarse.
-3 Error en transacción.
-4 Rechazo de transacción.
-5 Rechazo por error de tasa.
-6 Excede cupo máximo mensual.
-7 Excede límite diario por transacción.
-8 Rubro no autorizado.
'''
status = str(data.detailOutput[0].responseCode)
res = {
'acquirer_reference': data.sessionId,
'webpay_txn_type': data.detailOutput[0].paymentTypeCode,
}
if status in ['0']:
_logger.info('Validated webpay payment for tx %s: set as done' % (tx.reference))

res.update(state='done', date_validate=data.transactionDate)
return tx.write(res)
elif status in ['-6', '-7']:
_logger.info('Received notification for webpay payment %s: set as pending' % (tx.reference))
res.update(state='pending', state_message=data.get('pending_reason', ''))
return tx.write(res)
else:
error = 'Received unrecognized status for webpay payment %s: %s, set as error' % (tx.reference, status)
_logger.info(error)
res.update(state='error', state_message=error)
return tx.write(res)

class PaymentMethod(models.Model):
_inherit = 'payment.method'
19 changes: 19 additions & 0 deletions views/payment_transaction.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<openerp>
<data>
<record id="transaction_form_webpay" model="ir.ui.view">
<field name="name">transaction.form.webpay</field>
<field name="model">payment.transaction</field>
<field name="inherit_id" ref="payment.transaction_form"/>
<field name="arch" type="xml">
<xpath expr='//notebook' position='inside'>
<page string="Webpay TX Details">
<group>
<field name="webpay_txn_type" />
</group>
</page>
</xpath>
</field>
</record>
</data>
</openerp>
2 changes: 1 addition & 1 deletion views/webpay.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<data>
<template id="webpay_acquirer_button">
<form t-if="acquirer.webpay_commer_code" t-att-action="tx_url" method="post" target="_self">
<input type="hidden" name="cmd" t-att-value="cmd"/>
<input type="hidden" name="item_number" t-att-value="item_number"/>
<input type="hidden" name="business" t-att-value="business"/>
<input type="hidden" name="amount" t-att-value="amount"/>
<input t-if="handling" type="hidden" name="handling"
Expand Down

0 comments on commit 8fdeafb

Please sign in to comment.