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

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

Set pay_item_id according to payment category. Extend test.

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