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 status_updated(self):
86 return POSS[self.pos_id]
88 def get_representation(self, token=None):
90 "notifyUrl": self.get_notify_url(),
91 "customerIp": self.customer_ip,
92 "merchantPosId": self.pos_id,
93 "currencyCode": self.get_pos().currency_code,
94 "totalAmount": str(int(self.get_amount() * 100)),
95 "extOrderId": "wolne-lektury-%d" % self.pk,
97 "buyer": self.get_buyer() or {},
98 "continueUrl": self.get_continue_url(),
99 "description": self.get_description(),
100 "products": self.get_products(),
103 token = self.get_card_token()
104 rep['recurring'] = 'STANDARD' if token.reusable_token else 'FIRST'
105 rep['payMethods'] = {
107 "type": "CARD_TOKEN",
108 "value": token.reusable_token or token.disposable_token
114 token = self.get_card_token() if self.is_recurring() else None
115 representation = self.get_representation(token)
117 response = self.get_pos().request('POST', 'orders', representation)
118 except HTTPError as e:
119 resp = json.loads(e.read().decode('utf-8'))
120 if resp['status']['statusCode'] == 'ERROR_ORDER_NOT_UNIQUE':
126 reusable_token = response.get('payMethods', {}).get('payMethod', {}).get('value', None)
128 token.reusable_token = reusable_token
132 if 'orderId' not in response:
133 code = response.get('status', {}).get('codeLiteral', '')
135 self.status = 'ERR-' + str(code)
137 self.status_updated()
139 raise ValueError("Expecting dict with `orderId` key, got: %s" % response)
141 self.order_id = response['orderId']
144 return response.get('redirectUri', self.schedule.get_thanks_url())
147 class Notification(models.Model):
148 """ Add `order` FK to real Order model. """
149 body = models.TextField(_('body'))
150 received_at = models.DateTimeField(_('received_at'), auto_now_add=True)
154 verbose_name = _('PayU notification')
155 verbose_name_plural = _('PayU notifications')
157 def get_status(self):
158 return json.loads(self.body)['order']['status']
161 status = self.get_status()
162 if self.order.status not in (status, 'COMPLETED'):
163 self.order.status = status
164 if status == 'COMPLETED':
165 self.order.completed_at = now()
167 self.order.status_updated()