Skip to content

Commit

Permalink
Initial version of PreApprovals
Browse files Browse the repository at this point in the history
  • Loading branch information
edussilva committed Aug 16, 2018
1 parent d3d7cc1 commit 4ae9f9f
Show file tree
Hide file tree
Showing 12 changed files with 1,113 additions and 24 deletions.
2 changes: 1 addition & 1 deletion pagseguro/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
# -*- coding: utf-8 -*-
__version__ = '2.0.4'
__version__ = '2.0.5.dev.0'
41 changes: 40 additions & 1 deletion pagseguro/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
from __future__ import unicode_literals
from django.contrib import admin

from pagseguro.models import Checkout, Transaction, TransactionHistory
from pagseguro.models import (
Checkout, Transaction, TransactionHistory, PreApprovalPlan,
PreApproval, PreApprovalHistory
)


class CheckoutAdmin(admin.ModelAdmin):
Expand Down Expand Up @@ -34,5 +37,41 @@ class TransactionAdmin(admin.ModelAdmin):
]


class PreApprovalPlanAdmin(admin.ModelAdmin):

list_display = (
'id', 'name', 'amount_per_payment', 'reference', 'period',
'redirect_code'
)
list_display_links = ('id', 'name')
search_fields = ['redirect_code', 'name', 'reference']
list_filter = ('charge', 'period')


class PreApprovalHistoryInline(admin.TabularInline):

list_display = ('id', 'pre_approval', 'status', 'date')
list_display_links = ('id', )
search_fields = ['pre_approval__code', ]
list_filter = ('status', 'date')
model = PreApprovalHistory
extra = 0


class PreApprovalAdmin(admin.ModelAdmin):

list_display = (
'code', 'tracker', 'reference', 'status', 'date', 'last_event_date'
)
list_display_links = ('code', )
search_fields = ['code', 'reference']
list_filter = ('status', 'date', 'last_event_date')
inlines = [
PreApprovalHistoryInline,
]


admin.site.register(Checkout, CheckoutAdmin)
admin.site.register(Transaction, TransactionAdmin)
admin.site.register(PreApprovalPlan, PreApprovalPlanAdmin)
admin.site.register(PreApproval, PreApprovalAdmin)
216 changes: 203 additions & 13 deletions pagseguro/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,16 @@

from pagseguro.settings import (
PAGSEGURO_EMAIL, PAGSEGURO_TOKEN, CHECKOUT_URL, PAYMENT_URL,
NOTIFICATION_URL, TRANSACTION_URL, SESSION_URL
NOTIFICATION_URL, TRANSACTION_URL, SESSION_URL, PRE_APPROVAL_URL,
PRE_APPROVAL_REQUEST_URL, PRE_APPROVAL_REDIRECT_URL,
PRE_APPROVAL_NOTIFICATION_URL, PRE_APPROVAL_CANCEL_URL
)
from pagseguro.signals import (
notificacao_recebida, NOTIFICATION_STATUS, checkout_realizado,
checkout_realizado_com_sucesso, checkout_realizado_com_erro
checkout_realizado_com_sucesso, checkout_realizado_com_erro,
PRE_APPROVAL_NOTIFICATION_STATUS, pre_approval_notification,
pre_approval_status_cancelled, pre_approval_create_plan,
pre_approval_create_plan_error
)
from pagseguro.forms import PagSeguroItemForm

Expand Down Expand Up @@ -57,12 +62,20 @@ def __repr__(self):
class PagSeguroApi(object):
def __init__(self, checkout_url=None, redirect_url=None,
notification_url=None, transaction_url=None,
pagseguro_email=None, pagseguro_token=None, currency='BRL',
pagseguro_email=None, pagseguro_token=None,
pre_approval_url=None, pre_approval_request_url=None,
pre_approval_redirect_url=None, pre_approval_notification_url=None,
pre_approval_cancel_url=None, currency='BRL',
**kwargs):
self.checkout_url = checkout_url or CHECKOUT_URL
self.redirect_url = redirect_url or PAYMENT_URL
self.notification_url = notification_url or NOTIFICATION_URL
self.transaction_url = transaction_url or TRANSACTION_URL
self.pre_approval_url = pre_approval_url or PRE_APPROVAL_URL
self.pre_approval_request_url = pre_approval_request_url or PRE_APPROVAL_REQUEST_URL
self.pre_approval_redirect_url = pre_approval_redirect_url or PRE_APPROVAL_REDIRECT_URL
self.pre_approval_notification_url = pre_approval_notification_url or PRE_APPROVAL_NOTIFICATION_URL
self.pre_approval_cancel_url = pre_approval_cancel_url or PRE_APPROVAL_CANCEL_URL
self.pagseguro_email = pagseguro_email or PAGSEGURO_EMAIL
self.pagseguro_token = pagseguro_token or PAGSEGURO_TOKEN
self.currency = currency
Expand Down Expand Up @@ -141,9 +154,12 @@ def checkout(self):
logger.debug('operation=api_checkout, data={!r}'.format(data))
return data

def get_notification(self, notification_id):

def _get_notification(self, notification_id, url, notification_type,
notification_signal, notification_status):

response = requests.get(
self.notification_url + '/{}'.format(notification_id),
'{0}/{1}'.format(url, notification_id),
params={
'email': self.base_params['email'],
'token': self.base_params['token']
Expand All @@ -152,24 +168,46 @@ def get_notification(self, notification_id):

if response.status_code == 200:
root = xmltodict.parse(response.text)
transaction = root['transaction']
notificacao_recebida.send(
transaction = root[notification_type]
notification_signal.send(
sender=self, transaction=transaction
)

status = transaction['status']
if status in NOTIFICATION_STATUS:
signal = NOTIFICATION_STATUS[status]
signal.send(
sender=self, transaction=transaction
)
if status in notification_status:
signal = notification_status[status]
signal.send(sender=self, transaction=transaction)

return response

def get_notification(self, notification_id, notification_type='transaction'):
if notification_type == 'transaction':
response = self._get_notification(
notification_id,
self.notification_url,
'transaction',
notificacao_recebida,
NOTIFICATION_STATUS,
)
else:
response = self._get_notification(
notification_id,
self.pre_approval_notification_url,
'preApproval',
pre_approval_notification,
PRE_APPROVAL_NOTIFICATION_STATUS,
)

logger.debug(
'operation=api_get_notification, '
'notification_type={}, '
'notification_id={}, '
'response_body={}, '
'response_status={}'.format(
notification_id, response.text, response.status_code
notification_type,
notification_id,
response.text,
response.status_code
)
)
return response
Expand Down Expand Up @@ -211,6 +249,42 @@ def get_transaction(self, transaction_id):
)
return data

def get_pre_approval(self, pre_approval_id):
response = requests.get(
'{0}/{1}'.format(self.pre_approval_url, pre_approval_id),
params={
'email': self.base_params['email'],
'token': self.base_params['token']
}
)

if response.status_code == 200:
root = xmltodict.parse(response.text)
transaction = root['preApproval']

data = {
'transaction': transaction,
'status_code': response.status_code,
'success': True,
'date': timezone.now()
}
else:
data = {
'status_code': response.status_code,
'message': response.text,
'success': False,
'date': timezone.now()
}
logger.debug(
'operation=api_get_pre_approval, '
'pre_approval_id={}, '
'data={!r}, '
'response_status={}'.format(
pre_approval_id, data, response.status_code
)
)
return data


class PagSeguroApiTransparent(PagSeguroApi):
def __init__(self, session_url=None, **kwargs):
Expand Down Expand Up @@ -363,3 +437,119 @@ def get_session_id(self):
'data={!r}'.format(data)
)
return data


class PagSeguroApiPreApproval(PagSeguroApi):

def create(self, name, amount_per_payment, period, max_total_amount,
final_date='', max_amount_per_payment='', charge='auto',
details='', redirect_code=''):

from pagseguro.models import PreApprovalPlan

pre_approval = PreApprovalPlan(
name=name,
amount_per_payment=amount_per_payment,
period=period.upper(),
final_date=final_date,
max_total_amount=max_total_amount,
charge=charge,
details=details,
reference=self.base_params.get('reference', ''),
redirect_code=redirect_code,
)
pre_approval.save()

def set_pre_approval_data(self, name, amount_per_payment, period,
max_total_amount, final_date, charge='auto',
details=''):

self.params['preApprovalName'] = name
self.params['preApprovalAmountPerPayment'] = amount_per_payment
self.params['preApprovalPeriod'] = period
self.params['preApprovalFinalDate'] = final_date.isoformat()
self.params['preApprovalMaxTotalAmount'] = max_total_amount
self.params['preApprovalCharge'] = charge
self.params['preApprovalDetails'] = details

def create_plan(self, *args, **kwargs):
kwargs['max_total_amount'] = '{0:.2f}'.format(
kwargs['max_total_amount']
)
kwargs['amount_per_payment'] = '{0:.2f}'.format(
kwargs['amount_per_payment']
)

self.set_pre_approval_data(**kwargs)

self.build_params()
headers = {
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
response = requests.post(
self.pre_approval_request_url, self.params, headers=headers
)

if response.status_code == 200:
root = xmltodict.parse(response.text)
pre_approval = root['preApprovalRequest']

self.create(redirect_code=pre_approval['code'], **kwargs)

# FIXME
data = {
'pre_approval': pre_approval,
'status_code': response.status_code,
'success': True,
'date': parse(pre_approval['date']),
'code': pre_approval['code'],
'redirect_url': '{0}?code={1}'.format(
self.pre_approval_redirect_url, pre_approval['code']
),
}
pre_approval_create_plan.send(sender=self, data=data)
else:
# FIXME
data = {
'status_code': response.status_code,
'message': response.text,
'success': False,
'date': timezone.now()
}
pre_approval_create_plan_error.send(sender=self, data=data)
logger.debug(
'operation=preapproval_api_create_plan, '
'data={!r}'.format(data)
)
return data

def pre_approval_cancel(self, pre_approval_code):
# FIXME
headers = {
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
}

params = {
'email': self.base_params['email'],
'token': self.base_params['token'],
}

url = '{0}/{1}'.format(self.pre_approval_cancel_url, pre_approval_code)
response = requests.get(url, params, headers=headers)

if response.status_code == 200:
data = self.get_pre_approval(pre_approval_code).get('transaction')
pre_approval_notification.send(sender=self, transaction=data)
pre_approval_status_cancelled.send(sender=self, transaction=data)
else:
data = {
'status_code': response.status_code,
'message': response.text,
'success': False,
'date': timezone.now(),
}
logger.debug(
'operation=preapproval_api_pre_approval_cancel, '
'data={!r}'.format(data)
)
return data
Loading

0 comments on commit 4ae9f9f

Please sign in to comment.