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

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

Implement acceptance fee payments via Interswitch. (tests will follow).

  • Property svn:keywords set to Id
File size: 15.1 KB
Line 
1## $Id: browser.py 8256 2012-04-23 07:36:46Z 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.uniben.students.interfaces import ICustomStudentOnlinePayment
26from waeup.uniben.applicants.interfaces import ICustomApplicantOnlinePayment
27from waeup.kofa.students.browser import write_log_message
28from waeup.kofa.students.viewlets import RequestCallbackActionButton as RCABStudent
29from waeup.kofa.applicants.viewlets import RequestCallbackActionButton as RCABApplicant
30from waeup.uniben.students.utils import actions_after_student_payment
31from waeup.uniben.applicants.utils import actions_after_applicant_payment
32from waeup.uniben.interfaces import MessageFactory as _
33
34#    Interswitch test account data:
35#
36#    Card Number: 6274807700000007
37#    Expiry Date: July 2012
38#    PIN: 0000
39
40#    Card Number: 6278050000000007
41#    Expiry Date: July 2012
42#    PIN: 0000
43
44PRODUCT_ID = '57'
45SITE_NAME = 'xyz.waeup.org'
46PROVIDER_ACCT = '2345'
47PROVIDER_BANK_ID = '8'
48PROVIDER_ITEM_NAME = 'Kofa Provider Fee'
49INSTITUTION_ACCT = '1234'
50INSTITUTION_BANK_ID = '9'
51INSTITUTION_NAME = 'Sample University'
52CURRENCY = '566'
53PAY_ITEM_ID = '5700'
54QUERY_URL =   'https://testwebpay.interswitchng.com/test_paydirect/services/TransactionQueryURL.aspx'
55POST_ACTION = 'https://testwebpay.interswitchng.com/test_paydirect/webpay/pay.aspx'
56
57HOST = 'testwebpay.interswitchng.com'
58URL = '/test_paydirect/services/TransactionQueryWs.asmx'
59httplib.HTTPConnection.debuglevel = 0
60
61
62def collect_xml_data(payment, xmldict):
63    xmldict['detail_ref'] = payment.p_id
64    xmldict['provider_amt'] = 100 * payment.surcharge_1
65    xmldict['provider_acct'] = PROVIDER_ACCT
66    xmldict['provider_bank_id'] = PROVIDER_BANK_ID
67    xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
68    xmldict['institution_amt'] = 100 * payment.amount_auth
69    xmldict['institution_acct'] = INSTITUTION_ACCT
70    xmldict['institution_bank_id'] = INSTITUTION_BANK_ID
71    xmldict['institution_item_name'] = payment.p_category
72    xmldict['institution_name'] = INSTITUTION_NAME
73    # Interswitch amount is not part of the xml data
74    xmltext = """<payment_item_detail>
75<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
76<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" />
77<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" />
78</item_details>
79</payment_item_detail>""" % xmldict
80    xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
81    return xml_data
82
83def SOAP_post(soap_action,xml):
84    """Handles making the SOAP request.
85
86    Further reading:
87    http://testwebpay.interswitchng.com/test_paydirect/services/TransactionQueryWs.asmx?op=getTransactionData
88    """
89    h = httplib.HTTPConnection(HOST)
90    headers={
91        'Host':HOST,
92        'Content-Type':'text/xml; charset=utf-8',
93        'Content-Length':len(xml),
94        'SOAPAction':'"%s"' % soap_action,
95    }
96    h.request('POST', URL, body=xml,headers=headers)
97    r = h.getresponse()
98    d = r.read()
99    if r.status!=200:
100        raise ValueError('Error connecting: %s, %s' % (r.status, r.reason))
101    return d
102
103def get_SOAP_response(product_id, transref):
104    xml="""\
105<?xml version="1.0" encoding="utf-8"?>
106<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/">
107  <soap:Body>
108    <getTransactionData xmlns="http://tempuri.org/">
109      <product_id>%s</product_id>
110      <trans_ref>%s</trans_ref>
111    </getTransactionData>
112  </soap:Body>
113</soap:Envelope>""" % (product_id, transref)
114    result_xml=SOAP_post("http://tempuri.org/getTransactionData",xml)
115    doc=parseString(result_xml)
116    response=doc.getElementsByTagName('getTransactionDataResult')[0].firstChild.data
117    return response
118
119def query_interswitch(user, payment, view):
120    ob_class = view.__implemented__.__name__
121    sr = get_SOAP_response(PRODUCT_ID, payment.p_id)
122    user.loggerInfo(ob_class, 'callback received: %s' % sr)
123    wlist = sr.split(':')
124    if len(wlist) != 7:
125        view.flash(_('Invalid callback: ${a}',
126            mapping = {'a': wlist}))
127        user.loggerInfo(ob_class,'invalid callback: %s' % payment.p_id)
128        return False
129    payment.r_code = wlist[0]
130    payment.r_desc = wlist[1]
131    payment.r_amount_approved = float(wlist[2]) / 100
132    payment.r_card_num = wlist[3]
133    payment.r_pay_reference = wlist[5]
134    if payment.r_code != '00':
135        view.flash(_('Unsuccessful callback: ${a}', mapping = {'a': wlist[1]}))
136        user.loggerInfo(ob_class,'unsuccessful callback: %s' % payment.p_id)
137        payment.p_state = 'failed'
138        return False
139    total_amount_auth = (
140        payment.amount_auth
141        + payment.surcharge_1
142        + payment.surcharge_2)
143    if payment.r_amount_approved != total_amount_auth:
144        view.flash(_('Wrong amount'))
145        user.loggerInfo(ob_class,'successful callback but wrong amount: %s'
146            % payment.p_id)
147        payment.p_state = 'failed'
148        return False
149    if wlist[4] != payment.p_id:
150        view.flash(_('Wrong transaction id'))
151        user.loggerInfo(ob_class,'successful callback but wrong transaction id: %s'
152            % payment.p_id)
153        payment.p_state = 'failed'
154        return False
155    user.loggerInfo(ob_class,'successful callback: %s' % payment.p_id)
156    payment.p_state = 'paid'
157    payment.payment_date = datetime.now()
158    return True
159
160
161class InterswitchActionButtonStudent(RCABStudent):
162    grok.order(2)
163    grok.context(ICustomStudentOnlinePayment)
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
174class InterswitchActionButtonApplicant(RCABApplicant):
175    grok.order(2)
176    grok.context(ICustomApplicantOnlinePayment)
177    icon = 'actionicon_pay.png'
178    text = _('CollegePAY')
179    target = 'goto_interswitch'
180
181    @property
182    def target_url(self):
183        if self.context.p_state != 'unpaid':
184            return ''
185        return self.view.url(self.view.context, self.target)
186
187# Deprecated
188class InterswitchRequestCallbackActionButtonStudent(RCABStudent):
189    grok.order(3)
190    grok.context(ICustomStudentOnlinePayment)
191    icon = 'actionicon_call.png'
192    text = _('Request CollegePAY callback')
193
194    def target_url(self):
195        if self.context.p_state == 'paid':
196            return ''
197        site_redirect_url = self.view.url(self.view.context, 'isw_callback')
198        args = {
199            'transRef':self.context.p_id,
200            'prodID':PRODUCT_ID,
201            'redirectURL':site_redirect_url}
202        return QUERY_URL + '?%s' % urllib.urlencode(args)
203
204# Alternative preferred solution
205class InterswitchRequestWebserviceActionButtonStudent(RCABStudent):
206    grok.order(4)
207    grok.context(ICustomStudentOnlinePayment)
208    icon = 'actionicon_call.png'
209    text = _('Request CollegePAY webservice')
210    target = 'request_webservice'
211
212class InterswitchRequestWebserviceActionButtonApplicant(RCABApplicant):
213    grok.order(4)
214    grok.context(ICustomApplicantOnlinePayment)
215    icon = 'actionicon_call.png'
216    text = _('Request CollegePAY webservice')
217    target = 'request_webservice'
218
219
220class InterswitchPageStudent(KofaPage):
221    """ View which sends a POST request to the Interswitch
222    CollegePAY payment gateway.
223    """
224    grok.context(ICustomStudentOnlinePayment)
225    grok.name('goto_interswitch')
226    grok.template('student_goto_interswitch')
227    grok.require('waeup.payStudent')
228    label = _('Submit data to CollegePAY (Interswitch Payment Gateway)')
229    submit_button = _('Submit')
230    action = POST_ACTION
231    site_name = SITE_NAME
232    currency = CURRENCY
233    pay_item_id = PAY_ITEM_ID
234    product_id = PRODUCT_ID
235
236    def update(self):
237        #if self.context.p_state != 'unpaid':
238        if self.context.p_state == 'paid':
239            self.flash(_("Payment ticket can't be re-send to CollegePAY."))
240            self.redirect(self.url(self.context, '@@index'))
241            return
242
243        self.student = self.context.getStudent()
244        certificate = getattr(self.student['studycourse'],'certificate',None)
245        xmldict = {}
246        if certificate is not None:
247            xmldict['department'] = certificate.__parent__.__parent__.code
248            xmldict['faculty'] = certificate.__parent__.__parent__.__parent__.code
249        else:
250            xmldict['department'] = None
251            xmldict['faculty'] = None
252        self.amount = (self.context.amount_auth + self.context.surcharge_1 +
253            self.context.surcharge_2 + self.context.surcharge_3)
254        self.amount_100 = 100 * self.amount
255        self.local_date_time = str(self.context.creation_date)
256        self.site_redirect_url = self.url(self.context, 'request_webservice')
257        self.xml_data = collect_xml_data(self.context, xmldict)
258        return
259
260class InterswitchPageApplicant(InterswitchPageStudent):
261    """ View which sends a POST request to the Interswitch
262    CollegePAY payment gateway.
263    """
264    grok.context(ICustomApplicantOnlinePayment)
265    grok.require('waeup.payApplicant')
266    grok.template('applicant_goto_interswitch')
267
268    def update(self):
269        if self.context.p_state != 'unpaid':
270            self.flash(_("Payment ticket can't be re-send to CollegePAY."))
271            self.redirect(self.url(self.context, '@@index'))
272            return
273        self.applicant = self.context.__parent__
274        xmldict = {}
275        xmldict['department'] = None
276        xmldict['faculty'] = None
277        self.amount = (self.context.amount_auth + self.context.surcharge_1 +
278            self.context.surcharge_2 + self.context.surcharge_3)
279        self.amount_100 = 100 * self.amount
280        self.local_date_time = str(self.context.creation_date)
281        self.site_redirect_url = self.url(self.context, 'request_webservice')
282        self.xml_data = collect_xml_data(self.context, xmldict)
283        return
284
285# Deprecated
286class InterswitchPaymentCallbackPageStudent(UtilityView, grok.View):
287    """ Callback view for the CollegePAY gateway
288    """
289    grok.context(ICustomStudentOnlinePayment)
290    grok.name('isw_callback')
291    grok.require('waeup.payStudent')
292
293    # This view is not yet working for offline querying transactions
294    # since the query string differs from the query string sent after
295    # posting transactions. This Interswitch bug must be removed first.
296    # Alternatively, we could use the webservice only and replace
297    # the RequestCallbackActionButton by a RequestWebserviceActionButton
298
299    def update(self):
300        if self.context.p_state == 'paid':
301            self.flash(_('This ticket has already been paid.'))
302            return
303        student = self.context.getStudent()
304        query = self.request.form
305        write_log_message(self,'callback received: %s' % query)
306
307        self.context.r_card_num = query.get('cardNum', None)
308        self.context.r_code = query.get('resp', None)
309        self.context.r_pay_reference  = query.get('payRef', None)
310        self.context.r_amount_approved = float(query.get('apprAmt', '0.0')) / 100
311        self.context.r_desc = query.get('desc', None)
312
313        if self.context.r_code != '00':
314            self.flash(_('Unsuccessful callback: ${a}',
315                mapping = {'a': query.get('desc', _('Incomplete query string.'))}))
316            write_log_message(self,'unsuccessful callback: %s' % self.context.p_id)
317            self.context.p_state = 'failed'
318            return
319
320        total_amount_auth = (
321            self.context.amount_auth
322            + self.context.surcharge_1
323            + self.context.surcharge_2)
324
325        if self.context.r_amount_approved != total_amount_auth:
326            self.flash(_('Wrong amount'))
327            write_log_message(
328                self,'successful but wrong amount: %s' % self.context.p_id)
329            self.context.p_state = 'failed'
330            return
331
332        try:
333            validation_list = get_SOAP_response(
334                PRODUCT_ID, self.context.p_id).split(':')
335            # Validation does not make sense yet since the query string
336            # formats are conflicting. We are only printing the validation
337            # string, nothing else.
338            print 'WARNING: Webservice validation is not yet implemented'
339            print 'validation list: %s' % validation_list
340        except:
341            print 'Connection to webservice failed.'
342
343        # Add webservice validation here
344
345        write_log_message(self,'valid callback: %s' % self.context.p_id)
346        self.context.p_state = 'paid'
347        self.context.payment_date = datetime.now()
348        actions_after_student_payment(student, self.context, self)
349        return
350
351    def render(self):
352        self.redirect(self.url(self.context, '@@index'))
353        return
354
355# Alternative solution, replaces InterswitchPaymentCallbackPage
356class InterswitchPaymentRequestWebservicePageStudent(UtilityView, grok.View):
357    """ Request webservice view for the CollegePAY gateway
358    """
359    grok.context(ICustomStudentOnlinePayment)
360    grok.name('request_webservice')
361    grok.require('waeup.payStudent')
362
363    def update(self):
364        if self.context.p_state == 'paid':
365            self.flash(_('This ticket has already been paid.'))
366            return
367        student = self.context.getStudent()
368        if query_interswitch(student, self.context, self):
369            actions_after_student_payment(student, self.context, self)
370        return
371
372    def render(self):
373        self.redirect(self.url(self.context, '@@index'))
374        return
375
376class InterswitchPaymentRequestWebservicePageApplicant(UtilityView, grok.View):
377    """ Request webservice view for the CollegePAY gateway
378    """
379    grok.context(ICustomApplicantOnlinePayment)
380    grok.name('request_webservice')
381    grok.require('waeup.payApplicant')
382
383    def update(self):
384        if self.context.p_state == 'paid':
385            self.flash(_('This ticket has already been paid.'))
386            return
387        applicant = self.context.__parent__
388        if query_interswitch(applicant, self.context, self):
389            actions_after_applicant_payment(student, self.context, self)
390        return
391
392    def render(self):
393        self.redirect(self.url(self.context, '@@index'))
394        return
Note: See TracBrowser for help on using the repository browser.