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

Last change on this file since 8419 was 8401, checked in by Henrik Bettermann, 13 years ago

QUERY_URL no longer used.

Add CRPUOfficer Role.

  • Property svn:keywords set to Id
File size: 18.5 KB
RevLine 
[7894]1## $Id: browser.py 8401 2012-05-09 16:33:51Z 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##
18from datetime import datetime
[7898]19import httplib
20import urllib
21from xml.dom.minidom import parseString
[7894]22import grok
[8281]23from zope.component import getUtility
[7894]24from waeup.kofa.browser.layout import KofaPage, UtilityView
25from waeup.kofa.accesscodes import create_accesscode
[8281]26from waeup.kofa.interfaces import RETURNING, IKofaUtils
27from waeup.kofa.utils.helpers import to_timezone
[7894]28from waeup.kofa.students.browser import write_log_message
[8256]29from waeup.kofa.students.viewlets import RequestCallbackActionButton as RCABStudent
30from waeup.kofa.applicants.viewlets import RequestCallbackActionButton as RCABApplicant
[8259]31from waeup.kofa.payments.interfaces import payment_categories
[8263]32from waeup.uniben.students.interfaces import ICustomStudentOnlinePayment
33from waeup.uniben.applicants.interfaces import ICustomApplicantOnlinePayment
[8247]34from waeup.uniben.students.utils import actions_after_student_payment
[8256]35from waeup.uniben.applicants.utils import actions_after_applicant_payment
[8020]36from waeup.uniben.interfaces import MessageFactory as _
[7894]37
38PRODUCT_ID = '57'
[8263]39SITE_NAME = 'uniben-kofa.waeup.org'
40PROVIDER_ACCT = '0061001000021095'
41PROVIDER_BANK_ID = '89'
42PROVIDER_ITEM_NAME = 'BT Education'
43INSTITUTION_NAME = 'Uniben'
[7894]44CURRENCY = '566'
[8401]45#QUERY_URL = 'https://webpay.interswitchng.com/paydirect/services/TransactionQueryURL.aspx'
[8293]46#QUERY_URL = 'https://testwebpay.interswitchng.com/test_paydirect/services/TransactionQueryURL.aspx'
[8385]47POST_ACTION = 'https://webpay.interswitchng.com/paydirect/webpay/pay.aspx'
[8293]48#POST_ACTION = 'https://testwebpay.interswitchng.com/test_paydirect/webpay/pay.aspx'
[7894]49
[8293]50HOST = 'webpay.interswitchng.com'
51#HOST = 'testwebpay.interswitchng.com'
52URL = '/paydirect/services/TransactionQueryWs.asmx'
53#URL = '/test_paydirect/services/TransactionQueryWs.asmx'
[7898]54httplib.HTTPConnection.debuglevel = 0
55
[8256]56
[7898]57def SOAP_post(soap_action,xml):
58    """Handles making the SOAP request.
59
60    Further reading:
61    http://testwebpay.interswitchng.com/test_paydirect/services/TransactionQueryWs.asmx?op=getTransactionData
62    """
63    h = httplib.HTTPConnection(HOST)
64    headers={
65        'Host':HOST,
66        'Content-Type':'text/xml; charset=utf-8',
67        'Content-Length':len(xml),
68        'SOAPAction':'"%s"' % soap_action,
69    }
70    h.request('POST', URL, body=xml,headers=headers)
71    r = h.getresponse()
72    d = r.read()
73    if r.status!=200:
74        raise ValueError('Error connecting: %s, %s' % (r.status, r.reason))
75    return d
76
77def get_SOAP_response(product_id, transref):
78    xml="""\
79<?xml version="1.0" encoding="utf-8"?>
80<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
81  <soap:Body>
82    <getTransactionData xmlns="http://tempuri.org/">
83      <product_id>%s</product_id>
84      <trans_ref>%s</trans_ref>
85    </getTransactionData>
86  </soap:Body>
87</soap:Envelope>""" % (product_id, transref)
88    result_xml=SOAP_post("http://tempuri.org/getTransactionData",xml)
89    doc=parseString(result_xml)
90    response=doc.getElementsByTagName('getTransactionDataResult')[0].firstChild.data
91    return response
92
[8256]93def query_interswitch(user, payment, view):
94    ob_class = view.__implemented__.__name__
95    sr = get_SOAP_response(PRODUCT_ID, payment.p_id)
96    user.loggerInfo(ob_class, 'callback received: %s' % sr)
97    wlist = sr.split(':')
98    if len(wlist) != 7:
99        view.flash(_('Invalid callback: ${a}',
100            mapping = {'a': wlist}))
101        user.loggerInfo(ob_class,'invalid callback: %s' % payment.p_id)
102        return False
103    payment.r_code = wlist[0]
104    payment.r_desc = wlist[1]
105    payment.r_amount_approved = float(wlist[2]) / 100
106    payment.r_card_num = wlist[3]
107    payment.r_pay_reference = wlist[5]
108    if payment.r_code != '00':
109        view.flash(_('Unsuccessful callback: ${a}', mapping = {'a': wlist[1]}))
110        user.loggerInfo(ob_class,'unsuccessful callback: %s' % payment.p_id)
111        payment.p_state = 'failed'
112        return False
[8263]113    if payment.r_amount_approved != payment.amount_auth:
[8256]114        view.flash(_('Wrong amount'))
115        user.loggerInfo(ob_class,'successful callback but wrong amount: %s'
116            % payment.p_id)
117        payment.p_state = 'failed'
118        return False
119    if wlist[4] != payment.p_id:
120        view.flash(_('Wrong transaction id'))
121        user.loggerInfo(ob_class,'successful callback but wrong transaction id: %s'
122            % payment.p_id)
123        payment.p_state = 'failed'
124        return False
125    user.loggerInfo(ob_class,'successful callback: %s' % payment.p_id)
126    payment.p_state = 'paid'
127    payment.payment_date = datetime.now()
128    return True
129
130class InterswitchActionButtonStudent(RCABStudent):
[8259]131    grok.order(1)
[8255]132    grok.context(ICustomStudentOnlinePayment)
[7894]133    icon = 'actionicon_pay.png'
134    text = _('CollegePAY')
135    target = 'goto_interswitch'
136
137    @property
138    def target_url(self):
139        if self.context.p_state != 'unpaid':
140            return ''
141        return self.view.url(self.view.context, self.target)
142
[8256]143class InterswitchActionButtonApplicant(RCABApplicant):
[8259]144    grok.order(1)
[8256]145    grok.context(ICustomApplicantOnlinePayment)
146    icon = 'actionicon_pay.png'
147    text = _('CollegePAY')
148    target = 'goto_interswitch'
149
150    @property
151    def target_url(self):
152        if self.context.p_state != 'unpaid':
153            return ''
154        return self.view.url(self.view.context, self.target)
155
156# Deprecated
[8259]157#class InterswitchRequestCallbackActionButtonStudent(RCABStudent):
158#    grok.order(3)
159#    grok.context(ICustomStudentOnlinePayment)
160#    icon = 'actionicon_call.png'
161#    text = _('Request CollegePAY callback')
[7894]162
[8259]163#    def target_url(self):
164#        if self.context.p_state == 'paid':
165#            return ''
166#        site_redirect_url = self.view.url(self.view.context, 'isw_callback')
167#        args = {
168#            'transRef':self.context.p_id,
169#            'prodID':PRODUCT_ID,
170#            'redirectURL':site_redirect_url}
171#        return QUERY_URL + '?%s' % urllib.urlencode(args)
[7894]172
[7919]173# Alternative preferred solution
[8256]174class InterswitchRequestWebserviceActionButtonStudent(RCABStudent):
[8259]175    grok.order(2)
[8255]176    grok.context(ICustomStudentOnlinePayment)
[7919]177    icon = 'actionicon_call.png'
[8259]178    text = _('Request CollegePAY Webservice')
[7919]179    target = 'request_webservice'
180
[8256]181class InterswitchRequestWebserviceActionButtonApplicant(RCABApplicant):
[8259]182    grok.order(2)
[8256]183    grok.context(ICustomApplicantOnlinePayment)
184    icon = 'actionicon_call.png'
[8259]185    text = _('Request CollegePAY Webservice')
[8256]186    target = 'request_webservice'
[7919]187
[8256]188
189class InterswitchPageStudent(KofaPage):
[7894]190    """ View which sends a POST request to the Interswitch
191    CollegePAY payment gateway.
192    """
[8255]193    grok.context(ICustomStudentOnlinePayment)
[7894]194    grok.name('goto_interswitch')
[8256]195    grok.template('student_goto_interswitch')
[7894]196    grok.require('waeup.payStudent')
197    label = _('Submit data to CollegePAY (Interswitch Payment Gateway)')
198    submit_button = _('Submit')
199    action = POST_ACTION
200    site_name = SITE_NAME
201    currency = CURRENCY
[8263]202    pay_item_id = '5700'
[7894]203    product_id = PRODUCT_ID
204
205    def update(self):
[8256]206        #if self.context.p_state != 'unpaid':
207        if self.context.p_state == 'paid':
[7894]208            self.flash(_("Payment ticket can't be re-send to CollegePAY."))
209            self.redirect(self.url(self.context, '@@index'))
210            return
[8256]211
[8263]212        student = self.student = self.context.getStudent()
[7894]213        certificate = getattr(self.student['studycourse'],'certificate',None)
[8276]214        self.amount_auth = 100 * self.context.amount_auth
[7894]215        xmldict = {}
216        if certificate is not None:
217            xmldict['department'] = certificate.__parent__.__parent__.code
218            xmldict['faculty'] = certificate.__parent__.__parent__.__parent__.code
219        else:
220            xmldict['department'] = None
221            xmldict['faculty'] = None
[8259]222        self.category = payment_categories.getTermByToken(
223            self.context.p_category).title
[8281]224        tz = getUtility(IKofaUtils).tzinfo
225        self.local_date_time = to_timezone(
226            self.context.creation_date, tz).strftime("%Y-%m-%d %H:%M:%S %Z")
[8256]227        self.site_redirect_url = self.url(self.context, 'request_webservice')
[8263]228        # Provider data
229        xmldict['detail_ref'] = self.context.p_id
230        xmldict['provider_acct'] = PROVIDER_ACCT
231        xmldict['provider_bank_id'] = PROVIDER_BANK_ID
232        xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
233        if student.current_mode.endswith('_ft') \
234            and student.state == RETURNING:
235            provider_amt = 600
236        else:
237            provider_amt = 1500
238        xmldict['provider_amt'] = 100 * provider_amt
239        # Institution data
240        studycourse = student['studycourse']
241        xmldict['institution_acct'] = ''
242        xmldict['institution_bank_id'] = ''
243        if student.current_mode.endswith('_ft'):
244            #post-grad full-time students of all faculties
245            if studycourse.current_level in ('700','710','800','810','900','910'):
246                xmldict['institution_acct'] = '1012842833'
247                xmldict['institution_bank_id'] = '117'
248            #all other part-time students depending on faculty
249            elif student.faccode in ('SSC','LAW','MED'):
250                xmldict['institution_acct'] = '0005986938'
251                xmldict['institution_bank_id'] = '31'
252            elif student.faccode in ('ENG','PSC','PHA'):
253                xmldict['institution_acct'] = '0014413973'
254                xmldict['institution_bank_id'] = '129'
255            elif student.faccode in ('LSC','DEN','AGR'):
256                xmldict['institution_acct'] = '1012801319'
257                xmldict['institution_bank_id'] = '117'
258            elif student.faccode in ('ART','EDU','MGS','BMS'):
259                xmldict['institution_acct'] = '6220027556'
260                xmldict['institution_bank_id'] = '51'
261        elif student.current_mode.endswith('_pt'):
262            #post-grad part-time students of all faculties
263            if studycourse.current_level in ('700','710','800','810','900','910'):
264                xmldict['institution_acct'] = '0023708207'
265                xmldict['institution_bank_id'] = '72'
266            #all other part-time students depending on faculty
267            elif student.faccode in ('ENG','LAW','MGS'):
268                xmldict['institution_acct'] = '2019006824'
269                xmldict['institution_bank_id'] = '8'
270            elif student.faccode in ('IPA','PHA','SSC','AGR','EDU'):
271                xmldict['institution_acct'] = '0122012109'
272                xmldict['institution_bank_id'] = '16'
[8276]273        xmldict['institution_amt'] = 100 * (self.amount_auth - provider_amt - 150)
[8263]274        xmldict['institution_item_name'] = self.context.p_category
275        xmldict['institution_name'] = INSTITUTION_NAME
276        # Interswitch amount is not part of the xml data
277        xmltext = """<payment_item_detail>
278<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
279<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" />
280<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" />
281</item_details>
282</payment_item_detail>""" % xmldict
283        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
[7894]284        return
285
[8263]286class InterswitchPageApplicant(KofaPage):
[8256]287    """ View which sends a POST request to the Interswitch
288    CollegePAY payment gateway.
289    """
290    grok.context(ICustomApplicantOnlinePayment)
291    grok.require('waeup.payApplicant')
292    grok.template('applicant_goto_interswitch')
[8263]293    grok.name('goto_interswitch')
294    label = _('Submit data to CollegePAY (Interswitch Payment Gateway)')
295    submit_button = _('Submit')
296    action = POST_ACTION
297    site_name = SITE_NAME
298    currency = CURRENCY
[8274]299    pay_item_id = '5703'
[8263]300    product_id = PRODUCT_ID
[8256]301
302    def update(self):
[8263]303        if self.context.p_state != 'unpaid':
304            self.flash(_("Payment ticket can't be re-send to CollegePAY."))
305            self.redirect(self.url(self.context, '@@index'))
306            return
[8256]307        self.applicant = self.context.__parent__
[8276]308        self.amount_auth = 100 * self.context.amount_auth
[8256]309        xmldict = {}
[8259]310        self.category = payment_categories.getTermByToken(
311            self.context.p_category).title
[8281]312        tz = getUtility(IKofaUtils).tzinfo
313        self.local_date_time = to_timezone(
314            self.context.creation_date, tz).strftime("%Y-%m-%d %H:%M:%S %Z")
[8256]315        self.site_redirect_url = self.url(self.context, 'request_webservice')
[8263]316        # Provider data
317        xmldict['detail_ref'] = self.context.p_id
318        xmldict['provider_amt'] = 100 * 400
319        xmldict['provider_acct'] = PROVIDER_ACCT
320        xmldict['provider_bank_id'] = PROVIDER_BANK_ID
321        xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
322        # Institution data
323        xmldict['institution_amt'] = 100 * (self.context.amount_auth - 400 - 150)
[8281]324        xmldict['institution_acct'] = '0031716030'
325        xmldict['institution_bank_id'] = '10'
[8263]326        xmldict['institution_item_name'] = self.context.p_category
327        xmldict['institution_name'] = INSTITUTION_NAME
328        # Interswitch amount is not part of the xml data
329        xmltext = """<payment_item_detail>
330<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s">
331<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" />
332<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" />
333</item_details>
334</payment_item_detail>""" % xmldict
335        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
[8256]336        return
337
338# Deprecated
[8263]339#class InterswitchPaymentCallbackPageStudent(UtilityView, grok.View):
340#    """ Callback view for the CollegePAY gateway
341#    """
342#    grok.context(ICustomStudentOnlinePayment)
343#    grok.name('isw_callback')
344#    grok.require('waeup.payStudent')
[7894]345
346    # This view is not yet working for offline querying transactions
347    # since the query string differs from the query string sent after
348    # posting transactions. This Interswitch bug must be removed first.
349    # Alternatively, we could use the webservice only and replace
350    # the RequestCallbackActionButton by a RequestWebserviceActionButton
351
[8263]352#    def update(self):
353#        if self.context.p_state == 'paid':
354#            self.flash(_('This ticket has already been paid.'))
355#            return
356#        student = self.context.getStudent()
357#        query = self.request.form
358#        write_log_message(self,'callback received: %s' % query)
359#        self.context.r_card_num = query.get('cardNum', None)
360#        self.context.r_code = query.get('resp', None)
361#        self.context.r_pay_reference  = query.get('payRef', None)
362#        self.context.r_amount_approved = float(query.get('apprAmt', '0.0')) / 100
363#        self.context.r_desc = query.get('desc', None)
364#        if self.context.r_code != '00':
365#            self.flash(_('Unsuccessful callback: ${a}',
366#                mapping = {'a': query.get('desc', _('Incomplete query string.'))}))
367#            write_log_message(self,'unsuccessful callback: %s' % self.context.p_id)
368#            self.context.p_state = 'failed'
369#            return
370#        if self.context.r_amount_approved != payment.amount_auth:
371#            self.flash(_('Wrong amount'))
372#            write_log_message(
373#                self,'successful but wrong amount: %s' % self.context.p_id)
374#            self.context.p_state = 'failed'
375#            return
376#        try:
377#            validation_list = get_SOAP_response(
378#                PRODUCT_ID, self.context.p_id).split(':')
[7934]379            # Validation does not make sense yet since the query string
[7970]380            # formats are conflicting. We are only printing the validation
381            # string, nothing else.
[8263]382#            print 'WARNING: Webservice validation is not yet implemented'
383#            print 'validation list: %s' % validation_list
384#        except:
385#            print 'Connection to webservice failed.'
[7970]386        # Add webservice validation here
[8263]387#        write_log_message(self,'valid callback: %s' % self.context.p_id)
388#        self.context.p_state = 'paid'
389#        self.context.payment_date = datetime.now()
390#        actions_after_student_payment(student, self.context, self)
391#        return
[7970]392
[8263]393#    def render(self):
394#        self.redirect(self.url(self.context, '@@index'))
395#        return
[7894]396
[8256]397# Alternative solution, replaces InterswitchPaymentCallbackPage
398class InterswitchPaymentRequestWebservicePageStudent(UtilityView, grok.View):
[7919]399    """ Request webservice view for the CollegePAY gateway
400    """
[8255]401    grok.context(ICustomStudentOnlinePayment)
[7919]402    grok.name('request_webservice')
403    grok.require('waeup.payStudent')
404
405    def update(self):
406        if self.context.p_state == 'paid':
407            self.flash(_('This ticket has already been paid.'))
408            return
409        student = self.context.getStudent()
[8256]410        if query_interswitch(student, self.context, self):
411            actions_after_student_payment(student, self.context, self)
412        return
[7919]413
[8256]414    def render(self):
415        self.redirect(self.url(self.context, '@@index'))
416        return
[7926]417
[8256]418class InterswitchPaymentRequestWebservicePageApplicant(UtilityView, grok.View):
419    """ Request webservice view for the CollegePAY gateway
420    """
421    grok.context(ICustomApplicantOnlinePayment)
422    grok.name('request_webservice')
423    grok.require('waeup.payApplicant')
[7919]424
[8256]425    def update(self):
426        if self.context.p_state == 'paid':
427            self.flash(_('This ticket has already been paid.'))
[7919]428            return
[8256]429        applicant = self.context.__parent__
430        if query_interswitch(applicant, self.context, self):
[8293]431            actions_after_applicant_payment(applicant, self)
[7919]432        return
433
434    def render(self):
435        self.redirect(self.url(self.context, '@@index'))
436        return
Note: See TracBrowser for help on using the repository browser.