source: main/waeup.custom/trunk/src/waeup/custom/interswitch/browser.py @ 7919

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

Implement OnlinePaymentRequestWebservicePage?. OnlinePaymentCallbackPage? can be removed later.

  • Property svn:keywords set to Id
File size: 13.7 KB
Line 
1## $Id: browser.py 7919 2012-03-19 07:01:48Z 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 waeup.kofa.browser.layout import KofaPage, UtilityView
24from waeup.kofa.accesscodes import create_accesscode
25from waeup.kofa.students.interfaces import IStudentOnlinePayment
26from waeup.kofa.students.browser import write_log_message
27from waeup.kofa.students.viewlets import RequestCallbackActionButton
28from waeup.custom.interfaces import MessageFactory as _
29
30PRODUCT_ID = '57'
31SITE_NAME = 'xyz.waeup.org'
32PROVIDER_ACCT = '2345'
33PROVIDER_BANK_ID = '8'
34PROVIDER_ITEM_NAME = 'Kofa Provider Fee'
35INSTITUTION_ACCT = '1234'
36INSTITUTION_BANK_ID = '9'
37INSTITUTION_NAME = 'Sample University'
38CURRENCY = '566'
39PAY_ITEM_ID = '5700'
40QUERY_URL =   'https://testwebpay.interswitchng.com/test_paydirect/services/TransactionQueryURL.aspx'
41POST_ACTION = 'https://testwebpay.interswitchng.com/test_paydirect/webpay/pay.aspx'
42
43HOST = 'testwebpay.interswitchng.com'
44URL = '/test_paydirect/services/TransactionQueryWs.asmx'
45httplib.HTTPConnection.debuglevel = 0
46
47def SOAP_post(soap_action,xml):
48    """Handles making the SOAP request.
49
50    Further reading:
51    http://testwebpay.interswitchng.com/test_paydirect/services/TransactionQueryWs.asmx?op=getTransactionData
52    """
53    h = httplib.HTTPConnection(HOST)
54    headers={
55        'Host':HOST,
56        'Content-Type':'text/xml; charset=utf-8',
57        'Content-Length':len(xml),
58        'SOAPAction':'"%s"' % soap_action,
59    }
60    h.request('POST', URL, body=xml,headers=headers)
61    r = h.getresponse()
62    d = r.read()
63    if r.status!=200:
64        raise ValueError('Error connecting: %s, %s' % (r.status, r.reason))
65    return d
66
67def get_SOAP_response(product_id, transref):
68    xml="""\
69<?xml version="1.0" encoding="utf-8"?>
70<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/">
71  <soap:Body>
72    <getTransactionData xmlns="http://tempuri.org/">
73      <product_id>%s</product_id>
74      <trans_ref>%s</trans_ref>
75    </getTransactionData>
76  </soap:Body>
77</soap:Envelope>""" % (product_id, transref)
78    result_xml=SOAP_post("http://tempuri.org/getTransactionData",xml)
79    doc=parseString(result_xml)
80    response=doc.getElementsByTagName('getTransactionDataResult')[0].firstChild.data
81    return response
82
83class InterswitchActionButton(RequestCallbackActionButton):
84    grok.order(2)
85    icon = 'actionicon_pay.png'
86    text = _('CollegePAY')
87    target = 'goto_interswitch'
88
89    @property
90    def target_url(self):
91        if self.context.p_state != 'unpaid':
92            return ''
93        return self.view.url(self.view.context, self.target)
94
95class InterswitchRequestCallbackActionButton(RequestCallbackActionButton):
96    grok.order(3)
97    icon = 'actionicon_call.png'
98    text = _('Request CollegePAY callback')
99
100    def target_url(self):
101        if self.context.p_state == 'paid':
102            return ''
103        site_redirect_url = self.view.url(self.view.context, 'callback')
104        args = {
105            'transRef':self.context.p_id,
106            'prodID':PRODUCT_ID,
107            'redirectURL':site_redirect_url}
108        return QUERY_URL + '?%s' % urllib.urlencode(args)
109
110# Alternative preferred solution
111class InterswitchRequestWebserviceActionButton(RequestCallbackActionButton):
112    grok.order(4)
113    icon = 'actionicon_call.png'
114    text = _('Request CollegePAY webservice')
115    target = 'request_webservice'
116
117
118class InterswitchPage(KofaPage):
119    """ View which sends a POST request to the Interswitch
120    CollegePAY payment gateway.
121    """
122    grok.context(IStudentOnlinePayment)
123    grok.name('goto_interswitch')
124    grok.template('goto_interswitch')
125    grok.require('waeup.payStudent')
126    label = _('Submit data to CollegePAY (Interswitch Payment Gateway)')
127    submit_button = _('Submit')
128    action = POST_ACTION
129    site_name = SITE_NAME
130    currency = CURRENCY
131    pay_item_id = PAY_ITEM_ID
132    product_id = PRODUCT_ID
133
134    def update(self):
135        if self.context.p_state != 'unpaid':
136            self.flash(_("Payment ticket can't be re-send to CollegePAY."))
137            self.redirect(self.url(self.context, '@@index'))
138            return
139        self.student = self.context.getStudent()
140        self.amount = (self.context.amount_auth + self.context.surcharge_1 +
141            self.context.surcharge_2 + self.context.surcharge_3)
142        self.amount_100 = 100 * self.amount
143        self.local_date_time = str(self.context.creation_date)
144        self.site_redirect_url = self.url(self.context, 'callback')
145        certificate = getattr(self.student['studycourse'],'certificate',None)
146        xmldict = {}
147        if certificate is not None:
148            xmldict['department'] = certificate.__parent__.__parent__.code
149            xmldict['faculty'] = certificate.__parent__.__parent__.__parent__.code
150        else:
151            xmldict['department'] = None
152            xmldict['faculty'] = None
153        xmldict['detail_ref'] = self.context.p_id
154        xmldict['provider_amt'] = 100 * self.context.surcharge_1
155        xmldict['provider_acct'] = PROVIDER_ACCT
156        xmldict['provider_bank_id'] = PROVIDER_BANK_ID
157        xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
158        xmldict['institution_amt'] = 100 * self.context.amount_auth
159        xmldict['institution_acct'] = INSTITUTION_ACCT
160        xmldict['institution_bank_id'] = INSTITUTION_BANK_ID
161        xmldict['institution_item_name'] = self.context.p_category
162        xmldict['institution_name'] = INSTITUTION_NAME
163        # Interswitch amount is not part of the xml data
164        xmltext = """<payment_item_detail>
165<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
166<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" />
167<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" />
168</item_details>
169</payment_item_detail>""" % xmldict
170        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
171        return
172
173class OnlinePaymentCallbackPage(UtilityView, grok.View):
174    """ Callback view for the CollegePAY gateway
175    """
176    grok.context(IStudentOnlinePayment)
177    grok.name('callback')
178    grok.require('waeup.payStudent')
179
180    # This view is not yet working for offline querying transactions
181    # since the query string differs from the query string sent after
182    # posting transactions. This Interswitch bug must be removed first.
183    # Alternatively, we could use the webservice only and replace
184    # the RequestCallbackActionButton by a RequestWebserviceActionButton
185
186    def update(self):
187        if self.context.p_state == 'paid':
188            self.flash(_('This ticket has already been paid.'))
189            return
190        student = self.context.getStudent()
191        query = self.request.form
192        # Should be logged instead of printed
193        write_log_message(self,'callback received: %s' % query)
194        if query.get('resp', None) != '00':
195            self.flash(_('Unsuccessful callback: ${a}',
196                mapping = {'a': query.get('desc', _('Incomplete query string.'))}))
197            write_log_message(self,'unsuccessful callback: %s' % self.context.p_id)
198            self.context.r_card_num = query.get('cardNum', None)
199            self.context.r_code = query.get('resp', None)
200            self.context.p_state = 'failed'
201            return
202
203        if query.get('apprAmt', None) != str(self.context.amount_auth):
204            self.flash(_('Wrong amount'))
205            write_log_message(self,'successful but wrong amount: %s' % self.context.p_id)
206            self.context.r_card_num = query.get('cardNum', None)
207            self.context.r_code = query.get('resp', None)
208            self.context.p_state = 'failed'
209            return
210
211        # Add webservice validation
212        validation_list = get_SOAP_response(
213            PRODUCT_ID, self.context.p_id).split(':')
214        # Validation does not make sense yet since the query string
215        # formats are conflicting.
216        print validation_list
217
218        write_log_message(self,'valid callback: %s' % self.context.p_id)
219        self.context.r_amount_approved = self.context.amount_auth
220        self.context.r_card_num = query.get('cardNum', None)
221        self.context.r_code = query.get('resp', None)
222        self.context.r_desc = query.get('desc', None)
223        self.context.r_pay_reference  = query.get('payRef', None)
224        self.context.p_state = 'paid'
225        self.context.payment_date = datetime.now()
226
227        if self.context.p_category == 'clearance':
228            # Create CLR access code
229            pin, error = create_accesscode('CLR',0,student.student_id)
230            if error:
231                self.flash(_('Valid callback received. ${a}',
232                    mapping = {'a':error}))
233                return
234            self.context.ac = pin
235        elif self.context.p_category == 'schoolfee':
236            # Create SFE access code
237            pin, error = create_accesscode('SFE',0,student.student_id)
238            if error:
239                self.flash(_('Valid callback received. ${a}',
240                    mapping = {'a':error}))
241                return
242            self.context.ac = pin
243        elif self.context.p_category == 'bed_allocation':
244            # Create HOS access code
245            pin, error = create_accesscode('HOS',0,student.student_id)
246            if error:
247                self.flash(_('Valid callback received. ${a}',
248                    mapping = {'a':error}))
249                return
250            self.context.ac = pin
251        self.flash(_('Valid callback received.'))
252        return
253
254    def render(self):
255        self.redirect(self.url(self.context, '@@index'))
256        return
257
258# Alternative solution, replaces OnlinePaymentCallbackPage
259class OnlinePaymentRequestWebservicePage(UtilityView, grok.View):
260    """ Request webservice view for the CollegePAY gateway
261    """
262    grok.context(IStudentOnlinePayment)
263    grok.name('request_webservice')
264    grok.require('waeup.payStudent')
265
266    def update(self):
267        if self.context.p_state == 'paid':
268            self.flash(_('This ticket has already been paid.'))
269            return
270        student = self.context.getStudent()
271        sr = get_SOAP_response(PRODUCT_ID, self.context.p_id)
272        write_log_message(self,'callback received: %s' % sr)
273        wlist = sr.split(':')
274        if len(wlist) != 7:
275            self.flash(_('Invalid callback: ${a}',
276                mapping = {'a': wlist}))
277            write_log_message(self,'invalid callback: %s' % self.context.p_id)
278            return
279        self.context.r_code = wlist[0]
280        self.context.r_desc = wlist[1]
281        self.context.r_amount_approved = int(wlist[2])
282        self.context.r_card_num = wlist[3]
283        self.context.r_pay_reference = wlist[5]
284       
285        if wlist[0] != '00':
286            self.flash(_('Unsuccessful callback: ${a}',
287                mapping = {'a': wlist[1]}))
288            write_log_message(self,'unsuccessful callback: %s' % self.context.p_id)
289            self.context.p_state = 'failed'
290            return
291
292        if wlist[2] != str(self.context.amount_auth):
293            self.flash(_('Wrong amount'))
294            write_log_message(self,'successful callback but wrong amount: %s' % self.context.p_id)
295            self.context.p_state = 'failed'
296            return
297
298        if wlist[5] != self.context.p_id:
299            self.flash(_('Wrong transaction id'))
300            write_log_message(self,'successful callback but wrong transaction id: %s' % self.context.p_id)
301            self.context.p_state = 'failed'
302            return
303
304        write_log_message(self,'successful callback: %s' % self.context.p_id)
305
306        self.context.p_state = 'paid'
307        self.context.payment_date = datetime.now()
308
309        if self.context.p_category == 'clearance':
310            # Create CLR access code
311            pin, error = create_accesscode('CLR',0,student.student_id)
312            if error:
313                self.flash(_('Valid callback received. ${a}',
314                    mapping = {'a':error}))
315                return
316            self.context.ac = pin
317        elif self.context.p_category == 'schoolfee':
318            # Create SFE access code
319            pin, error = create_accesscode('SFE',0,student.student_id)
320            if error:
321                self.flash(_('Valid callback received. ${a}',
322                    mapping = {'a':error}))
323                return
324            self.context.ac = pin
325        elif self.context.p_category == 'bed_allocation':
326            # Create HOS access code
327            pin, error = create_accesscode('HOS',0,student.student_id)
328            if error:
329                self.flash(_('Valid callback received. ${a}',
330                    mapping = {'a':error}))
331                return
332            self.context.ac = pin
333        self.flash(_('Valid callback received.'))
334        return
335
336    def render(self):
337        self.redirect(self.url(self.context, '@@index'))
338        return
Note: See TracBrowser for help on using the repository browser.