1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. 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
14 class CardToken(models.Model):
15 """ This should be attached to a payment schedule. """
16 pos_id = models.CharField('POS id', max_length=255)
17 disposable_token = models.CharField('token jednorazowy', max_length=255)
18 reusable_token = models.CharField('token wielokrotnego użytku', max_length=255, null=True, blank=True)
19 created_at = models.DateTimeField('utworzony', auto_now_add=True)
23 verbose_name = 'token PayU karty płatniczej'
24 verbose_name_plural = 'tokeny PayU kart płatniczych'
27 class Order(models.Model):
28 pos_id = models.CharField('POS id', max_length=255) # TODO: redundant?
29 customer_ip = models.GenericIPAddressField('adres IP klienta')
30 order_id = models.CharField('ID zamówienia', max_length=255, blank=True)
32 status = models.CharField(max_length=128, blank=True, choices=[
34 ('WAITING_FOR_CONFIRMATION', 'Czeka na potwierdzenie'),
35 ('COMPLETED', 'Ukończone'),
36 ('CANCELED', 'Anulowane'),
37 ('REJECTED', 'Odrzucone'),
39 ('ERR-INVALID_TOKEN', 'Błędny token'),
41 created_at = models.DateTimeField(null=True, blank=True, auto_now_add=True)
42 completed_at = models.DateTimeField(null=True, blank=True)
46 verbose_name = 'Zamówienie PayU'
47 verbose_name_plural = 'Zamówienia PayU'
49 # These need to be provided in a subclass.
52 raise NotImplementedError()
55 raise NotImplementedError()
57 def get_continue_url(self):
58 raise NotImplementedError()
60 def get_description(self):
61 raise NotImplementedError()
63 def get_products(self):
64 """ At least: name, unitPrice, quantity. """
67 'name': self.get_description(),
68 'unitPrice': str(int(self.get_amount() * 100)),
73 def is_recurring(self):
76 def get_notify_url(self):
77 raise NotImplementedError
79 def get_thanks_url(self):
80 raise NotImplementedError
82 def status_updated(self):
88 return POSS[self.pos_id]
90 def get_continue_url(self):
91 return "https://{}{}".format(
92 Site.objects.get_current().domain,
93 self.get_thanks_url())
95 def get_representation(self, token=None):
97 "notifyUrl": self.get_notify_url(),
98 "customerIp": self.customer_ip,
99 "merchantPosId": self.pos_id,
100 "currencyCode": self.get_pos().currency_code,
101 "totalAmount": str(int(self.get_amount() * 100)),
102 "extOrderId": "wolne-lektury-%d" % self.pk,
104 "buyer": self.get_buyer() or {},
105 "continueUrl": self.get_continue_url(),
106 "description": self.get_description(),
107 "products": self.get_products(),
110 token = self.get_card_token()
111 rep['recurring'] = 'STANDARD' if token.reusable_token else 'FIRST'
112 rep['payMethods'] = {
114 "type": "CARD_TOKEN",
115 "value": token.reusable_token or token.disposable_token
121 token = self.get_card_token() if self.is_recurring() else None
122 representation = self.get_representation(token)
124 response = self.get_pos().request('POST', 'orders', representation)
125 except HTTPError as e:
126 resp = json.loads(e.read().decode('utf-8'))
127 if resp['status']['statusCode'] == 'ERROR_ORDER_NOT_UNIQUE':
133 reusable_token = response.get('payMethods', {}).get('payMethod', {}).get('value', None)
135 token.reusable_token = reusable_token
139 if 'orderId' not in response:
140 code = response.get('status', {}).get('codeLiteral', '')
142 self.status = 'ERR-' + str(code)
144 self.status_updated()
146 raise ValueError("Expecting dict with `orderId` key, got: %s" % response)
148 self.order_id = response['orderId']
151 return response.get('redirectUri', self.get_thanks_url())
154 class Notification(models.Model):
155 """ Add `order` FK to real Order model. """
156 body = models.TextField('treść')
157 received_at = models.DateTimeField('odebrana', auto_now_add=True)
161 verbose_name = 'notyfikacja PayU'
162 verbose_name_plural = 'notyfikacje PayU'
164 def get_status(self):
165 return json.loads(self.body)['order']['status']
168 status = self.get_status()
169 if self.order.status not in (status, 'COMPLETED'):
170 self.order.status = status
171 if status == 'COMPLETED':
172 self.order.completed_at = now()
174 self.order.status_updated()