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

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

Log payment category.

Adjust to previous revisions.

  • Property svn:keywords set to Id
File size: 15.1 KB
Line 
1## $Id: browser.py 9436 2012-10-26 21:49:15Z 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 %s payment %s: %s' % (
123        payment.p_category, 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 = getUtility(IKofaUtils).PAYMENT_CATEGORIES[self.context.p_category]
205        tz = getUtility(IKofaUtils).tzinfo
206        self.local_date_time = to_timezone(
207            self.context.creation_date, tz).strftime("%Y-%m-%d %H:%M:%S %Z")
208        self.site_redirect_url = self.url(self.context, 'request_webservice')
209        # Provider data
210        xmldict['detail_ref'] = self.context.p_id
211        xmldict['provider_acct'] = PROVIDER_ACCT
212        xmldict['provider_bank_id'] = PROVIDER_BANK_ID
213        xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
214        xmldict['provider_amt'] = 100 * 1200
215        # Dalash data
216        xmldict['dalash_amt'] = 100 * 1800
217        # Institution data
218        if xmldict['faculty'] in ('CPGS',):
219            xmldict['institution_acct'] = "1771180233"
220            xmldict['institution_bank_id'] = '120'
221        elif xmldict['faculty'] in ('IBAS',):
222            xmldict['institution_acct'] = "0006772436"
223            xmldict['institution_bank_id'] = '121'
224        elif xmldict['faculty'] in ('IETS',):
225            xmldict['institution_acct'] = "0106259811"
226            xmldict['institution_bank_id'] = '10'
227        elif xmldict['faculty'] in ('IFMS',):
228            xmldict['institution_acct'] = "2013910271"
229            xmldict['institution_bank_id'] = '8'
230        elif xmldict['faculty'] in ('ITCH',):
231            xmldict['institution_acct'] = "1010445144"
232            xmldict['institution_bank_id'] = '117'
233        else:
234            xmldict['institution_acct'] = "0000000000000"
235            xmldict['institution_bank_id'] = '0'
236        xmldict['institution_amt'] = 100 * (
237            self.context.amount_auth - 1200 - 300 - 1800)
238        xmldict['institution_item_name'] = self.context.p_category
239        xmldict['institution_name'] = INSTITUTION_NAME
240
241        hashargs = (
242            self.context.p_id +
243            PRODUCT_ID +
244            self.pay_item_id +
245            str(int(self.amount_auth)) +
246            self.site_redirect_url +
247            self.mac)
248        self.hashvalue = hashlib.sha512(hashargs).hexdigest()
249
250        # Interswitch amount is not part of the xml data
251        xmltext = """<payment_item_detail>
252<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
253<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" />
254<item_detail item_id="2" item_name="Dalash" item_amt="%(dalash_amt)s" bank_id="117" acct_num="1013196791" />
255<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" />
256</item_details>
257</payment_item_detail>""" % xmldict
258        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
259        return
260
261class InterswitchPageApplicant(KofaPage):
262    """ View which sends a POST request to the Interswitch
263    CollegePAY payment gateway.
264    """
265    grok.context(ICustomApplicantOnlinePayment)
266    grok.require('waeup.payApplicant')
267    grok.template('applicant_goto_interswitch')
268    grok.name('goto_interswitch')
269    label = _('Submit data to CollegePAY (Interswitch Payment Gateway)')
270    submit_button = _('Submit')
271    action = POST_ACTION
272    site_name = SITE_NAME
273    currency = CURRENCY
274    pay_item_id = ''
275    product_id = PRODUCT_ID
276
277    def update(self):
278        if self.context.p_state != 'unpaid':
279            self.flash(_("Payment ticket can't be re-send to CollegePAY."))
280            self.redirect(self.url(self.context, '@@index'))
281            return
282        if self.context.__parent__.__parent__.expired \
283            and self.context.__parent__.__parent__.strict_deadline:
284            self.flash(_("Payment ticket can't be send to CollegePAY. "
285                         "Application period has expired."))
286            self.redirect(self.url(self.context, '@@index'))
287            return
288        self.applicant = self.context.__parent__
289        self.amount_auth = 100 * self.context.amount_auth
290        xmldict = {}
291        self.category = getUtility(IKofaUtils).PAYMENT_CATEGORIES[self.context.p_category]
292        tz = getUtility(IKofaUtils).tzinfo
293        self.local_date_time = to_timezone(
294            self.context.creation_date, tz).strftime("%Y-%m-%d %H:%M:%S %Z")
295        self.site_redirect_url = self.url(self.context, 'request_webservice')
296        xmldict['detail_ref'] = self.context.p_id
297        # Provider data
298        xmldict['provider_amt'] = 100 * 500
299        xmldict['provider_acct'] = PROVIDER_ACCT
300        xmldict['provider_bank_id'] = PROVIDER_BANK_ID
301        xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
302        # Institution data
303        xmldict['institution_amt'] = 100 * (self.context.amount_auth - 500 - 150)
304        xmldict['institution_acct'] = '0'
305        xmldict['institution_bank_id'] = '0'
306        xmldict['institution_item_name'] = self.context.p_category
307        xmldict['institution_name'] = INSTITUTION_NAME
308        # Interswitch amount is not part of the xml data
309        xmltext = """<payment_item_detail>
310<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s">
311<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" />
312<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" />
313</item_details>
314</payment_item_detail>""" % xmldict
315        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
316        return
317
318
319class InterswitchPaymentRequestWebservicePageStudent(UtilityView, grok.View):
320    """ Request webservice view for the CollegePAY gateway
321    """
322    grok.context(ICustomStudentOnlinePayment)
323    grok.name('request_webservice')
324    grok.require('waeup.payStudent')
325
326    def update(self):
327        ob_class = self.__implemented__.__name__
328        if self.context.p_state == 'paid':
329            self.flash(_('This ticket has already been paid.'))
330            return
331        student = self.context.student
332        success, msg, log = query_interswitch(self.context)
333        student.writeLogMessage(self, log)
334        if not success:
335            self.flash(msg)
336            return
337        success, msg, log = self.context.doAfterStudentPayment()
338        if log is not None:
339            student.writeLogMessage(self, log)
340        self.flash(msg)
341        return
342
343    def render(self):
344        self.redirect(self.url(self.context, '@@index'))
345        return
346
347class InterswitchPaymentRequestWebservicePageApplicant(UtilityView, grok.View):
348    """ Request webservice view for the CollegePAY gateway
349    """
350    grok.context(ICustomApplicantOnlinePayment)
351    grok.name('request_webservice')
352    grok.require('waeup.payApplicant')
353
354    def update(self):
355        if self.context.p_state == 'paid':
356            self.flash(_('This ticket has already been paid.'))
357            return
358        applicant = self.context.__parent__
359        success, msg, log = query_interswitch(self.context)
360        applicant.writeLogMessage(self, log)
361        if not success:
362            self.flash(msg)
363            return
364        success, msg, log = self.context.doAfterApplicantPayment()
365        if log is not None:
366            applicant.writeLogMessage(self, log)
367        self.flash(msg)
368        return
369
370    def render(self):
371        self.redirect(self.url(self.context, '@@index'))
372        return
Note: See TracBrowser for help on using the repository browser.