source: main/waeup.kwarapoly/trunk/src/waeup/kwarapoly/interswitch/browser.py @ 9392

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

Configure Interswitch module with hash value in form.

  • Property svn:keywords set to Id
File size: 15.2 KB
Line 
1## $Id: browser.py 9392 2012-10-23 08:24:31Z 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
21import hashlib
22from xml.dom.minidom import parseString
23import grok
24from zope.component import getUtility
25from waeup.kofa.browser.layout import KofaPage, UtilityView
26from waeup.kofa.accesscodes import create_accesscode
27from waeup.kofa.interfaces import RETURNING, IKofaUtils
28from waeup.kofa.utils.helpers import to_timezone
29from waeup.kofa.students.viewlets import ApprovePaymentActionButton as APABStudent
30from waeup.kofa.applicants.viewlets import ApprovePaymentActionButton as APABApplicant
31from waeup.kofa.payments.interfaces import payment_categories
32from waeup.kwarapoly.students.interfaces import ICustomStudentOnlinePayment
33from waeup.kwarapoly.applicants.interfaces import ICustomApplicantOnlinePayment
34from waeup.kwarapoly.interfaces import MessageFactory as _
35
36PRODUCT_ID = '3986'
37SITE_NAME = 'kwarapoly-kofa.waeup.org'
38PROVIDER_ACCT = '1010764827'
39PROVIDER_BANK_ID = '117'
40PROVIDER_ITEM_NAME = 'BT Education'
41INSTITUTION_NAME = 'KwaraPoly'
42CURRENCY = '566'
43#QUERY_URL = 'https://webpay.interswitchng.com/paydirect/services/TransactionQueryURL.aspx'
44#QUERY_URL = 'https://testwebpay.interswitchng.com/test_paydirect/services/TransactionQueryURL.aspx'
45
46#POST_ACTION = 'https://webpay.interswitchng.com/paydirect/webpay/pay.aspx'
47POST_ACTION = 'https://testwebpay.interswitchng.com/test_paydirect/webpay/pay.aspx'
48
49#HOST = 'webpay.interswitchng.com'
50HOST = 'testwebpay.interswitchng.com'
51
52#URL = '/paydirect/services/TransactionQueryWs.asmx'
53URL = '/test_paydirect/services/TransactionQueryWs.asmx'
54httplib.HTTPConnection.debuglevel = 0
55
56
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
93def query_interswitch(payment):
94    sr = get_SOAP_response(PRODUCT_ID, payment.p_id)
95    wlist = sr.split(':')
96    if len(wlist) != 7:
97        msg = _('Invalid callback: ${a}', mapping = {'a': sr})
98        log = 'invalid callback for payment %s: %s' % (payment.p_id, sr)
99        return False, msg, log
100    payment.r_code = wlist[0]
101    payment.r_desc = wlist[1]
102    payment.r_amount_approved = float(wlist[2]) / 100
103    payment.r_card_num = wlist[3]
104    payment.r_pay_reference = wlist[5]
105    if payment.r_code != '00':
106        msg = _('Unsuccessful callback: ${a}', mapping = {'a': sr})
107        log = 'unsuccessful callback for payment %s: %s' % (payment.p_id, sr)
108        payment.p_state = 'failed'
109        return False, msg, log
110    if payment.r_amount_approved != payment.amount_auth:
111        msg = _('Callback amount does not match.')
112        log = 'wrong callback for payment %s: %s' % (payment.p_id, sr)
113        payment.p_state = 'failed'
114        return False, msg, log
115    if wlist[4] != payment.p_id:
116        msg = _('Callback transaction id does not match.')
117        log = 'wrong callback for payment %s: %s' % (payment.p_id, sr)
118        payment.p_state = 'failed'
119        return False, msg, log
120    payment.p_state = 'paid'
121    payment.payment_date = datetime.utcnow()
122    msg = _('Successful callback received')
123    log = 'valid callback for payment %s: %s' % (payment.p_id, sr)
124    return True, msg, log
125
126class InterswitchActionButtonStudent(APABStudent):
127    grok.order(1)
128    grok.context(ICustomStudentOnlinePayment)
129    grok.require('waeup.payStudent')
130    icon = 'actionicon_pay.png'
131    text = _('CollegePAY')
132    target = 'goto_interswitch'
133
134    @property
135    def target_url(self):
136        if self.context.p_state != 'unpaid':
137            return ''
138        return self.view.url(self.view.context, self.target)
139
140class InterswitchActionButtonApplicant(APABApplicant):
141    grok.order(1)
142    grok.context(ICustomApplicantOnlinePayment)
143    grok.require('waeup.payApplicant')
144    icon = 'actionicon_pay.png'
145    text = _('CollegePAY')
146    target = 'goto_interswitch'
147
148    @property
149    def target_url(self):
150        if self.context.p_state != 'unpaid':
151            return ''
152        return self.view.url(self.view.context, self.target)
153
154class InterswitchRequestWebserviceActionButtonStudent(APABStudent):
155    grok.order(2)
156    grok.context(ICustomStudentOnlinePayment)
157    grok.require('waeup.payStudent')
158    icon = 'actionicon_call.png'
159    text = _('Requery CollegePAY')
160    target = 'request_webservice'
161
162class InterswitchRequestWebserviceActionButtonApplicant(APABApplicant):
163    grok.order(2)
164    grok.context(ICustomApplicantOnlinePayment)
165    grok.require('waeup.payApplicant')
166    icon = 'actionicon_call.png'
167    text = _('Requery CollegePAY')
168    target = 'request_webservice'
169
170class InterswitchPageStudent(KofaPage):
171    """ View which sends a POST request to the Interswitch
172    CollegePAY payment gateway.
173    """
174    grok.context(ICustomStudentOnlinePayment)
175    grok.name('goto_interswitch')
176    grok.template('student_goto_interswitch')
177    grok.require('waeup.payStudent')
178    label = _('Submit data to CollegePAY (Interswitch Payment Gateway)')
179    submit_button = _('Submit')
180    action = POST_ACTION
181    site_name = SITE_NAME
182    currency = CURRENCY
183    pay_item_id = '101'
184    product_id = PRODUCT_ID
185    mac = '737396C271FB8E2BA1A612A942267553E16373658A5F83D90DAFFBB806C16E9E6284006C06CEFFB55768004179D7BC01CD237CCE6314B938A5A5D9F49369DE5A'
186
187    def update(self):
188        #if self.context.p_state != 'unpaid':
189        if self.context.p_state == 'paid':
190            self.flash(_("Payment ticket can't be re-send to CollegePAY."))
191            self.redirect(self.url(self.context, '@@index'))
192            return
193
194        student = self.student = self.context.student
195        certificate = getattr(student['studycourse'],'certificate',None)
196        self.amount_auth = 100 * self.context.amount_auth
197        xmldict = {}
198        if certificate is not None:
199            xmldict['department'] = certificate.__parent__.__parent__.code
200            xmldict['faculty'] = certificate.__parent__.__parent__.__parent__.code
201        else:
202            xmldict['department'] = None
203            xmldict['faculty'] = None
204        self.category = payment_categories.getTermByToken(
205            self.context.p_category).title
206        tz = getUtility(IKofaUtils).tzinfo
207        self.local_date_time = to_timezone(
208            self.context.creation_date, tz).strftime("%Y-%m-%d %H:%M:%S %Z")
209        self.site_redirect_url = self.url(self.context, 'request_webservice')
210        # Provider data
211        xmldict['detail_ref'] = self.context.p_id
212        xmldict['provider_acct'] = PROVIDER_ACCT
213        xmldict['provider_bank_id'] = PROVIDER_BANK_ID
214        xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
215        xmldict['provider_amt'] = 100 * 1200
216        # Dalash data
217        xmldict['dalash_amt'] = 100 * 1800
218        # Institution data
219        if xmldict['faculty'] in ('CPGS',):
220            xmldict['institution_acct'] = "1771180233"
221            xmldict['institution_bank_id'] = '120'
222        elif xmldict['faculty'] in ('IBAS',):
223            xmldict['institution_acct'] = "0006772436"
224            xmldict['institution_bank_id'] = '121'
225        elif xmldict['faculty'] in ('IETS',):
226            xmldict['institution_acct'] = "0106259811"
227            xmldict['institution_bank_id'] = '10'
228        elif xmldict['faculty'] in ('IFMS',):
229            xmldict['institution_acct'] = "2013910271"
230            xmldict['institution_bank_id'] = '8'
231        elif xmldict['faculty'] in ('ITCH',):
232            xmldict['institution_acct'] = "1010445144"
233            xmldict['institution_bank_id'] = '117'
234        else:
235            xmldict['institution_acct'] = "0000000000000"
236            xmldict['institution_bank_id'] = '0'
237        xmldict['institution_amt'] = 100 * (
238            self.context.amount_auth - 1200 - 300 - 1800)
239        xmldict['institution_item_name'] = self.context.p_category
240        xmldict['institution_name'] = INSTITUTION_NAME
241
242        hashargs = (
243            self.context.p_id +
244            PRODUCT_ID +
245            self.pay_item_id +
246            str(int(self.amount_auth)) +
247            self.site_redirect_url +
248            self.mac)
249        self.hashvalue = hashlib.sha512(hashargs).hexdigest()
250
251        # Interswitch amount is not part of the xml data
252        xmltext = """<payment_item_detail>
253<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
254<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" />
255<item_detail item_id="2" item_name="Dalash" item_amt="%(dalash_amt)s" bank_id="117" acct_num="1013196791" />
256<item_detail item_id="3" item_name="%(provider_item_name)s" item_amt="%(provider_amt)d" bank_id="%(provider_bank_id)s" acct_num="%(provider_acct)s" />
257</item_details>
258</payment_item_detail>""" % xmldict
259        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
260        return
261
262class InterswitchPageApplicant(KofaPage):
263    """ View which sends a POST request to the Interswitch
264    CollegePAY payment gateway.
265    """
266    grok.context(ICustomApplicantOnlinePayment)
267    grok.require('waeup.payApplicant')
268    grok.template('applicant_goto_interswitch')
269    grok.name('goto_interswitch')
270    label = _('Submit data to CollegePAY (Interswitch Payment Gateway)')
271    submit_button = _('Submit')
272    action = POST_ACTION
273    site_name = SITE_NAME
274    currency = CURRENCY
275    pay_item_id = ''
276    product_id = PRODUCT_ID
277
278    def update(self):
279        if self.context.p_state != 'unpaid':
280            self.flash(_("Payment ticket can't be re-send to CollegePAY."))
281            self.redirect(self.url(self.context, '@@index'))
282            return
283        if self.context.__parent__.__parent__.expired \
284            and self.context.__parent__.__parent__.strict_deadline:
285            self.flash(_("Payment ticket can't be send to CollegePAY. "
286                         "Application period has expired."))
287            self.redirect(self.url(self.context, '@@index'))
288            return
289        self.applicant = self.context.__parent__
290        self.amount_auth = 100 * self.context.amount_auth
291        xmldict = {}
292        self.category = payment_categories.getTermByToken(
293            self.context.p_category).title
294        tz = getUtility(IKofaUtils).tzinfo
295        self.local_date_time = to_timezone(
296            self.context.creation_date, tz).strftime("%Y-%m-%d %H:%M:%S %Z")
297        self.site_redirect_url = self.url(self.context, 'request_webservice')
298        xmldict['detail_ref'] = self.context.p_id
299        # Provider data
300        xmldict['provider_amt'] = 100 * 500
301        xmldict['provider_acct'] = PROVIDER_ACCT
302        xmldict['provider_bank_id'] = PROVIDER_BANK_ID
303        xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
304        # Institution data
305        xmldict['institution_amt'] = 100 * (self.context.amount_auth - 500 - 150)
306        xmldict['institution_acct'] = '0'
307        xmldict['institution_bank_id'] = '0'
308        xmldict['institution_item_name'] = self.context.p_category
309        xmldict['institution_name'] = INSTITUTION_NAME
310        # Interswitch amount is not part of the xml data
311        xmltext = """<payment_item_detail>
312<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s">
313<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" />
314<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" />
315</item_details>
316</payment_item_detail>""" % xmldict
317        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
318        return
319
320
321class InterswitchPaymentRequestWebservicePageStudent(UtilityView, grok.View):
322    """ Request webservice view for the CollegePAY gateway
323    """
324    grok.context(ICustomStudentOnlinePayment)
325    grok.name('request_webservice')
326    grok.require('waeup.payStudent')
327
328    def update(self):
329        ob_class = self.__implemented__.__name__
330        if self.context.p_state == 'paid':
331            self.flash(_('This ticket has already been paid.'))
332            return
333        student = self.context.student
334        success, msg, log = query_interswitch(self.context)
335        student.writeLogMessage(self, log)
336        if not success:
337            self.flash(msg)
338            return
339        success, msg, log = self.context.doAfterStudentPayment()
340        if log is not None:
341            student.writeLogMessage(self, log)
342        self.flash(msg)
343        return
344
345    def render(self):
346        self.redirect(self.url(self.context, '@@index'))
347        return
348
349class InterswitchPaymentRequestWebservicePageApplicant(UtilityView, grok.View):
350    """ Request webservice view for the CollegePAY gateway
351    """
352    grok.context(ICustomApplicantOnlinePayment)
353    grok.name('request_webservice')
354    grok.require('waeup.payApplicant')
355
356    def update(self):
357        if self.context.p_state == 'paid':
358            self.flash(_('This ticket has already been paid.'))
359            return
360        applicant = self.context.__parent__
361        success, msg, log = query_interswitch(self.context)
362        applicant.writeLogMessage(self, log)
363        if not success:
364            self.flash(msg)
365            return
366        success, msg, log = self.context.doAfterApplicantPayment()
367        if log is not None:
368            applicant.writeLogMessage(self, log)
369        self.flash(msg)
370        return
371
372    def render(self):
373        self.redirect(self.url(self.context, '@@index'))
374        return
Note: See TracBrowser for help on using the repository browser.