1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 from urllib.parse import urlencode
6 from urllib.request import HTTPError
7 from django.contrib.sites.models import Site
8 from django.db import models
9 from django.urls import reverse
10 from django.utils.timezone import now
11 from django.utils.translation import ugettext_lazy as _
15 class CardToken(models.Model):
16 """ This should be attached to a payment schedule. """
17 pos_id = models.CharField(_('POS id'), max_length=255)
18 disposable_token = models.CharField(_('disposable token'), max_length=255)
19 reusable_token = models.CharField(_('reusable token'), max_length=255, null=True, blank=True)
20 created_at = models.DateTimeField(_('created_at'), auto_now_add=True)
24 verbose_name = _('PayU card token')
25 verbose_name_plural = _('PayU card tokens')
28 class Order(models.Model):
29 pos_id = models.CharField(_('POS id'), max_length=255) # TODO: redundant?
30 customer_ip = models.GenericIPAddressField(_('customer IP'))
31 order_id = models.CharField(_('order ID'), max_length=255, blank=True)
33 status = models.CharField(max_length=128, blank=True, choices=[
34 ('PENDING', _('Pending')),
35 ('WAITING_FOR_CONFIRMATION', _('Waiting for confirmation')),
36 ('COMPLETED', _('Completed')),
37 ('CANCELED', _('Canceled')),
38 ('REJECTED', _('Rejected')),
40 ('ERR-INVALID_TOKEN', _('Invalid token')),
42 created_at = models.DateTimeField(null=True, blank=True, auto_now_add=True)
43 completed_at = models.DateTimeField(null=True, blank=True)
47 verbose_name = _('PayU order')
48 verbose_name_plural = _('PayU orders')
50 # These need to be provided in a subclass.
53 raise NotImplementedError()
56 raise NotImplementedError()
58 def get_continue_url(self):
59 raise NotImplementedError()
61 def get_description(self):
62 raise NotImplementedError()
64 def get_products(self):
65 """ At least: name, unitPrice, quantity. """
68 'name': self.get_description(),
69 'unitPrice': str(int(self.get_amount() * 100)),
74 def is_recurring(self):
77 def get_notify_url(self):
78 raise NotImplementedError
80 def get_thanks_url(self):
81 raise NotImplementedError
83 def status_updated(self):
89 return POSS[self.pos_id]
91 def get_continue_url(self):
92 return "https://{}{}".format(
93 Site.objects.get_current().domain,
94 self.get_thanks_url())
96 def get_representation(self, token=None):
98 "notifyUrl": self.get_notify_url(),
99 "customerIp": self.customer_ip,
100 "merchantPosId": self.pos_id,
101 "currencyCode": self.get_pos().currency_code,
102 "totalAmount": str(int(self.get_amount() * 100)),
103 "extOrderId": "wolne-lektury-%d" % self.pk,
105 "buyer": self.get_buyer() or {},
106 "continueUrl": self.get_continue_url(),
107 "description": self.get_description(),
108 "products": self.get_products(),
111 token = self.get_card_token()
112 rep['recurring'] = 'STANDARD' if token.reusable_token else 'FIRST'
113 rep['payMethods'] = {
115 "type": "CARD_TOKEN",
116 "value": token.reusable_token or token.disposable_token
122 token = self.get_card_token() if self.is_recurring() else None
123 representation = self.get_representation(token)
125 response = self.get_pos().request('POST', 'orders', representation)
126 except HTTPError as e:
127 resp = json.loads(e.read().decode('utf-8'))
128 if resp['status']['statusCode'] == 'ERROR_ORDER_NOT_UNIQUE':
134 reusable_token = response.get('payMethods', {}).get('payMethod', {}).get('value', None)
136 token.reusable_token = reusable_token
140 if 'orderId' not in response:
141 code = response.get('status', {}).get('codeLiteral', '')
143 self.status = 'ERR-' + str(code)
145 self.status_updated()
147 raise ValueError("Expecting dict with `orderId` key, got: %s" % response)
149 self.order_id = response['orderId']
152 return response.get('redirectUri', self.get_thanks_url())
155 class Notification(models.Model):
156 """ Add `order` FK to real Order model. """
157 body = models.TextField(_('body'))
158 received_at = models.DateTimeField(_('received_at'), auto_now_add=True)
162 verbose_name = _('PayU notification')
163 verbose_name_plural = _('PayU notifications')
165 def get_status(self):
166 return json.loads(self.body)['order']['status']
169 status = self.get_status()
170 if self.order.status not in (status, 'COMPLETED'):
171 self.order.status = status
172 if status == 'COMPLETED':
173 self.order.completed_at = now()
175 self.order.status_updated()