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 completed_at = models.DateTimeField(null=True, blank=True)
44 verbose_name = _('PayU order')
45 verbose_name_plural = _('PayU orders')
47 # These need to be provided in a subclass.
50 raise NotImplementedError()
53 raise NotImplementedError()
55 def get_continue_url(self):
56 raise NotImplementedError()
58 def get_description(self):
59 raise NotImplementedError()
61 def get_products(self):
62 """ At least: name, unitPrice, quantity. """
65 'name': self.get_description(),
66 'unitPrice': str(int(self.get_amount() * 100)),
71 def is_recurring(self):
74 def get_notify_url(self):
75 raise NotImplementedError
77 def status_updated(self):
83 return POSS[self.pos_id]
85 def get_representation(self, token=None):
87 "notifyUrl": self.get_notify_url(),
88 "customerIp": self.customer_ip,
89 "merchantPosId": self.pos_id,
90 "currencyCode": self.get_pos().currency_code,
91 "totalAmount": str(int(self.get_amount() * 100)),
92 "extOrderId": "wolne-lektury-rcz-%d" % self.pk,
94 "buyer": self.get_buyer() or {},
95 "continueUrl": self.get_continue_url(),
96 "description": self.get_description(),
97 "products": self.get_products(),
100 token = self.get_card_token()
101 rep['recurring'] = 'STANDARD' if token.reusable_token else 'FIRST'
102 rep['payMethods'] = {
104 "type": "CARD_TOKEN",
105 "value": token.reusable_token or token.disposable_token
111 token = self.get_card_token() if self.is_recurring() else None
112 representation = self.get_representation(token)
114 response = self.get_pos().request('POST', 'orders', representation)
115 except HTTPError as e:
116 resp = json.loads(e.read().decode('utf-8'))
117 if resp['status']['statusCode'] == 'ERROR_ORDER_NOT_UNIQUE':
123 reusable_token = response.get('payMethods', {}).get('payMethod', {}).get('value', None)
125 token.reusable_token = reusable_token
129 if 'orderId' not in response:
130 raise ValueError("Expecting dict with `orderId` key, got: %s" % response)
131 self.order_id = response['orderId']
135 return response.get('redirectUri', self.schedule.get_thanks_url())
138 class Notification(models.Model):
139 """ Add `order` FK to real Order model. """
140 body = models.TextField(_('body'))
141 received_at = models.DateTimeField(_('received_at'), auto_now_add=True)
145 verbose_name = _('PayU notification')
146 verbose_name_plural = _('PayU notifications')
148 def get_status(self):
149 return json.loads(self.body)['order']['status']
152 status = self.get_status()
153 if self.order.status not in (status, 'COMPLETED'):
154 self.order.status = status
155 if status == 'COMPLETED':
156 self.order.completed_at = now()
158 self.order.status_updated()