Permalink
Browse files

[REM] remove code for s2s payment

  • Loading branch information...
nla-odoo committed Feb 11, 2019
1 parent 22ea96c commit 7972c4d072b6495c84b94f1eb23a8079f753c231
@@ -5,9 +5,8 @@
import pprint
import werkzeug

from odoo import http, _
from odoo import http
from odoo.http import request
from odoo.addons.payment.models.payment_acquirer import ValidationError

_logger = logging.getLogger(__name__)

@@ -21,32 +20,3 @@ def payulatam_response(self, **post):
if post:
request.env['payment.transaction'].sudo().form_feedback(post, 'payulatam')
return werkzeug.utils.redirect('/payment/process')

@http.route(['/payment/payulatam/s2s/create_json_3ds'], type='json', auth='public', csrf=False)
def payulatam_s2s_create_json_3ds(self, verify_validity=False, **kwargs):
acquirer = request.env['payment.acquirer'].browse(int(kwargs.get('acquirer_id')))
if acquirer.environment == 'test' and verify_validity:
raise ValidationError(_('Adding a new card is not possible in Test mode.'))
if not kwargs.get('partner_id'):
kwargs = dict(kwargs, partner_id=request.env.user.partner_id.id)
token = acquirer.s2s_process(kwargs)

if not token:
res = {
'result': False,
}
return res

res = {
'result': True,
'id': token.id,
'short_name': token.short_name,
'3d_secure': False,
'verified': False,
}

if verify_validity:
token.validate(**kwargs)
res['verified'] = token.verified

return res
@@ -28,36 +28,17 @@ class PaymentAcquirerPayulatam(models.Model):
payulatam_api_key = fields.Char(string="PayUlatam API Key", required_if_provider='payulatam', groups='base.group_user')
payulatam_api_login = fields.Char(string="PayUlatam API Login", required_if_provider='payulatam', groups='base.group_user')

def _get_feature_support(self):
"""Get advanced feature support by provider.
Each provider should add its technical in the corresponding
key for the following features:
* fees: support payment fees computations
* tokenize: support saving payment data in a payment.tokenize
object
"""
res = super(PaymentAcquirerPayulatam, self)._get_feature_support()
res['tokenize'].append('payulatam')
return res

def _get_payulatam_urls(self, environment):
""" PayUlatam URLs"""
if environment == 'prod':
return {
'payulatam_form_url': 'https://checkout.payulatam.com/ppp-web-gateway-payu/',
'payulatam_rest_url': 'https://api.payulatam.com/payments-api/4.0/service.cgi'
}
return {
'payulatam_form_url': 'https://sandbox.checkout.payulatam.com/ppp-web-gateway-payu/',
'payulatam_rest_url': 'https://sandbox.api.payulatam.com/payments-api/4.0/service.cgi'
}
return 'https://checkout.payulatam.com/ppp-web-gateway-payu/'
return 'https://sandbox.checkout.payulatam.com/ppp-web-gateway-payu/'

def _payulatam_generate_sign(self, inout, values):
if inout not in ('in', 'in_s2s', 'out'):
raise Exception("Type must be 'in', 'in_s2s' or 'out'")
if inout not in ('in', 'out'):
raise Exception("Type must be 'in' or 'out'")

if inout in ['in', 'in_s2s']:
if inout == 'in':
data_string = ('~').join((self.payulatam_api_key, self.payulatam_merchant_id, values['referenceCode'],
str(values['amount']), values['currency']))
else:
@@ -92,30 +73,7 @@ def payulatam_form_generate_values(self, values):
@api.multi
def payulatam_get_form_action_url(self):
self.ensure_one()
return self._get_payulatam_urls(self.environment)['payulatam_form_url']

@api.model
def payulatam_s2s_form_process(self, data):
payment_token = self.env['payment.token'].sudo().create({
'cc_number': data['cc_number'],
'cc_holder_name': data['cc_holder_name'],
'cc_expiry': data['cc_expiry'],
'cc_brand': data['cc_brand'],
'cvc': data['cvc'],
'acquirer_id': int(data['acquirer_id']),
'partner_id': int(data['partner_id'])
})
return payment_token

@api.multi
def payulatam_s2s_form_validate(self, data):
self.ensure_one()

# mandatory fields
for field_name in ["cc_number", "cvc", "cc_holder_name", "cc_expiry", "cc_brand"]:
if not data.get(field_name):
return False
return True
return self._get_payulatam_urls(self.environment)


class PaymentTransactionPayulatam(models.Model):
@@ -124,8 +82,6 @@ class PaymentTransactionPayulatam(models.Model):
# payulatam will not allow any payment twice with same reference even if payment was failed last time
# so need to change the reference number each time so instead of changing order reference added new field
payulatam_reference_code = fields.Char('Reference Code', readonly=True)
# inorder to make refund one extra order ID need to passed which gets from payulatam while transaction.
payulatam_order_id = fields.Char('Order ID', readonly=True)

@api.model
def _payulatam_form_get_tx_from_data(self, data):
@@ -162,91 +118,6 @@ def _payulatam_form_get_invalid_parameters(self, data):
invalid_parameters.append(('Merchant Id', data.get('merchantId'), self.acquirer_id.payulatam_merchant_id))
return invalid_parameters

@api.multi
def _create_payulatam_charge(self, **kwargs):
if not kwargs.get('cvc') or not kwargs.get('cvc_number'):
raise ValidationError("CVC number is required for any transaction")
api_charge_url = self.acquirer_id._get_payulatam_urls(self.acquirer_id.environment)['payulatam_rest_url']
if self.state not in ['done', 'pending']:
self.payulatam_reference_code = str(uuid.uuid4())
charge_data = {
"language": "en",
"command": "SUBMIT_TRANSACTION",
"merchant": {
"apiKey": self.acquirer_id.payulatam_api_key,
"apiLogin": self.acquirer_id.payulatam_api_login
},
"transaction": {
"order": {
"accountId": self.acquirer_id.payulatam_account_id,
"referenceCode": self.payulatam_reference_code,
"description": self.reference,
"language": "en",
"signature": self.acquirer_id._payulatam_generate_sign('in_s2s', {'amount': self.amount, 'referenceCode': self.payulatam_reference_code, 'currency': self.currency_id.name}),
"additionalValues": {
"TX_VALUE": { # transaction value
"value": self.amount,
"currency": self.currency_id.name
}
}
},
"creditCardTokenId": self.payment_token_id.acquirer_ref,
"creditCard": {
"securityCode": kwargs.get('cvc') or kwargs.get('cvc_number')
},
"type": "AUTHORIZATION_AND_CAPTURE",
"paymentMethod": self.payment_token_id.name.split('-')[-1].replace(' ', '').upper()
},
'test': 'true' if self.acquirer_id.environment == 'test' else "false"
}
headers = {'Content-Type': 'application/json'}
resp = requests.post(api_charge_url, json.dumps(charge_data), headers=headers)
data = objectify.fromstring(resp.text)
_logger.info('_create_payulatam_charge: Values received:\n%s', pprint.pformat(resp.text))
if data.find('error'):
raise ValidationError('_create_payulatam_charge: Values received:\n%s' % pprint.pformat(resp.text))
return data

@api.multi
def payulatam_s2s_do_transaction(self, **kwargs):
self.ensure_one()
result = self._create_payulatam_charge(email=self.partner_email, **kwargs)
return self._payulatam_form_validate(result)

def _create_payulatam_refund(self):
api_refund_url = self.acquirer_id._get_payulatam_urls(self.acquirer_id.environment)['payulatam_rest_url']
refund_params = {
"language": "en",
"command": "SUBMIT_TRANSACTION",
"merchant": {
"apiKey": self.acquirer_id.payulatam_api_key,
"apiLogin": self.acquirer_id.payulatam_api_login
},
"transaction": {
"order": {
"id": self.payulatam_order_id
},
"type": "REFUND",
"reason": "Adding card",
"parentTransactionId": self.acquirer_reference
},
"test": 'true' if self.acquirer_id.environment == 'test' else "false"
}

headers = {'Content-Type': 'application/json'}
resp = requests.post(api_refund_url, json.dumps(refund_params), headers=headers)
data = objectify.fromstring(resp.text)
_logger.info('_create_payulatam_refund: Values received:\n%s', pprint.pformat(resp.text))
if data.find('error'):
raise ValidationError('_create_payulatam_refund: Values received:\n%s' % pprint.pformat(resp.text))
return data

@api.multi
def payulatam_s2s_do_refund(self, **kwargs):
self.ensure_one()
result = self._create_payulatam_refund()
return self._payulatam_form_validate(result)

@api.multi
def _payulatam_form_validate(self, data):
self.ensure_one()
@@ -260,9 +131,6 @@ def _payulatam_form_validate(self, data):
if status == 'APPROVED':
_logger.info('Validated PayUlatam payment for tx %s: set as done' % (self.reference))
res.update(state='done', date=fields.Datetime.now())
if self.payment_token_id:
res.update(payulatam_order_id=data.find('transactionResponse').find('orderId').text)
self.payment_token_id.verified = True
self._set_transaction_done()
self.write(res)
self.execute_callback()
@@ -283,40 +151,3 @@ def _payulatam_form_validate(self, data):
res.update(state='cancel', state_message=error)
self._set_transaction_cancel()
return self.write(res)


class PaymentToken(models.Model):
_inherit = 'payment.token'

@api.model
def payulatam_create(self, values):
res = {}
payment_acquirer = self.env['payment.acquirer'].browse(values.get('acquirer_id'))
if values.get('cc_number'):
data = json.dumps({
'language': 'en',
'command': 'CREATE_TOKEN',
'merchant': {
'apiLogin': payment_acquirer.payulatam_api_login,
'apiKey': payment_acquirer.payulatam_api_key
},
'creditCardToken': {
'payerId': self.env.user.id,
'name': values.get('cc_holder_name'),
'paymentMethod': values.get('cc_brand').upper(),
'number': values.get('cc_number').replace(' ', ''),
'expirationDate': "20" + str(values['cc_expiry'][-2:]) + "/" + str(values['cc_expiry'][:2]),
},
})
headers = {'Content-Type': 'application/json'}
response = requests.post(payment_acquirer._get_payulatam_urls(payment_acquirer.environment)['payulatam_rest_url'], data, headers=headers)
data = objectify.fromstring(response.text)
if data.find('code').text == 'SUCCESS':
_logger.info('_create_credit_card: Values received:\n%s', pprint.pformat(response.text))
res = {
'acquirer_ref': data.find('creditCardToken').find('creditCardTokenId').text,
'name': 'XXXXXXXXXXXX%s - %s - %s' % (values['cc_number'][-4:], values['cc_holder_name'], values['cc_brand'])
}
else:
raise ValidationError(data.find('error').text)
return res

This file was deleted.

Oops, something went wrong.
@@ -149,39 +149,3 @@ def test_20_payulatam_form_management(self):
# check transaction
self.assertEqual(tx.state, 'done', 'payulatam: wrong state after receiving a valid pending notification')
self.assertEqual(tx.acquirer_reference, 'b232989a-4aa8-42d1-bace-153236eee791', 'payulatam: wrong txn_id after receiving a valid pending notification')

def test_10_payulatam_s2s(self):
self.assertEqual(self.payulatam.environment, 'test', 'test without test environment')

self.payulatam.write({
'payulatam_merchant_id': '508029',
'payulatam_account_id': '512322',
'payulatam_api_key': '4Vj8eK4rloUd272L48hsrarnUA',
'payulatam_api_login': 'pRRXKOl8ikMmt9u'
})

# Create payment meethod for payulatam
vals = {
'acquirer_id': self.payulatam.id,
'partner_id': self.buyer_id,
'cc_number': '4111111111111111',
'cc_expiry': '02 / 2026',
'cc_brand': 'visa',
'cvc': '111',
'cc_holder_name': 'APPROVED',
}
payment_token = self.env['payment.token'].create(vals)
# Create transaction
tx = self.env['payment.transaction'].create({
'reference': 'test_ref_%s' % fields.date.today(),
'currency_id': self.currency_usd.id,
'acquirer_id': self.payulatam.id,
'partner_id': self.buyer_id,
'payment_token_id': payment_token.id,
'type': 'server2server',
'amount': 115.0
})

tx.payulatam_s2s_do_transaction(**vals)
# Check state
self.assertEqual(tx.state, 'done', 'Stripe: Transcation has been discarded.')
@@ -17,42 +17,4 @@
<input type="hidden" name="extra1" t-att-value="extra1"/>
</div>
</template>

<template id="payulatam_s2s_form">
<input type="hidden" name="data_set" data-create-route="/payment/payulatam/s2s/create_json_3ds"/>
<div t-attf-class="row mt8 #{'' if bootstrap_formatting else 'o_card_brand_detail'}">
<div t-att-class="'form-group col-md-12' if bootstrap_formatting else 'form-group'">
<input type="tel" name="cc_number" id="cc_number" class="form-control" placeholder="Card number" data-is-required="true"/>
<div class="card_placeholder"></div>
<div class="visa"></div>
<input type="hidden" name="cc_brand" value=""/>
</div>
<div t-att-class="'form-group col-md-5' if bootstrap_formatting else 'form-group'">
<input type="text" name="cc_holder_name" id="cc_holder_name" class="form-control" placeholder="Cardholder name" data-is-required="true"/>
</div>
<div t-att-class="'form-group col-md-4' if bootstrap_formatting else 'form-group'">
<input type="text" name="cc_expiry" id="cc_expiry" class="form-control" maxlength="9" minlength="9" placeholder="Expires (MM / YYYY)" data-is-required="true"/>
</div>
<div t-att-class="'form-group col-md-3' if bootstrap_formatting else 'form-group'">
<input type="text" name="cvc" id="cvc" class="form-control" maxlength="4" placeholder="CVC" data-is-required="true"/>
</div>
<input type="hidden" name="acquirer_id" t-att-value="id"/>
<input t-if="return_url" type="hidden" name="return_url" t-att-value="return_url"/>
<input t-if="partner_id" type="hidden" name="partner_id" t-att-value="partner_id"/>
<input type="hidden" name="csrf_token" t-att-value="request.csrf_token()"/>
<div class="clearfix"/>
</div>
</template>

<template id="payulatam_token_cvc" inherit_id="payment.payment_tokens_list">
<xpath expr="//label[hasclass('payment_token_name')]" position="after">
<input type="text" name="cvc_number" id="cvc" class="form-control hidden" maxlength="4" placeholder="CVC" data-is-required="true" style=" width: 30%; display: inline-block; margin-left: 25px;"/>
</xpath>
</template>

<template id="assets_frontend" inherit_id="web.assets_frontend">
<xpath expr="script[last()]" position="after">
<script type="text/javascript" src="/payment_payulatam/static/src/js/payulatam.js"></script>
</xpath>
</template>
</odoo>
@@ -23,7 +23,6 @@
<field name="arch" type="xml">
<field name="date" position="after">
<field name="payulatam_reference_code" attrs="{'invisible': [('provider', '!=', 'payulatam')]}"/>
<field name="payulatam_order_id" attrs="{'invisible': [('provider', '!=', 'payulatam')]}"/>
</field>
</field>
</record>

0 comments on commit 7972c4d

Please sign in to comment.