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

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

The payment_categories vocab does no longer exist. We have a dict in KofaUtils? instead.

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