source: main/waeup.fceokene/trunk/src/waeup/fceokene/interswitch/browser.py @ 8642

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

Customize amounts and bank data. pay_item_id and product_id still missing.

  • Property svn:keywords set to Id
File size: 14.0 KB
Line 
1## $Id: browser.py 8641 2012-06-06 20:15:47Z 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 zope.component import getUtility
24from waeup.kofa.browser.layout import KofaPage, UtilityView
25from waeup.kofa.accesscodes import create_accesscode
26from waeup.kofa.interfaces import RETURNING, IKofaUtils
27from waeup.kofa.utils.helpers import to_timezone
28from waeup.kofa.students.browser import write_log_message
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.fceokene.students.interfaces import ICustomStudentOnlinePayment
33from waeup.fceokene.applicants.interfaces import ICustomApplicantOnlinePayment
34from waeup.fceokene.interfaces import MessageFactory as _
35
36PRODUCT_ID = '00'
37SITE_NAME = 'fceokene-kofa.waeup.org'
38PROVIDER_ACCT = '0026781725'
39PROVIDER_BANK_ID = '31'
40PROVIDER_ITEM_NAME = 'BT Education'
41ICT_ACCT = '6216801058'
42ICT_BANK_ID = '117'
43ICT_ITEM_NAME = 'FCEOkene ICT'
44INSTITUTION_NAME = 'FCEOkene'
45CURRENCY = '566'
46#QUERY_URL = 'https://webpay.interswitchng.com/paydirect/services/TransactionQueryURL.aspx'
47#QUERY_URL = 'https://testwebpay.interswitchng.com/test_paydirect/services/TransactionQueryURL.aspx'
48POST_ACTION = 'https://webpay.interswitchng.com/paydirect/webpay/pay.aspx'
49#POST_ACTION = 'https://testwebpay.interswitchng.com/test_paydirect/webpay/pay.aspx'
50
51HOST = 'webpay.interswitchng.com'
52#HOST = 'testwebpay.interswitchng.com'
53URL = '/paydirect/services/TransactionQueryWs.asmx'
54#URL = '/test_paydirect/services/TransactionQueryWs.asmx'
55httplib.HTTPConnection.debuglevel = 0
56
57
58def SOAP_post(soap_action,xml):
59    """Handles making the SOAP request.
60
61    Further reading:
62    http://testwebpay.interswitchng.com/test_paydirect/services/TransactionQueryWs.asmx?op=getTransactionData
63    """
64    h = httplib.HTTPConnection(HOST)
65    headers={
66        'Host':HOST,
67        'Content-Type':'text/xml; charset=utf-8',
68        'Content-Length':len(xml),
69        'SOAPAction':'"%s"' % soap_action,
70    }
71    h.request('POST', URL, body=xml,headers=headers)
72    r = h.getresponse()
73    d = r.read()
74    if r.status!=200:
75        raise ValueError('Error connecting: %s, %s' % (r.status, r.reason))
76    return d
77
78def get_SOAP_response(product_id, transref):
79    xml="""\
80<?xml version="1.0" encoding="utf-8"?>
81<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/">
82  <soap:Body>
83    <getTransactionData xmlns="http://tempuri.org/">
84      <product_id>%s</product_id>
85      <trans_ref>%s</trans_ref>
86    </getTransactionData>
87  </soap:Body>
88</soap:Envelope>""" % (product_id, transref)
89    result_xml=SOAP_post("http://tempuri.org/getTransactionData",xml)
90    doc=parseString(result_xml)
91    response=doc.getElementsByTagName('getTransactionDataResult')[0].firstChild.data
92    return response
93
94def query_interswitch(payment):
95    sr = get_SOAP_response(PRODUCT_ID, payment.p_id)
96    wlist = sr.split(':')
97    if len(wlist) != 7:
98        msg = _('Invalid callback: ${a}', mapping = {'a': sr})
99        log = 'invalid callback for payment %s: %s' % (payment.p_id, sr)
100        return False, msg, log
101    payment.r_code = wlist[0]
102    payment.r_desc = wlist[1]
103    payment.r_amount_approved = float(wlist[2]) / 100
104    payment.r_card_num = wlist[3]
105    payment.r_pay_reference = wlist[5]
106    if payment.r_code != '00':
107        msg = _('Unsuccessful callback: ${a}', mapping = {'a': sr})
108        log = 'unsuccessful callback for payment %s: %s' % (payment.p_id, sr)
109        payment.p_state = 'failed'
110        return False, msg, log
111    if payment.r_amount_approved != payment.amount_auth:
112        msg = _('Callback amount does not match.')
113        log = 'wrong callback for payment %s: %s' % (payment.p_id, sr)
114        payment.p_state = 'failed'
115        return False, msg, log
116    if wlist[4] != payment.p_id:
117        msg = _('Callback transaction id does not match.')
118        log = 'wrong callback for payment %s: %s' % (payment.p_id, sr)
119        payment.p_state = 'failed'
120        return False, msg, log
121    payment.p_state = 'paid'
122    payment.payment_date = datetime.utcnow()
123    msg = _('Successful callback received')
124    log = 'valid callback for payment %s: %s' % (payment.p_id, sr)
125    return True, msg, log
126
127class InterswitchActionButtonStudent(APABStudent):
128    grok.order(1)
129    grok.context(ICustomStudentOnlinePayment)
130    grok.require('waeup.payStudent')
131    icon = 'actionicon_pay.png'
132    text = _('CollegePAY')
133    target = 'goto_interswitch'
134
135    @property
136    def target_url(self):
137        if self.context.p_state != 'unpaid':
138            return ''
139        return self.view.url(self.view.context, self.target)
140
141class InterswitchActionButtonApplicant(APABApplicant):
142    grok.order(1)
143    grok.context(ICustomApplicantOnlinePayment)
144    grok.require('waeup.payApplicant')
145    icon = 'actionicon_pay.png'
146    text = _('CollegePAY')
147    target = 'goto_interswitch'
148
149    @property
150    def target_url(self):
151        if self.context.p_state != 'unpaid':
152            return ''
153        return self.view.url(self.view.context, self.target)
154
155class InterswitchRequestWebserviceActionButtonStudent(APABStudent):
156    grok.order(2)
157    grok.context(ICustomStudentOnlinePayment)
158    grok.require('waeup.payStudent')
159    icon = 'actionicon_call.png'
160    text = _('Requery CollegePAY')
161    target = 'request_webservice'
162
163class InterswitchRequestWebserviceActionButtonApplicant(APABApplicant):
164    grok.order(2)
165    grok.context(ICustomApplicantOnlinePayment)
166    grok.require('waeup.payApplicant')
167    icon = 'actionicon_call.png'
168    text = _('Requery CollegePAY')
169    target = 'request_webservice'
170
171class InterswitchPageStudent(KofaPage):
172    """ View which sends a POST request to the Interswitch
173    CollegePAY payment gateway.
174    """
175    grok.context(ICustomStudentOnlinePayment)
176    grok.name('goto_interswitch')
177    grok.template('student_goto_interswitch')
178    grok.require('waeup.payStudent')
179    label = _('Submit data to CollegePAY (Interswitch Payment Gateway)')
180    submit_button = _('Submit')
181    action = POST_ACTION
182    site_name = SITE_NAME
183    currency = CURRENCY
184    pay_item_id = '5700'
185    product_id = PRODUCT_ID
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.getStudent()
195        certificate = getattr(self.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 * 1500
216        # Institution data
217        studycourse = student['studycourse']
218        xmldict['institution_acct'] = '000000000000'
219        xmldict['institution_bank_id'] = '00'
220        xmldict['institution_amt'] = 100 * (self.amount_auth - 1500 - 150)
221        xmldict['institution_item_name'] = self.context.p_category
222        xmldict['institution_name'] = INSTITUTION_NAME
223        # Interswitch amount is not part of the xml data
224        xmltext = """<payment_item_detail>
225<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
226<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" />
227<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" />
228</item_details>
229</payment_item_detail>""" % xmldict
230        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
231        return
232
233class InterswitchPageApplicant(KofaPage):
234    """ View which sends a POST request to the Interswitch
235    CollegePAY payment gateway.
236    """
237    grok.context(ICustomApplicantOnlinePayment)
238    grok.require('waeup.payApplicant')
239    grok.template('applicant_goto_interswitch')
240    grok.name('goto_interswitch')
241    label = _('Submit data to CollegePAY (Interswitch Payment Gateway)')
242    submit_button = _('Submit')
243    action = POST_ACTION
244    site_name = SITE_NAME
245    currency = CURRENCY
246    pay_item_id = '0000'
247    product_id = PRODUCT_ID
248
249    def update(self):
250        if self.context.p_state != 'unpaid':
251            self.flash(_("Payment ticket can't be re-send to CollegePAY."))
252            self.redirect(self.url(self.context, '@@index'))
253            return
254        self.applicant = self.context.__parent__
255        self.amount_auth = 100 * self.context.amount_auth
256        xmldict = {}
257        self.category = payment_categories.getTermByToken(
258            self.context.p_category).title
259        tz = getUtility(IKofaUtils).tzinfo
260        self.local_date_time = to_timezone(
261            self.context.creation_date, tz).strftime("%Y-%m-%d %H:%M:%S %Z")
262        self.site_redirect_url = self.url(self.context, 'request_webservice')
263        xmldict['detail_ref'] = self.context.p_id
264        # Provider data
265        xmldict['provider_amt'] = 100 * 365
266        xmldict['provider_acct'] = PROVIDER_ACCT
267        xmldict['provider_bank_id'] = PROVIDER_BANK_ID
268        xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
269        # ICT data
270        xmldict['ict_amt'] = 100 * 135
271        xmldict['ict_acct'] = ICT_ACCT
272        xmldict['ict_bank_id'] = ICT_BANK_ID
273        xmldict['ict_item_name'] = ICT_ITEM_NAME
274        # Institution data
275        xmldict['institution_amt'] = 100 * (
276            self.context.amount_auth - 365 - 150 - 135)
277        xmldict['institution_acct'] = '1012415659'
278        xmldict['institution_bank_id'] = '117'
279        xmldict['institution_item_name'] = self.context.p_category
280        xmldict['institution_name'] = INSTITUTION_NAME
281        # Interswitch amount is not part of the xml data
282        xmltext = """<payment_item_detail>
283<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s">
284<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" />
285<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" />
286<item_detail item_id="3" item_name="%(ict_item_name)s" item_amt="%(ict_amt)d" bank_id="%(ict_bank_id)s" acct_num="%(ict_acct)s" />
287</item_details>
288</payment_item_detail>""" % xmldict
289        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
290        return
291
292
293class InterswitchPaymentRequestWebservicePageStudent(UtilityView, grok.View):
294    """ Request webservice view for the CollegePAY gateway
295    """
296    grok.context(ICustomStudentOnlinePayment)
297    grok.name('request_webservice')
298    grok.require('waeup.payStudent')
299
300    def update(self):
301        ob_class = self.__implemented__.__name__
302        if self.context.p_state == 'paid':
303            self.flash(_('This ticket has already been paid.'))
304            return
305        student = self.context.getStudent()
306        success, msg, log = query_interswitch(self.context)
307        student.loggerInfo(ob_class, log)
308        if not success:
309            self.flash(msg)
310            return
311        success, msg, log = self.context.doAfterStudentPayment()
312        if log is not None:
313            student.loggerInfo(ob_class, log)
314        self.flash(msg)
315        return
316
317    def render(self):
318        self.redirect(self.url(self.context, '@@index'))
319        return
320
321class InterswitchPaymentRequestWebservicePageApplicant(UtilityView, grok.View):
322    """ Request webservice view for the CollegePAY gateway
323    """
324    grok.context(ICustomApplicantOnlinePayment)
325    grok.name('request_webservice')
326    grok.require('waeup.payApplicant')
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        applicant = self.context.__parent__
334        success, msg, log = query_interswitch(self.context)
335        applicant.loggerInfo(ob_class, log)
336        if not success:
337            self.flash(msg)
338            return
339        success, msg, log = self.context.doAfterApplicantPayment()
340        if log is not None:
341            applicant.loggerInfo(ob_class, log)
342        self.flash(msg)
343        return
344
345    def render(self):
346        self.redirect(self.url(self.context, '@@index'))
347        return
Note: See TracBrowser for help on using the repository browser.