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

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

Send local time of creation to Interswitch not UTC.

  • Property svn:keywords set to Id
File size: 18.9 KB
Line 
1## $Id: browser.py 8281 2012-04-26 07:16:27Z 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.browser import write_log_message
29from waeup.kofa.students.viewlets import RequestCallbackActionButton as RCABStudent
30from waeup.kofa.applicants.viewlets import RequestCallbackActionButton as RCABApplicant
31from waeup.kofa.payments.interfaces import payment_categories
32from waeup.uniben.students.interfaces import ICustomStudentOnlinePayment
33from waeup.uniben.applicants.interfaces import ICustomApplicantOnlinePayment
34from waeup.uniben.students.utils import actions_after_student_payment
35from waeup.uniben.applicants.utils import actions_after_applicant_payment
36from waeup.uniben.interfaces import MessageFactory as _
37
38#    Interswitch test account data:
39#
40#   Card Number: 6274807700000007
41#   Expiry Date: July 2012
42#   PIN: 0000
43
44#   Card Number: 6278050000000007
45#   Expiry Date: July 2012
46#   PIN: 0000
47#
48#   PAN,EXPIRY,PIN,CVV2
49#   5060990330000003386,1304,0000,543
50#   5060990330000003394,1304,0000,865
51#   5060990330000003402,1304,0000,012
52#   5060990330000003410,1304,0000,737
53#   5060990330000003428,1304,0000,310
54#   5060990330000003436,1304,0000,173
55
56PRODUCT_ID = '57'
57SITE_NAME = 'uniben-kofa.waeup.org'
58PROVIDER_ACCT = '0061001000021095'
59PROVIDER_BANK_ID = '89'
60PROVIDER_ITEM_NAME = 'BT Education'
61INSTITUTION_NAME = 'Uniben'
62CURRENCY = '566'
63#QUERY_URL = 'https://webpay.interswitchng.com/paydirect/services/TransactionQueryURL.aspx'
64QUERY_URL = 'https://testwebpay.interswitchng.com/test_paydirect/services/TransactionQueryURL.aspx'
65#POST_ACTION = 'https://webpay.interswitchng.com/paydirect/webpay/pay.aspx'
66POST_ACTION = 'https://testwebpay.interswitchng.com/test_paydirect/webpay/pay.aspx'
67
68#HOST = 'webpay.interswitchng.com'
69HOST = 'testwebpay.interswitchng.com'
70#URL = '/paydirect/services/TransactionQueryWs.asmx'
71URL = '/test_paydirect/services/TransactionQueryWs.asmx'
72httplib.HTTPConnection.debuglevel = 0
73
74
75def SOAP_post(soap_action,xml):
76    """Handles making the SOAP request.
77
78    Further reading:
79    http://testwebpay.interswitchng.com/test_paydirect/services/TransactionQueryWs.asmx?op=getTransactionData
80    """
81    h = httplib.HTTPConnection(HOST)
82    headers={
83        'Host':HOST,
84        'Content-Type':'text/xml; charset=utf-8',
85        'Content-Length':len(xml),
86        'SOAPAction':'"%s"' % soap_action,
87    }
88    h.request('POST', URL, body=xml,headers=headers)
89    r = h.getresponse()
90    d = r.read()
91    if r.status!=200:
92        raise ValueError('Error connecting: %s, %s' % (r.status, r.reason))
93    return d
94
95def get_SOAP_response(product_id, transref):
96    xml="""\
97<?xml version="1.0" encoding="utf-8"?>
98<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/">
99  <soap:Body>
100    <getTransactionData xmlns="http://tempuri.org/">
101      <product_id>%s</product_id>
102      <trans_ref>%s</trans_ref>
103    </getTransactionData>
104  </soap:Body>
105</soap:Envelope>""" % (product_id, transref)
106    result_xml=SOAP_post("http://tempuri.org/getTransactionData",xml)
107    doc=parseString(result_xml)
108    response=doc.getElementsByTagName('getTransactionDataResult')[0].firstChild.data
109    return response
110
111def query_interswitch(user, payment, view):
112    ob_class = view.__implemented__.__name__
113    sr = get_SOAP_response(PRODUCT_ID, payment.p_id)
114    user.loggerInfo(ob_class, 'callback received: %s' % sr)
115    wlist = sr.split(':')
116    if len(wlist) != 7:
117        view.flash(_('Invalid callback: ${a}',
118            mapping = {'a': wlist}))
119        user.loggerInfo(ob_class,'invalid callback: %s' % payment.p_id)
120        return False
121    payment.r_code = wlist[0]
122    payment.r_desc = wlist[1]
123    payment.r_amount_approved = float(wlist[2]) / 100
124    payment.r_card_num = wlist[3]
125    payment.r_pay_reference = wlist[5]
126    if payment.r_code != '00':
127        view.flash(_('Unsuccessful callback: ${a}', mapping = {'a': wlist[1]}))
128        user.loggerInfo(ob_class,'unsuccessful callback: %s' % payment.p_id)
129        payment.p_state = 'failed'
130        return False
131    if payment.r_amount_approved != payment.amount_auth:
132        view.flash(_('Wrong amount'))
133        user.loggerInfo(ob_class,'successful callback but wrong amount: %s'
134            % payment.p_id)
135        payment.p_state = 'failed'
136        return False
137    if wlist[4] != payment.p_id:
138        view.flash(_('Wrong transaction id'))
139        user.loggerInfo(ob_class,'successful callback but wrong transaction id: %s'
140            % payment.p_id)
141        payment.p_state = 'failed'
142        return False
143    user.loggerInfo(ob_class,'successful callback: %s' % payment.p_id)
144    payment.p_state = 'paid'
145    payment.payment_date = datetime.now()
146    return True
147
148class InterswitchActionButtonStudent(RCABStudent):
149    grok.order(1)
150    grok.context(ICustomStudentOnlinePayment)
151    icon = 'actionicon_pay.png'
152    text = _('CollegePAY')
153    target = 'goto_interswitch'
154
155    @property
156    def target_url(self):
157        if self.context.p_state != 'unpaid':
158            return ''
159        return self.view.url(self.view.context, self.target)
160
161class InterswitchActionButtonApplicant(RCABApplicant):
162    grok.order(1)
163    grok.context(ICustomApplicantOnlinePayment)
164    icon = 'actionicon_pay.png'
165    text = _('CollegePAY')
166    target = 'goto_interswitch'
167
168    @property
169    def target_url(self):
170        if self.context.p_state != 'unpaid':
171            return ''
172        return self.view.url(self.view.context, self.target)
173
174# Deprecated
175#class InterswitchRequestCallbackActionButtonStudent(RCABStudent):
176#    grok.order(3)
177#    grok.context(ICustomStudentOnlinePayment)
178#    icon = 'actionicon_call.png'
179#    text = _('Request CollegePAY callback')
180
181#    def target_url(self):
182#        if self.context.p_state == 'paid':
183#            return ''
184#        site_redirect_url = self.view.url(self.view.context, 'isw_callback')
185#        args = {
186#            'transRef':self.context.p_id,
187#            'prodID':PRODUCT_ID,
188#            'redirectURL':site_redirect_url}
189#        return QUERY_URL + '?%s' % urllib.urlencode(args)
190
191# Alternative preferred solution
192class InterswitchRequestWebserviceActionButtonStudent(RCABStudent):
193    grok.order(2)
194    grok.context(ICustomStudentOnlinePayment)
195    icon = 'actionicon_call.png'
196    text = _('Request CollegePAY Webservice')
197    target = 'request_webservice'
198
199class InterswitchRequestWebserviceActionButtonApplicant(RCABApplicant):
200    grok.order(2)
201    grok.context(ICustomApplicantOnlinePayment)
202    icon = 'actionicon_call.png'
203    text = _('Request CollegePAY Webservice')
204    target = 'request_webservice'
205
206
207class InterswitchPageStudent(KofaPage):
208    """ View which sends a POST request to the Interswitch
209    CollegePAY payment gateway.
210    """
211    grok.context(ICustomStudentOnlinePayment)
212    grok.name('goto_interswitch')
213    grok.template('student_goto_interswitch')
214    grok.require('waeup.payStudent')
215    label = _('Submit data to CollegePAY (Interswitch Payment Gateway)')
216    submit_button = _('Submit')
217    action = POST_ACTION
218    site_name = SITE_NAME
219    currency = CURRENCY
220    pay_item_id = '5700'
221    product_id = PRODUCT_ID
222
223    def update(self):
224        #if self.context.p_state != 'unpaid':
225        if self.context.p_state == 'paid':
226            self.flash(_("Payment ticket can't be re-send to CollegePAY."))
227            self.redirect(self.url(self.context, '@@index'))
228            return
229
230        student = self.student = self.context.getStudent()
231        certificate = getattr(self.student['studycourse'],'certificate',None)
232        self.amount_auth = 100 * self.context.amount_auth
233        xmldict = {}
234        if certificate is not None:
235            xmldict['department'] = certificate.__parent__.__parent__.code
236            xmldict['faculty'] = certificate.__parent__.__parent__.__parent__.code
237        else:
238            xmldict['department'] = None
239            xmldict['faculty'] = None
240        self.category = payment_categories.getTermByToken(
241            self.context.p_category).title
242        tz = getUtility(IKofaUtils).tzinfo
243        self.local_date_time = to_timezone(
244            self.context.creation_date, tz).strftime("%Y-%m-%d %H:%M:%S %Z")
245        self.site_redirect_url = self.url(self.context, 'request_webservice')
246        # Provider data
247        xmldict['detail_ref'] = self.context.p_id
248        xmldict['provider_acct'] = PROVIDER_ACCT
249        xmldict['provider_bank_id'] = PROVIDER_BANK_ID
250        xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
251        if student.current_mode.endswith('_ft') \
252            and student.state == RETURNING:
253            provider_amt = 600
254        else:
255            provider_amt = 1500
256        xmldict['provider_amt'] = 100 * provider_amt
257        # Institution data
258        studycourse = student['studycourse']
259        xmldict['institution_acct'] = ''
260        xmldict['institution_bank_id'] = ''
261        if student.current_mode.endswith('_ft'):
262            #post-grad full-time students of all faculties
263            if studycourse.current_level in ('700','710','800','810','900','910'):
264                xmldict['institution_acct'] = '1012842833'
265                xmldict['institution_bank_id'] = '117'
266            #all other part-time students depending on faculty
267            elif student.faccode in ('SSC','LAW','MED'):
268                xmldict['institution_acct'] = '0005986938'
269                xmldict['institution_bank_id'] = '31'
270            elif student.faccode in ('ENG','PSC','PHA'):
271                xmldict['institution_acct'] = '0014413973'
272                xmldict['institution_bank_id'] = '129'
273            elif student.faccode in ('LSC','DEN','AGR'):
274                xmldict['institution_acct'] = '1012801319'
275                xmldict['institution_bank_id'] = '117'
276            elif student.faccode in ('ART','EDU','MGS','BMS'):
277                xmldict['institution_acct'] = '6220027556'
278                xmldict['institution_bank_id'] = '51'
279        elif student.current_mode.endswith('_pt'):
280            #post-grad part-time students of all faculties
281            if studycourse.current_level in ('700','710','800','810','900','910'):
282                xmldict['institution_acct'] = '0023708207'
283                xmldict['institution_bank_id'] = '72'
284            #all other part-time students depending on faculty
285            elif student.faccode in ('ENG','LAW','MGS'):
286                xmldict['institution_acct'] = '2019006824'
287                xmldict['institution_bank_id'] = '8'
288            elif student.faccode in ('IPA','PHA','SSC','AGR','EDU'):
289                xmldict['institution_acct'] = '0122012109'
290                xmldict['institution_bank_id'] = '16'
291        xmldict['institution_amt'] = 100 * (self.amount_auth - provider_amt - 150)
292        xmldict['institution_item_name'] = self.context.p_category
293        xmldict['institution_name'] = INSTITUTION_NAME
294        # Interswitch amount is not part of the xml data
295        xmltext = """<payment_item_detail>
296<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
297<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" />
298<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" />
299</item_details>
300</payment_item_detail>""" % xmldict
301        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
302        return
303
304class InterswitchPageApplicant(KofaPage):
305    """ View which sends a POST request to the Interswitch
306    CollegePAY payment gateway.
307    """
308    grok.context(ICustomApplicantOnlinePayment)
309    grok.require('waeup.payApplicant')
310    grok.template('applicant_goto_interswitch')
311    grok.name('goto_interswitch')
312    label = _('Submit data to CollegePAY (Interswitch Payment Gateway)')
313    submit_button = _('Submit')
314    action = POST_ACTION
315    site_name = SITE_NAME
316    currency = CURRENCY
317    pay_item_id = '5703'
318    product_id = PRODUCT_ID
319
320    def update(self):
321        if self.context.p_state != 'unpaid':
322            self.flash(_("Payment ticket can't be re-send to CollegePAY."))
323            self.redirect(self.url(self.context, '@@index'))
324            return
325        self.applicant = self.context.__parent__
326        self.amount_auth = 100 * self.context.amount_auth
327        xmldict = {}
328        self.category = payment_categories.getTermByToken(
329            self.context.p_category).title
330        tz = getUtility(IKofaUtils).tzinfo
331        self.local_date_time = to_timezone(
332            self.context.creation_date, tz).strftime("%Y-%m-%d %H:%M:%S %Z")
333        self.site_redirect_url = self.url(self.context, 'request_webservice')
334        # Provider data
335        xmldict['detail_ref'] = self.context.p_id
336        xmldict['provider_amt'] = 100 * 400
337        xmldict['provider_acct'] = PROVIDER_ACCT
338        xmldict['provider_bank_id'] = PROVIDER_BANK_ID
339        xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
340        # Institution data
341        xmldict['institution_amt'] = 100 * (self.context.amount_auth - 400 - 150)
342        xmldict['institution_acct'] = '0031716030'
343        xmldict['institution_bank_id'] = '10'
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.getStudent()
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.now()
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        if self.context.p_state == 'paid':
425            self.flash(_('This ticket has already been paid.'))
426            return
427        student = self.context.getStudent()
428        if query_interswitch(student, self.context, self):
429            actions_after_student_payment(student, self.context, self)
430        return
431
432    def render(self):
433        self.redirect(self.url(self.context, '@@index'))
434        return
435
436class InterswitchPaymentRequestWebservicePageApplicant(UtilityView, grok.View):
437    """ Request webservice view for the CollegePAY gateway
438    """
439    grok.context(ICustomApplicantOnlinePayment)
440    grok.name('request_webservice')
441    grok.require('waeup.payApplicant')
442
443    def update(self):
444        if self.context.p_state == 'paid':
445            self.flash(_('This ticket has already been paid.'))
446            return
447        applicant = self.context.__parent__
448        if query_interswitch(applicant, self.context, self):
449            actions_after_applicant_payment(student, self.context, self)
450        return
451
452    def render(self):
453        self.redirect(self.url(self.context, '@@index'))
454        return
Note: See TracBrowser for help on using the repository browser.