source: main/waeup.aaue/trunk/src/waeup/aaue/interswitch/browser.py @ 17480

Last change on this file since 17480 was 17480, checked in by Henrik Bettermann, 16 months ago

Provide correct mac and product id.,

  • Property svn:executable set to *
File size: 20.7 KB
Line 
1    # -*- coding: utf-8 -*-
2## $Id: browser.py 17429 2023-06-05 04:34:30Z henrik $
3##
4## Copyright (C) 2012 Uli Fouquet & Henrik Bettermann
5## This program is free software; you can redistribute it and/or modify
6## it under the terms of the GNU General Public License as published by
7## the Free Software Foundation; either version 2 of the License, or
8## (at your option) any later version.
9##
10## This program is distributed in the hope that it will be useful,
11## but WITHOUT ANY WARRANTY; without even the implied warranty ofself.context.amount_auth
12## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13## GNU General Public License for more details.
14##
15## You should have received a copy of the GNU General Public License
16## along with this program; if not, write to the Free Software
17## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18##
19import httplib
20import hashlib
21import grok
22import os
23import csv
24from xml.dom import minidom
25from zope.interface import Interface
26from zope.component import queryAdapter
27from waeup.kofa.interfaces import CLEARED
28from kofacustom.nigeria.interswitch.browser import (
29    InterswitchPaymentRequestWebservicePageStudent,
30    InterswitchPaymentRequestWebservicePageApplicant,
31    InterswitchPaymentVerifyWebservicePageApplicant,
32    InterswitchPaymentVerifyWebservicePageStudent,
33    InterswitchPageStudent, InterswitchPageApplicant,
34    module_activated,
35    )
36from waeup.aaue.students.interfaces import ICustomStudentOnlinePayment
37from waeup.aaue.applicants.interfaces import ICustomApplicantOnlinePayment
38from waeup.aaue.students.utils import SFEECHANGES
39from waeup.aaue.interfaces import MessageFactory as _
40
41PRODUCT_ID = '5845'
42SITE_NAME = 'aaue.waeup.org'
43PROVIDER_ACCT = '0200244434'
44PROVIDER_BANK_ID = '11'
45PROVIDER_ITEM_NAME = 'WAeAC Portal Fee'
46INSTITUTION_NAME = 'AAU Ekpoma'
47CURRENCY = '566'
48GATEWAY_AMT = 200.0
49POST_ACTION = 'https://webpay.interswitchng.com/paydirect/pay'
50
51HOST = 'webpay.interswitchng.com'
52URL = '/paydirect/api/v1/gettransaction.json'
53HTTPS = True
54MAC = '9718FA00B0F5070B388A9896ADCED9B2FB02D30F71E12E68BDADC63F6852A3496FF97D8A0F9DA9F753B911A49BB09BB87B55FD02046BD325C74C46C0123CF023'
55
56httplib.HTTPSConnection.debuglevel = 0
57
58BANK_ACCOUNTS = {
59    'edohis':   ('1222577132', '117'),
60    'union':    ('1019763348', '7'),
61    'sport':    ('1021941220', '7'),
62    'access':   ('1012688013', '123'),
63    'notebook': ('4011210501', '51'),
64    'library':  ('2000122995', '8'),
65    'fac1':     ('1022438743', '7'),
66    'fac2':     ('2000249757', '8'),
67    'fac3':     ('1012678566', '123'),
68    'matricgown': ('2000249757', '8'),
69    'lapel':      ('2000249757', '8'),
70
71    'acceptance': ('2000249757', '8'),
72
73    'hostel_maintenance': ('1006406795', '123'),
74    'bed_allocation':     ('1006406795', '123'),
75    'late_registration':  ('5210006575', '51'),
76    'ent_combined':       ('6220029828', '51'),
77    'ent_registration_0': ('6220029828', '51'),
78    'ent_registration_1': ('6220029828', '51'),
79    'ent_registration_2': ('6220029828', '51'),
80    'ent_text_book_0':    ('6220029828', '51'),
81    'ent_text_book_1':    ('6220029828', '51'),
82    'ent_text_book_2':    ('6220029828', '51'),
83    'gst_registration_1': ('1010893123', '117'),
84    'gst_registration_2': ('1010893123', '117'),
85    'gst_text_book_0':    ('1010893123', '117'),
86    'gst_text_book_1':    ('1010893123', '117'),
87    'gst_text_book_2':    ('1010893123', '117'),
88    'gst_text_book_3':    ('1010893123', '117'),
89
90    'postgrad': ('1010827641', '117'),
91    }
92
93FEE_NAMES = {
94    'edohis':     'Edo State Health Insurance Scheme',
95    'union':      'Student Union Dues',
96    'sport':      'Sport Development Fee',
97    'access':     'Access Card Fee',
98    'notebook':   'Branded Notebook',
99    'library':    'Library Development Fee',
100    'tuition':    'Tuition',
101    'acceptance': 'Acceptance Fee',
102    'matricgown': 'Matriculation Gown Fee',
103    'lapel':      'File/Lapel Fee',
104    'lmsplus':    'LMS Plus Fee',
105    'nuga':       'NUGA Fee',
106    }
107
108
109SCHOOLFEES = dict()
110
111for year in SFEECHANGES:
112    schoolfees_path = os.path.join(
113        os.path.dirname(__file__), '../students/schoolfees_%s.csv' %year)
114    reader = csv.DictReader(open(schoolfees_path, 'rb'))
115    SCHOOLFEES[year] = {item['code']:item for item in reader}
116
117acceptancefees_path = os.path.join(
118    os.path.dirname(__file__), '../students/acceptancefees.csv')
119reader = csv.DictReader(open(acceptancefees_path, 'rb'))
120ACCEPTANCEFEES = {item['code']:item for item in reader}
121
122class CustomInterswitchPageApplicant(InterswitchPageApplicant):
123    """ View which sends a POST request to the Interswitch
124    CollegePAY payment gateway.
125
126    So far only PT application has been configured.
127    """
128    grok.context(ICustomApplicantOnlinePayment)
129    action = POST_ACTION
130    site_name = SITE_NAME
131    currency = CURRENCY
132    provider_bank_id = PROVIDER_BANK_ID
133    provider_acct = PROVIDER_ACCT
134    pay_item_id = '101'
135    product_id = PRODUCT_ID
136
137    def update(self):
138        if not module_activated(
139            self.context.__parent__.__parent__.year, self.context):
140            self.flash(_('Forbidden'), type='danger')
141            self.redirect(self.url(self.context, '@@index'))
142            return
143        error = self.init_update()
144        if error:
145            self.flash(error, type='danger')
146            self.redirect(self.url(self.context, '@@index'))
147            return
148        # Already now it becomes an Interswitch payment. We set the net amount
149        # and add the gateway amount.
150        if not self.context.r_company:
151            self.context.net_amt = self.context.amount_auth
152            self.context.amount_auth += GATEWAY_AMT
153            self.context.gateway_amt = GATEWAY_AMT
154            self.context.r_company = u'interswitch'
155        xmldict = {}
156        provider_amt = 2000.0
157        if self.applicant.__parent__.code in ('ver2019', 'send2019'):
158            provider_amt = 0.0
159        elif self.applicant.__parent__.code.startswith('cert'):
160            provider_amt = 3000.0
161        elif self.applicant.__parent__.code.startswith('trans'):
162            provider_amt = 3000.0
163        xmldict['institution_acct'] = '1012332141'
164        xmldict['institution_bank_id'] = '123'
165        if self.applicant.applicant_id.startswith('dsh'):
166            xmldict['institution_acct'] = '1014847058'
167            xmldict['institution_bank_id'] = '7'
168        if self.applicant.applicant_id.startswith('ijmbe'):
169            xmldict['institution_acct'] = '1012278272'
170            xmldict['institution_bank_id'] = '123'
171        xmldict['detail_ref'] = self.context.p_id
172        xmldict['provider_amt'] = 100 * provider_amt
173        xmldict['provider_acct'] = PROVIDER_ACCT
174        xmldict['provider_bank_id'] = PROVIDER_BANK_ID
175        xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
176        xmldict['institution_item_name'] = self.context.category
177        xmldict['institution_name'] = INSTITUTION_NAME
178        xmldict['institution_amt'] = 100 * self.context.net_amt
179        if not self.context.provider_amt:
180            self.context.provider_amt = provider_amt
181            self.context.amount_auth += provider_amt
182        if provider_amt:
183            xmltext = """<payment_item_detail>
184<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s">
185<item_detail item_id="1" item_name="%(institution_item_name)s" item_amt="%(institution_amt)d" bank_id="%(institution_bank_id)s" acct_num="%(institution_acct)s" />
186<item_detail item_id="2" item_name="%(provider_item_name)s" item_amt="%(provider_amt)d" bank_id="%(provider_bank_id)s" acct_num="%(provider_acct)s" />
187</item_details>
188</payment_item_detail>""" % xmldict
189        else:
190            xmltext = """<payment_item_detail>
191<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s">
192<item_detail item_id="1" item_name="%(institution_item_name)s" item_amt="%(institution_amt)d" bank_id="%(institution_bank_id)s" acct_num="%(institution_acct)s" />
193</item_details>
194</payment_item_detail>""" % xmldict
195        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
196        xmlitems = ''
197        xmldoc = minidom.parseString(xmltext)
198        itemlist = xmldoc.getElementsByTagName('item_detail')
199        for s in itemlist:
200            xmlitems += "%s (%s %s, %s (%s)),  " % (
201                s.attributes['item_name'].value,
202                u'\u20a6',
203                int(s.attributes['item_amt'].value)/100,
204                s.attributes['acct_num'].value,
205                s.attributes['bank_id'].value,
206                )
207        self.context.p_split_data = xmlitems
208        self.amount_auth = int(100 * self.context.amount_auth)
209        hashargs = (
210            self.context.p_id +
211            PRODUCT_ID +
212            self.pay_item_id +
213            str(int(self.amount_auth)) +
214            self.site_redirect_url +
215            MAC)
216        self.hashvalue = hashlib.sha512(hashargs).hexdigest()
217        return
218
219class CustomInterswitchPageStudent(InterswitchPageStudent):
220    """ View which sends a POST request to the Interswitch
221    CollegePAY payment gateway.
222    """
223    grok.context(ICustomStudentOnlinePayment)
224    action = POST_ACTION
225    site_name = SITE_NAME
226    currency = CURRENCY
227    pay_item_id = '101'
228    product_id = PRODUCT_ID
229
230    def update(self):
231        if not module_activated(
232            self.context.student.current_session, self.context):
233            self.flash(_('Forbidden'), type='danger')
234            self.redirect(self.url(self.context, '@@index'))
235            return
236        error = self.init_update()
237        if error:
238            self.flash(error, type='danger')
239            self.redirect(self.url(self.context, '@@index'))
240            return
241        student = self.student
242        category = self.context.p_category
243        # To guarantee that cleared students pay both acceptance fee
244        # and school fees, the page can only be accessed
245        # for school fee payments if acceptance/clearance fee has
246        # been successfully queried/paid beforehand. This
247        # requirement applies to students in state 'cleared' and
248        # entry_session greater than 2012 only.
249        if self.context.p_category.startswith('schoolfee') and \
250            student.state == CLEARED and \
251            student.entry_session > 2012:
252            acceptance_fee_paid = False
253            for ticket in student['payments'].values():
254                if ticket.p_state == 'paid' and \
255                    ticket.p_category.startswith('clearance'):
256                    acceptance_fee_paid = True
257                    break
258            if not acceptance_fee_paid:
259                self.flash(
260                    _('Please pay acceptance fee first.'), type="danger")
261                self.redirect(self.url(self.context, '@@index'))
262                return
263        # Already now it becomes an Interswitch payment. We set the net amount
264        # and add the gateway amount.
265        if not self.context.r_company:
266            self.context.net_amt = self.context.amount_auth
267            self.context.amount_auth += GATEWAY_AMT
268            self.context.gateway_amt = GATEWAY_AMT
269            self.context.r_company = u'interswitch'
270        xmldict = self.xmldict
271        # Provider data
272        xmldict['detail_ref'] = self.context.p_id
273        xmldict['provider_acct'] = PROVIDER_ACCT
274        xmldict['provider_bank_id'] = PROVIDER_BANK_ID
275        xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
276        # Institution data
277        xmldict['institution_acct'] = '00000000'
278        xmldict['institution_bank_id'] = '00'
279        provider_amt = 0.0
280        if category.startswith('clearance'):
281            provider_amt = 1500.0
282        elif category.startswith('hostel_maintenance'):
283            provider_amt = 1000.0
284        elif category in ('schoolfee', 'schoolfee_1', 'schoolfee_incl'):
285            provider_amt = 2500.0
286        xmldict['provider_amt'] = 100 * provider_amt
287        xmldict['institution_item_name'] = self.context.category
288        xmldict['institution_name'] = INSTITUTION_NAME
289        xmldict['institution_amt'] = 100 * self.context.net_amt
290        if not self.context.provider_amt:
291            self.context.provider_amt = provider_amt
292            self.context.amount_auth += provider_amt
293        xmltext = ''
294
295        # School fee
296        if category.startswith('schoolfee'):
297            # collect additional fees
298            if self.context.p_category in ('schoolfee_1', 'schoolfee_incl'):
299                xmltext = """<payment_item_detail>
300<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">""" % xmldict
301                item_id = 1
302
303                if student.entry_session < 2013:
304                    sorted_items = SCHOOLFEES[12][student.certcode].items()
305                elif student.entry_session < 2014:
306                    sorted_items = SCHOOLFEES[13][student.certcode].items()
307                elif student.entry_session < 2015:
308                    sorted_items = SCHOOLFEES[14][student.certcode].items()
309                elif student.entry_session < 2020:
310                    sorted_items = SCHOOLFEES[15][student.certcode].items()
311                elif student.entry_session < 2021:
312                    sorted_items = SCHOOLFEES[20][student.certcode].items()
313                elif student.entry_session < 2022:
314                    sorted_items = SCHOOLFEES[21][student.certcode].items()
315                else:
316                    sorted_items = SCHOOLFEES[22][student.certcode].items()
317                sorted_items.insert(0, sorted_items.pop(4))
318                for item in sorted_items:
319                    try:
320                        item_amt = 100 * int(item[1])
321                        if self.context.p_category == 'schoolfee_1' and item[0] == 'tuition':
322                            item_amt /= 2
323                        acct_num = ''
324                        bank_id = ''
325                        item_name = ''
326                        # Find appropriate bank
327                        try:
328                            bank = BANK_ACCOUNTS[item[0]]
329                        except: # transfer to faculty account
330                            if student.faccode in ('FAG', 'FAT', 'FBM', 'FMLS', 'fac1'):
331                                bank = BANK_ACCOUNTS['fac1']
332                            elif student.faccode in ('FCS', 'FED', 'FES', 'FET'):
333                                bank = BANK_ACCOUNTS['fac2']
334                            elif student.faccode in ('FLS', 'FLW', 'FMS', 'FPS', 'FSS'):
335                                bank = BANK_ACCOUNTS['fac3']
336                        acct_num = bank[0]
337                        bank_id = bank[1]
338                        item_name = FEE_NAMES[item[0]]
339                        xmltext += """
340<item_detail item_id="%s" item_name="%s" item_amt="%d" bank_id="%s" acct_num="%s" />""" % (item_id, item_name, item_amt, bank_id, acct_num)
341                        item_id += 1
342                    except:
343                        pass
344                xmldict['item_id'] = item_id
345                xmltext += """
346<item_detail item_id="%(item_id)d" item_name="%(provider_item_name)s" item_amt="%(provider_amt)d" bank_id="%(provider_bank_id)s" acct_num="%(provider_acct)s" />
347</item_details>
348</payment_item_detail>""" % xmldict
349            # no additional charges, determine faculty bank only
350            else:
351                if student.is_postgrad:
352                    bank = BANK_ACCOUNTS['postgrad']
353                elif student.faccode in ('FAG', 'FAT', 'FBM', 'FMLS', 'fac1'):
354                    bank = BANK_ACCOUNTS['fac1']
355                elif student.faccode in ('FCS', 'FED', 'FES', 'FET'):
356                    bank = BANK_ACCOUNTS['fac2']
357                elif student.faccode in ('FLS', 'FLW', 'FMS', 'FPS', 'FSS'):
358                    bank = BANK_ACCOUNTS['fac3']
359                xmldict['institution_acct'] = bank[0]
360                xmldict['institution_bank_id'] = bank[1]
361
362
363        # Clearance (acceptance) fee
364
365        elif category.startswith('clearance'):
366            # collect additional fees
367            if self.context.p_category == 'clearance_incl':
368                xmltext = """<payment_item_detail>
369<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">""" % xmldict
370                item_id = 1
371                for item in ACCEPTANCEFEES[student.certcode].items():
372                    try:
373                        item_amt = 100 * int(item[1])
374                        bank = BANK_ACCOUNTS[item[0]]
375                        acct_num = bank[0]
376                        bank_id = bank[1]
377                        item_name = FEE_NAMES[item[0]]
378                        xmltext += """
379<item_detail item_id="%s" item_name="%s" item_amt="%d" bank_id="%s" acct_num="%s" />""" % (item_id, item_name, item_amt, bank_id, acct_num)
380                        item_id += 1
381                    except:
382                        pass
383                xmldict['item_id'] = item_id
384                xmltext += """
385<item_detail item_id="%(item_id)d" item_name="%(provider_item_name)s" item_amt="%(provider_amt)d" bank_id="%(provider_bank_id)s" acct_num="%(provider_acct)s" />
386</item_details>
387</payment_item_detail>""" % xmldict
388            # no additional charges, determine faculty bank only
389            else:
390                if student.is_postgrad:
391                    bank = BANK_ACCOUNTS['postgrad']
392                else:
393                    bank = BANK_ACCOUNTS['acceptance']
394                xmldict['institution_acct'] = bank[0]
395                xmldict['institution_bank_id'] = bank[1]
396
397        # Other fees
398        elif category in BANK_ACCOUNTS.keys():
399            bank = BANK_ACCOUNTS[category]
400            xmldict['institution_acct'] = bank[0]
401            xmldict['institution_bank_id'] = bank[1]
402
403        if not xmltext and provider_amt == 0:
404            xmltext = """<payment_item_detail>
405<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
406<item_detail item_id="1" item_name="%(institution_item_name)s" item_amt="%(institution_amt)d" bank_id="%(institution_bank_id)s" acct_num="%(institution_acct)s" />
407</item_details>
408</payment_item_detail>""" % xmldict
409        elif not xmltext:
410            xmltext = """<payment_item_detail>
411<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
412<item_detail item_id="1" item_name="%(institution_item_name)s" item_amt="%(institution_amt)d" bank_id="%(institution_bank_id)s" acct_num="%(institution_acct)s" />
413<item_detail item_id="2" item_name="%(provider_item_name)s" item_amt="%(provider_amt)d" bank_id="%(provider_bank_id)s" acct_num="%(provider_acct)s" />
414</item_details>
415</payment_item_detail>""" % xmldict
416        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
417        xmlitems = ''
418        xmldoc = minidom.parseString(xmltext)
419        itemlist = xmldoc.getElementsByTagName('item_detail')
420        for s in itemlist:
421            xmlitems += "%s (%s %s, %s (%s)),  " % (
422                s.attributes['item_name'].value,
423                u'\u20a6',
424                int(s.attributes['item_amt'].value)/100,
425                s.attributes['acct_num'].value,
426                s.attributes['bank_id'].value,
427                )
428        self.context.p_split_data = xmlitems
429        self.context.provider_amt = provider_amt
430        self.amount_auth = int(100 * self.context.amount_auth)
431        hashargs = (
432            self.context.p_id +
433            PRODUCT_ID +
434            self.pay_item_id +
435            str(int(self.amount_auth)) +
436            self.site_redirect_url +
437            MAC)
438        self.hashvalue = hashlib.sha512(hashargs).hexdigest()
439        return
440
441
442class CustomInterswitchPaymentRequestWebservicePageApplicant(
443    InterswitchPaymentRequestWebservicePageApplicant):
444    """Request webservice view for the CollegePAY gateway
445    """
446    grok.context(ICustomApplicantOnlinePayment)
447    gateway_host = HOST
448    gateway_url = URL
449    https = HTTPS
450    mac = MAC
451    product_id = PRODUCT_ID
452
453class CustomInterswitchPaymentVerifyWebservicePageApplicant(
454    InterswitchPaymentVerifyWebservicePageApplicant):
455    """Payment verify view for the CollegePAY gateway
456    """
457    grok.context(ICustomApplicantOnlinePayment)
458    gateway_host = HOST
459    gateway_url = URL
460    https = HTTPS
461    mac = MAC
462    product_id = PRODUCT_ID
463
464class CustomInterswitchPaymentRequestWebservicePageStudent(
465    InterswitchPaymentRequestWebservicePageStudent):
466    """Request webservice view for the CollegePAY gateway
467    """
468    grok.context(ICustomStudentOnlinePayment)
469    gateway_host = HOST
470    gateway_url = URL
471    https = HTTPS
472    mac = MAC
473    product_id = PRODUCT_ID
474
475class CustomInterswitchPaymentVerifyWebservicePageStudent(
476    InterswitchPaymentVerifyWebservicePageStudent):
477    """Payment verify view for the CollegePAY gateway
478    """
479    grok.context(ICustomStudentOnlinePayment)
480    gateway_host = HOST
481    gateway_url = URL
482    https = HTTPS
483    mac = MAC
484    product_id = PRODUCT_ID
Note: See TracBrowser for help on using the repository browser.