source: main/waeup.uniben/trunk/src/waeup/uniben/interswitch/browser.py @ 9780

Last change on this file since 9780 was 9775, checked in by Henrik Bettermann, 12 years ago

Store provider_amt and gateway_amt when opening goto_interswitch pages.

Both fileds must be invisible on display pages and pdf slips.

  • Property svn:keywords set to Id
File size: 18.0 KB
Line 
1## $Id: browser.py 9775 2012-12-06 08:42:16Z henrik $
2##
3## Copyright (C) 2012 Uli Fouquet & Henrik Bettermann
4## This program is free software; you can redistribute it and/or modify
5## it under the terms of the GNU General Public License as published by
6## the Free Software Foundation; either version 2 of the License, or
7## (at your option) any later version.
8##
9## This program is distributed in the hope that it will be useful,
10## but WITHOUT ANY WARRANTY; without even the implied warranty of
11## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12## GNU General Public License for more details.
13##
14## You should have received a copy of the GNU General Public License
15## along with this program; if not, write to the Free Software
16## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17##
18import httplib
19import grok
20from zope.component import getUtility
21from kofacustom.nigeria.interswitch.helpers import (
22    query_interswitch, write_payments_log)
23from waeup.kofa.browser.layout import KofaPage, UtilityView
24from waeup.kofa.interfaces import IKofaUtils
25from waeup.kofa.utils.helpers import to_timezone
26from waeup.kofa.students.viewlets import ApprovePaymentActionButton as APABStudent
27from waeup.kofa.applicants.viewlets import ApprovePaymentActionButton as APABApplicant
28from waeup.uniben.students.interfaces import ICustomStudentOnlinePayment
29from waeup.uniben.applicants.interfaces import ICustomApplicantOnlinePayment
30from waeup.uniben.interfaces import MessageFactory as _
31
32PRODUCT_ID = '57'
33SITE_NAME = 'uniben-kofa.waeup.org'
34PROVIDER_ACCT = '1010764827'
35PROVIDER_BANK_ID = '117'
36PROVIDER_ITEM_NAME = 'BT Education'
37INSTITUTION_NAME = 'Uniben'
38CURRENCY = '566'
39GATEWAY_AMT = 150.0
40#QUERY_URL = 'https://webpay.interswitchng.com/paydirect/services/TransactionQueryURL.aspx'
41#QUERY_URL = 'https://testwebpay.interswitchng.com/test_paydirect/services/TransactionQueryURL.aspx'
42POST_ACTION = 'https://webpay.interswitchng.com/paydirect/webpay/pay.aspx'
43#POST_ACTION = 'https://testwebpay.interswitchng.com/test_paydirect/webpay/pay.aspx'
44
45HOST = 'webpay.interswitchng.com'
46#HOST = 'testwebpay.interswitchng.com'
47URL = '/paydirect/services/TransactionQueryWs.asmx'
48#URL = '/test_paydirect/services/TransactionQueryWs.asmx'
49httplib.HTTPConnection.debuglevel = 0
50
51class InterswitchActionButtonStudent(APABStudent):
52    grok.order(1)
53    grok.context(ICustomStudentOnlinePayment)
54    grok.require('waeup.payStudent')
55    icon = 'actionicon_pay.png'
56    text = _('CollegePAY')
57    target = 'goto_interswitch'
58
59    @property
60    def target_url(self):
61        if self.context.p_state != 'unpaid':
62            return ''
63        return self.view.url(self.view.context, self.target)
64
65class InterswitchActionButtonApplicant(APABApplicant):
66    grok.order(1)
67    grok.context(ICustomApplicantOnlinePayment)
68    grok.require('waeup.payApplicant')
69    icon = 'actionicon_pay.png'
70    text = _('CollegePAY')
71    target = 'goto_interswitch'
72
73    @property
74    def target_url(self):
75        if self.context.p_state != 'unpaid':
76            return ''
77        return self.view.url(self.view.context, self.target)
78
79# Deprecated
80#class InterswitchRequestCallbackActionButtonStudent(RCABStudent):
81#    grok.order(3)
82#    grok.context(ICustomStudentOnlinePayment)
83#    icon = 'actionicon_call.png'
84#    text = _('Request CollegePAY callback')
85
86#    def target_url(self):
87#        if self.context.p_state == 'paid':
88#            return ''
89#        site_redirect_url = self.view.url(self.view.context, 'isw_callback')
90#        args = {
91#            'transRef':self.context.p_id,
92#            'prodID':PRODUCT_ID,
93#            'redirectURL':site_redirect_url}
94#        return QUERY_URL + '?%s' % urllib.urlencode(args)
95
96# Alternative preferred solution
97class InterswitchRequestWebserviceActionButtonStudent(APABStudent):
98    grok.order(2)
99    grok.context(ICustomStudentOnlinePayment)
100    grok.require('waeup.payStudent')
101    icon = 'actionicon_call.png'
102    text = _('Requery CollegePAY')
103    target = 'request_webservice'
104
105class InterswitchRequestWebserviceActionButtonApplicant(APABApplicant):
106    grok.order(2)
107    grok.context(ICustomApplicantOnlinePayment)
108    grok.require('waeup.payApplicant')
109    icon = 'actionicon_call.png'
110    text = _('Requery CollegePAY')
111    target = 'request_webservice'
112
113class InterswitchPageStudent(KofaPage):
114    """ View which sends a POST request to the Interswitch
115    CollegePAY payment gateway.
116    """
117    grok.context(ICustomStudentOnlinePayment)
118    grok.name('goto_interswitch')
119    grok.template('student_goto_interswitch')
120    grok.require('waeup.payStudent')
121    label = _('Submit data to CollegePAY (Interswitch Payment Gateway)')
122    submit_button = _('Submit')
123    action = POST_ACTION
124    site_name = SITE_NAME
125    currency = CURRENCY
126    product_id = PRODUCT_ID
127
128    def update(self):
129        #if self.context.p_state != 'unpaid':
130        if self.context.p_state == 'paid':
131            self.flash(_("Payment ticket can't be re-send to CollegePAY."))
132            self.redirect(self.url(self.context, '@@index'))
133            return
134
135        student = self.student = self.context.student
136        certificate = getattr(student['studycourse'],'certificate',None)
137        self.amount_auth = 100 * self.context.amount_auth
138        xmldict = {}
139        if certificate is not None:
140            xmldict['department'] = certificate.__parent__.__parent__.code
141            xmldict['faculty'] = certificate.__parent__.__parent__.__parent__.code
142        else:
143            xmldict['department'] = None
144            xmldict['faculty'] = None
145        self.category = getUtility(IKofaUtils).PAYMENT_CATEGORIES[self.context.p_category]
146        tz = getUtility(IKofaUtils).tzinfo
147        self.local_date_time = to_timezone(
148            self.context.creation_date, tz).strftime("%Y-%m-%d %H:%M:%S %Z")
149        self.site_redirect_url = self.url(self.context, 'request_webservice')
150        # Provider data
151        xmldict['detail_ref'] = self.context.p_id
152        xmldict['provider_acct'] = PROVIDER_ACCT
153        xmldict['provider_bank_id'] = PROVIDER_BANK_ID
154        xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
155        # Institution data
156        xmldict['institution_acct'] = '000000000000'
157        xmldict['institution_bank_id'] = '00'
158        xmldict['institution_amt'] = '0.0'
159        if self.context.p_category == 'schoolfee':
160            provider_amt = 1500.0
161            if student.current_mode.endswith('_ft'):
162                self.pay_item_id = '5700'
163                if student.current_mode in ('ug_ft','de_ft','ct_ft','ume_ft'):
164                    xmldict['institution_acct'] = '2017506430'
165                    xmldict['institution_bank_id'] = '8'
166                elif student.current_mode in ('dp_ft'):
167                    xmldict['institution_acct'] = '9201805071'
168                    xmldict['institution_bank_id'] = '17'
169                elif student.current_mode in ('pg_ft'):
170                    xmldict['institution_acct'] = '5330832799'
171                    xmldict['institution_bank_id'] = '51'
172            elif student.current_mode.endswith('_pt'):
173                self.pay_item_id = '5701'
174                if student.current_mode in ('ug_pt','de_pt','ct_pt'):
175                    xmldict['institution_acct'] = '0122009929'
176                    xmldict['institution_bank_id'] = '16'
177                elif student.current_mode in ('dp_pt'):
178                    xmldict['institution_acct'] = '9201805071'
179                    xmldict['institution_bank_id'] = '17'
180                elif student.current_mode in ('pg_pt'):
181                    xmldict['institution_acct'] = '0031716047'
182                    xmldict['institution_bank_id'] = '10'
183        elif self.context.p_category == 'clearance':
184            self.pay_item_id = '5702'
185            provider_amt = 1500.0
186            if student.current_mode == 'pg_ft':
187                xmldict['institution_acct'] = '5330832799'
188                xmldict['institution_bank_id'] = '51'
189            elif student.current_mode == 'pg_pt':
190                xmldict['institution_acct'] = '0031716047'
191                xmldict['institution_bank_id'] = '10'
192            elif student.current_mode == 'dp_pt':
193                xmldict['institution_acct'] = '9201805071'
194                xmldict['institution_bank_id'] = '17'
195            else:
196                xmldict['institution_bank_id'] = '7'
197                xmldict['institution_acct'] = '1003475516'
198        elif self.context.p_category == 'gown':
199            self.pay_item_id = '5704'
200            provider_amt = 0.0
201            xmldict['institution_bank_id'] = '7'
202            xmldict['institution_acct'] = '1016232382'
203        elif self.context.p_category.startswith('hostel_maintenance'):
204            self.pay_item_id = '5705'
205            provider_amt = 0.0
206            xmldict['institution_bank_id'] = '129'
207            xmldict['institution_acct'] = '0014414547'
208
209        xmldict['provider_amt'] = 100 * provider_amt
210        xmldict['institution_item_name'] = self.category
211        xmldict['institution_name'] = INSTITUTION_NAME
212        xmldict['institution_amt'] = 100 * (
213            self.context.amount_auth - provider_amt - GATEWAY_AMT)
214        # Interswitch amount is not part of the xml data
215        if provider_amt == 0:
216            xmltext = """<payment_item_detail>
217<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
218<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" />
219</item_details>
220</payment_item_detail>""" % xmldict
221        else:
222            xmltext = """<payment_item_detail>
223<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
224<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" />
225<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" />
226</item_details>
227</payment_item_detail>""" % xmldict
228        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
229        self.context.provider_amt = provider_amt
230        self.context.gateway_amt = GATEWAY_AMT
231        return
232
233class InterswitchPageApplicant(KofaPage):
234    """ View which sends a POST request to the Interswitch
235    CollegePAY payment gateway.
236    """
237    grok.context(ICustomApplicantOnlinePayment)
238    grok.require('waeup.payApplicant')
239    grok.template('applicant_goto_interswitch')
240    grok.name('goto_interswitch')
241    label = _('Submit data to CollegePAY (Interswitch Payment Gateway)')
242    submit_button = _('Submit')
243    action = POST_ACTION
244    site_name = SITE_NAME
245    currency = CURRENCY
246    pay_item_id = '5703'
247    product_id = PRODUCT_ID
248
249    def update(self):
250        if self.context.p_state != 'unpaid':
251            self.flash(_("Payment ticket can't be re-send to CollegePAY."))
252            self.redirect(self.url(self.context, '@@index'))
253            return
254        if self.context.__parent__.__parent__.expired \
255            and self.context.__parent__.__parent__.strict_deadline:
256            self.flash(_("Payment ticket can't be send to CollegePAY. "
257                         "Application period has expired."))
258            self.redirect(self.url(self.context, '@@index'))
259            return
260        self.applicant = self.context.__parent__
261        self.amount_auth = 100 * self.context.amount_auth
262        xmldict = {}
263        self.category = getUtility(IKofaUtils).PAYMENT_CATEGORIES[self.context.p_category]
264        tz = getUtility(IKofaUtils).tzinfo
265        self.local_date_time = to_timezone(
266            self.context.creation_date, tz).strftime("%Y-%m-%d %H:%M:%S %Z")
267        self.site_redirect_url = self.url(self.context, 'request_webservice')
268        provider_amt = 400.0
269        if self.applicant.applicant_id.startswith('pg'):
270            xmldict['institution_acct'] = '0031716030'
271            xmldict['institution_bank_id'] = '10'
272        elif self.applicant.applicant_id.startswith('dp'):
273            xmldict['institution_acct'] = '9201805071'
274            xmldict['institution_bank_id'] = '17'
275        else:
276            xmldict['institution_acct'] = '6220032503'
277            xmldict['institution_bank_id'] = '51'
278        xmldict['detail_ref'] = self.context.p_id
279        xmldict['provider_amt'] = 100 * provider_amt
280        xmldict['provider_acct'] = PROVIDER_ACCT
281        xmldict['provider_bank_id'] = PROVIDER_BANK_ID
282        xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
283        xmldict['institution_amt'] = 100 * (self.context.amount_auth - provider_amt - GATEWAY_AMT)
284        xmldict['institution_item_name'] = self.context.p_category
285        xmldict['institution_name'] = INSTITUTION_NAME
286        # Interswitch amount is not part of the xml data
287        xmltext = """<payment_item_detail>
288<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s">
289<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" />
290<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" />
291</item_details>
292</payment_item_detail>""" % xmldict
293        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
294        self.context.provider_amt = provider_amt
295        self.context.gateway_amt = GATEWAY_AMT
296        return
297
298# Deprecated
299#class InterswitchPaymentCallbackPageStudent(UtilityView, grok.View):
300#    """ Callback view for the CollegePAY gateway
301#    """
302#    grok.context(ICustomStudentOnlinePayment)
303#    grok.name('isw_callback')
304#    grok.require('waeup.payStudent')
305
306    # This view is not yet working for offline querying transactions
307    # since the query string differs from the query string sent after
308    # posting transactions. This Interswitch bug must be removed first.
309    # Alternatively, we could use the webservice only and replace
310    # the RequestCallbackActionButton by a RequestWebserviceActionButton
311
312#    def update(self):
313#        if self.context.p_state == 'paid':
314#            self.flash(_('This ticket has already been paid.'))
315#            return
316#        student = self.context.student
317#        query = self.request.form
318#        write_log_message(self,'callback received: %s' % query)
319#        self.context.r_card_num = query.get('cardNum', None)
320#        self.context.r_code = query.get('resp', None)
321#        self.context.r_pay_reference  = query.get('payRef', None)
322#        self.context.r_amount_approved = float(query.get('apprAmt', '0.0')) / 100
323#        self.context.r_desc = query.get('desc', None)
324#        if self.context.r_code != '00':
325#            self.flash(_('Unsuccessful callback: ${a}',
326#                mapping = {'a': query.get('desc', _('Incomplete query string.'))}))
327#            write_log_message(self,'unsuccessful callback: %s' % self.context.p_id)
328#            self.context.p_state = 'failed'
329#            return
330#        if self.context.r_amount_approved != payment.amount_auth:
331#            self.flash(_('Wrong amount'))
332#            write_log_message(
333#                self,'successful but wrong amount: %s' % self.context.p_id)
334#            self.context.p_state = 'failed'
335#            return
336#        try:
337#            validation_list = get_SOAP_response(
338#                PRODUCT_ID, self.context.p_id).split(':')
339            # Validation does not make sense yet since the query string
340            # formats are conflicting. We are only printing the validation
341            # string, nothing else.
342#            print 'WARNING: Webservice validation is not yet implemented'
343#            print 'validation list: %s' % validation_list
344#        except:
345#            print 'Connection to webservice failed.'
346        # Add webservice validation here
347#        write_log_message(self,'valid callback: %s' % self.context.p_id)
348#        self.context.p_state = 'paid'
349#        self.context.payment_date = datetime.utcnow()
350#        actions_after_student_payment(student, self.context, self)
351#        return
352
353#    def render(self):
354#        self.redirect(self.url(self.context, '@@index'))
355#        return
356
357# Alternative solution, replaces InterswitchPaymentCallbackPage
358class InterswitchPaymentRequestWebservicePageStudent(UtilityView, grok.View):
359    """ Request webservice view for the CollegePAY gateway
360    """
361    grok.context(ICustomStudentOnlinePayment)
362    grok.name('request_webservice')
363    grok.require('waeup.payStudent')
364
365    def update(self):
366        if self.context.p_state == 'paid':
367            self.flash(_('This ticket has already been paid.'))
368            return
369        student = self.context.student
370        success, msg, log = query_interswitch(
371            self.context, PRODUCT_ID, HOST, URL)
372        student.writeLogMessage(self, log)
373        if not success:
374            self.flash(msg)
375            return
376        write_payments_log(student.student_id, self.context)
377        success, msg, log = self.context.doAfterStudentPayment()
378        if log is not None:
379            student.writeLogMessage(self, log)
380        self.flash(msg)
381        return
382
383    def render(self):
384        self.redirect(self.url(self.context, '@@index'))
385        return
386
387class InterswitchPaymentRequestWebservicePageApplicant(UtilityView, grok.View):
388    """ Request webservice view for the CollegePAY gateway
389    """
390    grok.context(ICustomApplicantOnlinePayment)
391    grok.name('request_webservice')
392    grok.require('waeup.payApplicant')
393
394    def update(self):
395        if self.context.p_state == 'paid':
396            self.flash(_('This ticket has already been paid.'))
397            return
398        applicant = self.context.__parent__
399        success, msg, log = query_interswitch(
400            self.context, PRODUCT_ID, HOST, URL)
401        applicant.writeLogMessage(self, log)
402        if not success:
403            self.flash(msg)
404            return
405        write_payments_log(applicant.applicant_id, self.context)
406        success, msg, log = self.context.doAfterApplicantPayment()
407        if log is not None:
408            applicant.writeLogMessage(self, log)
409        self.flash(msg)
410        return
411
412    def render(self):
413        self.redirect(self.url(self.context, '@@index'))
414        return
Note: See TracBrowser for help on using the repository browser.